Skip to content

Commit

Permalink
Merge pull request #440 from LIT-Protocol/feature/lit-3017-auth-unifi…
Browse files Browse the repository at this point in the history
…cation-migrate-actual-tests

Feature/lit 3017 auth unification migrate actual tests
  • Loading branch information
Ansonhkg authored May 1, 2024
2 parents 8709d11 + 7bc363d commit abd27c2
Show file tree
Hide file tree
Showing 5 changed files with 83 additions and 123 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { LitAccessControlConditionResource } from '@lit-protocol/auth-helpers';
import { getPkpSessionSigs } from 'local-tests/setup/session-sigs/get-pkp-session-sigs';
import { TinnyEnvironment } from 'local-tests/setup/tinny-environment';
import { log } from '@lit-protocol/misc';
import { getLitActionSessionSigs } from 'local-tests/setup/session-sigs/get-lit-action-session-sigs';

/**
* Test Commands:
Expand All @@ -28,13 +29,13 @@ export const testUseValidLitActionCodeGeneratedSessionSigsToEncryptDecryptFile =
userAddress: alice.authMethodOwnedPkp.ethAddress,
});

const pkpSessionSigs = await getPkpSessionSigs(devEnv, alice);
const litActionSessionSigs = await getLitActionSessionSigs(devEnv, alice);

const encryptRes = await LitJsSdk.encryptString(
{
accessControlConditions: accs,
chain: 'ethereum',
sessionSigs: pkpSessionSigs,
sessionSigs: litActionSessionSigs,
dataToEncrypt: 'Hello world',
},
devEnv.litNodeClient as unknown as ILitNodeClient
Expand Down
9 changes: 2 additions & 7 deletions packages/encryption/src/lib/encryption.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ export async function decryptFromJson<T extends DecryptFromJsonProps>(
? ReturnType<typeof decryptToString>
: never
> {
const { authSig, sessionSigs, parsedJsonData, litNodeClient } = params;
const { sessionSigs, parsedJsonData, litNodeClient } = params;

// -- validate
const paramsIsSafe = safeParams({
Expand All @@ -153,7 +153,6 @@ export async function decryptFromJson<T extends DecryptFromJsonProps>(
ciphertext: parsedJsonData.ciphertext,
dataToEncryptHash: parsedJsonData.dataToEncryptHash,
chain: parsedJsonData.chain,
authSig,
sessionSigs,
},
litNodeClient
Expand All @@ -169,7 +168,6 @@ export async function decryptFromJson<T extends DecryptFromJsonProps>(
ciphertext: parsedJsonData.ciphertext,
dataToEncryptHash: parsedJsonData.dataToEncryptHash,
chain: parsedJsonData.chain,
authSig,
sessionSigs,
},
litNodeClient
Expand Down Expand Up @@ -444,7 +442,6 @@ export const encryptFileAndZipWithMetadata = async (
params: EncryptFileAndZipWithMetadataProps
): Promise<any> => {
const {
authSig,
sessionSigs,
accessControlConditions,
evmContractConditions,
Expand All @@ -460,7 +457,6 @@ export const encryptFileAndZipWithMetadata = async (
const paramsIsSafe = safeParams({
functionName: 'encryptFileAndZipWithMetadata',
params: {
authSig,
sessionSigs,
accessControlConditions,
evmContractConditions,
Expand Down Expand Up @@ -545,13 +541,12 @@ export const encryptFileAndZipWithMetadata = async (
export const decryptZipFileWithMetadata = async (
params: DecryptZipFileWithMetadataProps
): Promise<DecryptZipFileWithMetadata | undefined> => {
const { authSig, sessionSigs, file, litNodeClient } = params;
const { sessionSigs, file, litNodeClient } = params;

// -- validate
const paramsIsSafe = safeParams({
functionName: 'decryptZipFileWithMetadata',
params: {
authSig,
sessionSigs,
file,
litNodeClient,
Expand Down
45 changes: 22 additions & 23 deletions packages/lit-auth-client/src/lib/providers/BaseProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,10 @@ export abstract class BaseProvider {

let authNeededCallback = params.sessionSigsParams.authNeededCallback;

// If no session key is provided, generate a new session key from the LitNodeClient
const sessionKey =
params.sessionSigsParams.sessionKey || this.litNodeClient.getSessionKey();

// If no authNeededCallback is provided, create one that uses the provided PKP and auth method
// to sign a session key and return an auth sig
if (!authNeededCallback) {
Expand All @@ -161,37 +165,31 @@ export abstract class BaseProvider {

let response: SignSessionKeyResponse;

// common data for the signSessionKey function call
const commonData = {
sessionKey: sessionKey,
statement: authCallbackParams.statement,
pkpPublicKey: params.pkpPublicKey,
expiration: authCallbackParams.expiration,
resources: authCallbackParams.resources,
chainId: chainId,
...(params.resourceAbilityRequests && {
resourceAbilityRequests: params.resourceAbilityRequests,
}),
};

if (params.authMethod.authMethodType === AuthMethodType.EthWallet) {
const authSig = JSON.parse(params.authMethod.accessToken);

response = await nodeClient.signSessionKey({
statement: authCallbackParams.statement,
sessionKey: params.sessionSigsParams.sessionKey,
authMethods: [],
...commonData,
authSig: authSig,
pkpPublicKey: params.pkpPublicKey,
expiration: authCallbackParams.expiration,
resources: authCallbackParams.resources,
chainId,

// optional
...(params.resourceAbilityRequests && {
resourceAbilityRequests: params.resourceAbilityRequests,
}),
authMethods: [],
});
} else {
response = await nodeClient.signSessionKey({
sessionKey: params.sessionSigsParams.sessionKey,
statement: authCallbackParams.statement,
...commonData,
authMethods: [params.authMethod],
pkpPublicKey: params.pkpPublicKey,
expiration: authCallbackParams.expiration,
resources: authCallbackParams.resources,
chainId,

// optional
...(params.resourceAbilityRequests && {
resourceAbilityRequests: params.resourceAbilityRequests,
}),
});
}

Expand All @@ -202,6 +200,7 @@ export abstract class BaseProvider {
// Generate session sigs with the given session params
const sessionSigs = await this.litNodeClient.getSessionSigs({
...params.sessionSigsParams,
sessionKey,
authNeededCallback,
});

Expand Down
133 changes: 49 additions & 84 deletions packages/lit-node-client-nodejs/src/lib/lit-node-client-nodejs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,13 +110,14 @@ import type {
CapacityCreditsRes,
JsonSignSessionKeyRequestV1,
BlsResponseData,
JsonPkpSignSdkParams,
JsonExecutionSdkParams,
ExecuteJsNoSigningResponse,
JsonExecutionSdkParamsTargetNode,
JsonExecutionRequestTargetNode,
JsonExecutionSdkParams,
ExecuteJsNoSigningResponse,
JsonPkpSignSdkParams,
SigResponse,
} from '@lit-protocol/types';

import * as blsSdk from '@lit-protocol/bls-sdk';
import { normalizeJsParams } from './helpers/normalize-params';
import { encodeCode } from './helpers/encode-code';
Expand Down Expand Up @@ -1974,23 +1975,15 @@ export class LitNodeClientNodeJs
params.expiration ||
new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString();

let sessionKeyUri: string;

// This allow the user to provide a sessionKeyUri directly without using the session key pair
if (params?.sessionKeyUri) {
sessionKeyUri = params.sessionKeyUri;
log(`[signSessionKey] sessionKeyUri found in params:`, sessionKeyUri);
} else {
// Try to get it from local storage, if not generates one~
let sessionKey: SessionKeyPair =
params.sessionKey ?? this.getSessionKey();
sessionKeyUri = LIT_SESSION_KEY_URI + sessionKey.publicKey;
// Try to get it from local storage, if not generates one~
const sessionKey: SessionKeyPair =
params.sessionKey ?? this.getSessionKey();
const sessionKeyUri = LIT_SESSION_KEY_URI + sessionKey.publicKey;

log(
`[signSessionKey] sessionKeyUri is not found in params, generating a new one`,
sessionKeyUri
);
}
log(
`[signSessionKey] sessionKeyUri is not found in params, generating a new one`,
sessionKeyUri
);

if (!sessionKeyUri) {
throw new Error(
Expand Down Expand Up @@ -2044,7 +2037,6 @@ export class LitNodeClientNodeJs
sessionKey: sessionKeyUri,
authMethods: params.authMethods,
...(params?.pkpPublicKey && { pkpPublicKey: params.pkpPublicKey }),
...(params?.authSig && { authSig: params.authSig }),
siweMessage: siweMessage,
curveType: LIT_CURVE.BLS,

Expand Down Expand Up @@ -2158,26 +2150,15 @@ export class LitNodeClientNodeJs
}

// each of this field cannot be empty
let requiredFields =
curveType === LIT_CURVE.BLS
? [
'signatureShare',
'curveType',
'shareIndex',
'siweMessage',
'dataSigned',
'blsRootPubkey',
'result',
]
: [
'sigType',
'dataSigned',
'signatureShare',
'bigr',
'publicKey',
'sigName',
'siweMessage',
];
let requiredFields = [
'signatureShare',
'curveType',
'shareIndex',
'siweMessage',
'dataSigned',
'blsRootPubkey',
'result',
];

// check if all required fields are present
for (const field of requiredFields) {
Expand Down Expand Up @@ -2224,57 +2205,41 @@ export class LitNodeClientNodeJs

let signatures: any;

if (curveType === LIT_CURVE.BLS) {
const blsSignedData: BlsResponseData[] =
validatedSignedDataList as BlsResponseData[];
const blsSignedData: BlsResponseData[] =
validatedSignedDataList as BlsResponseData[];

const sigType = mostCommonString(
blsSignedData.map((s: any) => s.sigType)
);
log(`[signSessionKey] sigType:`, sigType);
const sigType = mostCommonString(blsSignedData.map((s: any) => s.sigType));
log(`[signSessionKey] sigType:`, sigType);

const signatureShares = handleBlsResponseData(blsSignedData);
const signatureShares = handleBlsResponseData(blsSignedData);

log(`[signSessionKey] signatureShares:`, signatureShares);
log(`[signSessionKey] signatureShares:`, signatureShares);

const blsCombinedSignature = blsSdk.combine_signature_shares(
signatureShares.map((s) => JSON.stringify(s))
);
const blsCombinedSignature = blsSdk.combine_signature_shares(
signatureShares.map((s) => JSON.stringify(s))
);

log(`[signSessionKey] blsCombinedSignature:`, blsCombinedSignature);
log(`[signSessionKey] blsCombinedSignature:`, blsCombinedSignature);

const publicKey = params.pkpPublicKey.startsWith('0x')
? params.pkpPublicKey.slice(2)
: params.pkpPublicKey;
const publicKey = params.pkpPublicKey.startsWith('0x')
? params.pkpPublicKey.slice(2)
: params.pkpPublicKey;

const dataSigned = mostCommonString(
blsSignedData.map((s: any) => s.dataSigned)
);
const siweMessage = mostCommonString(
blsSignedData.map((s: any) => s.siweMessage)
);
signatures = {
sessionSig: {
signature: blsCombinedSignature,
publicKey,
dataSigned,
siweMessage,
},
};
} else {
// Shape: [signSessionKey] signatures: {
// sessionSig: {
// r: "xx",
// s: "yy",
// recid: 1,
// signature: "0x...",
// publicKey: "04e...",
// dataSigned: "7c1...",
// siweMessage: "litprotocol.com wants you to sign in with your Ethereum account:\n0xd69969c6a2E56C928d63F12325fe1d9D47115C91\n\nLit Protocol PKP session signature Some custom statement. I further authorize the stated URI to perform the following actions on my behalf: (1) 'Threshold': 'Signing' for 'lit-pkp://*'.\n\nURI: lit:session:95ff87b5d2210c382ccfcba6bdb16ceb217da9726c91d0fdda5eb888f087488f\nVersion: 1\nChain ID: 1\nNonce: 0x337906a8c2a6da52d438495fc1b0145ed5632ec32ffa1dda1064f43775b3a802\nIssued At: 2024-04-09T17:58:47Z\nExpiration Time: 2024-04-10T17:59:13.420Z\nResources:\n- urn:recap:eyJhdHQiOnt9LCJwcmYiOltdfQ\n- urn:recap:eyJhdHQiOnsibGl0LXBrcDovLyoiOnsiVGhyZXNob2xkL1NpZ25pbmciOlt7fV19fSwicHJmIjpbXX0",
// },
// }
signatures = this.getSessionSignatures(validatedSignedDataList);
}
const dataSigned = mostCommonString(
blsSignedData.map((s: any) => s.dataSigned)
);
const mostCommonSiweMessage = mostCommonString(
blsSignedData.map((s: any) => s.siweMessage)
);

signatures = {
sessionSig: {
signature: blsCombinedSignature,
publicKey,
dataSigned,
siweMessage: mostCommonSiweMessage,
},
};

log('[signSessionKey] signatures:', signatures);

Expand Down
14 changes: 7 additions & 7 deletions packages/types/src/lib/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,7 @@ export interface JsonSignSessionKeyRequestV1 {
pkpPublicKey?: string;
// authSig?: AuthSig;
siweMessage: string;
curveType: 'BLS' | 'ECDSA';
curveType: 'BLS';
code?: string;
litActionIpfsId?: string;
jsParams?: any;
Expand Down Expand Up @@ -974,9 +974,6 @@ export interface SignSessionKeyProp {

resourceAbilityRequests?: LitResourceAbilityRequest[];

// -- as part of auth unification
sessionKeyUri?: string;

litActionCode?: string;

jsParams?: {
Expand Down Expand Up @@ -1032,8 +1029,11 @@ export interface GetSessionSigsProps extends LitCustomAuth {
*/
authNeededCallback?: AuthCallback;

// The serialized session key pair to sign. If not provided, a session key pair will be fetched from localStorge or generated.
sessionKey?: any;
/**
* The serialized session key pair to sign.
* If not provided, a session key pair will be fetched from localStorge or generated.
*/
sessionKey?: SessionKeyPair;

/**
* @deprecated - use capabilityAuthSigs instead
Expand Down Expand Up @@ -1508,7 +1508,7 @@ export interface BaseProviderSessionSigsParams {
/**
* Lit Node Client to use. If not provided, will use an existing Lit Node Client or create a new one
*/
litNodeClient?: any;
litNodeClient?: ILitNodeClient;

resourceAbilityRequests?: LitResourceAbilityRequest[];
}
Expand Down

0 comments on commit abd27c2

Please sign in to comment.