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

Remove/verify jwt for v7 #701

Merged
merged 2 commits into from
Oct 23, 2024
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
12 changes: 6 additions & 6 deletions packages/access-control-conditions/src/lib/validator.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -314,8 +314,8 @@ describe('validator.ts', () => {
}

expect(error).toBeDefined();
expect(error!.errorKind).toBe(LIT_ERROR.INVALID_PARAM_TYPE.kind);
expect(error!.errorCode).toBe(LIT_ERROR.INVALID_PARAM_TYPE.name);
expect(error!.errorKind).toBe(LIT_ERROR['INVALID_PARAM_TYPE'].kind);
expect(error!.errorCode).toBe(LIT_ERROR['INVALID_PARAM_TYPE'].name);
});

it('should throw when schema has invalid fields', async () => {
Expand Down Expand Up @@ -348,8 +348,8 @@ describe('validator.ts', () => {
}

expect(error).toBeDefined();
expect(error!.errorKind).toBe(LIT_ERROR.INVALID_PARAM_TYPE.kind);
expect(error!.errorCode).toBe(LIT_ERROR.INVALID_PARAM_TYPE.name);
expect(error!.errorKind).toBe(LIT_ERROR['INVALID_PARAM_TYPE'].kind);
expect(error!.errorCode).toBe(LIT_ERROR['INVALID_PARAM_TYPE'].name);
});

it('should throw when schema of a nested ACC does not validate', async () => {
Expand Down Expand Up @@ -407,7 +407,7 @@ describe('validator.ts', () => {
}

expect(error).toBeDefined();
expect(error!.errorKind).toBe(LIT_ERROR.INVALID_PARAM_TYPE.kind);
expect(error!.errorCode).toBe(LIT_ERROR.INVALID_PARAM_TYPE.name);
expect(error!.errorKind).toBe(LIT_ERROR['INVALID_PARAM_TYPE'].kind);
expect(error!.errorCode).toBe(LIT_ERROR['INVALID_PARAM_TYPE'].name);
});
});
58 changes: 0 additions & 58 deletions packages/crypto/src/lib/crypto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,10 @@ import { checkType, log } from '@lit-protocol/misc';
import { nacl } from '@lit-protocol/nacl';
import {
CombinedECDSASignature,
IJWT,
NodeAttestation,
SessionKeyPair,
SigningAccessControlConditionJWTPayload,
SigShare,
VerifyJWTProps,
} from '@lit-protocol/types';
import {
uint8arrayFromString,
Expand Down Expand Up @@ -473,59 +471,3 @@ declare global {
// eslint-disable-next-line no-var, @typescript-eslint/no-explicit-any
var LitNodeClient: any;
}

/**
* // TODO check for expiration
*
* Verify a JWT from the LIT network. Use this for auth on your server. For some background, users can specify access control conditions for various URLs, and then other users can then request a signed JWT proving that their ETH account meets those on-chain conditions using the getSignedToken function. Then, servers can verify that JWT using this function. A successful verification proves that the user meets the access control conditions defined earlier. For example, the on-chain condition could be posession of a specific NFT.
*
* @param { VerifyJWTProps } jwt
*
* @returns { IJWT<T> } An object with 4 keys: "verified": A boolean that represents whether or not the token verifies successfully. A true result indicates that the token was successfully verified. "header": the JWT header. "payload": the JWT payload which includes the resource being authorized, etc. "signature": A uint8array that represents the raw signature of the JWT.
*/
export const verifyJwt = async ({
publicKey,
jwt,
}: VerifyJWTProps): Promise<IJWT<SigningAccessControlConditionJWTPayload>> => {
// -- validate
if (
!checkType({
value: jwt,
allowedTypes: ['String'],
paramName: 'jwt',
functionName: 'verifyJwt',
})
)
throw new InvalidParamType(
{
info: {
jwt,
},
},
'jwt must be a string'
);

log('verifyJwt', jwt);

const jwtParts = jwt.split('.');
const signature = uint8arrayFromString(jwtParts[2], 'base64url');

const unsignedJwt = `${jwtParts[0]}.${jwtParts[1]}`;

const message = uint8arrayFromString(unsignedJwt);

await verifySignature(publicKey, message, signature);

const _jwt: IJWT<SigningAccessControlConditionJWTPayload> = {
verified: true,
header: JSON.parse(
uint8arrayToString(uint8arrayFromString(jwtParts[0], 'base64url'))
),
payload: JSON.parse(
uint8arrayToString(uint8arrayFromString(jwtParts[1], 'base64url'))
),
signature,
};

return _jwt;
};
190 changes: 31 additions & 159 deletions packages/lit-node-client-nodejs/src/lib/lit-node-client-nodejs.ts
Original file line number Diff line number Diff line change
@@ -1,41 +1,38 @@
import { computeAddress } from '@ethersproject/transactions';
import { BigNumber, ethers } from 'ethers';
import { joinSignature, sha256 } from 'ethers/lib/utils';
import { sha256 } from 'ethers/lib/utils';
import { SiweMessage } from 'siwe';

import {
LitAccessControlConditionResource,
LitResourceAbilityRequest,
decode,
RecapSessionCapabilityObject,
generateAuthSig,
createSiweMessage,
createSiweMessageWithCapacityDelegation,
createSiweMessageWithRecaps,
createSiweMessage,
decode,
generateAuthSig,
} from '@lit-protocol/auth-helpers';
import {
AUTH_METHOD_TYPE,
EITHER_TYPE,
FALLBACK_IPFS_GATEWAYS,
GLOBAL_OVERWRITE_IPFS_CODE_BY_NETWORK,
InvalidArgumentException,
InvalidParamType,
InvalidSessionSigs,
InvalidSignatureError,
LIT_ACTION_IPFS_HASH,
LIT_CURVE,
LIT_ENDPOINT,
LIT_SESSION_KEY_URI,
LOCAL_STORAGE_KEYS,
ParamsMissingError,
ParamNullError,
NoValidShares,
UnknownSignatureType,
UnknownSignatureError,
LitNodeClientNotReadyError,
InvalidParamType,
InvalidArgumentException,
WalletSignatureNotFoundError,
ParamNullError,
ParamsMissingError,
UnknownError,
InvalidSignatureError,
UnsupportedMethodError,
InvalidSessionSigs,
WalletSignatureNotFoundError,
} from '@lit-protocol/constants';
import { LitCore, composeLitUrl } from '@lit-protocol/core';
import {
Expand All @@ -56,8 +53,8 @@ import {
logWithRequestId,
mostCommonString,
normalizeAndStringify,
safeParams,
removeHexPrefix,
safeParams,
validateSessionSigs,
} from '@lit-protocol/misc';
import {
Expand All @@ -66,17 +63,17 @@ import {
setStorageItem,
} from '@lit-protocol/misc-browser';
import { nacl } from '@lit-protocol/nacl';
import { ILitResource, ISessionCapabilityObject } from '@lit-protocol/types';
import {
uint8arrayFromString,
uint8arrayToString,
} from '@lit-protocol/uint8arrays';
import { ILitResource, ISessionCapabilityObject } from '@lit-protocol/types';

import { encodeCode } from './helpers/encode-code';
import { getBlsSignatures } from './helpers/get-bls-signatures';
import { getClaims } from './helpers/get-claims';
import { getClaimsList } from './helpers/get-claims-list';
import { getFlattenShare, getSignatures } from './helpers/get-signatures';
import { getSignatures } from './helpers/get-signatures';
import { normalizeArray } from './helpers/normalize-array';
import { normalizeJsParams } from './helpers/normalize-params';
import { parseAsJsonOrString } from './helpers/parse-as-json-or-string';
Expand All @@ -89,6 +86,9 @@ import type {
AuthCallback,
AuthCallbackParams,
AuthSig,
BlsResponseData,
CapacityCreditsReq,
CapacityCreditsRes,
ClaimKeyResponse,
ClaimProcessor,
ClaimRequest,
Expand All @@ -97,13 +97,25 @@ import type {
DecryptResponse,
EncryptRequest,
EncryptResponse,
EncryptSdkParams,
EncryptionSignRequest,
ExecuteJsNoSigningResponse,
ExecuteJsResponse,
FormattedMultipleAccs,
GetLitActionSessionSigs,
GetPkpSessionSigs,
GetSessionSigsProps,
GetSignedTokenRequest,
GetSignSessionKeySharesProp,
GetWalletSigProps,
ILitNodeClient,
JsonExecutionRequest,
JsonExecutionRequestTargetNode,
JsonExecutionSdkParams,
JsonExecutionSdkParamsTargetNode,
JsonPKPClaimKeyRequest,
JsonPkpSignRequest,
JsonPkpSignSdkParams,
JsonSignSessionKeyRequestV1,
LitClientSessionManager,
LitNodeClientConfig,
NodeBlsSigningShare,
Expand All @@ -115,30 +127,11 @@ import type {
SessionKeyPair,
SessionSigningTemplate,
SessionSigsMap,
SigShare,
SigResponse,
SignSessionKeyProp,
SignSessionKeyResponse,
Signature,
SuccessNodePromises,
ILitNodeClient,
GetPkpSessionSigs,
CapacityCreditsReq,
CapacityCreditsRes,
JsonSignSessionKeyRequestV1,
BlsResponseData,
JsonExecutionSdkParamsTargetNode,
JsonExecutionRequestTargetNode,
JsonExecutionSdkParams,
ExecuteJsNoSigningResponse,
JsonPkpSignSdkParams,
SigResponse,
EncryptSdkParams,
GetLitActionSessionSigs,
GetSignSessionKeySharesProp,
EncryptionSignRequest,
SigningAccessControlConditionRequest,
JsonPKPClaimKeyRequest,
IpfsOptions,
} from '@lit-protocol/types';

export class LitNodeClientNodeJs
Expand Down Expand Up @@ -1215,127 +1208,6 @@ export class LitNodeClientNodeJs
return signatures.signature; // only a single signature is ever present, so we just return it.
};

/**
*
* Request a signed JWT from the LIT network. Before calling this function, you must know the access control conditions for the item you wish to gain authorization for.
*
* @param { GetSignedTokenRequest } params
*
* @returns { Promise<string> } final JWT
*
*/
getSignedToken = async (params: GetSignedTokenRequest): Promise<string> => {
// ========== Prepare Params ==========
const { chain, authSig, sessionSigs } = params;

// ========== Validation ==========
// -- validate if it's ready
if (!this.ready) {
throw new LitNodeClientNotReadyError(
{},
'3 LitNodeClient is not ready. Please call await litNodeClient.connect() first.'
);
}

// -- validate if this.networkPubKeySet is null
if (this.networkPubKeySet === null) {
throw new ParamNullError({}, 'networkPubKeySet cannot be null');
}

const paramsIsSafe = safeParams({
functionName: 'getSignedToken',
params,
});

if (!paramsIsSafe) {
throw new InvalidParamType(
{
info: {
params,
},
},
'Parameter validation failed.'
);
}

// ========== Prepare ==========
// we need to send jwt params iat (issued at) and exp (expiration)
// because the nodes may have different wall clock times
// the nodes will verify that these params are withing a grace period
const { iat, exp } = this.getJWTParams();

// ========== Formatting Access Control Conditions =========
const {
error,
formattedAccessControlConditions,
formattedEVMContractConditions,
formattedSolRpcConditions,
formattedUnifiedAccessControlConditions,
}: FormattedMultipleAccs = this.getFormattedAccessControlConditions(params);

if (error) {
throw new InvalidArgumentException(
{
info: {
params,
},
},
'You must provide either accessControlConditions or evmContractConditions or solRpcConditions or unifiedAccessControlConditions'
);
}

// ========== Get Node Promises ==========
const requestId = this._getNewRequestId();
const nodePromises = this.getNodePromises((url: string) => {
// -- if session key is available, use it
const authSigToSend = sessionSigs ? sessionSigs[url] : authSig;

const reqBody: SigningAccessControlConditionRequest = {
accessControlConditions: formattedAccessControlConditions,
evmContractConditions: formattedEVMContractConditions,
solRpcConditions: formattedSolRpcConditions,
unifiedAccessControlConditions: formattedUnifiedAccessControlConditions,
chain,
authSig: authSigToSend,
iat,
exp,
};

const urlWithPath = composeLitUrl({
url,
endpoint: LIT_ENDPOINT.SIGN_ACCS,
});

return this.generatePromise(urlWithPath, reqBody, requestId);
});

// -- resolve promises
const res = await this.handleNodePromises(
nodePromises,
requestId,
this.config.minNodeCount
);

// -- case: promises rejected
if (!res.success) {
this._throwNodeError(res, requestId);
}

const signatureShares: NodeBlsSigningShare[] = (
res as SuccessNodePromises<NodeBlsSigningShare>
).values;

log('signatureShares', signatureShares);

// ========== Result ==========
const finalJwt: string = await this.combineSharesAndGetJWT(
signatureShares,
requestId
);

return finalJwt;
};

/**
*
* Encrypt data using the LIT network public key.
Expand Down
Loading
Loading