Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added holochain toggle on login page #425

Merged
merged 5 commits into from
Dec 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions cli/src/agent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ pub enum AgentFunctions {
/// Agent passphrase
#[arg(short, long)]
passphrase: Option<String>,

/// Agent passphrase
#[arg(short, long)]
holochain: Option<bool>,
},
/// Lookup agent by DID
ByDID {
Expand Down Expand Up @@ -87,14 +91,20 @@ pub async fn run(ad4m_client: Ad4mClient, command: AgentFunctions) -> Result<()>
println!("Agent locked");
}
}
AgentFunctions::Unlock { passphrase } => {
AgentFunctions::Unlock { passphrase, holochain } => {
let pp = if passphrase.is_some() {
passphrase.unwrap()
} else {
readline_masked("Passphrase: ")?
};

let result = ad4m_client.agent.unlock(pp).await?;
let holo = if holochain.is_some() {
holochain.unwrap()
} else {
true
};

let result = ad4m_client.agent.unlock(pp, holo).await?;
if let Some(error) = result.error {
bail!(error);
} else {
Expand Down
2 changes: 1 addition & 1 deletion cli/src/bootstrap_publish.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ pub async fn start_publishing(

let agent = ad4m_client
.agent
.unlock(passphrase)
.unlock(passphrase, true)
.await
.expect("could not unlock agent");

Expand Down
4 changes: 2 additions & 2 deletions connect/src/web.ts
Original file line number Diff line number Diff line change
Expand Up @@ -496,8 +496,8 @@ export class Ad4mConnectElement extends LitElement {
this.loadFont();
}

private async unlockAgent(passcode) {
await this._client.ad4mClient.agent.unlock(passcode);
private async unlockAgent(passcode, holochain = true) {
await this._client.ad4mClient.agent.unlock(passcode, holochain);
}

private verifyCode(code) {
Expand Down
6 changes: 3 additions & 3 deletions core/src/Ad4mClient.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ describe('Ad4mClient', () => {
})

it('unlock() smoke test', async () => {
const agentStatus = await ad4mClient.agent.unlock('secret')
const agentStatus = await ad4mClient.agent.unlock('secret', false)
expect(agentStatus.did).toBe("did:ad4m:test")
expect(agentStatus.isUnlocked).toBe(true)
})
Expand Down Expand Up @@ -949,7 +949,7 @@ describe('Ad4mClient', () => {

ad4mClientWithoutSubscription.agent.subscribeAgentStatusChanged()
await new Promise<void>(resolve => setTimeout(resolve, 100))
await ad4mClientWithoutSubscription.agent.unlock("test");
await ad4mClientWithoutSubscription.agent.unlock("test", false);
expect(agentStatusChangedCallback).toBeCalledTimes(1)
})

Expand Down Expand Up @@ -1030,7 +1030,7 @@ describe('Ad4mClient', () => {
expect(agentStatusChangedCallback).toBeCalledTimes(0)

await new Promise<void>(resolve => setTimeout(resolve, 100))
await ad4mClientWithSubscription.agent.unlock("test");
await ad4mClientWithSubscription.agent.unlock("test", false);
expect(agentStatusChangedCallback).toBeCalledTimes(1)
})

Expand Down
8 changes: 4 additions & 4 deletions core/src/agent/AgentClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,15 +183,15 @@ export class AgentClient {
return new AgentStatus(agentLock);
}

async unlock(passphrase: string): Promise<AgentStatus> {
async unlock(passphrase: string, holochain: boolean): Promise<AgentStatus> {
const { agentUnlock } = unwrapApolloResult(
await this.#apolloClient.mutate({
mutation: gql`mutation agentUnlock($passphrase: String!) {
agentUnlock(passphrase: $passphrase) {
mutation: gql`mutation agentUnlock($passphrase: String!, $holochain: Boolean!) {
agentUnlock(passphrase: $passphrase, holochain: $holochain) {
${AGENT_STATUS_FIELDS}
}
}`,
variables: { passphrase },
variables: { passphrase, holochain },
})
);
return new AgentStatus(agentUnlock);
Expand Down
1 change: 1 addition & 0 deletions core/src/agent/AgentResolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ export default class AgentResolver {
@Mutation((returns) => AgentStatus)
agentUnlock(
@Arg("passphrase") passphrase: string,
@Arg("holochain") holochain: boolean,
@PubSub() pubSub: any
): AgentStatus {
const status = new AgentStatus({
Expand Down
13 changes: 7 additions & 6 deletions executor/src/core/LanguageController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,8 @@ export default class LanguageController {

const customSettings = this.getSettings(hash)
const storageDirectory = this.getLanguageStoragePath(hash)
const Holochain = this.#holochainService.getDelegateForLanguage(hash)

const Holochain = this.#holochainService?.getDelegateForLanguage(hash)
//@ts-ignore
const ad4mSignal = this.#context.ad4mSignal.bind({language: hash, pubsub: this.#pubSub});
const language = await create({...this.#context, customSettings, storageDirectory, Holochain, ad4mSignal})
Expand Down Expand Up @@ -313,7 +314,7 @@ export default class LanguageController {
}
const customSettings = this.getSettings(hash)
const storageDirectory = this.getLanguageStoragePath(hash)
const Holochain = this.#holochainService.getDelegateForLanguage(hash)
const Holochain = this.#holochainService?.getDelegateForLanguage(hash)
//@ts-ignore
const ad4mSignal = this.#context.ad4mSignal.bind({language: address, pubsub: this.#pubSub});
//@ts-ignore
Expand Down Expand Up @@ -458,7 +459,7 @@ export default class LanguageController {
console.error(e)
//fs.rmdirSync(languagePath, {recursive: true})
//@ts-ignore
throw Error(`Error loading language [${sourcePath}]: ${e.toString()}`)
// throw Error(`Error loading language [${sourcePath}]: ${e.toString()}`)
}
}

Expand All @@ -473,7 +474,7 @@ export default class LanguageController {
this.#languages.delete(hash as string);
this.#languageConstructors.delete(hash as string);
try {
await this.#holochainService.removeDnaForLang(hash as string);
await this.#holochainService?.removeDnaForLang(hash as string);
} catch(e) {
console.log("No DNA found for language installed");
}
Expand Down Expand Up @@ -628,7 +629,7 @@ export default class LanguageController {
//Unpack the DNA
//TODO: we need to be able to check for errors in this fn call, currently we just crudly split the result
console.log("LanguageController.readAndTemplateHolochainDNA: unpacking DNA");
let unpackPath = (await this.#holochainService.unpackDna(tempDnaPath)).replace(/(\r\n|\n|\r)/gm, "");
let unpackPath = (await this.#holochainService?.unpackDna(tempDnaPath)).replace(/(\r\n|\n|\r)/gm, "");
fs.unlinkSync(tempDnaPath);
//TODO: are all dna's using the same dna.yaml?
const dnaYamlPath = path.join(unpackPath, "dna.yaml");
Expand Down Expand Up @@ -664,7 +665,7 @@ export default class LanguageController {

//TODO: we need to be able to check for errors in this fn call, currently we just crudly split the result
console.log("LanguageController.readAndTemplateHolochainDNA: packing DNA");
let packPath = (await this.#holochainService.packDna(unpackPath)).replace(/(\r\n|\n|\r)/gm, "");
let packPath = (await this.#holochainService?.packDna(unpackPath)).replace(/(\r\n|\n|\r)/gm, "");
const base64 = fs.readFileSync(packPath, "base64").replace(/[\r\n]+/gm, '');

//Cleanup temp directory
Expand Down
6 changes: 4 additions & 2 deletions executor/src/core/graphQL-interface/GraphQL.ts
Original file line number Diff line number Diff line change
Expand Up @@ -524,6 +524,7 @@ export function createResolvers(core: Ad4mCore, config: OuterConfig) {
},
//@ts-ignore
agentUnlock: async (args, context) => {

checkCapability(context.capabilities, Auth.AGENT_UNLOCK_CAPABILITY)
try {
await core.agentService.unlock(args.passphrase)
Expand All @@ -540,8 +541,9 @@ export function createResolvers(core: Ad4mCore, config: OuterConfig) {
} catch (e) {
// @ts-ignore
const {hcPortAdmin, connectHolochain, hcPortApp, hcUseLocalProxy, hcUseMdns, hcUseProxy, hcUseBootstrap, hcProxyUrl, hcBootstrapUrl} = config;

await core.initHolochain({ hcPortAdmin, hcPortApp, hcUseLocalProxy, hcUseMdns, hcUseProxy, hcUseBootstrap, passphrase: args.passphrase, hcProxyUrl, hcBootstrapUrl });
if (args.holochain === "true") {
await core.initHolochain({ hcPortAdmin, hcPortApp, hcUseLocalProxy, hcUseMdns, hcUseProxy, hcUseBootstrap, passphrase: args.passphrase, hcProxyUrl, hcBootstrapUrl });
}
await core.waitForAgent();
core.initControllers()
await core.initLanguages()
Expand Down
4 changes: 2 additions & 2 deletions rust-client/src/agent.gql
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,8 @@ mutation Lock($passphrase: String!) {
}
}

mutation Unlock($passphrase: String!) {
agentUnlock(passphrase: $passphrase) {
mutation Unlock($passphrase: String!, $holochain: Boolean!) {
agentUnlock(passphrase: $passphrase, holochain: $holochain) {
isInitialized
isUnlocked
did
Expand Down
6 changes: 4 additions & 2 deletions rust-client/src/agent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -221,11 +221,12 @@ pub async fn unlock(
executor_url: String,
cap_token: String,
passphrase: String,
holochain: bool
) -> Result<unlock::UnlockAgentUnlock> {
let response_data: unlock::ResponseData = query(
executor_url,
cap_token,
Unlock::build_query(unlock::Variables { passphrase }),
Unlock::build_query(unlock::Variables { passphrase, holochain }),
)
.await
.with_context(|| "Failed to run agent->unlock")?;
Expand Down Expand Up @@ -471,11 +472,12 @@ impl AgentClient {
.await
}

pub async fn unlock(&self, passphrase: String) -> Result<unlock::UnlockAgentUnlock> {
pub async fn unlock(&self, passphrase: String, holochain: bool) -> Result<unlock::UnlockAgentUnlock> {
unlock(
self.info.executor_url.clone(),
self.info.cap_token.clone(),
passphrase,
holochain
)
.await
}
Expand Down
5 changes: 3 additions & 2 deletions rust-executor/src/graphql/mutation_resolvers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -251,15 +251,16 @@ impl Mutation {
&self,
context: &RequestContext,
passphrase: String,
holochain: bool
) -> FieldResult<AgentStatus> {
let capabilities =
get_capabilies(context.js_handle.clone(), context.capability.clone()).await?;
let mut js = context.js_handle.clone();
let script = format!(
r#"JSON.stringify(
await core.callResolver("Mutation", "agentUnlock", {{ passphrase: "{}" }}, {{ capabilities: {} }})
await core.callResolver("Mutation", "agentUnlock", {{ passphrase: "{}", holochain: "{}" }}, {{ capabilities: {} }})
)"#,
passphrase, capabilities
passphrase, holochain, capabilities
);
let result = js.execute(script).await?;
let result: JsResultType<AgentStatus> = serde_json::from_str(&result)?;
Expand Down
15 changes: 13 additions & 2 deletions ui/src/components/Login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ const Login = (props: any) => {
const [usernameError, setUsernameError] = useState<string | null>(null);
let [passwordError, setPasswordError] = useState<string | null>(null);
const [clearAgentModalOpen, setClearAgentModalOpen] = useState(false);
const [holochain, setHolochain] = useState(true);

if (hasLoginError) {
passwordError = "Invalid password";
Expand All @@ -55,7 +56,7 @@ const Login = (props: any) => {
const onKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
if (event.key === "Enter") {
if (isInitialized) {
unlockAgent(password);
unlockAgent(password, holochain);
} else {
generate();
}
Expand Down Expand Up @@ -429,13 +430,23 @@ const Login = (props: any) => {
>
Reset agent
</j-button>
<j-box px="100" >
<j-toggle
checked={holochain}
onChange={(e) => {
setHolochain(e.target.checked);
}}
>
{`Turn ${holochain ? 'off' : "on"} Holochain`}
</j-toggle>
</j-box>
<j-button
full
size="lg"
class="full-button"
variant="primary"
style={{ alignSelf: "center" }}
onClick={() => unlockAgent(password)}
onClick={() => unlockAgent(password, holochain)}
loading={loading}
>
Unlock Agent
Expand Down
7 changes: 4 additions & 3 deletions ui/src/context/AgentContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ type State = {
type ContextProps = {
state: State;
methods: {
unlockAgent: (str: string) => void,
unlockAgent: (str: string, holochain: boolean) => void,
lockAgent: (str: string) => void,
generateAgent: (username: string, firstName: string, lastName: string, password: string) => void,
};
Expand Down Expand Up @@ -106,10 +106,11 @@ export function AgentProvider({ children }: any) {
navigate('/apps');
};

const unlockAgent = async (password: string) => {
const unlockAgent = async (password: string, holochain: boolean) => {
console.log("wow", password, holochain)
setLoading(true)

let agentStatus = await client?.agent.unlock(password);
let agentStatus = await client?.agent.unlock(password, holochain);

setLoading(false);

Expand Down
Loading