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

add auth method support to executeJs and helper methods #243

Merged
merged 5 commits into from
Oct 28, 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: 3 additions & 11 deletions e2e-nodejs/group-lit-actions/test-lit-action-claim-key.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,10 @@ export async function main() {
});

// ==================== Post-Validation ====================
if (!res.success) {
if (!res.success && !res.claims) {
return fail(`response should be success`);
}

if (Object.keys(res.signedData).length > 0) {
return fail(`signedData should be empty`);
}

if (Object.keys(res.decryptedData).length > 0) {
return fail(`decryptedData should be empty`);
}

// -- should have claimData
if (
res.claims === undefined ||
Expand All @@ -46,9 +38,9 @@ export async function main() {
return fail(`claimData.foo should have ${key}`);
}
});

const key = 'foo';
for (let i = 0; i < res.claims[key].signatures.length; i++) {
if (!res.claims[key].signatures[i].r || !res.claims[key].signatures[i].s || res.claims[key].signatures[i].v) {
if (!res.claims[key].signatures[i].r || !res.claims[key].signatures[i].s || !res.claims[key].signatures[i].v) {
return fail(`signature data misformed, should be of ethers signature format`);
}
}
Expand Down
10 changes: 1 addition & 9 deletions e2e-nodejs/group-lit-actions/test-lit-action-grouped-claims.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,10 @@ export async function main() {
});

