Agent-js identity web workers

Did anyone succeed passing the identity to a web worker?
How did you achieve that?

I already figured out I had to pass the host to create an actor on the web worker side, as there is no window available in the context (if interested here the sample repo).

Now I am looking to pass and re-create the identity on the web worker side too, as the actor is accessing it and my web app implements the user authentication.

I just found a way to solve this but, the way to access the information on the window side feels a bit hacky. I would be really happy if someone can share a better solution.

On the window side, I get the identity key and delegation chain through the storage.

const storage: LocalStorage = new LocalStorage('ic-');

const identityKey: string | null = await storage.get('identity');
const delegationChain: string | null = await storage.get('delegation');

On the worker side, I get these values and recreate the identity:

const chain: DelegationChain = DelegationChain.fromJSON(delegationChain);
const key: Ed25519KeyIdentity = Ed25519KeyIdentity.fromJSON(identityKey);

const identity: Identity = DelegationIdentity.fromDelegation(key, chain);
1 Like

That doesn’t seem particularly hacky to me. We share all these building blocks so that you can do this when your app leaves the happy path.

That said, I’m not sure of any reason that you couldn’t pass a fully constructed identity from the main thread to your worker

Not particularly but, a bit hacky to me because I have to re-create the local storage object and, access not exposted storage contant keys ('ic-', 'identity' and 'delegation'). Anyway good to know it is alright, means I can live with it :wink:.

I think you can pass “pure” objects between window and worker side. Functions won’t be serialized / accepted.

If I try to pass the fully constructed identity, I get following error at runtime when I create an actor on the web worker side:

TypeError: r.getPrincipal is not a function
at HttpAgent.query (p-83abda50.js:13)
at async p-83abda50.js:13
at async initSlidesActor (p-83abda50.js:13)
at async Object.initUserWorker (p-83abda50.js:13)
at async p-83abda50.js:1 undefined

You can skip the localstorage at least by taking identity.getKeyPair() and passing those values to the worker, where you can re-initialize using Ed25519KeyIdentity.fromKeyPair()

I also tried that path today but, it did not work out.

In my web app at least, identity is not an Ed25519KeyIdentity but rather a DelegationIdentity. Therefore there isn’t such a function as getKeyPair() available unfortunately.

const identity = this.authClient.getIdentity();
console.log(typeof (identity as Ed25519KeyIdentity).getKeyPair === 'function'); // -> false

Gotcha. Probably some ergonomics we can improve there, but I’m glad you’re not blocked for now

1 Like

Definitely not blocked, it works like a charm :ok_hand:.

Thanks for the feedback and ideas!

1 Like