@renown/sdk 6.2.3-dev.89 → 6.2.3-dev.90

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.
Files changed (51) hide show
  1. package/dist/crypto.d.ts +2 -2
  2. package/dist/crypto.js +2 -1
  3. package/dist/{index-DbiBjqs6.d.ts → index-Bf53Cq6x.d.ts} +2 -2
  4. package/dist/{index-DbiBjqs6.d.ts.map → index-Bf53Cq6x.d.ts.map} +1 -1
  5. package/dist/index.d.ts +5 -5
  6. package/dist/index.js +5 -5
  7. package/dist/memory-key-storage-CVVAWWS4.js +145 -0
  8. package/dist/memory-key-storage-CVVAWWS4.js.map +1 -0
  9. package/dist/{meta-Dpmn2Ywp.d.ts → meta-Co-vmMo-.d.ts} +2 -2
  10. package/dist/{meta-Dpmn2Ywp.d.ts.map → meta-Co-vmMo-.d.ts.map} +1 -1
  11. package/dist/{meta-qadFdiX7.d.ts → meta-ScD9zeLt.d.ts} +2 -2
  12. package/dist/{meta-qadFdiX7.d.ts.map → meta-ScD9zeLt.d.ts.map} +1 -1
  13. package/dist/node.d.ts +5 -5
  14. package/dist/node.d.ts.map +1 -1
  15. package/dist/node.js +14 -64
  16. package/dist/node.js.map +1 -1
  17. package/dist/{signed-message-Cp5oRPLN.js → signed-message-DuAelefH.js} +94 -6
  18. package/dist/signed-message-DuAelefH.js.map +1 -0
  19. package/dist/{signer-GzTlZLjR.js → signer-9gB5YUMp.js} +70 -139
  20. package/dist/signer-9gB5YUMp.js.map +1 -0
  21. package/dist/signer-trust-B4XTKeZ2.d.ts +170 -0
  22. package/dist/signer-trust-B4XTKeZ2.d.ts.map +1 -0
  23. package/dist/{signer-trust-H1rNzUcd.js → signer-trust-aVg9lYAn.js} +291 -7
  24. package/dist/signer-trust-aVg9lYAn.js.map +1 -0
  25. package/dist/trust.d.ts +2 -2
  26. package/dist/trust.js +2 -2
  27. package/dist/{types-DRnq2URw.d.ts → types-BmdG67IZ.d.ts} +2 -2
  28. package/dist/{types-DRnq2URw.d.ts.map → types-BmdG67IZ.d.ts.map} +1 -1
  29. package/dist/{types-7xgrEnx7.d.ts → types-CfSRJMyb.d.ts} +2 -2
  30. package/dist/{types-7xgrEnx7.d.ts.map → types-CfSRJMyb.d.ts.map} +1 -1
  31. package/dist/{types-Ceiz2dkk.d.ts → types-CplBDMtV.d.ts} +43 -2
  32. package/dist/types-CplBDMtV.d.ts.map +1 -0
  33. package/dist/{utils-DkVxP7Ug.d.ts → utils-K2mtcxhD.d.ts} +35 -4
  34. package/dist/utils-K2mtcxhD.d.ts.map +1 -0
  35. package/dist/wallet/index.d.ts +1 -1
  36. package/dist/wallet/mock/factory.d.ts +2 -2
  37. package/dist/wallet/mock/index.d.ts +2 -2
  38. package/dist/wallet/privy/factory.d.ts +3 -3
  39. package/dist/wallet/privy/index.d.ts +2 -2
  40. package/dist/wallet/rainbow/factory.d.ts +2 -2
  41. package/dist/wallet/rainbow/index.d.ts +2 -2
  42. package/package.json +2 -2
  43. package/dist/signed-message-Cp5oRPLN.js.map +0 -1
  44. package/dist/signer-GzTlZLjR.js.map +0 -1
  45. package/dist/signer-trust-FmbMTn39.d.ts +0 -53
  46. package/dist/signer-trust-FmbMTn39.d.ts.map +0 -1
  47. package/dist/signer-trust-H1rNzUcd.js.map +0 -1
  48. package/dist/types-Ceiz2dkk.d.ts.map +0 -1
  49. package/dist/utils-DLQ5VVqT.js +0 -75
  50. package/dist/utils-DLQ5VVqT.js.map +0 -1
  51. 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,MAA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T;;;;;;;;;;;AAYA,SAAgB,wBAAwB,WAGtC;CACA,MAAM,aAAa,UAAU,QAAQ,GAAG;CAExC,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 { a as verifyAuthBearerToken } from "./utils-DLQ5VVqT.js";
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) {
@@ -541,8 +542,7 @@ async function fetchDelegationCredentialRest(params) {
541
542
  if (!response.ok) return void 0;
542
543
  const { credential } = await response.json();
543
544
  if (!credential) return void 0;
544
- const [, , , issuerChainId, issuerAddress] = credential.issuer.id.split(":");
545
- if (credential.credentialSubject.id !== appDid || issuerChainId !== String(chainId) || issuerAddress.toLowerCase() !== address.toLowerCase() || credential.issuer.ethereumAddress.toLowerCase() !== address.toLowerCase()) return;
545
+ if (!credentialIssuedTo(credential, address, chainId, appDid)) return;
546
546
  if (credential.expirationDate) {
547
547
  const expiresAt = Date.parse(credential.expirationDate);
548
548
  if (Number.isNaN(expiresAt) || expiresAt <= Date.now()) return;
@@ -582,6 +582,72 @@ async function fetchDelegationCredential(options) {
582
582
  return;
583
583
  }
584
584
  }
585
+ const DEFAULT_CHECK_TIMEOUT_MS = 5e3;
586
+ function credentialIssuedTo(credential, address, chainId, appDid) {
587
+ const [, , , issuerChainId, issuerAddress] = credential.issuer.id.split(":");
588
+ return credential.credentialSubject.id === appDid && issuerChainId === String(chainId) && issuerAddress?.toLowerCase() === address.toLowerCase() && credential.issuer.ethereumAddress.toLowerCase() === address.toLowerCase();
589
+ }
590
+ function goneStatus(expirationDate) {
591
+ if (!expirationDate) return "revoked";
592
+ const expiresAt = Date.parse(expirationDate);
593
+ return !Number.isNaN(expiresAt) && expiresAt <= Date.now() ? "expired" : "revoked";
594
+ }
595
+ async function checkOverRest(options, baseUrl) {
596
+ const { address, chainId, appDid, expirationDate } = options;
597
+ const url = new URL(`/api/auth/credential?address=${encodeURIComponent(address)}&chainId=${encodeURIComponent(chainId)}&connectId=${encodeURIComponent(appDid)}&appId=${encodeURIComponent(appDid)}`, baseUrl);
598
+ const response = await fetch(url, {
599
+ method: "GET",
600
+ signal: AbortSignal.timeout(options.timeoutMs ?? DEFAULT_CHECK_TIMEOUT_MS)
601
+ });
602
+ if (!response.ok && response.status !== 404) return { status: "unknown" };
603
+ const body = await response.json().catch(() => void 0);
604
+ if (!body) return { status: "unknown" };
605
+ if (!body.credential) return { status: goneStatus(expirationDate) };
606
+ return {
607
+ status: "active",
608
+ credential: body.credential
609
+ };
610
+ }
611
+ async function checkOverSwitchboard(options, source) {
612
+ const { address, chainId, appDid, expirationDate } = options;
613
+ const client = new SwitchboardClient(source);
614
+ const credential = await client.getCredential({
615
+ address,
616
+ chainId,
617
+ appDid
618
+ });
619
+ if (credential) return {
620
+ status: "active",
621
+ credential
622
+ };
623
+ const issued = await client.getIssuedCredentials({
624
+ address,
625
+ chainId,
626
+ appDid
627
+ });
628
+ if (issued.length === 0 && !expirationDate) return { status: "unknown" };
629
+ return { status: goneStatus(issued.map((row) => row.expirationDate).filter((date) => Boolean(date)).sort().at(-1) ?? expirationDate) };
630
+ }
631
+ /**
632
+ * Asks Renown about a credential, keeping "no" apart from "no answer". Never
633
+ * throws. Used where a definite answer stops something, unlike
634
+ * {@link fetchDelegationCredential}, which reads both as undefined.
635
+ */
636
+ async function checkDelegationCredential(options) {
637
+ const source = options.switchboardRequest ?? options.switchboardUrl;
638
+ try {
639
+ const check = source ? await checkOverSwitchboard(options, source) : await checkOverRest(options, options.baseUrl ?? "https://www.renown.id");
640
+ if (check.status !== "active" || !check.credential) return check;
641
+ const { address, chainId, appDid } = options;
642
+ const verified = credentialIssuedTo(check.credential, address, chainId, appDid) ? await finalizeCredential(check.credential, chainId, true) : void 0;
643
+ return verified ? {
644
+ status: "active",
645
+ credential: verified
646
+ } : { status: "unknown" };
647
+ } catch {
648
+ return { status: "unknown" };
649
+ }
650
+ }
585
651
  async function verifyAuthCredential(jwt, options = {}) {
586
652
  const verified = await verifyAuthBearerToken(jwt, { audience: options.audience });
587
653
  if (!verified) return void 0;
@@ -607,6 +673,200 @@ async function verifyAuthCredential(jwt, options = {}) {
607
673
  };
608
674
  }
609
675
  //#endregion
676
+ //#region src/delegation.ts
677
+ /** The tag of the `signatures` entry holding a statement, and of its binding. */
678
+ const DELEGATION_TAG = "dlg1";
679
+ /** Keeps a statement apart from the bearer tokens the same key signs. */
680
+ const DELEGATION_JWT_TYPE = "ph-delegation+jwt";
681
+ /** What a statement may name in this version. Nothing wider is accepted. */
682
+ const DELEGABLE_OPERATIONS = ["PUBLISH_WORKFLOW"];
683
+ const DEFAULT_LIFETIME_SECONDS = 2592e3;
684
+ /** How far the browser's clock at issuance may run ahead of the signing tuple. */
685
+ const ISSUED_AT_TOLERANCE_SECONDS = 300;
686
+ const BINDING_PREFIX = `${DELEGATION_TAG}-`;
687
+ /**
688
+ * Signs a statement naming `delegate`, with no wallet step: the session key
689
+ * signs it, and the statement carries the credential so it verifies offline.
690
+ */
691
+ async function createDelegation(params) {
692
+ const { issuer, credential, delegate, environment, scope, lifetimeSeconds = DEFAULT_LIFETIME_SECONDS, now = Math.floor(Date.now() / 1e3) } = params;
693
+ const claims = {
694
+ iss: issuer.did,
695
+ aud: delegate,
696
+ sub: credential.issuer.id,
697
+ env: environment,
698
+ scp: scope,
699
+ iat: now,
700
+ exp: now + lifetimeSeconds,
701
+ jti: globalThis.crypto.randomUUID(),
702
+ prf: credential
703
+ };
704
+ const signingInput = [encodeSegment({
705
+ alg: "ES256",
706
+ typ: DELEGATION_JWT_TYPE
707
+ }), encodeSegment(claims)].join(".");
708
+ const signature = await issuer.signer(signingInput);
709
+ if (typeof signature !== "string") throw new Error("A delegation issuer must sign as base64url");
710
+ return `${signingInput}.${signature}`;
711
+ }
712
+ /** The statement's claims, unverified; undefined when it does not parse. */
713
+ function decodeDelegation(statement) {
714
+ const [, payload] = statement.split(".");
715
+ if (!payload) return void 0;
716
+ try {
717
+ const claims = JSON.parse(toString(fromString(payload, "base64url")));
718
+ return isClaims(claims) ? claims : void 0;
719
+ } catch {
720
+ return;
721
+ }
722
+ }
723
+ /**
724
+ * Whether `statement` lets `key` sign this action as `user`. Offline and pure:
725
+ * every replica reaches the same verdict at any time, so an old operation
726
+ * verifies forever. The credential's own dates are not read: link one is judged
727
+ * at issuance, and a credential outliving its seven days must not end a delegate.
728
+ */
729
+ async function verifyDelegation(statement, params) {
730
+ const { user, key, signedAt, actionType } = params;
731
+ const parts = statement.split(".");
732
+ if (parts.length !== 3) return refuse("is not a compact JWS");
733
+ const claims = decodeDelegation(statement);
734
+ if (!claims) return refuse("has malformed claims");
735
+ const header = decodeHeader(parts[0]);
736
+ if (header?.alg !== "ES256" || header.typ !== "ph-delegation+jwt") return refuse("has the wrong header");
737
+ if (!await signedBy(claims.iss, parts)) return refuse("is not signed by its issuer");
738
+ if (!samePerson(claims.sub, user)) return refuse(`does not name ${user.address}`);
739
+ if (claims.aud !== key) return refuse(`names ${claims.aud}, not the signing key ${key}`);
740
+ if (!await chainsToPerson(claims, user)) return refuse("has no credential binding its issuer to the person");
741
+ const scopeProblem = scopeRefusal(claims.scp, actionType);
742
+ if (scopeProblem) return refuse(scopeProblem);
743
+ if (signedAt < claims.iat - ISSUED_AT_TOLERANCE_SECONDS || signedAt >= claims.exp) return refuse("does not cover the time the action was signed");
744
+ return {
745
+ ok: true,
746
+ claims
747
+ };
748
+ }
749
+ /** What `signer` carries of a delegation; undefined when it carries nothing. */
750
+ function delegationOf(signer) {
751
+ const signatures = signer.signatures;
752
+ const tuple = signatures?.at(-1);
753
+ if (!signatures || !tuple) return void 0;
754
+ const statements = signatures.slice(0, -1).filter((entry) => entry[0] === DELEGATION_TAG).map((entry) => entry[3]);
755
+ const binding = tuple[3]?.startsWith(BINDING_PREFIX) ? tuple[3] : void 0;
756
+ if (statements.length === 0 && binding === void 0) return void 0;
757
+ return {
758
+ ...statements.length === 1 ? { statement: statements[0] } : {},
759
+ ...binding !== void 0 ? { binding } : {},
760
+ signedAt: Number(tuple[0])
761
+ };
762
+ }
763
+ /** Why what `signer` carries does not stand as bound; undefined when it does. */
764
+ async function bindingRefusal(carried) {
765
+ if (carried.statement === void 0) return "the signing tuple names a statement the action does not carry";
766
+ if (carried.binding === void 0) return "the signing tuple does not cover the statement";
767
+ if (carried.binding !== await delegationBinding(carried.statement)) return "the signing tuple covers a different statement";
768
+ }
769
+ /** What the signing tuple's element [3] holds, so the signature covers the statement. */
770
+ async function delegationBinding(statement) {
771
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(statement));
772
+ return BINDING_PREFIX + toString(new Uint8Array(digest), "base64url");
773
+ }
774
+ /**
775
+ * Signs `action` as the person, carrying the statement in an earlier entry of
776
+ * `signatures`. The reactor leaves an action already signed under a key as it
777
+ * is, so this goes through any client.
778
+ */
779
+ async function signDelegatedAction(params) {
780
+ const { action, target, crypto, appName, user, statement } = params;
781
+ const identity = actionSignerIdentity({
782
+ user,
783
+ app: {
784
+ name: appName,
785
+ key: crypto.did
786
+ }
787
+ });
788
+ const tuple = await signActionV2({
789
+ action,
790
+ target,
791
+ signer: identity,
792
+ sign: (message) => crypto.sign(message),
793
+ previousStateHash: await delegationBinding(statement)
794
+ });
795
+ const issuer = decodeDelegation(statement)?.iss ?? "";
796
+ const entry = [
797
+ DELEGATION_TAG,
798
+ issuer,
799
+ "",
800
+ statement,
801
+ ""
802
+ ];
803
+ return {
804
+ ...action,
805
+ context: {
806
+ ...action.context,
807
+ signer: {
808
+ ...identity,
809
+ signatures: [entry, tuple]
810
+ }
811
+ }
812
+ };
813
+ }
814
+ function refuse(reason) {
815
+ return {
816
+ ok: false,
817
+ reason: `the statement ${reason}`
818
+ };
819
+ }
820
+ function encodeSegment(value) {
821
+ return toString(fromString(JSON.stringify(value)), "base64url");
822
+ }
823
+ function decodeHeader(segment) {
824
+ try {
825
+ return JSON.parse(toString(fromString(segment, "base64url")));
826
+ } catch {
827
+ return;
828
+ }
829
+ }
830
+ function isClaims(value) {
831
+ 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;
832
+ }
833
+ async function signedBy(issuer, parts) {
834
+ try {
835
+ const key = await importDidPublicKey(issuer);
836
+ return await globalThis.crypto.subtle.verify({
837
+ name: "ECDSA",
838
+ hash: "SHA-256"
839
+ }, key, new Uint8Array(fromString(parts[2], "base64url")), new TextEncoder().encode(`${parts[0]}.${parts[1]}`));
840
+ } catch {
841
+ return false;
842
+ }
843
+ }
844
+ function samePerson(subject, user) {
845
+ try {
846
+ const person = parsePkhDid(subject);
847
+ return person.address.toLowerCase() === user.address.toLowerCase() && person.networkId === user.networkId && person.chainId === user.chainId;
848
+ } catch {
849
+ return false;
850
+ }
851
+ }
852
+ /** Link one: the credential in `prf` binds the person to the statement's issuer. */
853
+ async function chainsToPerson(claims, user) {
854
+ const credential = claims.prf;
855
+ const address = user.address.toLowerCase();
856
+ try {
857
+ if (credential.credentialSubject.id !== claims.iss || credential.issuer.id !== claims.sub || credential.issuer.ethereumAddress.toLowerCase() !== address) return false;
858
+ return await verifyDelegationProof(credential, user.chainId);
859
+ } catch {
860
+ return false;
861
+ }
862
+ }
863
+ function scopeRefusal(scope, actionType) {
864
+ if (!Array.isArray(scope.ops) || scope.ops.length === 0) return "names no operations";
865
+ const wider = scope.ops.find((op) => !DELEGABLE_OPERATIONS.includes(op));
866
+ if (wider !== void 0) return `names ${wider}, which cannot be delegated`;
867
+ if (!scope.ops.includes(actionType)) return `does not cover ${actionType}`;
868
+ }
869
+ //#endregion
610
870
  //#region src/signer-trust.ts
611
871
  const DEFAULT_MAX_ACCEPTED = 1e4;
612
872
  const DEFAULT_REFUSAL_TTL_MS = 6e4;
@@ -614,6 +874,10 @@ const DEFAULT_REFUSAL_TTL_MS = 6e4;
614
874
  * Accepts a key the user's EIP-712 Renown credential delegates to, ignoring
615
875
  * expiry and revocation. Verdicts are cached per (address, key); this node's
616
876
  * own key is checked before the cache and never cached.
877
+ *
878
+ * A signer carrying a delegation is verified from what it carries, with no
879
+ * lookup and no cache: the verdict depends on the statement, not on (address,
880
+ * key). `options.delegationOnly` accepts every other signer.
617
881
  */
618
882
  function createRenownTrustPolicy(options = {}) {
619
883
  const maxAccepted = options.maxAccepted ?? DEFAULT_MAX_ACCEPTED;
@@ -642,10 +906,13 @@ function createRenownTrustPolicy(options = {}) {
642
906
  refusedUntil.delete(entry);
643
907
  } else refusedUntil.set(entry, Date.now() + refusalTtlMs);
644
908
  }
645
- return { authorizeSigner(signer, key) {
909
+ return { authorizeSigner(signer, key, _documentId, context) {
646
910
  const user = signer.user;
647
911
  const self = ownIdentity(options);
648
912
  if (self && isSelf(self, user, key)) return Promise.resolve(true);
913
+ const carried = delegationOf(signer);
914
+ if (carried) return authorizeDelegated(carried, user, key, self?.key, context);
915
+ if (options.delegationOnly) return Promise.resolve(true);
649
916
  if (!user || !isLookupable(user, key)) return Promise.resolve(false);
650
917
  const entry = `${user.networkId}|${user.chainId}|${user.address.toLowerCase()}|${key}`;
651
918
  if (accepted.has(entry)) return Promise.resolve(true);
@@ -665,6 +932,23 @@ function createRenownTrustPolicy(options = {}) {
665
932
  return verdict;
666
933
  } };
667
934
  }
935
+ /**
936
+ * The statement alone decides, so every replica agrees and no network is
937
+ * needed. The one exception is `env`, checked only at first write: peers
938
+ * receive these operations legitimately on load.
939
+ */
940
+ async function authorizeDelegated(carried, user, key, ownKey, context) {
941
+ if (!user || !context || carried.statement === void 0) return false;
942
+ if (await bindingRefusal(carried) !== void 0) return false;
943
+ const verdict = await verifyDelegation(carried.statement, {
944
+ user,
945
+ key,
946
+ signedAt: carried.signedAt,
947
+ actionType: context.actionType
948
+ });
949
+ if (!verdict.ok) return false;
950
+ return context.path === "load" || verdict.claims.env === ownKey;
951
+ }
668
952
  function ownIdentity(options) {
669
953
  if (!options.ownSigner) return options.self;
670
954
  const { app, user } = options.ownSigner;
@@ -703,6 +987,6 @@ async function fetchIssuedCredentialRest(user, key, renownUrl) {
703
987
  return credential ? [credential] : [];
704
988
  }
705
989
  //#endregion
706
- export { verifyAuthCredential as a, MissingSwitchboardError as c, recoverCredentialSigner as i, SwitchboardClient as l, buildAndSignCredential as n, verifyCredentialSignature as o, fetchDelegationCredential as r, verifyDelegationProof as s, createRenownTrustPolicy as t, resolveSwitchboardEndpoint as u };
990
+ 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
991
 
708
- //# sourceMappingURL=signer-trust-H1rNzUcd.js.map
992
+ //# sourceMappingURL=signer-trust-aVg9lYAn.js.map