// ==================== Post-Validation ====================
if (!res.success) {
if (!res.success && !res.claims) {
return fail(`response should be success`);
}

if (Object.keys(res.signedData).length > 0) {
return fail(`signedData should be empty`);
}

if (Object.keys(res.decryptedData).length > 0) {
return fail(`decryptedData should be empty`);
}

// -- should have claims
Object.entries(res.claims).forEach(([key, value]) => {
if (key !== 'foo' || key !== 'bar') {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import path from 'path';
import { success, fail, testThis } from '../../tools/scripts/utils.mjs';
import LITCONFIG from '../../lit.config.json' assert { type: 'json' };
import { client } from '../00-setup.mjs';
import { LitAbility, LitActionResource } from '@lit-protocol/auth-helpers';
import { LitAuthClient } from '@lit-protocol/lit-auth-client';
import { AuthMethodType, ProviderType } from '@lit-protocol/constants';
import { ethers } from 'ethers';
import { PKPEthersWallet } from '@lit-protocol/pkp-ethers';

// NOTE: you need to hash data before you send it in.
// If you send something that isn't 32 bytes, the nodes will return an error.
const TO_SIGN = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode("meow")));

export async function main() {
// ==================== Setup ====================

const litAuthClient = new LitAuthClient({
litRelayConfig: {
relayApiKey: '67e55044-10b1-426f-9247-bb680e5fe0c8_relayer',
},
version: 'V3',
litNodeClient: client,
});

// -- eth wallet
const authProvider = litAuthClient.initProvider(ProviderType.EthWallet);
const authMethod = {
authMethodType: AuthMethodType.EthWallet,
accessToken: JSON.stringify(LITCONFIG.CONTROLLER_AUTHSIG),
};

let pkps = await authProvider.fetchPKPsThroughRelayer(authMethod);

if (pkps.length <= 0) {
try {
await authProvider.mintPKPThroughRelayer(authMethod);
} catch (e) {
return fail('Failed to mint PKP');
}
pkps = await authProvider.fetchPKPsThroughRelayer(authMethod);
}

const pkp = pkps[pkps.length - 1];

// convert BigNumber to string
pkp.tokenId = ethers.BigNumber.from(pkp.tokenId).toString();

const pkpPubKey = pkp.publicKey;

const pkpSignRes = await client?.executeJs({
authSig: LITCONFIG.CONTROLLER_AUTHSIG_2,
authMethods: [authMethod],
code: `(async () => {
const sigShare = await LitActions.signEcdsa({
toSign,
publicKey,
sigName: "sig",
});
LitActions.setResponse({response: JSON.stringify(Lit.Auth)});
})();`,
jsParams: {
toSign: TO_SIGN,
publicKey: LITCONFIG.PKP_PUBKEY,
},
});

// ==================== Post-Validation ====================

if (!pkpSignRes) {
return fail(
'Failed to sign data with sessionSigs generated by eth wallet auth method'
);
}

let missingKeys = [];

if (pkpSignRes) {
['r', 's', 'recid', 'signature', 'publicKey', 'dataSigned'].forEach(
(key) => {
if (pkpSignRes.signatures['sig'][key] === undefined) {
missingKeys.push(key);
}
}
);
}

if (missingKeys.length > 0) {
return fail(`Missing keys: ${missingKeys.join(', ')}`);
}

if (!pkpSignRes.response.authSigAddress == LITCONFIG.CONTROLLER_AUTHSIG_2.address) {
return fail(`Missing or non matching auth sig address in Lit.Auth context`);
}

if(pkpSignRes.response.authMethodContexts.length < 1) {
return fail('not enough authentication material in Lit.Auth context');
}

// ==================== Success ====================
return success(
`it should use sessionSigs generated by eth wallet auth method to sign data. Signature is ${pkpSignRes.signatures} and pkpSignRes is ${JSON.stringify(
pkpSignRes
)}`
);
}

await testThis({ name: path.basename(import.meta.url), fn: main });
30 changes: 27 additions & 3 deletions packages/core/src/lib/lit-core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,14 @@ import {
throwError,
} from '@lit-protocol/misc';
import {
AuthMethod,
AuthSig,
CustomNetwork,
FormattedMultipleAccs,
HandshakeWithSgx,
JsonExecutionRequest,
JsonHandshakeResponse,
JsonPkpSignRequest,
KV,
LitNodeClientConfig,
MultipleAccessControlConditions,
Expand Down Expand Up @@ -350,22 +353,24 @@ export class LitCore {
* Get either auth sig or session auth sig
*
*/
getAuthSigOrSessionAuthSig = ({
getAuthMaterial = ({
authMethods,
authSig,
sessionSigs,
url,
mustHave = true,
}: {
authMethods?: Array<Object>,
authSig?: AuthSig;
sessionSigs?: SessionSigsMap;
url: string;
mustHave?: boolean;
}): AuthSig | SessionSig => {
}): AuthSig | SessionSig | Object[] => {

if (!authSig && !sessionSigs) {
if (mustHave) {
throwError({
message: `You must pass either authSig or sessionSigs`,
message: `You must pass either authSig, or sessionSigs`,
errorKind: LIT_ERROR.INVALID_ARGUMENT_EXCEPTION.kind,
errorCode: LIT_ERROR.INVALID_ARGUMENT_EXCEPTION.name,
});
Expand All @@ -388,9 +393,28 @@ export class LitCore {
return sigToPassToNode;
}

if (authMethods) {
return authMethods;
}

return authSig!;
};

/*
Here we do a check on the 'length' property of the object
returned to see if it is an array type
we cast to the array type to check as the union of types does not overlap
*/
setAuthMaterial<T extends JsonExecutionRequest | JsonPkpSignRequest>(reqBody: T, authMaterial: AuthSig | SessionSig | Object[]): T {
if (!(authMaterial as Object[]).length){
reqBody.authSig = (authMaterial as AuthSig);
} else {
reqBody.authMethods = (authMaterial as Object[]);
}

return reqBody;
}

/**
*
* Get hash of access control conditions
Expand Down
47 changes: 30 additions & 17 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 @@ -154,6 +154,7 @@ export class LitNodeClientNodeJs extends LitCore {
const reqBody: JsonExecutionRequest = {
...(params.authSig && { authSig: params.authSig }),
...(params.sessionSigs && { sessionSigs: params.sessionSigs }),
...(params.authMethods && {authMethods: params.authMethods}),
jsParams: convertLitActionsParams(params.jsParams),
// singleNode: params.singleNode ?? false,
targetNodeRange: params.targetNodeRange ?? 0,
Expand Down Expand Up @@ -535,7 +536,7 @@ export class LitNodeClientNodeJs extends LitCore {
params: JsonExecutionRequest,
requestId: string
): Promise<NodeCommandResponse> => {
const { code, ipfsId, authSig, jsParams, sessionSigs, authMethods } =
const { code, ipfsId, authSig, jsParams, authMethods } =
params;

log('getJsExecutionShares');
Expand All @@ -544,15 +545,14 @@ export class LitNodeClientNodeJs extends LitCore {
const urlWithPath = `${url}/web/execute`;

if (!authSig) {
throw new Error('authSig is required');
throw new Error('authSig or sessionSig is required');
}

const data: JsonExecutionRequest = {
code,
ipfsId,
authSig,
jsParams,
authMethods,
let data: JsonExecutionRequest = {
authSig,
code,
ipfsId,
jsParams,
authMethods
};

return await this.sendCommandToNode({ url: urlWithPath, data, requestId });
Expand Down Expand Up @@ -757,7 +757,7 @@ export class LitNodeClientNodeJs extends LitCore {
): Promise<
SuccessNodePromises<NodeCommandResponse> | RejectedNodePromises
> => {
const { code, authSig, jsParams, debug, sessionSigs, targetNodeRange } =
const { code, authMethods, authSig, jsParams, debug, sessionSigs, targetNodeRange } =
params;

log('running runOnTargetedNodes:', targetNodeRange);
Expand Down Expand Up @@ -863,13 +863,14 @@ export class LitNodeClientNodeJs extends LitCore {
this.getLitActionRequestBody(params);

// -- choose the right signature
const sigToPassToNode = this.getAuthSigOrSessionAuthSig({
const sigToPassToNode = this.getAuthMaterial({
authMethods,
authSig,
sessionSigs,
url,
});

reqBody.authSig = sigToPassToNode;
this.setAuthMaterial(reqBody, sigToPassToNode);

// this return { url: string, data: JsonRequest }
const singleNodePromise = this.getJsExecutionShares(
Expand Down Expand Up @@ -1276,6 +1277,7 @@ export class LitNodeClientNodeJs extends LitCore {
executeJs = async (params: ExecuteJsProps): Promise<ExecuteJsResponse> => {
// ========== Prepare Params ==========
const {
authMethods,
code,
ipfsId,
authSig,
Expand Down Expand Up @@ -1311,8 +1313,17 @@ export class LitNodeClientNodeJs extends LitCore {
});
}

let res;
// the nodes will only accept a normal array type as a paramater due to serizalization issues with ArrayBuffer type.
// this loop below is to normalize the data to a basic array.
if (jsParams.toSign) {
let arr = [];
for (let i = 0; i < jsParams.toSign.length; i++) {
arr.push((jsParams.toSign as Buffer)[i]);
}
jsParams.toSign = arr;
}

let res;
// -- only run on a single node
if (targetNodeRange) {
res = await this.runOnTargetedNodes(params);
Expand All @@ -1327,12 +1338,14 @@ export class LitNodeClientNodeJs extends LitCore {
const requestId = this.getRequestId();
const nodePromises = this.getNodePromises((url: string) => {
// -- choose the right signature
let sigToPassToNode = this.getAuthSigOrSessionAuthSig({
let sigToPassToNode = this.getAuthMaterial({
authMethods,
authSig,
sessionSigs,
url,
});
reqBody.authSig = sigToPassToNode;

this.setAuthMaterial(reqBody, sigToPassToNode);

return this.getJsExecutionShares(url, reqBody, requestId);
});
Expand Down Expand Up @@ -1492,7 +1505,7 @@ export class LitNodeClientNodeJs extends LitCore {
const requestId = this.getRequestId();
const nodePromises = this.getNodePromises((url: string) => {
// -- choose the right signature
let sigToPassToNode = this.getAuthSigOrSessionAuthSig({
let sigToPassToNode = this.getAuthMaterial({
authSig,
sessionSigs,
url,
Expand Down
Loading