Skip to content

Commit

Permalink
chore: remove duplicate types, small code refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
martines3000 committed Jun 19, 2023
1 parent 7cd35aa commit 7de2baa
Show file tree
Hide file tree
Showing 22 changed files with 116 additions and 199 deletions.
4 changes: 2 additions & 2 deletions packages/connector/src/snap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -360,12 +360,12 @@ export async function sendOIDCAuthorizationResponse(

export async function setCeramicSession(
this: Masca,
sessionKey: string
serializedSession: string
): Promise<Result<boolean>> {
return sendSnapMethod(
{
method: 'setCeramicSession',
params: { sessionKey },
params: { serializedSession },
},
this.snapId
);
Expand Down
2 changes: 1 addition & 1 deletion packages/snap/snap.manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"url": "https://github.com/blockchain-lab-um/masca.git"
},
"source": {
"shasum": "4oWrs9nhRESibCc76Oi02stINN/l0p64gyFaeB2D+ps=",
"shasum": "O1UXSOxy+oi/+u0TyrzxY8rHpZ+9hrK+QfSdATkhV60=",
"location": {
"npm": {
"filePath": "dist/snap.js",
Expand Down
2 changes: 1 addition & 1 deletion packages/snap/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ export const onRpcRequest: OnRpcRequestHandler = async ({
// TODO (andy) validate request params
res = await setCeramicSession(
apiParams,
(request.params as any).sessionKey as string
(request.params as any).serializedSession as string
);
return ResultObject.success(res);
case 'validateStoredCeramicSession':
Expand Down
62 changes: 1 addition & 61 deletions packages/snap/src/interfaces.ts
Original file line number Diff line number Diff line change
@@ -1,67 +1,7 @@
import type {
MascaAccountConfig,
MascaConfig,
} from '@blockchain-lab-um/masca-types';
import { MascaState } from '@blockchain-lab-um/masca-types';
import { BIP44CoinTypeNode } from '@metamask/key-tree';
import { MetaMaskInpageProvider } from '@metamask/providers';
import type { SnapsGlobalObject } from '@metamask/snaps-types';
import type { IIdentifier, IKey, W3CVerifiableCredential } from '@veramo/core';
import type { ManagedPrivateKey } from '@veramo/key-manager';

export type MascaState = {
/**
* Account specific storage
*/
accountState: Record<string, MascaAccountState>;
/**
* Current account
*/
currentAccount: string;
/**
* Configuration for Masca
*/
snapConfig: MascaConfig;
};

export type ExtendedVerifiableCredential = W3CVerifiableCredential & {
/**
* key for dictionary
*/
key: string;
};

/**
* Ceramic Network storedVCs
*/
export type StoredCredentials = {
storedCredentials: ExtendedVerifiableCredential[];
};

/**
* Masca State for a MetaMask address
*/
export type MascaAccountState = {
/**
* Store for {@link SnapPrivateKeyStore}
*/
snapPrivateKeyStore: Record<string, ManagedPrivateKey>;
/**
* Store for {@link SnapKeyStore}
*/
snapKeyStore: Record<string, IKey>;
/**
* Store for {@link SnapDIDStore}
*/
identifiers: Record<string, IIdentifier>;
/**
* Store for {@link SnapVCStore}
*/
vcs: Record<string, W3CVerifiableCredential>;

publicKey: string;
index?: number;
accountConfig: MascaAccountConfig;
};

export type SnapConfirmParams = {
prompt: string;
Expand Down
10 changes: 6 additions & 4 deletions packages/snap/src/rpc/setCeramicSession.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { ApiParams } from '../interfaces';
import { setSession } from '../utils/ceramicUtils';
import { updateSnapState } from '../utils/stateUtils';

export async function setCeramicSession(
params: ApiParams,
sessionKey: string
serializedSession: string
): Promise<boolean> {
const res = await setSession(params.snap, params.state, sessionKey);
return res;
const { state } = params;
state.accountState[state.currentAccount].ceramicSession = serializedSession;
await updateSnapState(snap, state);
return true;
}
9 changes: 6 additions & 3 deletions packages/snap/src/rpc/validateStoredCeramicSession.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import { ApiParams } from '../interfaces';
import { validateStoredSession } from '../utils/ceramicUtils';
import { validateSession } from '../utils/ceramicUtils';

export async function validateStoredCeramicSession(
params: ApiParams
): Promise<string> {
const sessionKey = validateStoredSession(params.state);
return sessionKey;
const { state } = params;
const serializedSession = await validateSession(
state.accountState[state.currentAccount].ceramicSession
);
return serializedSession;
}
122 changes: 12 additions & 110 deletions packages/snap/src/utils/ceramicUtils.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,8 @@
import type { MascaState } from '@blockchain-lab-um/masca-types';
import { CeramicClient } from '@ceramicnetwork/http-client';
import { EthereumNodeAuth, getAccountId } from '@didtools/pkh-ethereum';
import { MetaMaskInpageProvider } from '@metamask/providers';
import type { SnapsGlobalObject } from '@metamask/snaps-types';
import { DIDSession } from 'did-session';
import { DID } from 'dids';
import { Wallet } from 'ethers';

import { getAddressKeyDeriver, snapGetKeysFromAddress } from './keyPair';
import { getCurrentAccount } from './snapUtils';
import { updateSnapState } from './stateUtils';

const ceramicDID = { did: undefined } as { did: DID | undefined };

export const aliases = {
definitions: {
Expand All @@ -25,119 +16,32 @@ export const aliases = {
tiles: {},
};

class CustomProvider {
constructor(
private readonly wallet: Wallet,
private readonly metamask: MetaMaskInpageProvider
) {
this.wallet = wallet;
this.metamask = metamask;
// Should return serialized session or throw an error
export async function validateSession(
serializedSession?: string
): Promise<string> {
if (!serializedSession) {
throw new Error('No session found');
}

async request(args: { method: string; params: Array<string> }) {
const { method, params } = args;

if (method === 'personal_sign') {
// First parameter is the message to sign, second parameter is the address
const [message] = params;
return this.wallet.signMessage(message);
}
const session = await DIDSession.fromSession(serializedSession);

if (method === 'eth_chainId') {
return this.metamask.request(args);
}

throw new Error('Unsupported method');
}
}

// Should return key or throw an error
async function validateSession(sessionKey: string): Promise<string> {
const session = await DIDSession.fromSession(sessionKey);
if (session.isExpired) {
throw new Error('Session expired');
}

if (session.expireInSecs < 3600) {
throw new Error('Session will expire soon');
}
return sessionKey;
}

// Returns session key if session is valid and throws an error if something goes wrong
export async function validateStoredSession(
state: MascaState
): Promise<string> {
const sessionKey = state.accountState[state.currentAccount].ceramicSession;

if (!sessionKey) {
throw new Error('No session found');
}
return validateSession(sessionKey);
}

export async function setSession(
snap: SnapsGlobalObject,
state: MascaState,
sessionKey: string
): Promise<boolean> {
state.accountState[state.currentAccount].ceramicSession = sessionKey;
await updateSnapState(snap, state);
return true;
}

async function authenticateWithEthers(params: {
ethereum: MetaMaskInpageProvider;
snap: SnapsGlobalObject;
state: MascaState;
}) {
if (ceramicDID.did) return ceramicDID.did;

const { ethereum, snap, state } = params;

const account = getCurrentAccount(state);

const bip44CoinTypeNode = await getAddressKeyDeriver({
state,
snap,
account,
});

const res = await snapGetKeysFromAddress(
bip44CoinTypeNode,
state,
account,
snap
);

if (res === null) throw new Error('Could not get keys from address');

const { privateKey } = res;

// Ethers is required to sign the DID auth message
const wallet = new Wallet(privateKey);

const customProvider = new CustomProvider(wallet, ethereum);

const accountId = await getAccountId(customProvider, wallet.address);

const authMethod = await EthereumNodeAuth.getAuthMethod(
customProvider,
accountId,
'masca'
);

const session = await DIDSession.authorize(authMethod, {
resources: [`ceramic://*`],
});

ceramicDID.did = session.did;
return session.did;
return serializedSession;
}

async function authenticateWithSessionKey(state: MascaState) {
const sessionKey = await validateStoredSession(state);
const session = await DIDSession.fromSession(sessionKey);
const serializedSession = await validateSession(
state.accountState[state.currentAccount].ceramicSession
);
const session = await DIDSession.fromSession(serializedSession);
return session.did;
}

Expand All @@ -147,8 +51,6 @@ export async function getCeramic(
state: MascaState
): Promise<CeramicClient> {
const ceramic = new CeramicClient('https://ceramic-clay.3boxlabs.com');

// const did = await authenticateWithEthers({ ethereum, snap, state });
const did = await authenticateWithSessionKey(state);

await ceramic.setDID(did);
Expand Down
2 changes: 1 addition & 1 deletion packages/snap/src/utils/didUtils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type {
AvailableMethods,
AvailableVCStores,
MascaState,
} from '@blockchain-lab-um/masca-types';
import { BIP44CoinTypeNode } from '@metamask/key-tree';
import { MetaMaskInpageProvider } from '@metamask/providers';
Expand All @@ -9,7 +10,6 @@ import type { IIdentifier } from '@veramo/core';
import type { DIDResolutionResult } from 'did-resolver';
import elliptic from 'elliptic';

import type { MascaState } from '../interfaces';
import { getAgent } from '../veramo/setup';
import { snapGetKeysFromAddress } from './keyPair';
import { getCurrentNetwork } from './snapUtils';
Expand Down
2 changes: 1 addition & 1 deletion packages/snap/src/utils/ebsiUtils.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import type { MascaState } from '@blockchain-lab-um/masca-types';
import type { SnapsGlobalObject } from '@metamask/snaps-types';
import type { IDIDManagerCreateArgs } from '@veramo/core';
import { keccak256 } from 'ethers';

import type { MascaState } from '../interfaces';
import { getAgent } from '../veramo/setup';
import { getAddressKeyDeriver, snapGetKeysFromAddress } from './keyPair';

Expand Down
2 changes: 1 addition & 1 deletion packages/snap/src/utils/init.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { MascaState } from '@blockchain-lab-um/masca-types';
import type { SnapsGlobalObject } from '@metamask/snaps-types';

import type { MascaState } from '../interfaces';
import { initSnapState } from './stateUtils';

export async function init(snap: SnapsGlobalObject): Promise<MascaState> {
Expand Down
6 changes: 4 additions & 2 deletions packages/snap/src/utils/keyPair.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import { didCoinTypeMappping } from '@blockchain-lab-um/masca-types';
import {
didCoinTypeMappping,
type MascaState,
} from '@blockchain-lab-um/masca-types';
import {
BIP44CoinTypeNode,
getBIP44AddressKeyDeriver,
} from '@metamask/key-tree';
import type { SnapsGlobalObject } from '@metamask/snaps-types';
import { Wallet } from 'ethers';

import type { MascaState } from '../interfaces';
import { updateSnapState } from './stateUtils';

export async function setAccountIndex(
Expand Down
2 changes: 1 addition & 1 deletion packages/snap/src/utils/params.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
type CreateVCRequestParams,
type CreateVPRequestParams,
type DeleteVCsRequestParams,
type MascaState,
type QueryVCsRequestParams,
type ResolveDIDRequestParams,
type SaveVCRequestParams,
Expand All @@ -15,7 +16,6 @@ import {
type VerifyDataRequestParams,
} from '@blockchain-lab-um/masca-types';

import type { MascaState } from '../interfaces';
import { isEnabledVCStore } from './snapUtils';

function isStringArray(input: unknown): input is string[] {
Expand Down
7 changes: 5 additions & 2 deletions packages/snap/src/utils/snapUtils.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import type { AvailableVCStores } from '@blockchain-lab-um/masca-types';
import type {
AvailableVCStores,
MascaState,
} from '@blockchain-lab-um/masca-types';
import { BIP44CoinTypeNode } from '@metamask/key-tree';
import { MetaMaskInpageProvider } from '@metamask/providers';
import type { SnapsGlobalObject } from '@metamask/snaps-types';
import type { Component } from '@metamask/snaps-ui';

import type { ApiParams, MascaState } from '../interfaces';
import type { ApiParams } from '../interfaces';
import { snapGetKeysFromAddress } from './keyPair';
import { updateSnapState } from './stateUtils';

Expand Down
3 changes: 2 additions & 1 deletion packages/snap/src/utils/stateUtils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { MascaState } from '@blockchain-lab-um/masca-types';
import type { Json, SnapsGlobalObject } from '@metamask/snaps-types';

import type { ApiParams, MascaState } from '../interfaces';
import type { ApiParams } from '../interfaces';
import { getEmptyAccountState, getInitialSnapState } from './config';

/**
Expand Down
Loading

0 comments on commit 7de2baa

Please sign in to comment.