Skip to content

Commit

Permalink
Merge branch 'next' into contributors-page1
Browse files Browse the repository at this point in the history
  • Loading branch information
quininez authored Oct 31, 2024
2 parents a1cc394 + 26f51fa commit addf3bc
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 83 deletions.
54 changes: 6 additions & 48 deletions libs/sdk/src/auth/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { authStatus, SwActionType } from './constants';
import { authStatus } from './constants';
import { inject, injectable } from 'inversify';
import {
AUTH_EVENTS,
Expand All @@ -21,7 +21,7 @@ import Settings from '../settings';

import Gql from '../gql';
import { createFormattedValue } from '../helpers/observable';
import { executeOnSW } from './helpers';
// import { executeOnSW } from './helpers';
import pino from 'pino';
import Lit from '../common/lit';
import CeramicService from '../common/ceramic';
Expand Down Expand Up @@ -159,15 +159,8 @@ class AWF_Auth {
try {
const address = await this._connectAddress();
const localUser = localStorage.getItem(this.currentUserKey);
const chainNameSpace = 'eip155';
const chainId = this._web3.networkId[this._web3.network];
const chainIdNameSpace = `${chainNameSpace}:${chainId}`;
const ceramicResources = await this._ceramic.geResourcesHash();
this.sessKey = `@identity:${chainIdNameSpace}:${address?.toLowerCase()}:${
this._web3.state.providerType
}:${ceramicResources.hash}`;
const sessValue = localStorage.getItem(this.sessKey);
if (localUser && sessValue) {

if (localUser) {
const tmpSession = JSON.parse(localUser);
if (address && tmpSession?.ethAddress === address?.toLowerCase()) {
this._globalChannel.next({
Expand All @@ -183,23 +176,8 @@ class AWF_Auth {
await this.checkIfSignedUp(address);
}
this._log.info(`using eth address ${address}`);
if (sessValue) {
const sessionKey = await executeOnSW<{ value?: string }>(
Object.assign(
{
type: SwActionType.DECRYPT,
},
JSON.parse(sessValue),
),
);
if (sessionKey?.value) {
this.#_didSession = await this._ceramic.restoreSession(sessionKey.value);
}
}

if (!this._ceramic.hasSession()) {
this.#_didSession = await this._ceramic.connect();
}
this.#_didSession = await this._ceramic.connect();
this.currentUser = {
id: this.#_didSession?.id,
ethAddress: address?.toLowerCase(),
Expand All @@ -208,7 +186,6 @@ class AWF_Auth {
} catch (e) {
this._lockSignIn = false;
this.#_didSession = undefined;
localStorage.removeItem(this.sessKey);
localStorage.removeItem(this.currentUserKey);
this._log.error(e);
await this._web3.disconnect();
Expand All @@ -218,15 +195,6 @@ class AWF_Auth {
if (!this.#_didSession) {
throw new Error('DID session could not be initialised!');
}
if (typeof this.#_didSession.serialize === 'function') {
const swResponse = await executeOnSW({
type: SwActionType.ENCRYPT,
value: this.#_didSession.serialize(),
});
if (swResponse) {
localStorage.setItem(this.sessKey, JSON.stringify(swResponse));
}
}

localStorage.setItem(this.currentUserKey, JSON.stringify(this.currentUser));

Expand Down Expand Up @@ -344,21 +312,11 @@ class AWF_Auth {
private async _signOut() {
sessionStorage.clear();
localStorage.removeItem(this.currentUserKey);
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
if (!key) {
continue;
}
// remove any dangling did session
if (key.startsWith('@identity')) {
localStorage.removeItem(key);
}
}
this.currentUser = undefined;
await this._ceramic.disconnect();
await this._gql.setContextViewerID('');
await this._web3.disconnect();
await this._lit.disconnect();
await this._ceramic.disconnect();
await this._gql.resetCache();
// notify appLoader on sign out
this._globalChannel.next({
Expand Down
49 changes: 26 additions & 23 deletions libs/sdk/src/common/ceramic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,17 @@ export default class CeramicService {
});
}

async getAccountID(): Promise<AccountId> {
const ethAddress = await this._web3.getCurrentEthAddress();
if (!ethAddress) {
throw new Error('No eth address connected!');
}
return new AccountId({
address: ethAddress,
chainId: this._web3.CAIP10.chainIdNameSpace,
});
}

/*
Creates an Ethereum account ID and DID session to authenticate with Ceramic.
Expand All @@ -79,17 +90,14 @@ Functionality:
if (!ethAddress) {
throw new Error('No eth address connected!');
}
const accountId = new AccountId({
address: ethAddress,
chainId: this._web3.CAIP10.chainIdNameSpace,
});
const accountId = await this.getAccountID();
const web3Provider = this._web3.walletProvider;
if (!web3Provider) {
throw new Error('No provider found for ceramic:connect!');
}

const authMethod = await EthereumWebAuth.getAuthMethod(web3Provider, accountId);
this._didSession = await DIDSession.authorize(authMethod, {
this._didSession = await DIDSession.get(accountId, authMethod, {
resources: this._composeClient.resources,
expiresInSecs: 60 * 60 * 24 * 7, // 1 week
});
Expand All @@ -109,28 +117,13 @@ Functionality:
return did;
}

async restoreSession(serialisedSession: string): Promise<DIDSession> {
this._didSession = await DIDSession.fromSession(serialisedSession);
if (!this._didSession || (this._didSession.hasSession && this._didSession.isExpired)) {
return this.connect();
}
this._composeClient.setDID(this._didSession.did);
return this._didSession;
}

getComposeClient() {
return this._composeClient;
}

hasSession(): boolean {
return !!this._didSession && this._didSession.hasSession;
}

serialize() {
if (this.hasSession()) {
return this._didSession?.serialize();
}
return null;
async hasSession(): Promise<boolean> {
const accountId = await this.getAccountID();
return DIDSession.hasSessionFor(accountId, this._composeClient.resources);
}

async geResourcesHash() {
Expand All @@ -153,6 +146,16 @@ Functionality:
}

async disconnect() {
try {
const accountId = await this.getAccountID();
const hasSession = await this.hasSession();
if (hasSession) {
await DIDSession.remove(accountId);
}
} catch (e) {
this._log.warn('Error disconnecting DIDSession', e);
}

if (this._didSession) {
this._didSession = undefined;
this._composeClient = new ComposeClient({
Expand Down
22 changes: 11 additions & 11 deletions libs/sdk/src/common/ipfs.connector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ import pino from 'pino';
import { z } from 'zod';
import { validate } from './validator';
import CeramicService from './ceramic';
import { fromString } from 'uint8arrays/from-string';
import { toString } from 'uint8arrays/to-string';
// import { fromString } from 'uint8arrays/from-string';
// import { toString } from 'uint8arrays/to-string';
import { extract } from '@ucanto/core/delegation';
import type { Cacao } from '@didtools/cacao';
import { StoreMemory } from '@web3-storage/access/stores/store-memory';
Expand Down Expand Up @@ -71,15 +71,15 @@ class AWF_IpfsConnector {
* @returns {Promise<void>}
*/
private async _createClient() {
const serialisedSession = this._ceramic.serialize();
if (!serialisedSession) {
throw new Error('Must start a did-session first!');
}
const { sessionKeySeed } = JSON.parse(
toString(fromString(serialisedSession, 'base64url')),
) as SessionObj;
const keySeed = fromString(sessionKeySeed, 'base64pad');
const principal = await Signer.derive(keySeed);
// const serialisedSession = await this._ceramic.serialize();
// if (!serialisedSession) {
// throw new Error('Must start a did-session first!');
// }
// const { sessionKeySeed } = JSON.parse(
// toString(fromString(serialisedSession, 'base64url')),
// ) as SessionObj;
// const keySeed = fromString(sessionKeySeed, 'base64pad');
const principal = await Signer.generate();
this.#w3upClient = await create({ principal, store: new StoreMemory() });
}

Expand Down
12 changes: 11 additions & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -7575,7 +7575,7 @@ __metadata:
languageName: node
linkType: hard

"@ipld/dag-cbor@npm:^9.0.0, @ipld/dag-cbor@npm:^9.0.1, @ipld/dag-cbor@npm:^9.0.5, @ipld/dag-cbor@npm:^9.0.6, @ipld/dag-cbor@npm:^9.0.7, @ipld/dag-cbor@npm:^9.1.0":
"@ipld/dag-cbor@npm:^9.0.0, @ipld/dag-cbor@npm:^9.0.5, @ipld/dag-cbor@npm:^9.0.6, @ipld/dag-cbor@npm:^9.0.7, @ipld/dag-cbor@npm:^9.1.0":
version: 9.2.0
resolution: "@ipld/dag-cbor@npm:9.2.0"
dependencies:
Expand All @@ -7585,6 +7585,16 @@ __metadata:
languageName: node
linkType: hard

"@ipld/dag-cbor@npm:^9.0.1":
version: 9.2.2
resolution: "@ipld/dag-cbor@npm:9.2.2"
dependencies:
cborg: "npm:^4.0.0"
multiformats: "npm:^13.1.0"
checksum: 10/71b464313f745e4c0b62fbfd2f257f526b87dba8e007246239b44d121ca82c453adf4f659d9036140dc0a485307727ce0a8749fbda0f648d950c9ccdf496bd97
languageName: node
linkType: hard

"@ipld/dag-cbor@npm:^9.0.3, @ipld/dag-cbor@npm:^9.2.1":
version: 9.2.1
resolution: "@ipld/dag-cbor@npm:9.2.1"
Expand Down

0 comments on commit addf3bc

Please sign in to comment.