@renown/sdk 6.2.3 → 6.3.0-dev.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/crypto.d.ts +2 -2
- package/dist/crypto.js +2 -1
- package/dist/{index-DbiBjqs6.d.ts → index-Bf53Cq6x.d.ts} +2 -2
- package/dist/{index-DbiBjqs6.d.ts.map → index-Bf53Cq6x.d.ts.map} +1 -1
- package/dist/index.d.ts +5 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -5
- package/dist/index.js.map +1 -1
- package/dist/memory-key-storage-CVVAWWS4.js +145 -0
- package/dist/memory-key-storage-CVVAWWS4.js.map +1 -0
- package/dist/{meta-Dpmn2Ywp.d.ts → meta-Co-vmMo-.d.ts} +2 -2
- package/dist/{meta-Dpmn2Ywp.d.ts.map → meta-Co-vmMo-.d.ts.map} +1 -1
- package/dist/{meta-qadFdiX7.d.ts → meta-ScD9zeLt.d.ts} +2 -2
- package/dist/{meta-qadFdiX7.d.ts.map → meta-ScD9zeLt.d.ts.map} +1 -1
- package/dist/node.d.ts +5 -5
- package/dist/node.d.ts.map +1 -1
- package/dist/node.js +15 -70
- package/dist/node.js.map +1 -1
- package/dist/{signed-message-Cp5oRPLN.js → signed-message-jM49yI1o.js} +94 -6
- package/dist/signed-message-jM49yI1o.js.map +1 -0
- package/dist/{signer-GzTlZLjR.js → signer-9gB5YUMp.js} +70 -139
- package/dist/signer-9gB5YUMp.js.map +1 -0
- package/dist/signer-trust-B4XTKeZ2.d.ts +170 -0
- package/dist/signer-trust-B4XTKeZ2.d.ts.map +1 -0
- package/dist/{signer-trust-H1rNzUcd.js → signer-trust-vhUCCmfg.js} +304 -18
- package/dist/signer-trust-vhUCCmfg.js.map +1 -0
- package/dist/trust.d.ts +2 -2
- package/dist/trust.js +2 -2
- package/dist/{types-DRnq2URw.d.ts → types-BmdG67IZ.d.ts} +2 -2
- package/dist/{types-DRnq2URw.d.ts.map → types-BmdG67IZ.d.ts.map} +1 -1
- package/dist/{types-7xgrEnx7.d.ts → types-CfSRJMyb.d.ts} +2 -2
- package/dist/{types-7xgrEnx7.d.ts.map → types-CfSRJMyb.d.ts.map} +1 -1
- package/dist/{types-Ceiz2dkk.d.ts → types-CplBDMtV.d.ts} +43 -2
- package/dist/types-CplBDMtV.d.ts.map +1 -0
- package/dist/{utils-DkVxP7Ug.d.ts → utils-K2mtcxhD.d.ts} +35 -4
- package/dist/utils-K2mtcxhD.d.ts.map +1 -0
- package/dist/wallet/index.d.ts +1 -1
- package/dist/wallet/mock/factory.d.ts +2 -2
- package/dist/wallet/mock/index.d.ts +2 -2
- package/dist/wallet/privy/factory.d.ts +3 -3
- package/dist/wallet/privy/index.d.ts +2 -2
- package/dist/wallet/rainbow/factory.d.ts +2 -2
- package/dist/wallet/rainbow/index.d.ts +2 -2
- package/package.json +3 -3
- package/dist/signed-message-Cp5oRPLN.js.map +0 -1
- package/dist/signer-GzTlZLjR.js.map +0 -1
- package/dist/signer-trust-FmbMTn39.d.ts +0 -53
- package/dist/signer-trust-FmbMTn39.d.ts.map +0 -1
- package/dist/signer-trust-H1rNzUcd.js.map +0 -1
- package/dist/types-Ceiz2dkk.d.ts.map +0 -1
- package/dist/utils-DLQ5VVqT.js +0 -75
- package/dist/utils-DLQ5VVqT.js.map +0 -1
- package/dist/utils-DkVxP7Ug.d.ts.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"signer-9gB5YUMp.js","names":["getResolver","keyDidResolver"],"sources":["../src/utils.ts","../src/crypto/signer.ts"],"sourcesContent":["import type { JwtCredentialPayload } from \"did-jwt-vc\";\nimport { createVerifiableCredentialJwt, verifyCredential } from \"did-jwt-vc\";\nimport { Resolver } from \"did-resolver\";\nimport { getResolver as keyDidResolver } from \"key-did-resolver\";\nimport type {\n AuthVerifiedCredential,\n CreateBearerTokenOptions,\n IAuthCredentialSubject,\n Issuer,\n PKHDid,\n VerifiedCredential,\n} from \"./types.js\";\n\nexport type ILogger = {\n level: \"verbose\" | \"debug\" | \"info\" | \"warn\" | \"error\";\n\n verbose: (message: string, ...replacements: any[]) => void;\n debug: (message: string, ...replacements: any[]) => void;\n info: (message: string, ...replacements: any[]) => void;\n warn: (message: string, ...replacements: any[]) => void;\n error: (message: string, ...replacements: any[]) => void;\n};\n\n/**\n * Parse a DID:pkh string to extract network, chain ID, and address information\n * @param did - The DID string in format \"did:pkh:networkId:chainId:address\"\n * @returns Parsed DID information\n * @throws Error if the DID format is invalid\n */\nexport function parsePkhDid(did: string): PKHDid {\n const parts = did.split(\":\");\n if (!did.startsWith(\"did:pkh:\") || parts.length !== 5) {\n throw new Error(\"Invalid pkh did\");\n }\n const [, , networkId, chainIdStr, address] = parts;\n\n if (!address.startsWith(\"0x\")) {\n throw new Error(`Invalid address: ${address}`);\n }\n\n const chainId = Number(chainIdStr);\n if (isNaN(chainId)) {\n throw new Error(`Invalid chain id: ${chainIdStr}`);\n }\n\n return {\n chainId,\n networkId,\n address: address as PKHDid[\"address\"],\n };\n}\n\nexport interface VerifyAuthBearerTokenOptions {\n /** Expected `aud` claim. Required when verifying tokens that include an\n * audience claim — did-jwt rejects them otherwise with\n * `invalid_config: JWT audience is required but your app address has not\n * been configured`. Tokens minted without `aud` are unaffected. */\n audience?: string;\n}\n\nexport async function verifyAuthBearerToken(\n jwt: string,\n options?: VerifyAuthBearerTokenOptions,\n): Promise<false | AuthVerifiedCredential> {\n try {\n const now = parseInt(String(Date.now() / 1000));\n const verified: VerifiedCredential = await verifyCredential(\n jwt,\n getResolver(),\n {\n ...(options?.audience !== undefined && { audience: options.audience }),\n policies: {\n now: parseInt(String(Date.now() / 1000)),\n expirationDate: true,\n issuanceDate: true,\n },\n },\n );\n\n if (verified.payload.exp && verified.payload.exp < now) {\n return false;\n }\n assertIsAuthCredential(verified);\n return verified;\n } catch (e) {\n console.error(e);\n return false;\n }\n}\n\nexport function assertIsAuthCredential(\n credential: VerifiedCredential,\n): asserts credential is AuthVerifiedCredential {\n const subjectKeys = Object.keys(\n credential.verifiableCredential.credentialSubject,\n );\n if (\n ![\"address\", \"chainId\", \"networkId\"].every((key) =>\n subjectKeys.includes(key),\n )\n ) {\n throw new Error(\n \"Invalid Auth Credential Subject:\" +\n JSON.stringify(\n credential.verifiableCredential.credentialSubject,\n null,\n 2,\n ),\n );\n }\n}\n\nexport async function createAuthBearerToken(\n chainId: number,\n networkId: string,\n address: string,\n issuer: Issuer,\n options?: CreateBearerTokenOptions,\n) {\n const vcPayload: JwtCredentialPayload = {\n sub: issuer.did,\n vc: {\n \"@context\": [\"https://www.w3.org/2018/credentials/v1\"],\n type: [\"VerifiableCredential\"],\n credentialSubject: {\n chainId,\n networkId,\n address,\n } satisfies IAuthCredentialSubject,\n },\n aud: options?.aud,\n };\n\n const jwt = await createVerifiableCredentialJwt(vcPayload, issuer, {\n expiresIn: options?.expiresIn,\n });\n return jwt;\n}\n\nexport const getResolver = () => {\n const keyResolver = keyDidResolver();\n if (!keyResolver) {\n throw new Error(\"Failed to get key resolver\");\n }\n\n return new Resolver(keyResolver);\n};\n","import type {\n Action,\n ActionSigningTarget,\n AppActionSigner,\n ISigner,\n Operation,\n Signature,\n SignatureVerificationHandler,\n UserActionSigner,\n} from \"@powerhousedao/shared/document-model\";\nimport {\n actionSignerIdentity,\n signActionV2,\n} from \"@powerhousedao/shared/document-model\";\nimport type { IRenownCrypto } from \"./index.js\";\n\nexport class InvalidSignatureError extends Error {\n constructor() {\n super(\"Invalid signature\");\n }\n}\n\nexport class RenownCryptoSigner implements ISigner {\n readonly app: AppActionSigner;\n\n constructor(\n private readonly crypto: IRenownCrypto,\n private readonly appName: string,\n public user?: UserActionSigner,\n ) {\n this.app = {\n key: this.crypto.did,\n name: this.appName,\n };\n }\n\n get publicKey() {\n return this.crypto.publicKey;\n }\n\n async sign(data: Uint8Array): Promise<Uint8Array> {\n return this.crypto.sign(data);\n }\n\n async verify(data: Uint8Array, signature: Uint8Array): Promise<void> {\n const isValid = await this.crypto.verify(data, signature);\n if (!isValid) {\n throw new InvalidSignatureError();\n }\n }\n\n async signAction(\n action: Action,\n target: ActionSigningTarget,\n abortSignal?: AbortSignal,\n ): Promise<Signature> {\n const hashField = action.context?.prevOpHash ?? \"\";\n return this._signAction(action, target, hashField, abortSignal);\n }\n\n /**\n * Signs an action including a predicted resulting state hash, packed into\n * element [3] as `${prevStateHash}:${resultingStateHash}`.\n */\n async signActionWithResultingState(\n action: Action,\n target: ActionSigningTarget,\n resultingStateHash: string,\n abortSignal?: AbortSignal,\n ): Promise<Signature> {\n const prevStateHash = action.context?.prevOpHash ?? \"\";\n const hashField = `${prevStateHash}:${resultingStateHash}`;\n return this._signAction(action, target, hashField, abortSignal);\n }\n\n /**\n * The pre-v2 tuple, over scope, type and input only. For peers and tests\n * that still need one; it binds neither the document nor the signer.\n */\n async signActionLegacy(\n action: Action,\n abortSignal?: AbortSignal,\n ): Promise<Signature> {\n if (abortSignal?.aborted) {\n throw new Error(\"Signing aborted\");\n }\n\n const params: [string, string, string, string] = [\n (new Date().getTime() / 1000).toFixed(0),\n this.crypto.did,\n await this.hashAction(action),\n action.context?.prevOpHash ?? \"\",\n ];\n const signatureBytes = await this.crypto.sign(\n this.buildSignatureMessage(params),\n );\n\n if (abortSignal?.aborted) {\n throw new Error(\"Signing aborted\");\n }\n return [...params, `0x${this.arrayBufferToHex(signatureBytes)}`];\n }\n\n private async _signAction(\n action: Action,\n target: ActionSigningTarget,\n hashField: string,\n abortSignal?: AbortSignal,\n ): Promise<Signature> {\n if (abortSignal?.aborted) {\n throw new Error(\"Signing aborted\");\n }\n\n const signature = await signActionV2({\n action,\n target,\n signer: actionSignerIdentity(this),\n sign: (message) => this.crypto.sign(message),\n previousStateHash: hashField,\n });\n\n if (abortSignal?.aborted) {\n throw new Error(\"Signing aborted\");\n }\n\n return signature;\n }\n\n private async hashAction(action: Action): Promise<string> {\n const payload = [\n action.scope,\n action.type,\n JSON.stringify(action.input),\n ].join(\"\");\n const encoder = new TextEncoder();\n const data = encoder.encode(payload);\n const hashBuffer = await crypto.subtle.digest(\"SHA-256\", data);\n return this.arrayBufferToBase64(hashBuffer);\n }\n\n private buildSignatureMessage(\n params: [string, string, string, string],\n ): Uint8Array {\n const message = params.join(\"\");\n const prefix = \"\\x19Signed Operation:\\n\" + message.length.toString();\n const encoder = new TextEncoder();\n return encoder.encode(prefix + message);\n }\n\n private arrayBufferToHex(buffer: Uint8Array | ArrayBuffer): string {\n const bytes =\n buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);\n return Array.from(bytes)\n .map((byte) => byte.toString(16).padStart(2, \"0\"))\n .join(\"\");\n }\n\n private arrayBufferToBase64(buffer: ArrayBuffer): string {\n const bytes = new Uint8Array(buffer);\n let binary = \"\";\n for (let i = 0; i < bytes.length; i++) {\n binary += String.fromCharCode(bytes[i]);\n }\n return btoa(binary);\n }\n}\n\n/**\n * Creates a signature verification handler that verifies signatures using the Web Crypto API.\n * The verification uses ECDSA with P-256 curve and SHA-256 hash, matching the RenownCrypto signing algorithm.\n */\nexport function createSignatureVerifier(\n requireSignature = false,\n): SignatureVerificationHandler {\n return async (operation: Operation, publicKey: string): Promise<boolean> => {\n const signer = operation.action.context?.signer;\n if (!signer || !publicKey) {\n return !requireSignature;\n }\n\n const signatures = signer.signatures;\n if (signatures.length === 0) {\n return false;\n }\n\n const signature = signatures[signatures.length - 1];\n const [timestamp, signerKey, hash, prevStateHash, signatureHex] = signature;\n\n if (signerKey !== publicKey) {\n return false;\n }\n\n const params: [string, string, string, string] = [\n timestamp,\n signerKey,\n hash,\n prevStateHash,\n ];\n const message = buildSignatureMessage(params);\n const signatureBytes = hexToUint8Array(signatureHex);\n\n const cryptoKey = await importDidPublicKey(publicKey);\n\n const isValid = await crypto.subtle.verify(\n { name: \"ECDSA\", hash: \"SHA-256\" },\n cryptoKey,\n signatureBytes.buffer as ArrayBuffer,\n message.buffer as ArrayBuffer,\n );\n\n return isValid;\n };\n}\n\nfunction buildSignatureMessage(\n params: [string, string, string, string],\n): Uint8Array {\n const message = params.join(\"\");\n const prefix = \"\\x19Signed Operation:\\n\" + message.length.toString();\n const encoder = new TextEncoder();\n return encoder.encode(prefix + message);\n}\n\nfunction hexToUint8Array(hex: string): Uint8Array {\n const cleanHex = hex.startsWith(\"0x\") ? hex.slice(2) : hex;\n const bytes = new Uint8Array(cleanHex.length / 2);\n for (let i = 0; i < cleanHex.length; i += 2) {\n bytes[i / 2] = parseInt(cleanHex.substring(i, i + 2), 16);\n }\n return bytes;\n}\n\n/** The P-256 public key a `did:key` names, for verifying. */\nexport async function importDidPublicKey(did: string): Promise<CryptoKey> {\n const keyData = extractKeyFromDid(did);\n return crypto.subtle.importKey(\n \"raw\",\n keyData.buffer as ArrayBuffer,\n { name: \"ECDSA\", namedCurve: \"P-256\" },\n true,\n [\"verify\"],\n );\n}\n\nfunction extractKeyFromDid(did: string): Uint8Array {\n const parts = did.split(\":\");\n if (parts.length < 3 || parts[0] !== \"did\" || parts[1] !== \"key\") {\n throw new Error(`Invalid DID format: ${did}`);\n }\n\n const multibaseKey = parts[2];\n if (!multibaseKey.startsWith(\"z\")) {\n throw new Error(`Unsupported multibase encoding: ${multibaseKey[0]}`);\n }\n\n const decoded = base58Decode(multibaseKey.slice(1));\n\n if (decoded[0] !== 0x80 || decoded[1] !== 0x24) {\n throw new Error(\"Not a P-256 public key multicodec\");\n }\n\n const compressedKey = decoded.slice(2);\n return decompressP256PublicKey(compressedKey);\n}\n\nfunction base58Decode(input: string): Uint8Array {\n const ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n const ALPHABET_MAP = new Map<string, number>();\n for (let i = 0; i < ALPHABET.length; i++) {\n ALPHABET_MAP.set(ALPHABET[i], i);\n }\n\n if (input.length === 0) {\n return new Uint8Array(0);\n }\n\n const bytes: number[] = [0];\n for (const char of input) {\n const value = ALPHABET_MAP.get(char);\n if (value === undefined) {\n throw new Error(`Invalid base58 character: ${char}`);\n }\n\n let carry = value;\n for (let j = 0; j < bytes.length; j++) {\n carry += bytes[j] * 58;\n bytes[j] = carry & 0xff;\n carry >>= 8;\n }\n\n while (carry > 0) {\n bytes.push(carry & 0xff);\n carry >>= 8;\n }\n }\n\n for (const char of input) {\n if (char !== \"1\") break;\n bytes.push(0);\n }\n\n return new Uint8Array(bytes.reverse());\n}\n\nfunction decompressP256PublicKey(compressed: Uint8Array): Uint8Array {\n if (compressed.length !== 33) {\n throw new Error(`Invalid compressed key length: ${compressed.length}`);\n }\n\n const prefix = compressed[0];\n if (prefix !== 0x02 && prefix !== 0x03) {\n throw new Error(`Invalid compression prefix: ${prefix}`);\n }\n\n const p = BigInt(\n \"0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff\",\n );\n const a = BigInt(\n \"0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc\",\n );\n const b = BigInt(\n \"0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b\",\n );\n\n let x = BigInt(0);\n for (let i = 1; i < compressed.length; i++) {\n x = (x << BigInt(8)) | BigInt(compressed[i]);\n }\n\n const ySquared = (modPow(x, BigInt(3), p) + a * x + b) % p;\n let y = modPow(ySquared, (p + BigInt(1)) / BigInt(4), p);\n\n const isYEven = y % BigInt(2) === BigInt(0);\n const shouldBeEven = prefix === 0x02;\n if (isYEven !== shouldBeEven) {\n y = p - y;\n }\n\n const uncompressed = new Uint8Array(65);\n uncompressed[0] = 0x04;\n\n const xBytes = bigIntToBytes(x, 32);\n const yBytes = bigIntToBytes(y, 32);\n\n uncompressed.set(xBytes, 1);\n uncompressed.set(yBytes, 33);\n\n return uncompressed;\n}\n\nfunction modPow(base: bigint, exp: bigint, mod: bigint): bigint {\n let result = BigInt(1);\n base = base % mod;\n while (exp > BigInt(0)) {\n if (exp % BigInt(2) === BigInt(1)) {\n result = (result * base) % mod;\n }\n exp = exp >> BigInt(1);\n base = (base * base) % mod;\n }\n return result;\n}\n\nfunction bigIntToBytes(n: bigint, length: number): Uint8Array {\n const bytes = new Uint8Array(length);\n for (let i = length - 1; i >= 0; i--) {\n bytes[i] = Number(n & BigInt(0xff));\n n = n >> BigInt(8);\n }\n return bytes;\n}\n\n/**\n * Parses the hash field (element [3]) from a signature tuple.\n *\n * Supports two formats:\n * - Old format: just `prevStateHash` (no colon)\n * - New format: `prevStateHash:resultingStateHash` (colon-separated)\n *\n * @param hashField - The 4th element of a Signature tuple\n * @returns Object with prevStateHash and optional resultingStateHash\n */\nexport function parseSignatureHashField(hashField: string): {\n prevStateHash: string;\n resultingStateHash: string | undefined;\n} {\n const colonIndex = hashField.indexOf(\":\");\n\n if (colonIndex === -1) {\n return {\n prevStateHash: hashField,\n resultingStateHash: undefined,\n };\n }\n\n return {\n prevStateHash: hashField.substring(0, colonIndex),\n resultingStateHash: hashField.substring(colonIndex + 1),\n };\n}\n\n/**\n * Extracts the resulting state hash from a signature, if present.\n *\n * @param signature - A Signature tuple\n * @returns The resulting state hash, or undefined if not present\n */\nexport function extractResultingHashFromSignature(\n signature: Signature,\n): string | undefined {\n const hashField = signature[3];\n const { resultingStateHash } = parseSignatureHashField(hashField);\n return resultingStateHash;\n}\n\n/**\n * Checks if a signature includes a resulting state hash.\n *\n * @param signature - A Signature tuple\n * @returns true if the signature includes a resulting state hash\n */\nexport function signatureHasResultingHash(signature: Signature): boolean {\n return extractResultingHashFromSignature(signature) !== undefined;\n}\n"],"mappings":";;;;;;;;;;;AA6BA,SAAgB,YAAY,KAAqB;CAC/C,MAAM,QAAQ,IAAI,MAAM,GAAG;CAC3B,IAAI,CAAC,IAAI,WAAW,UAAU,KAAK,MAAM,WAAW,GAClD,MAAM,IAAI,MAAM,iBAAiB;CAEnC,MAAM,KAAK,WAAW,YAAY,WAAW;CAE7C,IAAI,CAAC,QAAQ,WAAW,IAAI,GAC1B,MAAM,IAAI,MAAM,oBAAoB,SAAS;CAG/C,MAAM,UAAU,OAAO,UAAU;CACjC,IAAI,MAAM,OAAO,GACf,MAAM,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C,IAAI,eAAe,IACjB,OAAO;EACL,eAAe;EACf,oBAAoB,KAAA;CACtB;CAGF,OAAO;EACL,eAAe,UAAU,UAAU,GAAG,UAAU;EAChD,oBAAoB,UAAU,UAAU,aAAa,CAAC;CACxD;AACF;;;;;;;AAQA,SAAgB,kCACd,WACoB;CACpB,MAAM,YAAY,UAAU;CAC5B,MAAM,EAAE,uBAAuB,wBAAwB,SAAS;CAChE,OAAO;AACT;;;;;;;AAQA,SAAgB,0BAA0B,WAA+B;CACvE,OAAO,kCAAkC,SAAS,MAAM,KAAA;AAC1D"}
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import { Ct as SwitchboardSource, M as PowerhouseVerifiableCredential, r as IRenownCrypto, w as Issuer } from "./types-CplBDMtV.js";
|
|
2
|
+
import { Action, ActionSigner, ActionSigningTarget, UserActionSigner } from "@powerhousedao/shared/document-model";
|
|
3
|
+
//#region src/delegation.d.ts
|
|
4
|
+
/** The tag of the `signatures` entry holding a statement, and of its binding. */
|
|
5
|
+
declare const DELEGATION_TAG = "dlg1";
|
|
6
|
+
/** Keeps a statement apart from the bearer tokens the same key signs. */
|
|
7
|
+
declare const DELEGATION_JWT_TYPE = "ph-delegation+jwt";
|
|
8
|
+
/** What a statement may name in this version. Nothing wider is accepted. */
|
|
9
|
+
declare const DELEGABLE_OPERATIONS: readonly string[];
|
|
10
|
+
type DelegationScope = {
|
|
11
|
+
/** Action types the delegate may sign. */
|
|
12
|
+
ops: string[];
|
|
13
|
+
/** What the statement is for; the host using it checks this. */
|
|
14
|
+
res: string;
|
|
15
|
+
};
|
|
16
|
+
type DelegationClaims = {
|
|
17
|
+
iss: string;
|
|
18
|
+
aud: string;
|
|
19
|
+
sub: string;
|
|
20
|
+
env: string;
|
|
21
|
+
scp: DelegationScope;
|
|
22
|
+
iat: number;
|
|
23
|
+
exp: number;
|
|
24
|
+
jti: string;
|
|
25
|
+
prf: PowerhouseVerifiableCredential;
|
|
26
|
+
};
|
|
27
|
+
interface CreateDelegationParams {
|
|
28
|
+
/** The session key named in `credential`. */
|
|
29
|
+
issuer: Issuer;
|
|
30
|
+
/** The Renown credential binding the person to `issuer`. */
|
|
31
|
+
credential: PowerhouseVerifiableCredential;
|
|
32
|
+
/** The delegate's `did:key`. */
|
|
33
|
+
delegate: string;
|
|
34
|
+
/** The `did:key` of the host the delegate writes to. */
|
|
35
|
+
environment: string;
|
|
36
|
+
scope: DelegationScope;
|
|
37
|
+
/** Defaults to 30 days. */
|
|
38
|
+
lifetimeSeconds?: number;
|
|
39
|
+
/** Epoch seconds; defaults to the clock. */
|
|
40
|
+
now?: number;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Signs a statement naming `delegate`, with no wallet step: the session key
|
|
44
|
+
* signs it, and the statement carries the credential so it verifies offline.
|
|
45
|
+
*/
|
|
46
|
+
declare function createDelegation(params: CreateDelegationParams): Promise<string>;
|
|
47
|
+
/** The statement's claims, unverified; undefined when it does not parse. */
|
|
48
|
+
declare function decodeDelegation(statement: string): DelegationClaims | undefined;
|
|
49
|
+
type DelegationVerdict = {
|
|
50
|
+
ok: true;
|
|
51
|
+
claims: DelegationClaims;
|
|
52
|
+
} | {
|
|
53
|
+
ok: false;
|
|
54
|
+
reason: string;
|
|
55
|
+
};
|
|
56
|
+
interface VerifyDelegationParams {
|
|
57
|
+
/** Who the action claims to act as. */
|
|
58
|
+
user: UserActionSigner;
|
|
59
|
+
/** The key that signed the action. */
|
|
60
|
+
key: string;
|
|
61
|
+
/** The signing tuple's time, in epoch seconds. */
|
|
62
|
+
signedAt: number;
|
|
63
|
+
/** The action's type. */
|
|
64
|
+
actionType: string;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Whether `statement` lets `key` sign this action as `user`. Offline and pure:
|
|
68
|
+
* every replica reaches the same verdict at any time, so an old operation
|
|
69
|
+
* verifies forever. The credential's own dates are not read: link one is judged
|
|
70
|
+
* at issuance, and a credential outliving its seven days must not end a delegate.
|
|
71
|
+
*/
|
|
72
|
+
declare function verifyDelegation(statement: string, params: VerifyDelegationParams): Promise<DelegationVerdict>;
|
|
73
|
+
type DelegationCarried = {
|
|
74
|
+
/** Absent: the tuple names a statement the signer does not carry. */
|
|
75
|
+
statement?: string;
|
|
76
|
+
/** The binding in the signing tuple; absent: not bound. */
|
|
77
|
+
binding?: string;
|
|
78
|
+
/** The signing tuple's time. */
|
|
79
|
+
signedAt: number;
|
|
80
|
+
};
|
|
81
|
+
/** What `signer` carries of a delegation; undefined when it carries nothing. */
|
|
82
|
+
declare function delegationOf(signer: ActionSigner): DelegationCarried | undefined;
|
|
83
|
+
/** Why what `signer` carries does not stand as bound; undefined when it does. */
|
|
84
|
+
declare function bindingRefusal(carried: DelegationCarried): Promise<string | undefined>;
|
|
85
|
+
/** What the signing tuple's element [3] holds, so the signature covers the statement. */
|
|
86
|
+
declare function delegationBinding(statement: string): Promise<string>;
|
|
87
|
+
interface SignDelegatedActionParams {
|
|
88
|
+
action: Action;
|
|
89
|
+
target: ActionSigningTarget;
|
|
90
|
+
/** The delegate's key. */
|
|
91
|
+
crypto: Pick<IRenownCrypto, "did" | "sign">;
|
|
92
|
+
/** A label for `signer.app.name`; unsigned. */
|
|
93
|
+
appName: string;
|
|
94
|
+
/** The person the delegate signs as. */
|
|
95
|
+
user: UserActionSigner;
|
|
96
|
+
statement: string;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Signs `action` as the person, carrying the statement in an earlier entry of
|
|
100
|
+
* `signatures`. The reactor leaves an action already signed under a key as it
|
|
101
|
+
* is, so this goes through any client.
|
|
102
|
+
*/
|
|
103
|
+
declare function signDelegatedAction(params: SignDelegatedActionParams): Promise<Action>;
|
|
104
|
+
//#endregion
|
|
105
|
+
//#region src/discovery.d.ts
|
|
106
|
+
interface ResolveSwitchboardEndpointOptions {
|
|
107
|
+
switchboardUrl?: string;
|
|
108
|
+
baseUrl?: string;
|
|
109
|
+
timeoutMs?: number;
|
|
110
|
+
}
|
|
111
|
+
declare function resolveSwitchboardEndpoint(options: ResolveSwitchboardEndpointOptions): Promise<string | undefined>;
|
|
112
|
+
//#endregion
|
|
113
|
+
//#region src/signer-trust.d.ts
|
|
114
|
+
type SignerUser = ActionSigner["user"];
|
|
115
|
+
/** A signer whose `app.key` and `user` are read on every ask. */
|
|
116
|
+
interface RenownOwnSigner {
|
|
117
|
+
readonly app?: {
|
|
118
|
+
readonly key: string;
|
|
119
|
+
};
|
|
120
|
+
readonly user?: SignerUser;
|
|
121
|
+
}
|
|
122
|
+
interface RenownTrustPolicyOptions {
|
|
123
|
+
/** Serves the renown read model; without it, Renown's REST API is read. */
|
|
124
|
+
switchboard?: SwitchboardSource;
|
|
125
|
+
/** Renown base URL for the REST lookup. Defaults to DEFAULT_RENOWN_URL. */
|
|
126
|
+
renownUrl?: string;
|
|
127
|
+
/** This node's signer, read on every ask; its key signing as its current user is accepted without a lookup. Wins over `self`. */
|
|
128
|
+
ownSigner?: RenownOwnSigner;
|
|
129
|
+
/**
|
|
130
|
+
* A snapshot of this node's key and user, for a pooled worker whose signer
|
|
131
|
+
* cannot cross the thread boundary. Only matches the worker's own key.
|
|
132
|
+
*/
|
|
133
|
+
self?: {
|
|
134
|
+
key: string;
|
|
135
|
+
user: SignerUser;
|
|
136
|
+
};
|
|
137
|
+
/** How many acceptances are remembered. Defaults to 10000. */
|
|
138
|
+
maxAccepted?: number;
|
|
139
|
+
/** How long a refusal is remembered before asking again. Defaults to 60s. */
|
|
140
|
+
refusalTtlMs?: number;
|
|
141
|
+
/**
|
|
142
|
+
* Verify delegated signers only, and accept every other signer: what a host
|
|
143
|
+
* with `authEnforcement` off does. It makes no lookup, so it needs no network.
|
|
144
|
+
*/
|
|
145
|
+
delegationOnly?: boolean;
|
|
146
|
+
}
|
|
147
|
+
/** What admission knows of the write; the reactor's `SignatureTrustContext`. */
|
|
148
|
+
interface RenownTrustContext {
|
|
149
|
+
/** Where this reactor first stores the write. */
|
|
150
|
+
path: "mutation" | "load";
|
|
151
|
+
actionType: string;
|
|
152
|
+
}
|
|
153
|
+
/** Structurally a reactor `SignatureTrustPolicy`. */
|
|
154
|
+
interface RenownTrustPolicy {
|
|
155
|
+
authorizeSigner(signer: ActionSigner, key: string, documentId: string, context?: RenownTrustContext): Promise<boolean>;
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Accepts a key the user's EIP-712 Renown credential delegates to, ignoring
|
|
159
|
+
* expiry and revocation. Verdicts are cached per (address, key); this node's
|
|
160
|
+
* own key is checked before the cache and never cached.
|
|
161
|
+
*
|
|
162
|
+
* A signer carrying a delegation is verified from what it carries, with no
|
|
163
|
+
* lookup and no cache: the verdict depends on the statement, not on (address,
|
|
164
|
+
* key). `options.delegationOnly` accepts every other signer.
|
|
165
|
+
*/
|
|
166
|
+
declare function createRenownTrustPolicy(options?: RenownTrustPolicyOptions): RenownTrustPolicy;
|
|
167
|
+
//#endregion
|
|
168
|
+
export { signDelegatedAction as C, delegationOf as S, VerifyDelegationParams as _, createRenownTrustPolicy as a, decodeDelegation as b, CreateDelegationParams as c, DELEGATION_TAG as d, DelegationCarried as f, SignDelegatedActionParams as g, DelegationVerdict as h, RenownTrustPolicyOptions as i, DELEGABLE_OPERATIONS as l, DelegationScope as m, RenownTrustContext as n, ResolveSwitchboardEndpointOptions as o, DelegationClaims as p, RenownTrustPolicy as r, resolveSwitchboardEndpoint as s, RenownOwnSigner as t, DELEGATION_JWT_TYPE as u, bindingRefusal as v, verifyDelegation as w, delegationBinding as x, createDelegation as y };
|
|
169
|
+
export {};
|
|
170
|
+
//# sourceMappingURL=signer-trust-B4XTKeZ2.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"signer-trust-B4XTKeZ2.d.ts","names":[],"sources":["../src/delegation.ts","../src/discovery.ts","../src/signer-trust.ts"],"mappings":";;;;cAmBa;;cAGA;;cAGA;KAOD;;EAEV;;EAEA;;KAGU;EACV;EACA;EACA;EACA;EACA,KAAK;EACL;EACA;EACA;EACA,KAAK;;UAGU;;EAEf,QAAQ;;EAER,YAAY;;EAEZ;;EAEA;EACA,OAAO;;EAEP;;EAEA;;;;;;iBAOoB,iBACpB,QAAQ,yBACP;;iBAiCa,iBACd,oBACC;KAaS;EACN;EAAU,QAAQ;;EAClB;EAAW;;UAEA;;EAEf,MAAM;;EAEN;;EAEA;;EAEA;;;;;;;;iBASoB,iBACpB,mBACA,QAAQ,yBACP,QAAQ;KAkCC;;EAEV;;EAEA;;EAEA;;;iBAIc,aACd,QAAQ,eACP;;iBAkBmB,eACpB,SAAS,oBACR;;iBAcmB,kBAAkB,oBAAoB;UAQ3C;EACf,QAAQ;EACR,QAAQ;;EAER,QAAQ,KAAK;;EAEb;;EAEA,MAAM;EACN;;;;;;;iBAQoB,oBACpB,QAAQ,4BACP,QAAQ;;;UC5PM;EAEf;EAEA;EAEA;;iBAcoB,2BACpB,SAAS,oCACR;;;KCVE,aAAa;;UAGD;WACN;aAAiB;;WACjB,OAAO;;UAGD;;EAEf,cAAc;;EAEd;;EAEA,YAAY;;;;;EAKZ;IAAS;IAAa,MAAM;;;EAE5B;;EAEA;;;;;EAKA;;;UAIe;;EAEf;EACA;;;UAIe;EACf,gBACE,QAAQ,cACR,aACA,oBACA,UAAU,qBACT;;;;;;;;;;;iBAeW,wBACd,UAAS,2BACR"}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { a as DEFAULT_RENOWN_NETWORK_ID, r as CREDENTIAL_TYPES } from "./constants-DVOF17NB.js";
|
|
2
|
-
import {
|
|
2
|
+
import { d as verifyAuthBearerToken, i as importDidPublicKey, u as parsePkhDid } from "./signer-9gB5YUMp.js";
|
|
3
3
|
import { recoverTypedDataAddress } from "viem";
|
|
4
|
-
import { createAction } from "@powerhousedao/shared/document-model";
|
|
4
|
+
import { actionSignerIdentity, createAction, signActionV2 } from "@powerhousedao/shared/document-model";
|
|
5
|
+
import { fromString, toString } from "uint8arrays";
|
|
5
6
|
//#region src/discovery.ts
|
|
6
7
|
const DEFAULT_DISCOVERY_TIMEOUT_MS = 3e3;
|
|
7
8
|
async function resolveSwitchboardEndpoint(options) {
|
|
@@ -85,11 +86,11 @@ const USERS_QUERY = `
|
|
|
85
86
|
const CREATE_EMPTY_DOCUMENT_MUTATION = `
|
|
86
87
|
mutation CreateEmptyDocument(
|
|
87
88
|
$documentType: String!
|
|
88
|
-
$
|
|
89
|
+
$parentIdOrSlug: String
|
|
89
90
|
) {
|
|
90
91
|
createEmptyDocument(
|
|
91
92
|
documentType: $documentType
|
|
92
|
-
|
|
93
|
+
parentIdOrSlug: $parentIdOrSlug
|
|
93
94
|
) {
|
|
94
95
|
id
|
|
95
96
|
}
|
|
@@ -97,11 +98,11 @@ const CREATE_EMPTY_DOCUMENT_MUTATION = `
|
|
|
97
98
|
`;
|
|
98
99
|
const MUTATE_DOCUMENT_MUTATION = `
|
|
99
100
|
mutation MutateDocument(
|
|
100
|
-
$
|
|
101
|
+
$documentIdOrSlug: String!
|
|
101
102
|
$actions: [ActionInput!]!
|
|
102
103
|
) {
|
|
103
104
|
mutateDocument: execute(
|
|
104
|
-
|
|
105
|
+
documentIdOrSlug: $documentIdOrSlug
|
|
105
106
|
actions: $actions
|
|
106
107
|
) {
|
|
107
108
|
id
|
|
@@ -325,23 +326,25 @@ var SwitchboardClient = class {
|
|
|
325
326
|
async createEmptyDocument(documentType, parentIdentifier, token) {
|
|
326
327
|
const { createEmptyDocument } = await this.#request(CREATE_EMPTY_DOCUMENT_MUTATION, {
|
|
327
328
|
documentType,
|
|
328
|
-
parentIdentifier
|
|
329
|
+
parentIdOrSlug: parentIdentifier
|
|
329
330
|
}, token);
|
|
330
331
|
return createEmptyDocument.id;
|
|
331
332
|
}
|
|
332
333
|
async mutateDocument(documentIdentifier, actions, token) {
|
|
333
|
-
const variables = {
|
|
334
|
-
documentIdentifier,
|
|
335
|
-
actions
|
|
336
|
-
};
|
|
337
334
|
if (!this.#legacyMutate) try {
|
|
338
|
-
const { mutateDocument } = await this.#request(MUTATE_DOCUMENT_MUTATION,
|
|
335
|
+
const { mutateDocument } = await this.#request(MUTATE_DOCUMENT_MUTATION, {
|
|
336
|
+
documentIdOrSlug: documentIdentifier,
|
|
337
|
+
actions
|
|
338
|
+
}, token);
|
|
339
339
|
return mutateDocument.id;
|
|
340
340
|
} catch (error) {
|
|
341
341
|
if (!isUnknownExecuteField(error)) throw error;
|
|
342
342
|
this.#legacyMutate = true;
|
|
343
343
|
}
|
|
344
|
-
const { mutateDocument } = await this.#request(LEGACY_MUTATE_DOCUMENT_MUTATION,
|
|
344
|
+
const { mutateDocument } = await this.#request(LEGACY_MUTATE_DOCUMENT_MUTATION, {
|
|
345
|
+
documentIdentifier,
|
|
346
|
+
actions
|
|
347
|
+
}, token);
|
|
345
348
|
return mutateDocument.id;
|
|
346
349
|
}
|
|
347
350
|
async issueCredential(credential, parentIdentifier) {
|
|
@@ -541,8 +544,7 @@ async function fetchDelegationCredentialRest(params) {
|
|
|
541
544
|
if (!response.ok) return void 0;
|
|
542
545
|
const { credential } = await response.json();
|
|
543
546
|
if (!credential) return void 0;
|
|
544
|
-
|
|
545
|
-
if (credential.credentialSubject.id !== appDid || issuerChainId !== String(chainId) || issuerAddress.toLowerCase() !== address.toLowerCase() || credential.issuer.ethereumAddress.toLowerCase() !== address.toLowerCase()) return;
|
|
547
|
+
if (!credentialIssuedTo(credential, address, chainId, appDid)) return;
|
|
546
548
|
if (credential.expirationDate) {
|
|
547
549
|
const expiresAt = Date.parse(credential.expirationDate);
|
|
548
550
|
if (Number.isNaN(expiresAt) || expiresAt <= Date.now()) return;
|
|
@@ -582,6 +584,72 @@ async function fetchDelegationCredential(options) {
|
|
|
582
584
|
return;
|
|
583
585
|
}
|
|
584
586
|
}
|
|
587
|
+
const DEFAULT_CHECK_TIMEOUT_MS = 5e3;
|
|
588
|
+
function credentialIssuedTo(credential, address, chainId, appDid) {
|
|
589
|
+
const [, , , issuerChainId, issuerAddress] = credential.issuer.id.split(":");
|
|
590
|
+
return credential.credentialSubject.id === appDid && issuerChainId === String(chainId) && issuerAddress?.toLowerCase() === address.toLowerCase() && credential.issuer.ethereumAddress.toLowerCase() === address.toLowerCase();
|
|
591
|
+
}
|
|
592
|
+
function goneStatus(expirationDate) {
|
|
593
|
+
if (!expirationDate) return "revoked";
|
|
594
|
+
const expiresAt = Date.parse(expirationDate);
|
|
595
|
+
return !Number.isNaN(expiresAt) && expiresAt <= Date.now() ? "expired" : "revoked";
|
|
596
|
+
}
|
|
597
|
+
async function checkOverRest(options, baseUrl) {
|
|
598
|
+
const { address, chainId, appDid, expirationDate } = options;
|
|
599
|
+
const url = new URL(`/api/auth/credential?address=${encodeURIComponent(address)}&chainId=${encodeURIComponent(chainId)}&connectId=${encodeURIComponent(appDid)}&appId=${encodeURIComponent(appDid)}`, baseUrl);
|
|
600
|
+
const response = await fetch(url, {
|
|
601
|
+
method: "GET",
|
|
602
|
+
signal: AbortSignal.timeout(options.timeoutMs ?? DEFAULT_CHECK_TIMEOUT_MS)
|
|
603
|
+
});
|
|
604
|
+
if (!response.ok && response.status !== 404) return { status: "unknown" };
|
|
605
|
+
const body = await response.json().catch(() => void 0);
|
|
606
|
+
if (!body) return { status: "unknown" };
|
|
607
|
+
if (!body.credential) return { status: goneStatus(expirationDate) };
|
|
608
|
+
return {
|
|
609
|
+
status: "active",
|
|
610
|
+
credential: body.credential
|
|
611
|
+
};
|
|
612
|
+
}
|
|
613
|
+
async function checkOverSwitchboard(options, source) {
|
|
614
|
+
const { address, chainId, appDid, expirationDate } = options;
|
|
615
|
+
const client = new SwitchboardClient(source);
|
|
616
|
+
const credential = await client.getCredential({
|
|
617
|
+
address,
|
|
618
|
+
chainId,
|
|
619
|
+
appDid
|
|
620
|
+
});
|
|
621
|
+
if (credential) return {
|
|
622
|
+
status: "active",
|
|
623
|
+
credential
|
|
624
|
+
};
|
|
625
|
+
const issued = await client.getIssuedCredentials({
|
|
626
|
+
address,
|
|
627
|
+
chainId,
|
|
628
|
+
appDid
|
|
629
|
+
});
|
|
630
|
+
if (issued.length === 0 && !expirationDate) return { status: "unknown" };
|
|
631
|
+
return { status: goneStatus(issued.map((row) => row.expirationDate).filter((date) => Boolean(date)).sort().at(-1) ?? expirationDate) };
|
|
632
|
+
}
|
|
633
|
+
/**
|
|
634
|
+
* Asks Renown about a credential, keeping "no" apart from "no answer". Never
|
|
635
|
+
* throws. Used where a definite answer stops something, unlike
|
|
636
|
+
* {@link fetchDelegationCredential}, which reads both as undefined.
|
|
637
|
+
*/
|
|
638
|
+
async function checkDelegationCredential(options) {
|
|
639
|
+
const source = options.switchboardRequest ?? options.switchboardUrl;
|
|
640
|
+
try {
|
|
641
|
+
const check = source ? await checkOverSwitchboard(options, source) : await checkOverRest(options, options.baseUrl ?? "https://www.renown.id");
|
|
642
|
+
if (check.status !== "active" || !check.credential) return check;
|
|
643
|
+
const { address, chainId, appDid } = options;
|
|
644
|
+
const verified = credentialIssuedTo(check.credential, address, chainId, appDid) ? await finalizeCredential(check.credential, chainId, true) : void 0;
|
|
645
|
+
return verified ? {
|
|
646
|
+
status: "active",
|
|
647
|
+
credential: verified
|
|
648
|
+
} : { status: "unknown" };
|
|
649
|
+
} catch {
|
|
650
|
+
return { status: "unknown" };
|
|
651
|
+
}
|
|
652
|
+
}
|
|
585
653
|
async function verifyAuthCredential(jwt, options = {}) {
|
|
586
654
|
const verified = await verifyAuthBearerToken(jwt, { audience: options.audience });
|
|
587
655
|
if (!verified) return void 0;
|
|
@@ -607,6 +675,200 @@ async function verifyAuthCredential(jwt, options = {}) {
|
|
|
607
675
|
};
|
|
608
676
|
}
|
|
609
677
|
//#endregion
|
|
678
|
+
//#region src/delegation.ts
|
|
679
|
+
/** The tag of the `signatures` entry holding a statement, and of its binding. */
|
|
680
|
+
const DELEGATION_TAG = "dlg1";
|
|
681
|
+
/** Keeps a statement apart from the bearer tokens the same key signs. */
|
|
682
|
+
const DELEGATION_JWT_TYPE = "ph-delegation+jwt";
|
|
683
|
+
/** What a statement may name in this version. Nothing wider is accepted. */
|
|
684
|
+
const DELEGABLE_OPERATIONS = ["PUBLISH_WORKFLOW"];
|
|
685
|
+
const DEFAULT_LIFETIME_SECONDS = 2592e3;
|
|
686
|
+
/** How far the browser's clock at issuance may run ahead of the signing tuple. */
|
|
687
|
+
const ISSUED_AT_TOLERANCE_SECONDS = 300;
|
|
688
|
+
const BINDING_PREFIX = `${DELEGATION_TAG}-`;
|
|
689
|
+
/**
|
|
690
|
+
* Signs a statement naming `delegate`, with no wallet step: the session key
|
|
691
|
+
* signs it, and the statement carries the credential so it verifies offline.
|
|
692
|
+
*/
|
|
693
|
+
async function createDelegation(params) {
|
|
694
|
+
const { issuer, credential, delegate, environment, scope, lifetimeSeconds = DEFAULT_LIFETIME_SECONDS, now = Math.floor(Date.now() / 1e3) } = params;
|
|
695
|
+
const claims = {
|
|
696
|
+
iss: issuer.did,
|
|
697
|
+
aud: delegate,
|
|
698
|
+
sub: credential.issuer.id,
|
|
699
|
+
env: environment,
|
|
700
|
+
scp: scope,
|
|
701
|
+
iat: now,
|
|
702
|
+
exp: now + lifetimeSeconds,
|
|
703
|
+
jti: globalThis.crypto.randomUUID(),
|
|
704
|
+
prf: credential
|
|
705
|
+
};
|
|
706
|
+
const signingInput = [encodeSegment({
|
|
707
|
+
alg: "ES256",
|
|
708
|
+
typ: DELEGATION_JWT_TYPE
|
|
709
|
+
}), encodeSegment(claims)].join(".");
|
|
710
|
+
const signature = await issuer.signer(signingInput);
|
|
711
|
+
if (typeof signature !== "string") throw new Error("A delegation issuer must sign as base64url");
|
|
712
|
+
return `${signingInput}.${signature}`;
|
|
713
|
+
}
|
|
714
|
+
/** The statement's claims, unverified; undefined when it does not parse. */
|
|
715
|
+
function decodeDelegation(statement) {
|
|
716
|
+
const [, payload] = statement.split(".");
|
|
717
|
+
if (!payload) return void 0;
|
|
718
|
+
try {
|
|
719
|
+
const claims = JSON.parse(toString(fromString(payload, "base64url")));
|
|
720
|
+
return isClaims(claims) ? claims : void 0;
|
|
721
|
+
} catch {
|
|
722
|
+
return;
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
/**
|
|
726
|
+
* Whether `statement` lets `key` sign this action as `user`. Offline and pure:
|
|
727
|
+
* every replica reaches the same verdict at any time, so an old operation
|
|
728
|
+
* verifies forever. The credential's own dates are not read: link one is judged
|
|
729
|
+
* at issuance, and a credential outliving its seven days must not end a delegate.
|
|
730
|
+
*/
|
|
731
|
+
async function verifyDelegation(statement, params) {
|
|
732
|
+
const { user, key, signedAt, actionType } = params;
|
|
733
|
+
const parts = statement.split(".");
|
|
734
|
+
if (parts.length !== 3) return refuse("is not a compact JWS");
|
|
735
|
+
const claims = decodeDelegation(statement);
|
|
736
|
+
if (!claims) return refuse("has malformed claims");
|
|
737
|
+
const header = decodeHeader(parts[0]);
|
|
738
|
+
if (header?.alg !== "ES256" || header.typ !== "ph-delegation+jwt") return refuse("has the wrong header");
|
|
739
|
+
if (!await signedBy(claims.iss, parts)) return refuse("is not signed by its issuer");
|
|
740
|
+
if (!samePerson(claims.sub, user)) return refuse(`does not name ${user.address}`);
|
|
741
|
+
if (claims.aud !== key) return refuse(`names ${claims.aud}, not the signing key ${key}`);
|
|
742
|
+
if (!await chainsToPerson(claims, user)) return refuse("has no credential binding its issuer to the person");
|
|
743
|
+
const scopeProblem = scopeRefusal(claims.scp, actionType);
|
|
744
|
+
if (scopeProblem) return refuse(scopeProblem);
|
|
745
|
+
if (signedAt < claims.iat - ISSUED_AT_TOLERANCE_SECONDS || signedAt >= claims.exp) return refuse("does not cover the time the action was signed");
|
|
746
|
+
return {
|
|
747
|
+
ok: true,
|
|
748
|
+
claims
|
|
749
|
+
};
|
|
750
|
+
}
|
|
751
|
+
/** What `signer` carries of a delegation; undefined when it carries nothing. */
|
|
752
|
+
function delegationOf(signer) {
|
|
753
|
+
const signatures = signer.signatures;
|
|
754
|
+
const tuple = signatures?.at(-1);
|
|
755
|
+
if (!signatures || !tuple) return void 0;
|
|
756
|
+
const statements = signatures.slice(0, -1).filter((entry) => entry[0] === DELEGATION_TAG).map((entry) => entry[3]);
|
|
757
|
+
const binding = tuple[3]?.startsWith(BINDING_PREFIX) ? tuple[3] : void 0;
|
|
758
|
+
if (statements.length === 0 && binding === void 0) return void 0;
|
|
759
|
+
return {
|
|
760
|
+
...statements.length === 1 ? { statement: statements[0] } : {},
|
|
761
|
+
...binding !== void 0 ? { binding } : {},
|
|
762
|
+
signedAt: Number(tuple[0])
|
|
763
|
+
};
|
|
764
|
+
}
|
|
765
|
+
/** Why what `signer` carries does not stand as bound; undefined when it does. */
|
|
766
|
+
async function bindingRefusal(carried) {
|
|
767
|
+
if (carried.statement === void 0) return "the signing tuple names a statement the action does not carry";
|
|
768
|
+
if (carried.binding === void 0) return "the signing tuple does not cover the statement";
|
|
769
|
+
if (carried.binding !== await delegationBinding(carried.statement)) return "the signing tuple covers a different statement";
|
|
770
|
+
}
|
|
771
|
+
/** What the signing tuple's element [3] holds, so the signature covers the statement. */
|
|
772
|
+
async function delegationBinding(statement) {
|
|
773
|
+
const digest = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(statement));
|
|
774
|
+
return BINDING_PREFIX + toString(new Uint8Array(digest), "base64url");
|
|
775
|
+
}
|
|
776
|
+
/**
|
|
777
|
+
* Signs `action` as the person, carrying the statement in an earlier entry of
|
|
778
|
+
* `signatures`. The reactor leaves an action already signed under a key as it
|
|
779
|
+
* is, so this goes through any client.
|
|
780
|
+
*/
|
|
781
|
+
async function signDelegatedAction(params) {
|
|
782
|
+
const { action, target, crypto, appName, user, statement } = params;
|
|
783
|
+
const identity = actionSignerIdentity({
|
|
784
|
+
user,
|
|
785
|
+
app: {
|
|
786
|
+
name: appName,
|
|
787
|
+
key: crypto.did
|
|
788
|
+
}
|
|
789
|
+
});
|
|
790
|
+
const tuple = await signActionV2({
|
|
791
|
+
action,
|
|
792
|
+
target,
|
|
793
|
+
signer: identity,
|
|
794
|
+
sign: (message) => crypto.sign(message),
|
|
795
|
+
previousStateHash: await delegationBinding(statement)
|
|
796
|
+
});
|
|
797
|
+
const issuer = decodeDelegation(statement)?.iss ?? "";
|
|
798
|
+
const entry = [
|
|
799
|
+
DELEGATION_TAG,
|
|
800
|
+
issuer,
|
|
801
|
+
"",
|
|
802
|
+
statement,
|
|
803
|
+
""
|
|
804
|
+
];
|
|
805
|
+
return {
|
|
806
|
+
...action,
|
|
807
|
+
context: {
|
|
808
|
+
...action.context,
|
|
809
|
+
signer: {
|
|
810
|
+
...identity,
|
|
811
|
+
signatures: [entry, tuple]
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
};
|
|
815
|
+
}
|
|
816
|
+
function refuse(reason) {
|
|
817
|
+
return {
|
|
818
|
+
ok: false,
|
|
819
|
+
reason: `the statement ${reason}`
|
|
820
|
+
};
|
|
821
|
+
}
|
|
822
|
+
function encodeSegment(value) {
|
|
823
|
+
return toString(fromString(JSON.stringify(value)), "base64url");
|
|
824
|
+
}
|
|
825
|
+
function decodeHeader(segment) {
|
|
826
|
+
try {
|
|
827
|
+
return JSON.parse(toString(fromString(segment, "base64url")));
|
|
828
|
+
} catch {
|
|
829
|
+
return;
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
function isClaims(value) {
|
|
833
|
+
return !!value && typeof value.iss === "string" && typeof value.aud === "string" && typeof value.sub === "string" && typeof value.env === "string" && typeof value.iat === "number" && typeof value.exp === "number" && typeof value.jti === "string" && typeof value.scp === "object" && value.scp !== null && typeof value.prf === "object" && value.prf !== null;
|
|
834
|
+
}
|
|
835
|
+
async function signedBy(issuer, parts) {
|
|
836
|
+
try {
|
|
837
|
+
const key = await importDidPublicKey(issuer);
|
|
838
|
+
return await globalThis.crypto.subtle.verify({
|
|
839
|
+
name: "ECDSA",
|
|
840
|
+
hash: "SHA-256"
|
|
841
|
+
}, key, new Uint8Array(fromString(parts[2], "base64url")), new TextEncoder().encode(`${parts[0]}.${parts[1]}`));
|
|
842
|
+
} catch {
|
|
843
|
+
return false;
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
function samePerson(subject, user) {
|
|
847
|
+
try {
|
|
848
|
+
const person = parsePkhDid(subject);
|
|
849
|
+
return person.address.toLowerCase() === user.address.toLowerCase() && person.networkId === user.networkId && person.chainId === user.chainId;
|
|
850
|
+
} catch {
|
|
851
|
+
return false;
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
/** Link one: the credential in `prf` binds the person to the statement's issuer. */
|
|
855
|
+
async function chainsToPerson(claims, user) {
|
|
856
|
+
const credential = claims.prf;
|
|
857
|
+
const address = user.address.toLowerCase();
|
|
858
|
+
try {
|
|
859
|
+
if (credential.credentialSubject.id !== claims.iss || credential.issuer.id !== claims.sub || credential.issuer.ethereumAddress.toLowerCase() !== address) return false;
|
|
860
|
+
return await verifyDelegationProof(credential, user.chainId);
|
|
861
|
+
} catch {
|
|
862
|
+
return false;
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
function scopeRefusal(scope, actionType) {
|
|
866
|
+
if (!Array.isArray(scope.ops) || scope.ops.length === 0) return "names no operations";
|
|
867
|
+
const wider = scope.ops.find((op) => !DELEGABLE_OPERATIONS.includes(op));
|
|
868
|
+
if (wider !== void 0) return `names ${wider}, which cannot be delegated`;
|
|
869
|
+
if (!scope.ops.includes(actionType)) return `does not cover ${actionType}`;
|
|
870
|
+
}
|
|
871
|
+
//#endregion
|
|
610
872
|
//#region src/signer-trust.ts
|
|
611
873
|
const DEFAULT_MAX_ACCEPTED = 1e4;
|
|
612
874
|
const DEFAULT_REFUSAL_TTL_MS = 6e4;
|
|
@@ -614,6 +876,10 @@ const DEFAULT_REFUSAL_TTL_MS = 6e4;
|
|
|
614
876
|
* Accepts a key the user's EIP-712 Renown credential delegates to, ignoring
|
|
615
877
|
* expiry and revocation. Verdicts are cached per (address, key); this node's
|
|
616
878
|
* own key is checked before the cache and never cached.
|
|
879
|
+
*
|
|
880
|
+
* A signer carrying a delegation is verified from what it carries, with no
|
|
881
|
+
* lookup and no cache: the verdict depends on the statement, not on (address,
|
|
882
|
+
* key). `options.delegationOnly` accepts every other signer.
|
|
617
883
|
*/
|
|
618
884
|
function createRenownTrustPolicy(options = {}) {
|
|
619
885
|
const maxAccepted = options.maxAccepted ?? DEFAULT_MAX_ACCEPTED;
|
|
@@ -642,10 +908,13 @@ function createRenownTrustPolicy(options = {}) {
|
|
|
642
908
|
refusedUntil.delete(entry);
|
|
643
909
|
} else refusedUntil.set(entry, Date.now() + refusalTtlMs);
|
|
644
910
|
}
|
|
645
|
-
return { authorizeSigner(signer, key) {
|
|
911
|
+
return { authorizeSigner(signer, key, _documentId, context) {
|
|
646
912
|
const user = signer.user;
|
|
647
913
|
const self = ownIdentity(options);
|
|
648
914
|
if (self && isSelf(self, user, key)) return Promise.resolve(true);
|
|
915
|
+
const carried = delegationOf(signer);
|
|
916
|
+
if (carried) return authorizeDelegated(carried, user, key, self?.key, context);
|
|
917
|
+
if (options.delegationOnly) return Promise.resolve(true);
|
|
649
918
|
if (!user || !isLookupable(user, key)) return Promise.resolve(false);
|
|
650
919
|
const entry = `${user.networkId}|${user.chainId}|${user.address.toLowerCase()}|${key}`;
|
|
651
920
|
if (accepted.has(entry)) return Promise.resolve(true);
|
|
@@ -665,6 +934,23 @@ function createRenownTrustPolicy(options = {}) {
|
|
|
665
934
|
return verdict;
|
|
666
935
|
} };
|
|
667
936
|
}
|
|
937
|
+
/**
|
|
938
|
+
* The statement alone decides, so every replica agrees and no network is
|
|
939
|
+
* needed. The one exception is `env`, checked only at first write: peers
|
|
940
|
+
* receive these operations legitimately on load.
|
|
941
|
+
*/
|
|
942
|
+
async function authorizeDelegated(carried, user, key, ownKey, context) {
|
|
943
|
+
if (!user || !context || carried.statement === void 0) return false;
|
|
944
|
+
if (await bindingRefusal(carried) !== void 0) return false;
|
|
945
|
+
const verdict = await verifyDelegation(carried.statement, {
|
|
946
|
+
user,
|
|
947
|
+
key,
|
|
948
|
+
signedAt: carried.signedAt,
|
|
949
|
+
actionType: context.actionType
|
|
950
|
+
});
|
|
951
|
+
if (!verdict.ok) return false;
|
|
952
|
+
return context.path === "load" || verdict.claims.env === ownKey;
|
|
953
|
+
}
|
|
668
954
|
function ownIdentity(options) {
|
|
669
955
|
if (!options.ownSigner) return options.self;
|
|
670
956
|
const { app, user } = options.ownSigner;
|
|
@@ -703,6 +989,6 @@ async function fetchIssuedCredentialRest(user, key, renownUrl) {
|
|
|
703
989
|
return credential ? [credential] : [];
|
|
704
990
|
}
|
|
705
991
|
//#endregion
|
|
706
|
-
export {
|
|
992
|
+
export { verifyCredentialSignature as _, bindingRefusal as a, SwitchboardClient as b, delegationBinding as c, verifyDelegation as d, buildAndSignCredential as f, verifyAuthCredential as g, recoverCredentialSigner as h, DELEGATION_TAG as i, delegationOf as l, fetchDelegationCredential as m, DELEGABLE_OPERATIONS as n, createDelegation as o, checkDelegationCredential as p, DELEGATION_JWT_TYPE as r, decodeDelegation as s, createRenownTrustPolicy as t, signDelegatedAction as u, verifyDelegationProof as v, resolveSwitchboardEndpoint as x, MissingSwitchboardError as y };
|
|
707
993
|
|
|
708
|
-
//# sourceMappingURL=signer-trust-
|
|
994
|
+
//# sourceMappingURL=signer-trust-vhUCCmfg.js.map
|