@orangecheck/agent-core 1.1.0 → 1.2.0

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/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/types.ts","../src/scope.ts","../src/canonical.ts","../src/private-scope.ts","../src/verify.ts","../src/federation.ts"],"names":["hexEncode","sha256","canonicalize","lockSeal","lockUnseal"],"mappings":";;;;;;;AAEO,IAAM,gBAAA,GAAmB;;;ACyBzB,IAAM,iBAAA,GAAwD;AAAA,EACjE,aAAa,EAAE,IAAA,EAAM,CAAC,WAAA,EAAa,MAAA,EAAQ,WAAW,CAAA,EAAE;AAAA,EACxD,aAAa,EAAE,IAAA,EAAM,CAAC,WAAA,EAAa,mBAAA,EAAqB,UAAU,CAAA,EAAE;AAAA,EACpE,cAAc,EAAE,IAAA,EAAM,CAAC,MAAA,EAAQ,WAAA,EAAa,qBAAqB,CAAA,EAAE;AAAA,EACnE,aAAa,EAAE,IAAA,EAAM,CAAC,SAAA,EAAW,QAAQ,CAAA,EAAE;AAAA,EAC3C,iBAAiB,EAAE,IAAA,EAAM,CAAC,MAAA,EAAQ,OAAA,EAAS,WAAW,CAAA,EAAE;AAAA,EACxD,cAAA,EAAgB,EAAE,IAAA,EAAM,CAAC,UAAU,QAAA,EAAU,SAAA,EAAW,eAAe,CAAA,EAAE;AAAA,EACzE,WAAW,EAAE,IAAA,EAAM,CAAC,UAAA,EAAY,MAAA,EAAQ,cAAc,CAAA,EAAE;AAAA,EACxD,cAAc,EAAE,IAAA,EAAM,CAAC,QAAA,EAAU,MAAA,EAAQ,iBAAiB,CAAA;AAC9D;AAGA,IAAM,YAAA,uBAAmB,GAAA,CAAY;AAAA,EACjC,WAAA;AAAA,EACA,mBAAA;AAAA,EACA,UAAA;AAAA,EACA,eAAA;AAAA,EACA,SAAA;AAAA,EACA,UAAA;AAAA,EACA,cAAA;AAAA,EACA,iBAAA;AAAA,EACA;AACJ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AA,CAAI,MAAA,EAAQ,iBAAiB,EAAE,CAAA,CAAA;AAAA,IACtD,eAAe,GAAA,CAAI,aAAA;AAAA,IACnB,QAAQ,GAAA,CAAI,MAAA;AAAA,IACZ,WAAW,GAAA,CAAI;AAAA,GACnB;AACA,EAAA,MAAM,eAAA,GAAkB,oBAAoB,UAAU,CAAA;AACtD,EAAA,IAAI,eAAA,KAAoB,IAAI,EAAA,EAAI;AAC5B,IAAA,OAAO,KAAK,UAAA,EAAY,CAAA,kBAAA,EAAqB,eAAe,CAAA,kBAAA,EAAqB,GAAA,CAAI,EAAE,CAAA,CAAA,CAAG,CAAA;AAAA,EAC9F;AAEA,EAAA,MAAM,MAAA,GAAS,MAAM,qBAAA,CAAsB,GAAA,CAAI,QAAQ,GAAA,CAAI,GAAA,EAAK,GAAA,CAAI,EAAA,EAAI,KAAK,CAAA;AAC7E,EAAA,IAAI,CAAC,MAAA,CAAO,EAAA,EAAI,OAAO,MAAA;AAEvB,EAAA,OAAO,EAAE,IAAI,IAAA,EAAM,EAAA,EAAI,IAAI,EAAA,EAAI,gBAAA,EAAkB,0BAAA,CAA2B,UAAU,CAAA,EAAE;AAC5F;AAEA,SAAS,IAAA,CAAK,MAAsB,OAAA,EAAuE;AACvG,EAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,IAAA,EAAM,OAAA,EAAQ;AACtC","file":"index.js","sourcesContent":["// Wire types for OC Agent v1 envelopes. See SPEC.md §4, §5, §9.\n\nexport const ENVELOPE_VERSION = 1 as const;\n\nexport type EnvelopeKind =\n | 'agent-delegation'\n | 'agent-action'\n | 'agent-revocation'\n | 'agent-subdelegation';\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Shared building blocks\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface ActorRef {\n /** mainnet Bitcoin address (P2WPKH, P2TR, or P2PKH). */\n address: string;\n alg: 'bip322';\n}\n\nexport interface Signature {\n alg: 'bip322';\n pubkey: string; // equals the producing actor's address\n value: string; // base64 BIP-322 signature over hex(id)\n}\n\nexport type RevocationHolder = 'principal' | 'agent';\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Delegation (SPEC §4)\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface DelegationBond {\n /** Non-negative sats declared as bonded at issuance time. */\n sats: number;\n /** SHA-256 hex of the OrangeCheck canonical message signed by principal.address. */\n attestation_id: string;\n}\n\nexport interface DelegationRevocationRef {\n /** Who MAY publish a revocation. Default [\"principal\"]. */\n holders: RevocationHolder[];\n /** Optional Nostr-addressable pointer to a published revocation. Non-cryptographic. */\n ref: string | null;\n}\n\n/**\n * v1.2 private-scope mode: a wholesale OC Lock v2 LockEnvelope wrapping the\n * canonical scope list as its payload. We re-import the LockEnvelope type\n * structurally rather than depending on the @orangecheck/lock-core type — agent-\n * core's type surface stays loose so verifiers can be authored in either an\n * agent-only or full-family setup.\n */\nexport interface ScopesEncryptedEnvelope {\n v: 2;\n kind: 'identity';\n id: string;\n alg: { kem: 'x25519'; aead: 'aes-256-gcm'; kdf: 'hkdf-sha256' };\n from: { address: string; attestation_id?: string };\n recipients: Array<{\n address: string;\n device_id: string;\n device_pk: string;\n eph_pk: string;\n wrapped_key: string;\n nonce_kek: string;\n }>;\n ciphertext: string;\n nonce_ct: string;\n hint?: string;\n created_at: string;\n expires_at: string | null;\n payment: unknown | null;\n sig: { alg: 'bip322'; pubkey: string; value: string };\n}\n\nexport interface DelegationEnvelope {\n v: typeof ENVELOPE_VERSION;\n kind: 'agent-delegation';\n id: string; // 64-hex sha256(canonical_message)\n principal: ActorRef;\n agent: ActorRef;\n /**\n * v1.0 / v1.1 public mode: sorted lexicographically in the canonical\n * message; stored in sorted order on the envelope too.\n *\n * v1.2 private mode: this field is OMITTED from the envelope JSON;\n * `scopes_encrypted` is set instead. After decryption, the recovered\n * scope list takes this field's place in the in-memory envelope object\n * for the remainder of verification.\n */\n scopes?: string[];\n /**\n * v1.2 private mode (PRIVATE-SCOPE.md §1.1): an OC Lock v2 envelope\n * wrapping the canonical scope-list bytes as its payload, sealed to one\n * or more recipients (typically the agent ± named verifiers). MUTUALLY\n * EXCLUSIVE with `scopes`.\n */\n scopes_encrypted?: ScopesEncryptedEnvelope;\n bond: DelegationBond | null;\n issued_at: string; // ISO 8601 UTC\n expires_at: string; // ISO 8601 UTC\n nonce: string; // 32-hex random\n revocation: DelegationRevocationRef;\n sig: Signature;\n}\n\nexport interface DelegationCanonicalInput {\n principal: string;\n agent: string;\n scopes: string[]; // pre-canonicalized, pre-sorted\n bond_sats: number;\n /** 64-hex attestation id or the literal string \"none\". */\n bond_attestation: string;\n issued_at: string;\n expires_at: string;\n nonce: string;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Agent-action (SPEC §5) — strict extension of OC Stamp\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface ActionContent {\n hash: string; // \"sha256:<64-hex>\"\n length: number;\n mime: string;\n ref: string | null;\n}\n\nexport interface ActionOts {\n status: 'pending' | 'confirmed';\n proof: string;\n calendars: string[];\n block_height: number | null;\n block_hash: string | null;\n upgraded_at: string | null;\n}\n\nexport interface ActionEnvelope {\n v: typeof ENVELOPE_VERSION;\n kind: 'agent-action';\n id: string;\n content: ActionContent;\n signer: ActorRef; // agent\n signed_at: string;\n delegation_id: string; // 64-hex\n scope_exercised: string; // a sub-scope of some granted scope\n ots: ActionOts | null;\n sig: Signature;\n}\n\nexport interface ActionCanonicalInput {\n address: string; // agent address\n content_hash: string;\n content_length: number;\n content_mime: string;\n signed_at: string;\n delegation_id: string;\n scope_exercised: string;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Sub-delegation (SUB-DELEGATION.md, v1.1)\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface SubdelegationEnvelope {\n v: typeof ENVELOPE_VERSION;\n kind: 'agent-subdelegation';\n id: string; // 64-hex sha256(canonical_message)\n parent_id: string; // 64-hex; the immediate parent envelope's id\n /** The sub-principal — equal to parent.agent.address. */\n principal: ActorRef;\n /** The recipient sub-agent. */\n agent: ActorRef;\n /**\n * v1.0 / v1.1 public mode: each scope MUST be a sub-scope of some scope\n * on the parent. v1.2 private mode: omitted; `scopes_encrypted` set.\n */\n scopes?: string[];\n /** v1.2 private mode — same shape as the root delegation field. */\n scopes_encrypted?: ScopesEncryptedEnvelope;\n issued_at: string; // ISO 8601 UTC; >= parent.issued_at\n expires_at: string; // ISO 8601 UTC; <= parent.expires_at\n nonce: string; // 32-hex random\n revocation: DelegationRevocationRef;\n sig: Signature;\n}\n\nexport interface SubdelegationCanonicalInput {\n parent_id: string;\n principal: string;\n agent: string;\n scopes: string[]; // pre-canonicalized, pre-sorted\n issued_at: string;\n expires_at: string;\n nonce: string;\n}\n\n/** Either a root or a sub envelope; chain links walk up to a root delegation. */\nexport type ChainLink = DelegationEnvelope | SubdelegationEnvelope;\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Revocation (SPEC §9)\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface RevocationEnvelope {\n v: typeof ENVELOPE_VERSION;\n kind: 'agent-revocation';\n id: string;\n delegation_id: string;\n signer: ActorRef;\n /** Short ASCII rationale, <= 128 bytes. Empty string if omitted. */\n reason: string;\n signed_at: string;\n ots: ActionOts | null;\n sig: Signature;\n}\n\nexport interface RevocationCanonicalInput {\n address: string;\n delegation_id: string;\n reason: string;\n signed_at: string;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Error codes (SPEC §11)\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport type AgentErrorCode =\n | 'E_UNSUPPORTED_VERSION'\n | 'E_MALFORMED'\n | 'E_BAD_ID'\n | 'E_BAD_SIG'\n | 'E_BAD_SCOPE_GRAMMAR'\n | 'E_NOT_YET_VALID'\n | 'E_EXPIRED'\n | 'E_REVOKED'\n | 'E_DELEGATION_MISMATCH'\n | 'E_AGENT_MISMATCH'\n | 'E_OUT_OF_WINDOW'\n | 'E_SCOPE_DENIED'\n | 'E_BAD_ACTION_STAMP'\n | 'E_NO_BOND'\n | 'E_BOND_UNMET'\n | 'E_BOND_UNVERIFIED'\n | 'E_REVOKER_UNAUTHORIZED'\n | 'E_CALENDAR_UNREACHABLE'\n | 'E_SUBDELEGATION_DEPTH_EXCEEDED'\n | 'E_SUBDELEGATION_PRINCIPAL_MISMATCH'\n | 'E_SUBDELEGATION_EXPIRES_EXTENDED'\n | 'E_SUBDELEGATION_SCOPE_ESCALATED'\n | 'E_SCOPES_BOTH_PROVIDED'\n | 'E_SCOPES_NEITHER_PROVIDED'\n | 'E_SCOPES_UNREADABLE'\n | 'E_BAD_LOCK_ENVELOPE'\n // v1.2 federation principal (FEDERATION.md §3.3)\n | 'E_BAD_FEDERATION_DESCRIPTOR'\n | 'E_THRESHOLD_MISMATCH'\n | 'E_THRESHOLD_NOT_MET'\n | 'E_UNKNOWN_GUARDIAN'\n | 'E_DUPLICATE_GUARDIAN';\n\nexport interface VerifyOk<T> {\n ok: true;\n envelope: T;\n canonicalMessage: string;\n id: string;\n}\n\nexport interface VerifyErr {\n ok: false;\n code: AgentErrorCode;\n message: string;\n}\n\nexport type VerifyDelegationResult = VerifyOk<DelegationEnvelope> | VerifyErr;\nexport type VerifyRevocationResult = VerifyOk<RevocationEnvelope> | VerifyErr;\nexport type VerifySubdelegationResult = VerifyOk<SubdelegationEnvelope> | VerifyErr;\n\nexport interface VerifyActionOkExtra {\n /** The ROOT delegation rooting the authority chain. */\n delegation: DelegationEnvelope;\n /**\n * The sub-delegation chain `[S_1, …, S_leaf]`. Empty when the action cites\n * the root directly. The action's authority leaf is\n * `chain[chain.length - 1] ?? delegation`.\n */\n chain: SubdelegationEnvelope[];\n scopeExercised: string;\n anchor:\n | { status: 'none' }\n | { status: 'pending' }\n | { status: 'confirmed'; blockHeight: number; blockHash: string; verified: boolean };\n}\n\nexport type VerifyActionResult =\n | (VerifyOk<ActionEnvelope> & VerifyActionOkExtra)\n | VerifyErr;\n","// Scope grammar, canonicalization, and sub-scope relation. See SPEC.md §7.\n//\n// A scope is <product>:<verb>(<constraint-list>).\n// Constraints are <key><op><value>, op ∈ { =, !=, <, <=, >, >=, * }.\n// Canonical form: constraints sorted by key; no whitespace.\n\nexport type ScopeOp = '=' | '!=' | '<' | '<=' | '>' | '>=' | '*';\n\nexport interface ScopeConstraint {\n key: string;\n op: ScopeOp;\n /** `undefined` for the wildcard `*` op; otherwise the raw textual value (unquoted). */\n value: string | undefined;\n /** True if the value was supplied as a quoted string; preserved for round-trip fidelity. */\n quoted: boolean;\n}\n\nexport interface Scope {\n product: string;\n verb: string;\n constraints: ScopeConstraint[];\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Registered products/verbs (SPEC §7.3) and constraint keys (SPEC §7.6).\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport const REGISTERED_SCOPES: Record<string, { keys: string[] }> = {\n 'lock:seal': { keys: ['recipient', 'mime', 'max_bytes'] },\n 'lock:chat': { keys: ['recipient', 'max_bytes_per_msg', 'max_msgs'] },\n 'stamp:sign': { keys: ['mime', 'max_bytes', 'content_hash_prefix'] },\n 'vote:cast': { keys: ['poll_id', 'choice'] },\n 'nostr:publish': { keys: ['kind', 'relay', 'max_bytes'] },\n 'http:request': { keys: ['origin', 'method', 'max_rps', 'max_bytes_out'] },\n 'ln:send': { keys: ['max_sats', 'node', 'max_fee_sats'] },\n 'mcp:invoke': { keys: ['server', 'tool', 'max_invocations'] },\n};\n\n/** Keys whose values are compared numerically for sub-scope ordering. */\nconst NUMERIC_KEYS = new Set<string>([\n 'max_bytes',\n 'max_bytes_per_msg',\n 'max_msgs',\n 'max_bytes_out',\n 'max_rps',\n 'max_sats',\n 'max_fee_sats',\n 'max_invocations',\n 'kind',\n]);\n\nconst IDENT_RE = /^[a-z][a-z0-9_]*$/;\nconst BARE_TOKEN_RE = /^[A-Za-z0-9_.:/@+\\-]+$/;\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Parse\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport class ScopeParseError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ScopeParseError';\n }\n}\n\nexport function parseScope(input: string): Scope {\n if (typeof input !== 'string' || input.length === 0) {\n throw new ScopeParseError('scope must be a non-empty string');\n }\n if (/\\s/.test(input)) {\n throw new ScopeParseError(`scope may not contain whitespace: ${JSON.stringify(input)}`);\n }\n\n const colonIdx = input.indexOf(':');\n if (colonIdx < 0) throw new ScopeParseError('scope missing \"product:verb\" separator');\n\n const product = input.slice(0, colonIdx);\n if (!IDENT_RE.test(product)) throw new ScopeParseError(`invalid product: ${product}`);\n\n const rest = input.slice(colonIdx + 1);\n const parenIdx = rest.indexOf('(');\n\n let verb: string;\n let constraintText = '';\n if (parenIdx < 0) {\n verb = rest;\n } else {\n verb = rest.slice(0, parenIdx);\n if (!rest.endsWith(')')) throw new ScopeParseError('scope constraint list must end with \")\"');\n constraintText = rest.slice(parenIdx + 1, -1);\n }\n if (!IDENT_RE.test(verb)) throw new ScopeParseError(`invalid verb: ${verb}`);\n\n const constraints: ScopeConstraint[] = [];\n if (constraintText.length > 0) {\n for (const piece of splitTopLevelCommas(constraintText)) {\n constraints.push(parseConstraint(piece));\n }\n }\n\n // No duplicate keys.\n const seen = new Set<string>();\n for (const c of constraints) {\n if (seen.has(c.key)) throw new ScopeParseError(`duplicate constraint key: ${c.key}`);\n seen.add(c.key);\n }\n\n return { product, verb, constraints };\n}\n\nfunction splitTopLevelCommas(text: string): string[] {\n const out: string[] = [];\n let depth = 0;\n let inQuotes = false;\n let start = 0;\n for (let i = 0; i < text.length; i++) {\n const ch = text[i];\n if (inQuotes) {\n if (ch === '\\\\' && i + 1 < text.length) {\n i++;\n continue;\n }\n if (ch === '\"') inQuotes = false;\n continue;\n }\n if (ch === '\"') {\n inQuotes = true;\n continue;\n }\n if (ch === '(') depth++;\n else if (ch === ')') depth--;\n else if (ch === ',' && depth === 0) {\n out.push(text.slice(start, i));\n start = i + 1;\n }\n }\n out.push(text.slice(start));\n return out;\n}\n\nfunction parseConstraint(piece: string): ScopeConstraint {\n if (piece.length === 0) throw new ScopeParseError('empty constraint');\n\n // The `*` op (wildcard) is an op with no value. Recognized by \"key=*\" form.\n // SPEC uses \"key=*\"; we also accept \"key*\" as legacy alias.\n // Ops in descending length so \">=\" beats \">\" and \"!=\" beats \"!\".\n const OPS: ScopeOp[] = ['>=', '<=', '!=', '=', '>', '<'];\n\n // Special-case wildcard: \"key=*\" or \"key*\".\n const wildcardMatch = /^([a-z][a-z0-9_]*)(?:=\\*|\\*)$/.exec(piece);\n if (wildcardMatch) {\n return { key: wildcardMatch[1]!, op: '*', value: undefined, quoted: false };\n }\n\n for (const op of OPS) {\n const idx = piece.indexOf(op);\n if (idx <= 0) continue; // key must come first and be non-empty\n const key = piece.slice(0, idx);\n if (!IDENT_RE.test(key)) continue;\n const raw = piece.slice(idx + op.length);\n const { value, quoted } = parseValue(raw);\n return { key, op, value, quoted };\n }\n throw new ScopeParseError(`constraint missing operator: ${piece}`);\n}\n\nfunction parseValue(raw: string): { value: string; quoted: boolean } {\n if (raw.length === 0) throw new ScopeParseError('constraint value is empty');\n if (raw.startsWith('\"')) {\n if (!raw.endsWith('\"') || raw.length < 2) {\n throw new ScopeParseError(`unterminated quoted value: ${raw}`);\n }\n let v = '';\n for (let i = 1; i < raw.length - 1; i++) {\n const ch = raw[i]!;\n if (ch === '\\\\' && i + 1 < raw.length - 1) {\n const next = raw[++i]!;\n v += next;\n } else if (ch === '\"') {\n throw new ScopeParseError(`unescaped quote in value: ${raw}`);\n } else {\n v += ch;\n }\n }\n return { value: v, quoted: true };\n }\n if (!BARE_TOKEN_RE.test(raw)) {\n throw new ScopeParseError(`invalid bare-token value: ${JSON.stringify(raw)}`);\n }\n return { value: raw, quoted: false };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Canonicalize\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport function canonicalizeScope(scope: Scope): string {\n const sorted = [...scope.constraints].sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));\n const parts = sorted.map(serializeConstraint);\n const inner = parts.join(',');\n return `${scope.product}:${scope.verb}${parts.length === 0 ? '' : `(${inner})`}`;\n}\n\nexport function canonicalizeScopeString(input: string): string {\n return canonicalizeScope(parseScope(input));\n}\n\nfunction serializeConstraint(c: ScopeConstraint): string {\n if (c.op === '*') return `${c.key}=*`;\n const v = c.quoted ? quoteValue(c.value ?? '') : c.value ?? '';\n return `${c.key}${c.op}${v}`;\n}\n\nfunction quoteValue(v: string): string {\n let out = '\"';\n for (const ch of v) {\n if (ch === '\"' || ch === '\\\\') out += '\\\\' + ch;\n else out += ch;\n }\n out += '\"';\n return out;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Registry-based validation\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface ValidationOptions {\n /**\n * Strict: reject unknown products/verbs and unknown constraint keys.\n * Permissive: accept unknown products/verbs; ignore unknown keys without treating them as wider.\n * Default: 'strict'.\n */\n mode?: 'strict' | 'permissive';\n}\n\nexport function validateScope(scope: Scope, options: ValidationOptions = {}): void {\n const mode = options.mode ?? 'strict';\n const reg = REGISTERED_SCOPES[`${scope.product}:${scope.verb}`];\n if (!reg) {\n if (mode === 'strict') {\n throw new ScopeParseError(`unregistered scope: ${scope.product}:${scope.verb}`);\n }\n return; // permissive: no further checks\n }\n const registered = new Set(reg.keys);\n for (const c of scope.constraints) {\n if (!registered.has(c.key)) {\n if (mode === 'strict') {\n throw new ScopeParseError(\n `unregistered constraint key for ${scope.product}:${scope.verb}: ${c.key}`\n );\n }\n // permissive: ignore\n }\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Sub-scope relation (SPEC §7.4)\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Is `exercised` a sub-scope of `granted`?\n * Returns true iff every constraint of `granted` admits the corresponding constraint\n * (or absence) in `exercised`, per SPEC §7.4.\n */\nexport function isSubScope(exercised: Scope, granted: Scope): boolean {\n if (exercised.product !== granted.product) return false;\n if (exercised.verb !== granted.verb) return false;\n\n const exIndex = new Map<string, ScopeConstraint>();\n for (const c of exercised.constraints) exIndex.set(c.key, c);\n\n for (const g of granted.constraints) {\n const ex = exIndex.get(g.key);\n if (g.op === '*') continue; // wildcard: no requirement\n\n if (g.op === '=') {\n if (!ex) return false;\n if (ex.op !== '=' || ex.value !== g.value) return false;\n continue;\n }\n\n if (g.op === '!=') {\n if (!ex) return false;\n if (ex.op === '=' && ex.value !== g.value) continue;\n if (ex.op === '!=' && ex.value === g.value) continue;\n return false;\n }\n\n // Ordered ops: >=, <=, >, <. Exercised's implied range must be ⊆ granted's.\n if (g.op === '<' || g.op === '<=' || g.op === '>' || g.op === '>=') {\n if (!ex) return false;\n if (!NUMERIC_KEYS.has(g.key)) return false;\n if (ex.op === '*') return false;\n if (ex.value === undefined || g.value === undefined) return false;\n if (!rangeSubset(ex, g)) return false;\n continue;\n }\n }\n return true;\n}\n\nfunction rangeSubset(ex: ScopeConstraint, g: ScopeConstraint): boolean {\n const exRange = opToRange(ex);\n const gRange = opToRange(g);\n if (!exRange || !gRange) return false;\n return gRange.lo <= exRange.lo && exRange.hi <= gRange.hi;\n}\n\nfunction opToRange(c: ScopeConstraint): { lo: number; hi: number } | null {\n if (c.value === undefined) return null;\n const n = Number(c.value);\n if (!Number.isFinite(n)) return null;\n switch (c.op) {\n case '=':\n return { lo: n, hi: n };\n case '<':\n return { lo: -Infinity, hi: n - 1 }; // integers only\n case '<=':\n return { lo: -Infinity, hi: n };\n case '>':\n return { lo: n + 1, hi: Infinity };\n case '>=':\n return { lo: n, hi: Infinity };\n default:\n return null;\n }\n}\n","// Canonical messages + envelope canonicalization for OC Agent. SPEC §4.1, §5.1, §9.1.\n//\n// Three canonical-message builders live here — one per envelope kind. Each one\n// produces the exact byte sequence a signer signs via BIP-322 and the hash\n// input for the envelope id.\n//\n// The RFC 8785 JSON canonicalizer and hex utilities are re-exported from\n// @orangecheck/stamp-core so OC Agent and OC Stamp are guaranteed to produce\n// identical bytes for identical structural inputs.\n\nimport { sha256 } from '@noble/hashes/sha256';\nimport { canonicalize, hexEncode } from '@orangecheck/stamp-core/canonical';\n\nimport { canonicalizeScope, parseScope, type Scope } from './scope.js';\nimport type {\n ActionCanonicalInput,\n ActionEnvelope,\n DelegationCanonicalInput,\n DelegationEnvelope,\n RevocationCanonicalInput,\n RevocationEnvelope,\n SubdelegationCanonicalInput,\n} from './types.js';\n\nexport { canonicalize, hexEncode };\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Scope sorting + serialization\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Canonicalize and sort a list of scope strings for the delegation canonical\n * message. Each scope is first parsed, then re-emitted in canonical form\n * (constraints sorted by key), and the whole list is sorted lexicographically.\n */\nexport function canonicalizeScopes(scopes: string[]): string[] {\n const canonical = scopes.map((s) => canonicalizeScope(parseScope(s)));\n return [...canonical].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));\n}\n\n/**\n * Same as `canonicalizeScopes` but returns `Scope` objects too, for callers\n * that need them.\n */\nexport function parseAndCanonicalizeScopes(scopes: string[]): { canonical: string[]; parsed: Scope[] } {\n const parsed = scopes.map(parseScope);\n const canonicalStrings = parsed.map(canonicalizeScope);\n const indexed = canonicalStrings.map((s, i) => ({ s, p: parsed[i]! }));\n indexed.sort((a, b) => (a.s < b.s ? -1 : a.s > b.s ? 1 : 0));\n return {\n canonical: indexed.map((x) => x.s),\n parsed: indexed.map((x) => x.p),\n };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Canonical messages (SPEC §4.1, §5.1, §9.1)\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport function delegationCanonicalMessage(input: DelegationCanonicalInput): string {\n const scopeField = input.scopes.join(',');\n return [\n 'oc-agent:delegation:v1',\n `principal: ${input.principal}`,\n `agent: ${input.agent}`,\n `scopes: ${scopeField}`,\n `bond_sats: ${input.bond_sats}`,\n `bond_attestation: ${input.bond_attestation}`,\n `issued_at: ${input.issued_at}`,\n `expires_at: ${input.expires_at}`,\n `nonce: ${input.nonce}`,\n ].join('\\n');\n}\n\nexport function actionCanonicalMessage(input: ActionCanonicalInput): string {\n return [\n 'oc-agent:action:v1',\n `address: ${input.address}`,\n `content_hash: ${input.content_hash}`,\n `content_length: ${input.content_length}`,\n `content_mime: ${input.content_mime}`,\n `signed_at: ${input.signed_at}`,\n `delegation_id: ${input.delegation_id}`,\n `scope_exercised: ${input.scope_exercised}`,\n ].join('\\n');\n}\n\nexport function revocationCanonicalMessage(input: RevocationCanonicalInput): string {\n return [\n 'oc-agent:revocation:v1',\n `address: ${input.address}`,\n `delegation_id: ${input.delegation_id}`,\n `reason: ${input.reason}`,\n `signed_at: ${input.signed_at}`,\n ].join('\\n');\n}\n\nexport function subdelegationCanonicalMessage(input: SubdelegationCanonicalInput): string {\n const scopeField = input.scopes.join(',');\n return [\n 'oc-agent:subdelegation:v1',\n `parent_id: ${input.parent_id}`,\n `principal: ${input.principal}`,\n `agent: ${input.agent}`,\n `scopes: ${scopeField}`,\n `issued_at: ${input.issued_at}`,\n `expires_at: ${input.expires_at}`,\n `nonce: ${input.nonce}`,\n ].join('\\n');\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Bytes + ids\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport function delegationCanonicalBytes(input: DelegationCanonicalInput): Uint8Array {\n return new TextEncoder().encode(delegationCanonicalMessage(input));\n}\n\nexport function actionCanonicalBytes(input: ActionCanonicalInput): Uint8Array {\n return new TextEncoder().encode(actionCanonicalMessage(input));\n}\n\nexport function revocationCanonicalBytes(input: RevocationCanonicalInput): Uint8Array {\n return new TextEncoder().encode(revocationCanonicalMessage(input));\n}\n\nexport function subdelegationCanonicalBytes(input: SubdelegationCanonicalInput): Uint8Array {\n return new TextEncoder().encode(subdelegationCanonicalMessage(input));\n}\n\nexport function computeDelegationId(input: DelegationCanonicalInput): string {\n return hexEncode(sha256(delegationCanonicalBytes(input)));\n}\n\nexport function computeActionId(input: ActionCanonicalInput): string {\n return hexEncode(sha256(actionCanonicalBytes(input)));\n}\n\nexport function computeRevocationId(input: RevocationCanonicalInput): string {\n return hexEncode(sha256(revocationCanonicalBytes(input)));\n}\n\nexport function computeSubdelegationId(input: SubdelegationCanonicalInput): string {\n return hexEncode(sha256(subdelegationCanonicalBytes(input)));\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Envelope canonicalization (SPEC §6; RFC 8785 + scope-sorting)\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport function canonicalizeDelegation(env: DelegationEnvelope): string {\n return canonicalize(env as unknown as Parameters<typeof canonicalize>[0]);\n}\n\nexport function canonicalizeAction(env: ActionEnvelope): string {\n return canonicalize(env as unknown as Parameters<typeof canonicalize>[0]);\n}\n\nexport function canonicalizeRevocation(env: RevocationEnvelope): string {\n return canonicalize(env as unknown as Parameters<typeof canonicalize>[0]);\n}\n\nexport function canonicalDelegationBytes(env: DelegationEnvelope): Uint8Array {\n return new TextEncoder().encode(canonicalizeDelegation(env) + '\\n');\n}\n\nexport function canonicalActionBytes(env: ActionEnvelope): Uint8Array {\n return new TextEncoder().encode(canonicalizeAction(env) + '\\n');\n}\n\nexport function canonicalRevocationBytes(env: RevocationEnvelope): Uint8Array {\n return new TextEncoder().encode(canonicalizeRevocation(env) + '\\n');\n}\n\nexport function sha256Hex(bytes: Uint8Array): string {\n return hexEncode(sha256(bytes));\n}\n","// Private-scope helpers (PRIVATE-SCOPE.md, v1.2). Wrapping the OC Lock\n// `seal` and `unseal` primitives with the OC Agent-specific payload format\n// (canonical JSON array of scope strings, UTF-8 encoded).\n//\n// Why this lives in agent-core and not the consumer side: the canonical-\n// message commitment is the same across modes, so verifyDelegation needs to\n// be able to recover the plaintext. Centralizing the payload codec here\n// means every conformant verifier hashes the same bytes.\n\nimport { seal as lockSeal, unseal as lockUnseal } from '@orangecheck/lock-core';\nimport type {\n DeviceRecord,\n LockEnvelope,\n SealInput,\n UnsealInput,\n} from '@orangecheck/lock-core';\n\nimport { canonicalizeScopes } from './canonical.js';\nimport type { ScopesEncryptedEnvelope } from './types.js';\n\n/**\n * The plaintext payload sealed inside the OC Lock envelope. Canonical JSON\n * array of scope strings. Scopes are first put in canonical form (constraints\n * sorted by key) and the array is sorted lexicographically — same discipline\n * as v1.0 public-mode `scopes` field, so that the canonical-message bytes\n * match byte-for-byte across modes.\n */\nexport function encodeScopesPayload(scopes: string[]): Uint8Array {\n const canonical = canonicalizeScopes(scopes);\n const json = JSON.stringify(canonical);\n return new TextEncoder().encode(json);\n}\n\n/**\n * Inverse of `encodeScopesPayload`. Returns the canonicalized scope array.\n * Throws if the payload doesn't decode to a string array.\n */\nexport function decodeScopesPayload(bytes: Uint8Array): string[] {\n const json = new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n const parsed: unknown = JSON.parse(json);\n if (!Array.isArray(parsed) || !parsed.every((s) => typeof s === 'string')) {\n throw new Error('scopes payload must be a JSON array of strings');\n }\n return parsed as string[];\n}\n\nexport interface SealScopesInput {\n scopes: string[];\n /** Principal / sender — the same address that signs the OC Agent envelope. */\n sender: SealInput['sender'];\n /** Authorized decryptors. Must include at least the agent. */\n recipients: DeviceRecord[];\n /** Optional human hint stored in the OC Lock envelope. */\n hint?: string;\n /** Optional expiry on the OC Lock envelope itself. Independent of the\n * delegation's expires_at; usually left null. */\n expiresAt?: Date | null;\n}\n\n/**\n * Seal a scope list to one or more recipients. Returns the OC Lock envelope\n * to be embedded as `delegation.scopes_encrypted`.\n */\nexport async function sealScopes(\n input: SealScopesInput\n): Promise<ScopesEncryptedEnvelope> {\n const env = await lockSeal({\n kind: 'identity',\n payload: encodeScopesPayload(input.scopes),\n sender: input.sender,\n recipients: input.recipients,\n ...(input.hint !== undefined && { hint: input.hint }),\n ...(input.expiresAt !== undefined && { expiresAt: input.expiresAt }),\n });\n return env as unknown as ScopesEncryptedEnvelope;\n}\n\nexport interface UnsealScopesInput {\n envelope: ScopesEncryptedEnvelope;\n device: UnsealInput['device'];\n /** BIP-322 verifier callback. If omitted, the embedded LockEnvelope's\n * signature is NOT checked — useful for inspection or test paths. */\n verifyBip322?: UnsealInput['verifyBip322'];\n /** Skip the inner sender-signature check entirely. Default false. */\n skipSenderVerification?: boolean;\n}\n\n/** Result of unseal: decoded scope list plus the recovered sender address. */\nexport interface UnsealedScopes {\n scopes: string[];\n sender: { address: string; attestation_id?: string };\n matchedDeviceId: string;\n}\n\n/**\n * Decrypt an OC Agent v1.2 `scopes_encrypted` field with one of the\n * recipient device keys.\n */\nexport async function unsealScopes(\n input: UnsealScopesInput\n): Promise<UnsealedScopes> {\n const r = await lockUnseal({\n envelope: input.envelope as unknown as LockEnvelope,\n device: input.device,\n ...(input.verifyBip322 ? { verifyBip322: input.verifyBip322 } : {}),\n ...(input.skipSenderVerification !== undefined && {\n skipSenderVerification: input.skipSenderVerification,\n }),\n });\n return {\n scopes: decodeScopesPayload(r.payload),\n sender: r.sender,\n matchedDeviceId: r.matchedDeviceId,\n };\n}\n\n/** Convenience predicate. */\nexport function hasPrivateScopes<\n T extends { scopes?: string[]; scopes_encrypted?: ScopesEncryptedEnvelope }\n>(envelope: T): envelope is T & { scopes_encrypted: ScopesEncryptedEnvelope } {\n return !!envelope.scopes_encrypted;\n}\n","// verifyDelegation / verifyAction / verifyRevocation — reference implementation\n// of OC Agent v1 verification. SPEC §8.\n\nimport { sha256 } from '@noble/hashes/sha256';\n\nimport {\n actionCanonicalBytes,\n actionCanonicalMessage,\n canonicalizeScopes,\n computeSubdelegationId,\n delegationCanonicalBytes,\n delegationCanonicalMessage,\n hexEncode,\n revocationCanonicalBytes,\n revocationCanonicalMessage,\n} from './canonical.js';\nimport { unsealScopes } from './private-scope.js';\nimport {\n canonicalizeScope,\n isSubScope,\n parseScope,\n ScopeParseError,\n validateScope,\n type ValidationOptions,\n} from './scope.js';\nimport {\n ENVELOPE_VERSION,\n type ActionEnvelope,\n type AgentErrorCode,\n type ChainLink,\n type DelegationEnvelope,\n type RevocationEnvelope,\n type SubdelegationEnvelope,\n type VerifyActionResult,\n type VerifyDelegationResult,\n type VerifyRevocationResult,\n type VerifySubdelegationResult,\n} from './types.js';\n\n/** Default maximum chain depth, per SUB-DELEGATION.md §2.1. */\nexport const DEFAULT_MAX_CHAIN_DEPTH = 5;\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Shared options\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface VerifyBase {\n verifyBip322?: (msg: string, signatureB64: string, address: string) => Promise<boolean>;\n skipSignatureVerification?: boolean;\n scopeMode?: ValidationOptions['mode'];\n}\n\nexport class AgentError extends Error {\n code: AgentErrorCode;\n constructor(code: AgentErrorCode, message: string) {\n super(message);\n this.code = code;\n this.name = 'AgentError';\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Delegation (SPEC §8.1)\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface VerifyDelegationInput extends VerifyBase {\n envelope: DelegationEnvelope;\n /** Current time for temporal checks; defaults to new Date(). */\n now?: Date;\n /** Skip temporal checks entirely (useful for inspecting historical envelopes). */\n skipTemporalCheck?: boolean;\n /**\n * v1.2 private-scope decryption key. When the envelope carries\n * `scopes_encrypted`, the verifier MUST supply a device key matching one\n * of the recipient entries to recover the plaintext scope list. Without\n * this, verification returns `E_SCOPES_UNREADABLE`.\n */\n decryptScopesWith?: {\n device_id: string;\n secretKey: Uint8Array;\n };\n}\n\nexport async function verifyDelegation(input: VerifyDelegationInput): Promise<VerifyDelegationResult> {\n const env = input.envelope;\n\n if (env.v !== ENVELOPE_VERSION) {\n return err('E_UNSUPPORTED_VERSION', `delegation version ${env.v} not supported`);\n }\n\n const shape = checkDelegationShape(env);\n if (shape) return shape;\n\n // ─── v1.2 PRE-VERIFICATION (PRIVATE-SCOPE.md §2 steps P1–P6) ───────────\n // Steps P1 / P2: mutual exclusion + presence.\n if (env.scopes !== undefined && env.scopes_encrypted !== undefined) {\n return err(\n 'E_SCOPES_BOTH_PROVIDED',\n 'envelope carries both scopes and scopes_encrypted; pick one'\n );\n }\n if (env.scopes === undefined && env.scopes_encrypted === undefined) {\n return err(\n 'E_SCOPES_NEITHER_PROVIDED',\n 'envelope carries neither scopes nor scopes_encrypted'\n );\n }\n\n // The plaintext scope list. Either copied from env.scopes (public mode)\n // or recovered by decrypting env.scopes_encrypted (private mode).\n let workingScopes: string[];\n\n if (env.scopes_encrypted !== undefined) {\n // Step P3: issuer binding — the inner Lock envelope's `from.address`\n // must match the OC Agent envelope's principal.\n if (env.scopes_encrypted.from?.address !== env.principal.address) {\n return err(\n 'E_MALFORMED',\n `scopes_encrypted.from.address (${env.scopes_encrypted.from?.address}) does not match principal.address (${env.principal.address})`\n );\n }\n // Step P5: decryption capability.\n if (!input.decryptScopesWith) {\n return err(\n 'E_SCOPES_UNREADABLE',\n 'envelope carries scopes_encrypted; no decryption key provided'\n );\n }\n // Step P6: decrypt. Step P4 (inner-sig verify) is handled inside\n // unsealScopes via the same BIP-322 verifier — but only when\n // skipSignatureVerification is false.\n try {\n const r = await unsealScopes({\n envelope: env.scopes_encrypted,\n device: input.decryptScopesWith,\n ...(input.verifyBip322 ? { verifyBip322: input.verifyBip322 } : {}),\n skipSenderVerification: !!input.skipSignatureVerification,\n });\n workingScopes = r.scopes;\n } catch (e) {\n const msg = (e as Error).message ?? String(e);\n // Distinguish \"I had a key but the cryptographic operation failed\n // (bad envelope)\" from \"I had no matching recipient\" — the latter\n // is the more common case and gets E_SCOPES_UNREADABLE; the\n // former gets E_BAD_LOCK_ENVELOPE.\n if (/no matching recipient|no recipient|device_id/i.test(msg)) {\n return err('E_SCOPES_UNREADABLE', msg);\n }\n return err('E_BAD_LOCK_ENVELOPE', msg);\n }\n } else {\n workingScopes = env.scopes!;\n }\n\n // ─── Standard verification (SPEC.md §8.1) ──────────────────────────────\n // Scope grammar.\n let canonicalScopes: string[];\n try {\n for (const s of workingScopes) validateScope(parseScope(s), { mode: input.scopeMode ?? 'strict' });\n canonicalScopes = canonicalizeScopes(workingScopes);\n } catch (e) {\n const msg = e instanceof ScopeParseError ? e.message : (e as Error).message;\n return err('E_BAD_SCOPE_GRAMMAR', msg);\n }\n\n // In public mode the envelope's `scopes` array must already be in\n // canonical sorted order. (Private mode: the decrypted plaintext is\n // canonicalized at seal time, so this loop is a no-op for it.)\n for (let i = 0; i < canonicalScopes.length; i++) {\n if (workingScopes[i] !== canonicalScopes[i]) {\n return err(\n 'E_BAD_SCOPE_GRAMMAR',\n `scope at index ${i} not in canonical form; expected ${canonicalScopes[i]} got ${workingScopes[i]}`\n );\n }\n }\n\n // Canonical message reconstruction.\n const bondSats = env.bond?.sats ?? 0;\n const bondAttestation = env.bond?.attestation_id ?? 'none';\n const canonInput = {\n principal: env.principal.address,\n agent: env.agent.address,\n scopes: canonicalScopes,\n bond_sats: bondSats,\n bond_attestation: bondAttestation,\n issued_at: env.issued_at,\n expires_at: env.expires_at,\n nonce: env.nonce,\n };\n const reconstructedMessage = delegationCanonicalMessage(canonInput);\n const reconstructedId = hexEncode(sha256(delegationCanonicalBytes(canonInput)));\n if (reconstructedId !== env.id) {\n return err(\n 'E_BAD_ID',\n `reconstructed id (${reconstructedId}) does not match envelope.id (${env.id})`\n );\n }\n\n // Signature.\n if (!input.skipSignatureVerification) {\n if (!input.verifyBip322) return err('E_BAD_SIG', 'no BIP-322 verifier supplied');\n const ok = await input.verifyBip322(env.id, env.sig.value, env.principal.address);\n if (!ok) return err('E_BAD_SIG', 'BIP-322 signature did not verify');\n }\n\n // Temporal.\n if (!input.skipTemporalCheck) {\n const now = input.now ?? new Date();\n const issued = new Date(env.issued_at);\n const expires = new Date(env.expires_at);\n if (expires <= issued) return err('E_MALFORMED', 'expires_at <= issued_at');\n if (now < issued) return err('E_NOT_YET_VALID', `delegation not valid until ${env.issued_at}`);\n if (now >= expires) return err('E_EXPIRED', `delegation expired at ${env.expires_at}`);\n }\n\n // In private mode, return a hydrated envelope that includes the recovered\n // plaintext scopes so callers (verifyAction's chain walker, web-app\n // consumers) don't have to repeat the decryption.\n const returnedEnvelope: DelegationEnvelope =\n env.scopes_encrypted !== undefined\n ? { ...env, scopes: canonicalScopes }\n : env;\n\n return {\n ok: true,\n envelope: returnedEnvelope,\n canonicalMessage: reconstructedMessage,\n id: env.id,\n };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Action (SPEC §8.2–8.3)\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface VerifyActionInput extends VerifyBase {\n action: ActionEnvelope;\n /** The ROOT delegation rooting the authority chain. Always required. */\n delegation: DelegationEnvelope;\n /**\n * Optional v1.1 sub-delegation chain from S_1 (immediate child of `delegation`)\n * to S_leaf (the envelope `action.delegation_id` cites). When provided, the\n * verifier walks each link checking parent-id linkage, principal-equals-\n * parent-agent, scope containment, and temporal containment. The action's\n * delegation_id MUST equal the leaf's id; the action's signer MUST equal\n * the leaf's agent. See SUB-DELEGATION.md §2.2.\n */\n subdelegationChain?: SubdelegationEnvelope[];\n /**\n * Maximum permitted chain depth (number of subdelegations).\n * Default `DEFAULT_MAX_CHAIN_DEPTH` (5). Verifiers MAY lower; MUST NOT raise\n * silently above their advertised cap. Chains exceeding this fail with\n * E_SUBDELEGATION_DEPTH_EXCEEDED before any per-link work is performed.\n */\n maxChainDepth?: number;\n /**\n * Known revocations targeting any envelope in the chain (root + each\n * subdelegation). The verifier checks every link per SUB-DELEGATION.md §2.2\n * step 5 — a revocation against ANY link invalidates the action.\n */\n revocations?: RevocationEnvelope[];\n content?: Uint8Array;\n verifyOtsAnchor?: (proofB64: string, blockHeight: number, blockHash: string) => Promise<boolean>;\n /** If action and revocation are both OTS-anchored, pass a function that returns the comparable block height of each via proof parsing. Defaults: use envelope.ots.block_height. */\n resolveAnchorBlockHeight?: (env: ActionEnvelope | RevocationEnvelope) => number | null;\n /**\n * v1.2 private-scope decryption key. Applied to the root delegation AND\n * every subdelegation in the chain that carries `scopes_encrypted`. If a\n * link is private-mode and no key matches its recipients, verification\n * fails E_SCOPES_UNREADABLE — the chain's transitive narrowing cannot be\n * checked without the plaintext.\n */\n decryptScopesWith?: {\n device_id: string;\n secretKey: Uint8Array;\n };\n}\n\nexport async function verifyAction(input: VerifyActionInput): Promise<VerifyActionResult> {\n const a = input.action;\n const d = input.delegation;\n\n // 0. Chain-depth check (SUB-DELEGATION.md §2.1) — before any per-link work.\n const chain: SubdelegationEnvelope[] = input.subdelegationChain ?? [];\n const maxDepth = input.maxChainDepth ?? DEFAULT_MAX_CHAIN_DEPTH;\n if (chain.length > maxDepth) {\n return err(\n 'E_SUBDELEGATION_DEPTH_EXCEEDED',\n `chain depth ${chain.length} exceeds maximum ${maxDepth}`\n );\n }\n\n // 1. First verify the root delegation. verifyDelegation handles v1.2\n // private-scope hydration internally — when the root is private-mode,\n // the returned envelope already has `scopes` populated from the\n // decrypted plaintext.\n const dr = await verifyDelegation({\n envelope: d,\n verifyBip322: input.verifyBip322,\n skipSignatureVerification: input.skipSignatureVerification,\n scopeMode: input.scopeMode,\n skipTemporalCheck: true, // action window check dominates\n ...(input.decryptScopesWith ? { decryptScopesWith: input.decryptScopesWith } : {}),\n });\n if (!dr.ok) return dr;\n const rootHydrated: DelegationEnvelope = dr.envelope;\n\n // 1b. Walk the sub-delegation chain (SUB-DELEGATION.md §2.2 step 3).\n // Each link may independently be private-mode; we hydrate it before\n // handing it to verifyChainLink so the chain walker sees plaintext\n // scopes uniformly.\n let parent: ChainLink = rootHydrated;\n const hydratedChain: SubdelegationEnvelope[] = [];\n for (const sub of chain) {\n const hydrated = await hydrateSubdelegationScopes(sub, input);\n if (!hydrated.ok) return hydrated;\n const r = await verifyChainLink(hydrated.envelope, parent, input);\n if (!r.ok) return r;\n hydratedChain.push(hydrated.envelope);\n parent = hydrated.envelope;\n }\n /** The envelope `action.delegation_id` should cite (root if no chain, leaf otherwise). */\n const leaf: ChainLink =\n hydratedChain.length > 0 ? hydratedChain[hydratedChain.length - 1]! : rootHydrated;\n\n // 2. Core action checks.\n if (a.v !== ENVELOPE_VERSION) {\n return err('E_UNSUPPORTED_VERSION', `action version ${a.v} not supported`);\n }\n const shape = checkActionShape(a);\n if (shape) return shape;\n\n const canonInput = {\n address: a.signer.address,\n content_hash: a.content.hash,\n content_length: a.content.length,\n content_mime: a.content.mime,\n signed_at: a.signed_at,\n delegation_id: a.delegation_id,\n scope_exercised: a.scope_exercised,\n };\n const reconstructedMessage = actionCanonicalMessage(canonInput);\n const reconstructedId = hexEncode(sha256(actionCanonicalBytes(canonInput)));\n if (reconstructedId !== a.id) {\n return err('E_BAD_ID', `reconstructed id (${reconstructedId}) does not match action.id (${a.id})`);\n }\n\n if (!input.skipSignatureVerification) {\n if (!input.verifyBip322) return err('E_BAD_SIG', 'no BIP-322 verifier supplied');\n const ok = await input.verifyBip322(a.id, a.sig.value, a.signer.address);\n if (!ok) return err('E_BAD_ACTION_STAMP', 'action BIP-322 signature did not verify');\n }\n\n // 3. Authority chain — leaf-binding (action cites the leaf of the chain,\n // which is the root delegation when no subdelegation chain is present).\n if (a.delegation_id !== leaf.id) {\n return err('E_DELEGATION_MISMATCH', `action.delegation_id (${a.delegation_id}) != leaf.id (${leaf.id})`);\n }\n if (a.signer.address !== leaf.agent.address) {\n return err('E_AGENT_MISMATCH', `action signer (${a.signer.address}) != leaf.agent (${leaf.agent.address})`);\n }\n\n // 4. Window — against the leaf.\n const issued = new Date(leaf.issued_at).getTime();\n const expires = new Date(leaf.expires_at).getTime();\n const signed = new Date(a.signed_at).getTime();\n if (Number.isNaN(issued) || Number.isNaN(expires) || Number.isNaN(signed)) {\n return err('E_MALFORMED', 'unparseable ISO 8601 timestamp');\n }\n if (signed < issued || signed >= expires) {\n return err('E_OUT_OF_WINDOW', `action.signed_at ${a.signed_at} is outside leaf window [${leaf.issued_at}, ${leaf.expires_at})`);\n }\n\n // 5. Scope containment — against the leaf's granted set.\n // Leaf is post-hydration, so `scopes` is guaranteed populated. The\n // runtime guard satisfies the type checker and would only fire if a\n // caller bypassed the hydration path.\n if (!leaf.scopes) {\n return err('E_SCOPES_NEITHER_PROVIDED', 'leaf has no plaintext scopes after hydration');\n }\n let exercised, accepted;\n try {\n exercised = canonicalizeScope(parseScope(a.scope_exercised));\n const granted = leaf.scopes.map((s) => parseScope(s));\n const exercisedParsed = parseScope(a.scope_exercised);\n validateScope(exercisedParsed, { mode: input.scopeMode ?? 'strict' });\n accepted = granted.some((g) => isSubScope(exercisedParsed, g));\n } catch (e) {\n const msg = e instanceof ScopeParseError ? e.message : (e as Error).message;\n return err('E_BAD_SCOPE_GRAMMAR', msg);\n }\n if (!accepted) return err('E_SCOPE_DENIED', `scope_exercised (${exercised}) not a sub-scope of any granted scope`);\n\n // 6. Revocation check — applies per-link to ALL envelopes in the chain\n // (root + every subdelegation). Per SUB-DELEGATION.md §2.2 step 5, a\n // revocation against ANY link invalidates the action.\n if (input.revocations && input.revocations.length > 0) {\n const allLinks: ChainLink[] = [rootHydrated, ...hydratedChain];\n for (const link of allLinks) {\n for (const rev of input.revocations) {\n if (rev.delegation_id !== link.id) continue;\n // Verify the revocation itself (signature + canonical + signer\n // authorization). verifyRevocation accepts ChainLink, so the\n // call shape is identical for root vs sub.\n const rr = await verifyRevocation({\n envelope: rev,\n delegation: link,\n verifyBip322: input.verifyBip322,\n skipSignatureVerification: input.skipSignatureVerification,\n });\n if (!rr.ok) continue; // malformed revocations don't affect the action\n const effective = effectiveRevocationTime(rev, input.resolveAnchorBlockHeight);\n const actionTime = actionEffectiveTime(a, input.resolveAnchorBlockHeight);\n if (compareTimes(effective, actionTime) <= 0) {\n return err('E_REVOKED', `chain link ${link.id} was revoked by ${rev.id} before action was signed`);\n }\n }\n }\n }\n\n // 7. Content check.\n if (input.content) {\n const actualHash = 'sha256:' + hexEncode(sha256(input.content));\n if (actualHash !== a.content.hash) {\n return err('E_BAD_ACTION_STAMP', `content hash (${actualHash}) != action.content.hash (${a.content.hash})`);\n }\n }\n\n // 8. Anchor info.\n let anchor: VerifyActionResult extends infer R ? R extends { anchor: infer X } ? X : never : never;\n if (a.ots === null) {\n anchor = { status: 'none' } as typeof anchor;\n } else if (a.ots.status === 'pending') {\n anchor = { status: 'pending' } as typeof anchor;\n } else {\n const h = a.ots.block_height;\n const hash = a.ots.block_hash;\n if (h === null || hash === null) {\n return err('E_MALFORMED', 'confirmed OTS proof missing block_height or block_hash');\n }\n let verified = false;\n if (input.verifyOtsAnchor) {\n try {\n verified = await input.verifyOtsAnchor(a.ots.proof, h, hash);\n } catch (e) {\n return err('E_MALFORMED', `anchor verifier threw: ${(e as Error).message}`);\n }\n }\n anchor = { status: 'confirmed', blockHeight: h, blockHash: hash, verified } as typeof anchor;\n }\n\n return {\n ok: true,\n envelope: a,\n canonicalMessage: reconstructedMessage,\n id: a.id,\n delegation: rootHydrated,\n chain: hydratedChain,\n scopeExercised: exercised,\n anchor,\n };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// v1.2 chain-link hydration — decrypt scopes_encrypted on subdelegations\n// before passing them to the chain walker so all containment checks operate\n// on plaintext.\n// ─────────────────────────────────────────────────────────────────────────────\n\nasync function hydrateSubdelegationScopes(\n sub: SubdelegationEnvelope,\n input: VerifyBase & {\n decryptScopesWith?: { device_id: string; secretKey: Uint8Array };\n }\n): Promise<{ ok: true; envelope: SubdelegationEnvelope } | VerifyErrResult> {\n if (sub.scopes !== undefined && sub.scopes_encrypted !== undefined) {\n return err(\n 'E_SCOPES_BOTH_PROVIDED',\n 'subdelegation carries both scopes and scopes_encrypted'\n );\n }\n if (sub.scopes === undefined && sub.scopes_encrypted === undefined) {\n return err(\n 'E_SCOPES_NEITHER_PROVIDED',\n 'subdelegation carries neither scopes nor scopes_encrypted'\n );\n }\n if (sub.scopes_encrypted === undefined) {\n return { ok: true, envelope: sub };\n }\n if (sub.scopes_encrypted.from?.address !== sub.principal.address) {\n return err(\n 'E_MALFORMED',\n `subdelegation.scopes_encrypted.from.address (${sub.scopes_encrypted.from?.address}) does not match principal.address (${sub.principal.address})`\n );\n }\n if (!input.decryptScopesWith) {\n return err(\n 'E_SCOPES_UNREADABLE',\n 'subdelegation carries scopes_encrypted; no decryption key provided for the chain'\n );\n }\n try {\n const r = await unsealScopes({\n envelope: sub.scopes_encrypted,\n device: input.decryptScopesWith,\n ...(input.verifyBip322 ? { verifyBip322: input.verifyBip322 } : {}),\n skipSenderVerification: !!input.skipSignatureVerification,\n });\n return { ok: true, envelope: { ...sub, scopes: r.scopes } };\n } catch (e) {\n const msg = (e as Error).message ?? String(e);\n if (/no matching recipient|no recipient|device_id/i.test(msg)) {\n return err('E_SCOPES_UNREADABLE', msg);\n }\n return err('E_BAD_LOCK_ENVELOPE', msg);\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Revocation (SPEC §9, §8 transitive)\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface VerifyRevocationInput extends VerifyBase {\n envelope: RevocationEnvelope;\n /**\n * The envelope targeted by the revocation. Required to check signer is\n * authorized. May be a v1.0 root delegation OR a v1.1 sub-delegation —\n * both have identical `principal`, `agent`, `id`, and `revocation.holders`\n * field shapes per SUB-DELEGATION.md §3.\n */\n delegation: ChainLink;\n}\n\nexport async function verifyRevocation(input: VerifyRevocationInput): Promise<VerifyRevocationResult> {\n const env = input.envelope;\n const d = input.delegation;\n\n if (env.v !== ENVELOPE_VERSION) {\n return err('E_UNSUPPORTED_VERSION', `revocation version ${env.v} not supported`);\n }\n const shape = checkRevocationShape(env);\n if (shape) return shape;\n\n if (env.delegation_id !== d.id) {\n return err('E_DELEGATION_MISMATCH', `revocation.delegation_id (${env.delegation_id}) != delegation.id (${d.id})`);\n }\n\n // Signer must be authorized per delegation.revocation.holders.\n const holders = d.revocation?.holders ?? ['principal'];\n const holderAddrs = new Set<string>();\n if (holders.includes('principal')) holderAddrs.add(d.principal.address);\n if (holders.includes('agent')) holderAddrs.add(d.agent.address);\n if (!holderAddrs.has(env.signer.address)) {\n return err('E_REVOKER_UNAUTHORIZED', `revocation signer ${env.signer.address} not in delegation holders`);\n }\n\n const canonInput = {\n address: env.signer.address,\n delegation_id: env.delegation_id,\n reason: env.reason,\n signed_at: env.signed_at,\n };\n const reconstructedMessage = revocationCanonicalMessage(canonInput);\n const reconstructedId = hexEncode(sha256(revocationCanonicalBytes(canonInput)));\n if (reconstructedId !== env.id) {\n return err('E_BAD_ID', `reconstructed id (${reconstructedId}) does not match revocation.id (${env.id})`);\n }\n\n if (!input.skipSignatureVerification) {\n if (!input.verifyBip322) return err('E_BAD_SIG', 'no BIP-322 verifier supplied');\n const ok = await input.verifyBip322(env.id, env.sig.value, env.signer.address);\n if (!ok) return err('E_BAD_SIG', 'revocation BIP-322 signature did not verify');\n }\n\n return { ok: true, envelope: env, canonicalMessage: reconstructedMessage, id: env.id };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Shape checks\n// ─────────────────────────────────────────────────────────────────────────────\n\nfunction checkDelegationShape(env: DelegationEnvelope): VerifyDelegationResult | null {\n if (env.kind !== 'agent-delegation') return err('E_MALFORMED', 'kind must be \"agent-delegation\"');\n if (!isHex64(env.id)) return err('E_MALFORMED', 'id must be 64 lowercase hex chars');\n if (!env.principal?.address || env.principal.alg !== 'bip322') return err('E_MALFORMED', 'principal invalid');\n if (!env.agent?.address || env.agent.alg !== 'bip322') return err('E_MALFORMED', 'agent invalid');\n // v1.2: scopes OR scopes_encrypted (exactly one). Mutual exclusion +\n // presence checks are performed by the verify-time PRE-VERIFICATION block\n // (PRIVATE-SCOPE.md §2 steps P1–P2) so they can return their own error\n // codes (E_SCOPES_BOTH_PROVIDED / E_SCOPES_NEITHER_PROVIDED) rather than\n // collapsing into E_MALFORMED.\n if (env.scopes !== undefined) {\n if (!Array.isArray(env.scopes) || env.scopes.length === 0)\n return err('E_MALFORMED', 'scopes must be non-empty array');\n }\n if (env.bond !== null) {\n if (!Number.isInteger(env.bond.sats) || env.bond.sats < 0) return err('E_MALFORMED', 'bond.sats must be non-negative integer');\n if (!isHex64(env.bond.attestation_id)) return err('E_MALFORMED', 'bond.attestation_id must be 64-hex');\n }\n if (!isIsoUtc(env.issued_at)) return err('E_MALFORMED', 'issued_at must be ISO 8601 UTC');\n if (!isIsoUtc(env.expires_at)) return err('E_MALFORMED', 'expires_at must be ISO 8601 UTC');\n if (!/^[0-9a-f]{32}$/.test(env.nonce)) return err('E_MALFORMED', 'nonce must be 32 lowercase hex chars');\n if (env.sig?.alg !== 'bip322' || typeof env.sig.value !== 'string') return err('E_MALFORMED', 'sig invalid');\n if (env.sig.pubkey !== env.principal.address) return err('E_MALFORMED', 'sig.pubkey must equal principal.address');\n return null;\n}\n\nfunction checkActionShape(a: ActionEnvelope): VerifyActionResult | null {\n if (a.kind !== 'agent-action') return err('E_MALFORMED', 'kind must be \"agent-action\"');\n if (!isHex64(a.id)) return err('E_MALFORMED', 'id must be 64 lowercase hex chars');\n if (!a.content || typeof a.content.hash !== 'string' || !a.content.hash.startsWith('sha256:')) {\n return err('E_MALFORMED', 'content.hash must start with \"sha256:\"');\n }\n if (!Number.isInteger(a.content.length) || a.content.length < 0) return err('E_MALFORMED', 'content.length invalid');\n if (!a.signer?.address || a.signer.alg !== 'bip322') return err('E_MALFORMED', 'signer invalid');\n if (!isIsoUtc(a.signed_at)) return err('E_MALFORMED', 'signed_at must be ISO 8601 UTC');\n if (!isHex64(a.delegation_id)) return err('E_MALFORMED', 'delegation_id must be 64-hex');\n if (typeof a.scope_exercised !== 'string' || a.scope_exercised.length === 0) return err('E_MALFORMED', 'scope_exercised required');\n if (a.sig?.alg !== 'bip322' || typeof a.sig.value !== 'string') return err('E_MALFORMED', 'sig invalid');\n if (a.sig.pubkey !== a.signer.address) return err('E_MALFORMED', 'sig.pubkey must equal signer.address');\n return null;\n}\n\nfunction checkRevocationShape(env: RevocationEnvelope): VerifyRevocationResult | null {\n if (env.kind !== 'agent-revocation') return err('E_MALFORMED', 'kind must be \"agent-revocation\"');\n if (!isHex64(env.id)) return err('E_MALFORMED', 'id must be 64 lowercase hex chars');\n if (!isHex64(env.delegation_id)) return err('E_MALFORMED', 'delegation_id must be 64-hex');\n if (!env.signer?.address || env.signer.alg !== 'bip322') return err('E_MALFORMED', 'signer invalid');\n if (typeof env.reason !== 'string' || env.reason.length > 128) return err('E_MALFORMED', 'reason must be a string <=128 bytes');\n if (!isIsoUtc(env.signed_at)) return err('E_MALFORMED', 'signed_at must be ISO 8601 UTC');\n if (env.sig?.alg !== 'bip322' || typeof env.sig.value !== 'string') return err('E_MALFORMED', 'sig invalid');\n if (env.sig.pubkey !== env.signer.address) return err('E_MALFORMED', 'sig.pubkey must equal signer.address');\n return null;\n}\n\nfunction checkSubdelegationShape(env: SubdelegationEnvelope): VerifySubdelegationResult | null {\n if (env.kind !== 'agent-subdelegation') return err('E_MALFORMED', 'kind must be \"agent-subdelegation\"');\n if (!isHex64(env.id)) return err('E_MALFORMED', 'id must be 64 lowercase hex chars');\n if (!isHex64(env.parent_id)) return err('E_MALFORMED', 'parent_id must be 64-hex');\n if (!env.principal?.address || env.principal.alg !== 'bip322') return err('E_MALFORMED', 'principal invalid');\n if (!env.agent?.address || env.agent.alg !== 'bip322') return err('E_MALFORMED', 'agent invalid');\n // v1.2: scopes OR scopes_encrypted (post-hydration the chain walker\n // always sees `scopes` populated). Mutual exclusion + presence checked\n // by hydrateSubdelegationScopes.\n if (env.scopes !== undefined) {\n if (!Array.isArray(env.scopes) || env.scopes.length === 0)\n return err('E_MALFORMED', 'scopes must be non-empty array');\n }\n // Sub-delegations MUST NOT carry a bond field (SUB-DELEGATION.md §1.3).\n if ('bond' in env && (env as { bond?: unknown }).bond !== undefined) {\n return err('E_MALFORMED', 'sub-delegation envelopes MUST NOT carry a bond field');\n }\n if (!isIsoUtc(env.issued_at)) return err('E_MALFORMED', 'issued_at must be ISO 8601 UTC');\n if (!isIsoUtc(env.expires_at)) return err('E_MALFORMED', 'expires_at must be ISO 8601 UTC');\n if (!/^[0-9a-f]{32}$/.test(env.nonce)) return err('E_MALFORMED', 'nonce must be 32 lowercase hex chars');\n if (env.sig?.alg !== 'bip322' || typeof env.sig.value !== 'string') return err('E_MALFORMED', 'sig invalid');\n if (env.sig.pubkey !== env.principal.address) return err('E_MALFORMED', 'sig.pubkey must equal principal.address');\n return null;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Sub-delegation chain link (SUB-DELEGATION.md §2.2 step 3)\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Verify a single sub-delegation envelope as a chain link from `parent`.\n * Performs steps 3a–3g in order; returns the corresponding VerifyErr on\n * failure or `{ ok: true, envelope: s }` on success.\n *\n * Skips the standalone temporal-validity check (SUB-DELEGATION.md §2.2 step\n * 3d) — for action verification, the action-window check (step 4c) on the\n * leaf is the binding temporal constraint. Callers that want a current-time\n * \"is this subdelegation active right now\" check can use `verifySubdelegation`.\n */\nasync function verifyChainLink(\n s: SubdelegationEnvelope,\n parent: ChainLink,\n input: VerifyBase\n): Promise<VerifySubdelegationResult> {\n if (s.v !== ENVELOPE_VERSION) {\n return err('E_UNSUPPORTED_VERSION', `subdelegation version ${s.v} not supported`);\n }\n const shape = checkSubdelegationShape(s);\n if (shape) return shape;\n\n // verifyChainLink expects post-hydration scopes (callers run\n // hydrateSubdelegationScopes upfront). The runtime guard makes the\n // type-checker happy and protects against bypass.\n if (!s.scopes) {\n return err(\n 'E_SCOPES_NEITHER_PROVIDED',\n 'subdelegation has no plaintext scopes — caller must hydrate v1.2 envelopes before invoking verifyChainLink'\n );\n }\n\n // Step 3a: canonical id.\n let canonicalScopesList: string[];\n try {\n canonicalScopesList = canonicalizeScopes(s.scopes);\n } catch (e) {\n const msg = e instanceof ScopeParseError ? e.message : (e as Error).message;\n return err('E_BAD_SCOPE_GRAMMAR', msg);\n }\n const canonInput = {\n parent_id: s.parent_id,\n principal: s.principal.address,\n agent: s.agent.address,\n scopes: canonicalScopesList,\n issued_at: s.issued_at,\n expires_at: s.expires_at,\n nonce: s.nonce,\n };\n const reconstructedId = computeSubdelegationId(canonInput);\n if (reconstructedId !== s.id) {\n return err('E_BAD_ID', `reconstructed subdelegation id (${reconstructedId}) does not match envelope id (${s.id})`);\n }\n\n // Step 3b: scope grammar validation (registry-aware).\n let parsedScopes;\n try {\n parsedScopes = s.scopes.map((str) => parseScope(str));\n for (const p of parsedScopes) validateScope(p, { mode: input.scopeMode ?? 'strict' });\n } catch (e) {\n const msg = e instanceof ScopeParseError ? e.message : (e as Error).message;\n return err('E_BAD_SCOPE_GRAMMAR', msg);\n }\n\n // Step 3c: BIP-322 signature.\n if (!input.skipSignatureVerification) {\n if (!input.verifyBip322) return err('E_BAD_SIG', 'no BIP-322 verifier supplied for subdelegation');\n const ok = await input.verifyBip322(s.id, s.sig.value, s.principal.address);\n if (!ok) return err('E_BAD_SIG', 'subdelegation BIP-322 signature did not verify');\n }\n\n // Step 3e: linkage.\n if (s.parent_id !== parent.id) {\n return err(\n 'E_SUBDELEGATION_PRINCIPAL_MISMATCH',\n `subdelegation.parent_id (${s.parent_id}) does not match parent envelope id (${parent.id})`\n );\n }\n if (s.principal.address !== parent.agent.address) {\n return err(\n 'E_SUBDELEGATION_PRINCIPAL_MISMATCH',\n `subdelegation.principal (${s.principal.address}) does not match parent.agent (${parent.agent.address})`\n );\n }\n\n // Step 3f: temporal containment.\n const sIssued = new Date(s.issued_at).getTime();\n const sExpires = new Date(s.expires_at).getTime();\n const pIssued = new Date(parent.issued_at).getTime();\n const pExpires = new Date(parent.expires_at).getTime();\n if (Number.isNaN(sIssued) || Number.isNaN(sExpires) || Number.isNaN(pIssued) || Number.isNaN(pExpires)) {\n return err('E_MALFORMED', 'unparseable ISO 8601 timestamp in chain');\n }\n if (sExpires <= sIssued) {\n return err('E_MALFORMED', 'subdelegation expires_at must be > issued_at');\n }\n if (sIssued < pIssued || sExpires > pExpires) {\n return err(\n 'E_SUBDELEGATION_EXPIRES_EXTENDED',\n `subdelegation window [${s.issued_at}, ${s.expires_at}) is not contained in parent's [${parent.issued_at}, ${parent.expires_at})`\n );\n }\n\n // Step 3g: scope containment (transitive narrowing).\n if (!parent.scopes) {\n return err(\n 'E_SCOPES_NEITHER_PROVIDED',\n 'parent has no plaintext scopes — caller must hydrate v1.2 parents before invoking verifyChainLink'\n );\n }\n const parentScopesParsed = parent.scopes.map((str) => parseScope(str));\n for (let i = 0; i < parsedScopes.length; i++) {\n const childScope = parsedScopes[i]!;\n const containedBySomeParentScope = parentScopesParsed.some((p) => isSubScope(childScope, p));\n if (!containedBySomeParentScope) {\n return err(\n 'E_SUBDELEGATION_SCOPE_ESCALATED',\n `subdelegation scope ${canonicalizeScope(childScope)} is not a sub-scope of any granted scope on the parent`\n );\n }\n }\n\n return {\n ok: true,\n envelope: s,\n canonicalMessage: '', // not populated for chain links; computeSubdelegationId is the binding form\n id: s.id,\n };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Standalone subdelegation verification (no action context)\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface VerifySubdelegationInput extends VerifyBase {\n envelope: SubdelegationEnvelope;\n /**\n * The immediate parent envelope. Required for linkage / containment checks.\n * If the parent is itself v1.2 private-mode (`scopes_encrypted`) the caller\n * MUST pre-hydrate it (e.g., via verifyDelegation's returned envelope) —\n * the chain walker reads `parent.scopes` directly.\n */\n parent: ChainLink;\n /** Skip the \"now ∈ [issued, expires)\" check. Useful for inspection. */\n skipTemporalCheck?: boolean;\n /** Defaults to new Date(). */\n now?: Date;\n /**\n * v1.2 private-scope decryption key for the subdelegation envelope itself.\n * Not used for the parent — the caller hydrates the parent.\n */\n decryptScopesWith?: {\n device_id: string;\n secretKey: Uint8Array;\n };\n}\n\n/**\n * Verify a single sub-delegation envelope against its immediate parent.\n * Includes the standalone temporal-validity check (`now ∈ [issued, expires)`)\n * unless `skipTemporalCheck` is set. Useful for pre-flighting a chain link\n * outside of action verification.\n */\nexport async function verifySubdelegation(\n input: VerifySubdelegationInput\n): Promise<VerifySubdelegationResult> {\n // v1.2: hydrate private-mode envelopes before chain-link checks so\n // the walker uniformly reads plaintext scopes.\n const hydrated = await hydrateSubdelegationScopes(input.envelope, input);\n if (!hydrated.ok) return hydrated;\n const r = await verifyChainLink(hydrated.envelope, input.parent, input);\n if (!r.ok) return r;\n\n if (!input.skipTemporalCheck) {\n const now = (input.now ?? new Date()).getTime();\n const issued = new Date(input.envelope.issued_at).getTime();\n const expires = new Date(input.envelope.expires_at).getTime();\n if (now < issued) return err('E_NOT_YET_VALID', `subdelegation issued_at ${input.envelope.issued_at} is in the future`);\n if (now >= expires) return err('E_EXPIRED', `subdelegation expires_at ${input.envelope.expires_at} is past`);\n }\n\n return r;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Time comparison for revocation vs action (SPEC §9.3)\n// ─────────────────────────────────────────────────────────────────────────────\n\ntype EffectiveTime =\n | { kind: 'anchor'; blockHeight: number }\n | { kind: 'signed'; ms: number };\n\nfunction actionEffectiveTime(\n a: ActionEnvelope,\n resolve?: (env: ActionEnvelope | RevocationEnvelope) => number | null\n): EffectiveTime {\n if (a.ots?.status === 'confirmed') {\n const h = resolve ? resolve(a) : a.ots.block_height;\n if (h !== null && h !== undefined) return { kind: 'anchor', blockHeight: h };\n }\n return { kind: 'signed', ms: new Date(a.signed_at).getTime() };\n}\n\nfunction effectiveRevocationTime(\n r: RevocationEnvelope,\n resolve?: (env: ActionEnvelope | RevocationEnvelope) => number | null\n): EffectiveTime {\n if (r.ots?.status === 'confirmed') {\n const h = resolve ? resolve(r) : r.ots.block_height;\n if (h !== null && h !== undefined) return { kind: 'anchor', blockHeight: h };\n }\n return { kind: 'signed', ms: new Date(r.signed_at).getTime() };\n}\n\n/** Returns <0 if a < b, 0 if equal, >0 if a > b. Anchored always beats signed-only. */\nfunction compareTimes(a: EffectiveTime, b: EffectiveTime): number {\n if (a.kind === 'anchor' && b.kind === 'anchor') return a.blockHeight - b.blockHeight;\n // If only one anchored, the anchored one is authoritative: an unanchored action cannot\n // prove priority against an anchored revocation, so the anchored side is treated as \"earlier\".\n if (a.kind === 'anchor') return -1;\n if (b.kind === 'anchor') return 1;\n return a.ms - b.ms;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n\nfunction err(code: AgentErrorCode, message: string): VerifyErrResult {\n return { ok: false, code, message };\n}\n\ntype VerifyErrResult = { ok: false; code: AgentErrorCode; message: string };\n\nfunction isHex64(s: unknown): s is string {\n return typeof s === 'string' && /^[0-9a-f]{64}$/.test(s);\n}\n\nfunction isIsoUtc(s: unknown): s is string {\n return (\n typeof s === 'string' &&\n /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$/.test(s)\n );\n}\n","// OC Agent v1.2 — Federation Principal (FEDERATION.md).\n//\n// ADDITIVE module. Implements the federation-principal extension WITHOUT\n// touching the v1 single-address path (types.ts DelegationEnvelope, verify.ts\n// verifyDelegation are unchanged + byte-identical against their vectors). A\n// dispatcher routes by `principal.alg` / `signer.alg`:\n//\n// principal.alg === 'bip322' → verifyDelegation (v1, unchanged)\n// principal.alg === 'federation' → verifyFederationDelegation (this module)\n//\n// A federation principal is a content-addressed M-of-N guardian set. A\n// delegation / revocation under it is authentic iff M of N declared guardians\n// have BIP-322-signed the canonical message. The canonical-message + id rules\n// are unchanged — only the principal line (`federation:<descriptor_id>`) and the\n// signature block (`federation-bip322` with M-of-N) generalize. FEDERATION.md\n// §2 / §3 / §4.\n\nimport { sha256 } from '@noble/hashes/sha256';\n\nimport {\n canonicalizeScopes,\n computeDelegationId,\n computeRevocationId,\n delegationCanonicalMessage,\n hexEncode,\n revocationCanonicalMessage,\n} from './canonical.js';\nimport type { ActorRef, AgentErrorCode, DelegationBond, DelegationRevocationRef } from './types.js';\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Types (FEDERATION.md §2 / §3.2)\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface FederationGuardian {\n /** mainnet Bitcoin address (P2WPKH, P2TR, or P2PKH). */\n address: string;\n alg: 'bip322';\n /** Optional human label. NOT part of the cryptographic identity. */\n name?: string;\n}\n\nexport interface FederationDescriptor {\n v: 1;\n kind: 'agent-federation';\n /** \"M-of-N\", 1 ≤ M ≤ N, N === guardians.length. */\n threshold: string;\n guardians: FederationGuardian[];\n}\n\nexport interface FederationPrincipal {\n alg: 'federation';\n descriptor_id: string;\n descriptor: FederationDescriptor;\n}\n\nexport interface FederationSignature {\n alg: 'federation-bip322';\n threshold: string;\n signatures: Array<{ guardian_address: string; value: string }>;\n}\n\nexport interface FederationDelegationEnvelope {\n v: 1;\n kind: 'agent-delegation';\n id: string;\n principal: FederationPrincipal;\n agent: ActorRef;\n scopes: string[];\n bond: DelegationBond | null;\n issued_at: string;\n expires_at: string;\n nonce: string;\n revocation: DelegationRevocationRef;\n sig: FederationSignature;\n}\n\nexport interface FederationRevocationEnvelope {\n v: 1;\n kind: 'agent-revocation';\n id: string;\n delegation_id: string;\n /** Federation principal that authorizes the revocation (the guardian set). */\n signer: FederationPrincipal;\n reason: string;\n signed_at: string;\n ots?: unknown | null;\n sig: FederationSignature;\n}\n\nexport type FederationVerifyResult =\n | { ok: true; id: string; canonicalMessage: string }\n | { ok: false; code: AgentErrorCode; message: string };\n\nexport interface VerifyFederationBase {\n /** Injected BIP-322 verifier. Required unless `skipSignatureVerification`. */\n verifyBip322?: (msg: string, signatureB64: string, address: string) => Promise<boolean>;\n skipSignatureVerification?: boolean;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Descriptor canonicalization (FEDERATION.md §2.1 / §2.2)\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * The canonical, line-oriented descriptor message. Guardians are emitted in\n * lexicographic byte order of their address (NOT the JSON array order); the\n * `name` label is excluded — it is JSON-only metadata. No trailing LF.\n */\nexport function federationDescriptorCanonicalMessage(descriptor: FederationDescriptor): string {\n const addresses = descriptor.guardians\n .map((g) => g.address)\n .sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));\n return [\n 'oc-agent:federation:v1',\n `threshold: ${descriptor.threshold}`,\n ...addresses.map((a) => `guardian: ${a}`),\n ].join('\\n');\n}\n\n/** descriptor_id := H(canonical_descriptor_bytes). 64 lowercase hex. */\nexport function computeFederationDescriptorId(descriptor: FederationDescriptor): string {\n return hexEncode(sha256(new TextEncoder().encode(federationDescriptorCanonicalMessage(descriptor))));\n}\n\nfunction parseThreshold(t: unknown): { m: number; n: number } | null {\n if (typeof t !== 'string') return null;\n const m = /^(\\d+)-of-(\\d+)$/.exec(t);\n if (!m) return null;\n const mm = Number(m[1]);\n const nn = Number(m[2]);\n if (!Number.isInteger(mm) || !Number.isInteger(nn) || mm < 1 || mm > nn) return null;\n return { m: mm, n: nn };\n}\n\nconst HEX64 = /^[0-9a-f]{64}$/;\nconst ISO_UTC = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$/;\n\n/**\n * Shared descriptor + quorum validation (FEDERATION.md §3.3 checks 3–8 minus the\n * id check, plus BIP-322). `reconstructedId` is the already-computed envelope id.\n */\nasync function checkFederationQuorum(\n principal: FederationPrincipal,\n sig: FederationSignature,\n reconstructedId: string,\n input: VerifyFederationBase\n): Promise<{ ok: true } | { ok: false; code: AgentErrorCode; message: string }> {\n // §3.3.2 — principal alg.\n if (principal?.alg !== 'federation') {\n return fail('E_MALFORMED', 'principal.alg must be \"federation\"');\n }\n const descriptor = principal.descriptor;\n if (!descriptor || descriptor.kind !== 'agent-federation') {\n return fail('E_MALFORMED', 'principal.descriptor missing or wrong kind');\n }\n const parsed = parseThreshold(descriptor.threshold);\n if (!parsed) return fail('E_MALFORMED', `malformed threshold \"${descriptor.threshold}\"`);\n if (!Array.isArray(descriptor.guardians) || descriptor.guardians.length !== parsed.n) {\n return fail('E_MALFORMED', 'guardians length must equal N in M-of-N');\n }\n\n // §3.3.3 — descriptor_id matches the canonical hash of the inlined descriptor.\n const computedDescId = computeFederationDescriptorId(descriptor);\n if (principal.descriptor_id !== computedDescId) {\n return fail(\n 'E_BAD_FEDERATION_DESCRIPTOR',\n `declared descriptor_id (${principal.descriptor_id}) != canonical hash (${computedDescId})`\n );\n }\n\n // §3.3.4 — sig.threshold equals descriptor.threshold.\n if (sig?.alg !== 'federation-bip322') {\n return fail('E_MALFORMED', 'sig.alg must be \"federation-bip322\"');\n }\n if (sig.threshold !== descriptor.threshold) {\n return fail(\n 'E_THRESHOLD_MISMATCH',\n `sig.threshold (${sig.threshold}) != descriptor.threshold (${descriptor.threshold})`\n );\n }\n\n // §3.3.5 — at least M signatures.\n const sigs = sig.signatures;\n if (!Array.isArray(sigs)) return fail('E_MALFORMED', 'sig.signatures must be an array');\n if (sigs.length < parsed.m) {\n return fail(\n 'E_THRESHOLD_NOT_MET',\n `${sigs.length} signature(s) below threshold M=${parsed.m}`\n );\n }\n\n // §3.3.6 / §3.3.7 — every signer is a declared guardian; no duplicates.\n const guardianSet = new Set(descriptor.guardians.map((g) => g.address));\n const seen = new Set<string>();\n for (const s of sigs) {\n if (!guardianSet.has(s.guardian_address)) {\n return fail('E_UNKNOWN_GUARDIAN', `${s.guardian_address} is not a declared guardian`);\n }\n if (seen.has(s.guardian_address)) {\n return fail('E_DUPLICATE_GUARDIAN', `${s.guardian_address} signed more than once`);\n }\n seen.add(s.guardian_address);\n }\n\n // §3.3.8 — each signature verifies under BIP-322 over the hex-encoded id.\n if (!input.skipSignatureVerification) {\n if (!input.verifyBip322) return fail('E_BAD_SIG', 'no BIP-322 verifier supplied');\n for (const s of sigs) {\n const ok = await input.verifyBip322(reconstructedId, s.value, s.guardian_address);\n if (!ok) {\n return fail('E_BAD_SIG', `guardian ${s.guardian_address} signature did not verify`);\n }\n }\n }\n return { ok: true };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Delegation under a federation principal (FEDERATION.md §3)\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface VerifyFederationDelegationInput extends VerifyFederationBase {\n envelope: FederationDelegationEnvelope;\n now?: Date;\n skipTemporalCheck?: boolean;\n}\n\nexport async function verifyFederationDelegation(\n input: VerifyFederationDelegationInput\n): Promise<FederationVerifyResult> {\n const env = input.envelope;\n if (env?.kind !== 'agent-delegation') return fail('E_MALFORMED', 'kind must be \"agent-delegation\"');\n if (!HEX64.test(env.id ?? '')) return fail('E_MALFORMED', 'id must be 64 lowercase hex chars');\n if (!env.agent?.address || env.agent.alg !== 'bip322') return fail('E_MALFORMED', 'agent invalid');\n if (!Array.isArray(env.scopes) || env.scopes.length === 0) {\n return fail('E_MALFORMED', 'scopes must be a non-empty array');\n }\n if (!ISO_UTC.test(env.issued_at) || !ISO_UTC.test(env.expires_at)) {\n return fail('E_MALFORMED', 'issued_at / expires_at must be ISO 8601 UTC');\n }\n if (!/^[0-9a-f]{32}$/.test(env.nonce)) return fail('E_MALFORMED', 'nonce must be 32 hex chars');\n\n // Canonical scopes (identical rules to v1) must be sorted on the envelope.\n let canonicalScopes: string[];\n try {\n canonicalScopes = canonicalizeScopes(env.scopes);\n } catch (e) {\n return fail('E_BAD_SCOPE_GRAMMAR', (e as Error).message);\n }\n for (let i = 0; i < canonicalScopes.length; i++) {\n if (env.scopes[i] !== canonicalScopes[i]) {\n return fail('E_BAD_SCOPE_GRAMMAR', `scope index ${i} not in canonical order`);\n }\n }\n\n // §3.3.1 / §3.1 — reconstruct the id with the `federation:<descriptor_id>`\n // principal substitution. Everything else is the v1 canonical message.\n const canonInput = {\n principal: `federation:${env.principal?.descriptor_id ?? ''}`,\n agent: env.agent.address,\n scopes: canonicalScopes,\n bond_sats: env.bond?.sats ?? 0,\n bond_attestation: env.bond?.attestation_id ?? 'none',\n issued_at: env.issued_at,\n expires_at: env.expires_at,\n nonce: env.nonce,\n };\n const reconstructedId = computeDelegationId(canonInput);\n if (reconstructedId !== env.id) {\n return fail('E_BAD_ID', `reconstructed id (${reconstructedId}) != envelope.id (${env.id})`);\n }\n\n const quorum = await checkFederationQuorum(env.principal, env.sig, env.id, input);\n if (!quorum.ok) return quorum;\n\n if (!input.skipTemporalCheck) {\n const now = input.now ?? new Date();\n const issued = new Date(env.issued_at);\n const expires = new Date(env.expires_at);\n if (expires <= issued) return fail('E_MALFORMED', 'expires_at <= issued_at');\n if (now < issued) return fail('E_NOT_YET_VALID', `delegation not valid until ${env.issued_at}`);\n if (now >= expires) return fail('E_EXPIRED', `delegation expired at ${env.expires_at}`);\n }\n\n return { ok: true, id: env.id, canonicalMessage: delegationCanonicalMessage(canonInput) };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Revocation under a federation principal (FEDERATION.md §4)\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface VerifyFederationRevocationInput extends VerifyFederationBase {\n envelope: FederationRevocationEnvelope;\n}\n\nexport async function verifyFederationRevocation(\n input: VerifyFederationRevocationInput\n): Promise<FederationVerifyResult> {\n const env = input.envelope;\n if (env?.kind !== 'agent-revocation') return fail('E_MALFORMED', 'kind must be \"agent-revocation\"');\n if (!HEX64.test(env.id ?? '')) return fail('E_MALFORMED', 'id must be 64 lowercase hex chars');\n if (!HEX64.test(env.delegation_id ?? '')) return fail('E_MALFORMED', 'delegation_id must be 64-hex');\n if (typeof env.reason !== 'string' || env.reason.length > 128) {\n return fail('E_MALFORMED', 'reason must be a string ≤128 bytes');\n }\n if (!ISO_UTC.test(env.signed_at)) return fail('E_MALFORMED', 'signed_at must be ISO 8601 UTC');\n\n // §4 — the `address:` line carries the `federation:<descriptor_id>`\n // substitution; everything else is the v1 revocation canonical message.\n const canonInput = {\n address: `federation:${env.signer?.descriptor_id ?? ''}`,\n delegation_id: env.delegation_id,\n reason: env.reason,\n signed_at: env.signed_at,\n };\n const reconstructedId = computeRevocationId(canonInput);\n if (reconstructedId !== env.id) {\n return fail('E_BAD_ID', `reconstructed id (${reconstructedId}) != envelope.id (${env.id})`);\n }\n\n const quorum = await checkFederationQuorum(env.signer, env.sig, env.id, input);\n if (!quorum.ok) return quorum;\n\n return { ok: true, id: env.id, canonicalMessage: revocationCanonicalMessage(canonInput) };\n}\n\nfunction fail(code: AgentErrorCode, message: string): { ok: false; code: AgentErrorCode; message: string } {\n return { ok: false, code, message };\n}\n"]}
1
+ {"version":3,"sources":["../src/types.ts","../src/scope.ts","../src/canonical.ts","../src/private-scope.ts","../src/verify.ts","../src/federation.ts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AAG;AAC7C,IAAA,MAAM,IAAI,oBAAA;AAAA,MACN,WAAA;AAAA,MACA,CAAA,EAAG,MAAM,CAAA,oCAAA,EAAuC,cAAc,CAAA,iGAAA;AAAA,KAElE;AAAA,EACJ;AAEA,EAAA,MAAM,SAAA,GAAY,WAAW,cAAc,CAAA;AAC3C,EAAA,IAAI,CAAC,MAAA,CAAO,GAAA,CAAI,UAAU,CAAA,CAAE,IAAA,CAAK,CAAC,CAAA,KAAM,UAAA,CAAW,SAAA,EAAW,CAAC,CAAC,CAAA,EAAG;AAC/D,IAAA,MAAM,IAAI,oBAAA;AAAA,MACN,cAAA;AAAA,MACA,CAAA,EAAG,MAAM,CAAA,mBAAA,EAAsB,cAAc,8CAC/B,MAAA,CAAO,IAAA,CAAK,IAAI,CAAC,CAAA,CAAA;AAAA,KACnC;AAAA,EACJ;AACJ","file":"index.js","sourcesContent":["// Wire types for OC Agent v1 envelopes. See SPEC.md §4, §5, §9.\n\nexport const ENVELOPE_VERSION = 1 as const;\n\nexport type EnvelopeKind =\n | 'agent-delegation'\n | 'agent-action'\n | 'agent-revocation'\n | 'agent-subdelegation';\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Shared building blocks\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface ActorRef {\n /** mainnet Bitcoin address (P2WPKH, P2TR, or P2PKH). */\n address: string;\n alg: 'bip322';\n}\n\nexport interface Signature {\n alg: 'bip322';\n pubkey: string; // equals the producing actor's address\n value: string; // base64 BIP-322 signature over hex(id)\n}\n\nexport type RevocationHolder = 'principal' | 'agent';\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Delegation (SPEC §4)\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface DelegationBond {\n /** Non-negative sats declared as bonded at issuance time. */\n sats: number;\n /** SHA-256 hex of the OrangeCheck canonical message signed by principal.address. */\n attestation_id: string;\n}\n\nexport interface DelegationRevocationRef {\n /** Who MAY publish a revocation. Default [\"principal\"]. */\n holders: RevocationHolder[];\n /** Optional Nostr-addressable pointer to a published revocation. Non-cryptographic. */\n ref: string | null;\n}\n\n/**\n * v1.2 private-scope mode: a wholesale OC Lock v2 LockEnvelope wrapping the\n * canonical scope list as its payload. We re-import the LockEnvelope type\n * structurally rather than depending on the @orangecheck/lock-core type — agent-\n * core's type surface stays loose so verifiers can be authored in either an\n * agent-only or full-family setup.\n */\nexport interface ScopesEncryptedEnvelope {\n v: 2;\n kind: 'identity';\n id: string;\n alg: { kem: 'x25519'; aead: 'aes-256-gcm'; kdf: 'hkdf-sha256' };\n from: { address: string; attestation_id?: string };\n recipients: Array<{\n address: string;\n device_id: string;\n device_pk: string;\n eph_pk: string;\n wrapped_key: string;\n nonce_kek: string;\n }>;\n ciphertext: string;\n nonce_ct: string;\n hint?: string;\n created_at: string;\n expires_at: string | null;\n payment: unknown | null;\n sig: { alg: 'bip322'; pubkey: string; value: string };\n}\n\nexport interface DelegationEnvelope {\n v: typeof ENVELOPE_VERSION;\n kind: 'agent-delegation';\n id: string; // 64-hex sha256(canonical_message)\n principal: ActorRef;\n agent: ActorRef;\n /**\n * v1.0 / v1.1 public mode: sorted lexicographically in the canonical\n * message; stored in sorted order on the envelope too.\n *\n * v1.2 private mode: this field is OMITTED from the envelope JSON;\n * `scopes_encrypted` is set instead. After decryption, the recovered\n * scope list takes this field's place in the in-memory envelope object\n * for the remainder of verification.\n */\n scopes?: string[];\n /**\n * v1.2 private mode (PRIVATE-SCOPE.md §1.1): an OC Lock v2 envelope\n * wrapping the canonical scope-list bytes as its payload, sealed to one\n * or more recipients (typically the agent ± named verifiers). MUTUALLY\n * EXCLUSIVE with `scopes`.\n */\n scopes_encrypted?: ScopesEncryptedEnvelope;\n bond: DelegationBond | null;\n issued_at: string; // ISO 8601 UTC\n expires_at: string; // ISO 8601 UTC\n nonce: string; // 32-hex random\n revocation: DelegationRevocationRef;\n sig: Signature;\n}\n\nexport interface DelegationCanonicalInput {\n principal: string;\n agent: string;\n scopes: string[]; // pre-canonicalized, pre-sorted\n bond_sats: number;\n /** 64-hex attestation id or the literal string \"none\". */\n bond_attestation: string;\n issued_at: string;\n expires_at: string;\n nonce: string;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Agent-action (SPEC §5) — strict extension of OC Stamp\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface ActionContent {\n hash: string; // \"sha256:<64-hex>\"\n length: number;\n mime: string;\n ref: string | null;\n}\n\nexport interface ActionOts {\n status: 'pending' | 'confirmed';\n proof: string;\n calendars: string[];\n block_height: number | null;\n block_hash: string | null;\n upgraded_at: string | null;\n}\n\nexport interface ActionEnvelope {\n v: typeof ENVELOPE_VERSION;\n kind: 'agent-action';\n id: string;\n content: ActionContent;\n signer: ActorRef; // agent\n signed_at: string;\n delegation_id: string; // 64-hex\n scope_exercised: string; // a sub-scope of some granted scope\n ots: ActionOts | null;\n sig: Signature;\n}\n\nexport interface ActionCanonicalInput {\n address: string; // agent address\n content_hash: string;\n content_length: number;\n content_mime: string;\n signed_at: string;\n delegation_id: string;\n scope_exercised: string;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Sub-delegation (SUB-DELEGATION.md, v1.1)\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface SubdelegationEnvelope {\n v: typeof ENVELOPE_VERSION;\n kind: 'agent-subdelegation';\n id: string; // 64-hex sha256(canonical_message)\n parent_id: string; // 64-hex; the immediate parent envelope's id\n /** The sub-principal — equal to parent.agent.address. */\n principal: ActorRef;\n /** The recipient sub-agent. */\n agent: ActorRef;\n /**\n * v1.0 / v1.1 public mode: each scope MUST be a sub-scope of some scope\n * on the parent. v1.2 private mode: omitted; `scopes_encrypted` set.\n */\n scopes?: string[];\n /** v1.2 private mode — same shape as the root delegation field. */\n scopes_encrypted?: ScopesEncryptedEnvelope;\n issued_at: string; // ISO 8601 UTC; >= parent.issued_at\n expires_at: string; // ISO 8601 UTC; <= parent.expires_at\n nonce: string; // 32-hex random\n revocation: DelegationRevocationRef;\n sig: Signature;\n}\n\nexport interface SubdelegationCanonicalInput {\n parent_id: string;\n principal: string;\n agent: string;\n scopes: string[]; // pre-canonicalized, pre-sorted\n issued_at: string;\n expires_at: string;\n nonce: string;\n}\n\n/** Either a root or a sub envelope; chain links walk up to a root delegation. */\nexport type ChainLink = DelegationEnvelope | SubdelegationEnvelope;\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Revocation (SPEC §9)\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface RevocationEnvelope {\n v: typeof ENVELOPE_VERSION;\n kind: 'agent-revocation';\n id: string;\n delegation_id: string;\n signer: ActorRef;\n /** Short ASCII rationale, <= 128 bytes. Empty string if omitted. */\n reason: string;\n signed_at: string;\n ots: ActionOts | null;\n sig: Signature;\n}\n\nexport interface RevocationCanonicalInput {\n address: string;\n delegation_id: string;\n reason: string;\n signed_at: string;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Error codes (SPEC §11)\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport type AgentErrorCode =\n | 'E_UNSUPPORTED_VERSION'\n | 'E_MALFORMED'\n | 'E_BAD_ID'\n | 'E_BAD_SIG'\n | 'E_BAD_SCOPE_GRAMMAR'\n | 'E_NOT_YET_VALID'\n | 'E_EXPIRED'\n | 'E_REVOKED'\n | 'E_DELEGATION_MISMATCH'\n | 'E_AGENT_MISMATCH'\n | 'E_OUT_OF_WINDOW'\n | 'E_SCOPE_DENIED'\n | 'E_BAD_ACTION_STAMP'\n | 'E_NO_BOND'\n | 'E_BOND_UNMET'\n | 'E_BOND_UNVERIFIED'\n | 'E_REVOKER_UNAUTHORIZED'\n | 'E_CALENDAR_UNREACHABLE'\n | 'E_SUBDELEGATION_DEPTH_EXCEEDED'\n | 'E_SUBDELEGATION_PRINCIPAL_MISMATCH'\n | 'E_SUBDELEGATION_EXPIRES_EXTENDED'\n | 'E_SUBDELEGATION_SCOPE_ESCALATED'\n | 'E_SCOPES_BOTH_PROVIDED'\n | 'E_SCOPES_NEITHER_PROVIDED'\n | 'E_SCOPES_UNREADABLE'\n | 'E_BAD_LOCK_ENVELOPE'\n // v1.2 federation principal (FEDERATION.md §3.3)\n | 'E_BAD_FEDERATION_DESCRIPTOR'\n | 'E_THRESHOLD_MISMATCH'\n | 'E_THRESHOLD_NOT_MET'\n | 'E_UNKNOWN_GUARDIAN'\n | 'E_DUPLICATE_GUARDIAN';\n\nexport interface VerifyOk<T> {\n ok: true;\n envelope: T;\n canonicalMessage: string;\n id: string;\n}\n\nexport interface VerifyErr {\n ok: false;\n code: AgentErrorCode;\n message: string;\n}\n\nexport type VerifyDelegationResult = VerifyOk<DelegationEnvelope> | VerifyErr;\nexport type VerifyRevocationResult = VerifyOk<RevocationEnvelope> | VerifyErr;\nexport type VerifySubdelegationResult = VerifyOk<SubdelegationEnvelope> | VerifyErr;\n\nexport interface VerifyActionOkExtra {\n /** The ROOT delegation rooting the authority chain. */\n delegation: DelegationEnvelope;\n /**\n * The sub-delegation chain `[S_1, …, S_leaf]`. Empty when the action cites\n * the root directly. The action's authority leaf is\n * `chain[chain.length - 1] ?? delegation`.\n */\n chain: SubdelegationEnvelope[];\n scopeExercised: string;\n anchor:\n | { status: 'none' }\n | { status: 'pending' }\n | { status: 'confirmed'; blockHeight: number; blockHash: string; verified: boolean };\n}\n\nexport type VerifyActionResult =\n | (VerifyOk<ActionEnvelope> & VerifyActionOkExtra)\n | VerifyErr;\n","// Scope grammar, canonicalization, and sub-scope relation. See SPEC.md §7.\n//\n// A scope is <product>:<verb>(<constraint-list>).\n// Constraints are <key><op><value>, op ∈ { =, !=, <, <=, >, >=, * }.\n// Canonical form: constraints sorted by key; no whitespace.\n\nexport type ScopeOp = '=' | '!=' | '<' | '<=' | '>' | '>=' | '*';\n\nexport interface ScopeConstraint {\n key: string;\n op: ScopeOp;\n /** `undefined` for the wildcard `*` op; otherwise the raw textual value (unquoted). */\n value: string | undefined;\n /** True if the value was supplied as a quoted string; preserved for round-trip fidelity. */\n quoted: boolean;\n}\n\nexport interface Scope {\n product: string;\n verb: string;\n constraints: ScopeConstraint[];\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Registered products/verbs (SPEC §7.3) and constraint keys (SPEC §7.6).\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport const REGISTERED_SCOPES: Record<string, { keys: string[] }> = {\n 'lock:seal': { keys: ['recipient', 'mime', 'max_bytes'] },\n 'lock:chat': { keys: ['recipient', 'max_bytes_per_msg', 'max_msgs'] },\n 'stamp:sign': { keys: ['mime', 'max_bytes', 'content_hash_prefix'] },\n 'vote:cast': { keys: ['poll_id', 'choice'] },\n 'nostr:publish': { keys: ['kind', 'relay', 'max_bytes'] },\n 'http:request': { keys: ['origin', 'method', 'max_rps', 'max_bytes_out'] },\n 'ln:send': { keys: ['max_sats', 'node', 'max_fee_sats'] },\n 'mcp:invoke': { keys: ['server', 'tool', 'max_invocations'] },\n};\n\n/** Keys whose values are compared numerically for sub-scope ordering. */\nconst NUMERIC_KEYS = new Set<string>([\n 'max_bytes',\n 'max_bytes_per_msg',\n 'max_msgs',\n 'max_bytes_out',\n 'max_rps',\n 'max_sats',\n 'max_fee_sats',\n 'max_invocations',\n 'kind',\n]);\n\nconst IDENT_RE = /^[a-z][a-z0-9_]*$/;\nconst BARE_TOKEN_RE = /^[A-Za-z0-9_.:/@+\\-]+$/;\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Parse\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport class ScopeParseError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ScopeParseError';\n }\n}\n\nexport function parseScope(input: string): Scope {\n if (typeof input !== 'string' || input.length === 0) {\n throw new ScopeParseError('scope must be a non-empty string');\n }\n if (/\\s/.test(input)) {\n throw new ScopeParseError(`scope may not contain whitespace: ${JSON.stringify(input)}`);\n }\n\n const colonIdx = input.indexOf(':');\n if (colonIdx < 0) throw new ScopeParseError('scope missing \"product:verb\" separator');\n\n const product = input.slice(0, colonIdx);\n if (!IDENT_RE.test(product)) throw new ScopeParseError(`invalid product: ${product}`);\n\n const rest = input.slice(colonIdx + 1);\n const parenIdx = rest.indexOf('(');\n\n let verb: string;\n let constraintText = '';\n if (parenIdx < 0) {\n verb = rest;\n } else {\n verb = rest.slice(0, parenIdx);\n if (!rest.endsWith(')')) throw new ScopeParseError('scope constraint list must end with \")\"');\n constraintText = rest.slice(parenIdx + 1, -1);\n }\n if (!IDENT_RE.test(verb)) throw new ScopeParseError(`invalid verb: ${verb}`);\n\n const constraints: ScopeConstraint[] = [];\n if (constraintText.length > 0) {\n for (const piece of splitTopLevelCommas(constraintText)) {\n constraints.push(parseConstraint(piece));\n }\n }\n\n // No duplicate keys.\n const seen = new Set<string>();\n for (const c of constraints) {\n if (seen.has(c.key)) throw new ScopeParseError(`duplicate constraint key: ${c.key}`);\n seen.add(c.key);\n }\n\n return { product, verb, constraints };\n}\n\nfunction splitTopLevelCommas(text: string): string[] {\n const out: string[] = [];\n let depth = 0;\n let inQuotes = false;\n let start = 0;\n for (let i = 0; i < text.length; i++) {\n const ch = text[i];\n if (inQuotes) {\n if (ch === '\\\\' && i + 1 < text.length) {\n i++;\n continue;\n }\n if (ch === '\"') inQuotes = false;\n continue;\n }\n if (ch === '\"') {\n inQuotes = true;\n continue;\n }\n if (ch === '(') depth++;\n else if (ch === ')') depth--;\n else if (ch === ',' && depth === 0) {\n out.push(text.slice(start, i));\n start = i + 1;\n }\n }\n out.push(text.slice(start));\n return out;\n}\n\nfunction parseConstraint(piece: string): ScopeConstraint {\n if (piece.length === 0) throw new ScopeParseError('empty constraint');\n\n // The `*` op (wildcard) is an op with no value. Recognized by \"key=*\" form.\n // SPEC uses \"key=*\"; we also accept \"key*\" as legacy alias.\n // Ops in descending length so \">=\" beats \">\" and \"!=\" beats \"!\".\n const OPS: ScopeOp[] = ['>=', '<=', '!=', '=', '>', '<'];\n\n // Special-case wildcard: \"key=*\" or \"key*\".\n const wildcardMatch = /^([a-z][a-z0-9_]*)(?:=\\*|\\*)$/.exec(piece);\n if (wildcardMatch) {\n return { key: wildcardMatch[1]!, op: '*', value: undefined, quoted: false };\n }\n\n for (const op of OPS) {\n const idx = piece.indexOf(op);\n if (idx <= 0) continue; // key must come first and be non-empty\n const key = piece.slice(0, idx);\n if (!IDENT_RE.test(key)) continue;\n const raw = piece.slice(idx + op.length);\n const { value, quoted } = parseValue(raw);\n return { key, op, value, quoted };\n }\n throw new ScopeParseError(`constraint missing operator: ${piece}`);\n}\n\nfunction parseValue(raw: string): { value: string; quoted: boolean } {\n if (raw.length === 0) throw new ScopeParseError('constraint value is empty');\n if (raw.startsWith('\"')) {\n if (!raw.endsWith('\"') || raw.length < 2) {\n throw new ScopeParseError(`unterminated quoted value: ${raw}`);\n }\n let v = '';\n for (let i = 1; i < raw.length - 1; i++) {\n const ch = raw[i]!;\n if (ch === '\\\\' && i + 1 < raw.length - 1) {\n const next = raw[++i]!;\n v += next;\n } else if (ch === '\"') {\n throw new ScopeParseError(`unescaped quote in value: ${raw}`);\n } else {\n v += ch;\n }\n }\n return { value: v, quoted: true };\n }\n if (!BARE_TOKEN_RE.test(raw)) {\n throw new ScopeParseError(`invalid bare-token value: ${JSON.stringify(raw)}`);\n }\n return { value: raw, quoted: false };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Canonicalize\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport function canonicalizeScope(scope: Scope): string {\n const sorted = [...scope.constraints].sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));\n const parts = sorted.map(serializeConstraint);\n const inner = parts.join(',');\n return `${scope.product}:${scope.verb}${parts.length === 0 ? '' : `(${inner})`}`;\n}\n\nexport function canonicalizeScopeString(input: string): string {\n return canonicalizeScope(parseScope(input));\n}\n\nfunction serializeConstraint(c: ScopeConstraint): string {\n if (c.op === '*') return `${c.key}=*`;\n const v = c.quoted ? quoteValue(c.value ?? '') : c.value ?? '';\n return `${c.key}${c.op}${v}`;\n}\n\nfunction quoteValue(v: string): string {\n let out = '\"';\n for (const ch of v) {\n if (ch === '\"' || ch === '\\\\') out += '\\\\' + ch;\n else out += ch;\n }\n out += '\"';\n return out;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Registry-based validation\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface ValidationOptions {\n /**\n * Strict: reject unknown products/verbs and unknown constraint keys.\n * Permissive: accept unknown products/verbs; ignore unknown keys without treating them as wider.\n * Default: 'strict'.\n */\n mode?: 'strict' | 'permissive';\n}\n\nexport function validateScope(scope: Scope, options: ValidationOptions = {}): void {\n const mode = options.mode ?? 'strict';\n const reg = REGISTERED_SCOPES[`${scope.product}:${scope.verb}`];\n if (!reg) {\n if (mode === 'strict') {\n throw new ScopeParseError(`unregistered scope: ${scope.product}:${scope.verb}`);\n }\n return; // permissive: no further checks\n }\n const registered = new Set(reg.keys);\n for (const c of scope.constraints) {\n if (!registered.has(c.key)) {\n if (mode === 'strict') {\n throw new ScopeParseError(\n `unregistered constraint key for ${scope.product}:${scope.verb}: ${c.key}`\n );\n }\n // permissive: ignore\n }\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Sub-scope relation (SPEC §7.4)\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Is `exercised` a sub-scope of `granted`?\n * Returns true iff every constraint of `granted` admits the corresponding constraint\n * (or absence) in `exercised`, per SPEC §7.4.\n */\nexport function isSubScope(exercised: Scope, granted: Scope): boolean {\n if (exercised.product !== granted.product) return false;\n if (exercised.verb !== granted.verb) return false;\n\n const exIndex = new Map<string, ScopeConstraint>();\n for (const c of exercised.constraints) exIndex.set(c.key, c);\n\n for (const g of granted.constraints) {\n const ex = exIndex.get(g.key);\n if (g.op === '*') continue; // wildcard: no requirement\n\n if (g.op === '=') {\n if (!ex) return false;\n if (ex.op !== '=' || ex.value !== g.value) return false;\n continue;\n }\n\n if (g.op === '!=') {\n if (!ex) return false;\n if (ex.op === '=' && ex.value !== g.value) continue;\n if (ex.op === '!=' && ex.value === g.value) continue;\n return false;\n }\n\n // Ordered ops: >=, <=, >, <. Exercised's implied range must be ⊆ granted's.\n if (g.op === '<' || g.op === '<=' || g.op === '>' || g.op === '>=') {\n if (!ex) return false;\n if (!NUMERIC_KEYS.has(g.key)) return false;\n if (ex.op === '*') return false;\n if (ex.value === undefined || g.value === undefined) return false;\n if (!rangeSubset(ex, g)) return false;\n continue;\n }\n }\n return true;\n}\n\nfunction rangeSubset(ex: ScopeConstraint, g: ScopeConstraint): boolean {\n const exRange = opToRange(ex);\n const gRange = opToRange(g);\n if (!exRange || !gRange) return false;\n return gRange.lo <= exRange.lo && exRange.hi <= gRange.hi;\n}\n\nfunction opToRange(c: ScopeConstraint): { lo: number; hi: number } | null {\n if (c.value === undefined) return null;\n const n = Number(c.value);\n if (!Number.isFinite(n)) return null;\n switch (c.op) {\n case '=':\n return { lo: n, hi: n };\n case '<':\n return { lo: -Infinity, hi: n - 1 }; // integers only\n case '<=':\n return { lo: -Infinity, hi: n };\n case '>':\n return { lo: n + 1, hi: Infinity };\n case '>=':\n return { lo: n, hi: Infinity };\n default:\n return null;\n }\n}\n","// Canonical messages + envelope canonicalization for OC Agent. SPEC §4.1, §5.1, §9.1.\n//\n// Three canonical-message builders live here — one per envelope kind. Each one\n// produces the exact byte sequence a signer signs via BIP-322 and the hash\n// input for the envelope id.\n//\n// The RFC 8785 JSON canonicalizer and hex utilities are re-exported from\n// @orangecheck/stamp-core so OC Agent and OC Stamp are guaranteed to produce\n// identical bytes for identical structural inputs.\n\nimport { sha256 } from '@noble/hashes/sha256';\nimport { canonicalize, hexEncode } from '@orangecheck/stamp-core/canonical';\n\nimport { canonicalizeScope, parseScope, type Scope } from './scope.js';\nimport type {\n ActionCanonicalInput,\n ActionEnvelope,\n DelegationCanonicalInput,\n DelegationEnvelope,\n RevocationCanonicalInput,\n RevocationEnvelope,\n SubdelegationCanonicalInput,\n} from './types.js';\n\nexport { canonicalize, hexEncode };\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Scope sorting + serialization\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Canonicalize and sort a list of scope strings for the delegation canonical\n * message. Each scope is first parsed, then re-emitted in canonical form\n * (constraints sorted by key), and the whole list is sorted lexicographically.\n */\nexport function canonicalizeScopes(scopes: string[]): string[] {\n const canonical = scopes.map((s) => canonicalizeScope(parseScope(s)));\n return [...canonical].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));\n}\n\n/**\n * Same as `canonicalizeScopes` but returns `Scope` objects too, for callers\n * that need them.\n */\nexport function parseAndCanonicalizeScopes(scopes: string[]): { canonical: string[]; parsed: Scope[] } {\n const parsed = scopes.map(parseScope);\n const canonicalStrings = parsed.map(canonicalizeScope);\n const indexed = canonicalStrings.map((s, i) => ({ s, p: parsed[i]! }));\n indexed.sort((a, b) => (a.s < b.s ? -1 : a.s > b.s ? 1 : 0));\n return {\n canonical: indexed.map((x) => x.s),\n parsed: indexed.map((x) => x.p),\n };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Canonical messages (SPEC §4.1, §5.1, §9.1)\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport function delegationCanonicalMessage(input: DelegationCanonicalInput): string {\n const scopeField = input.scopes.join(',');\n return [\n 'oc-agent:delegation:v1',\n `principal: ${input.principal}`,\n `agent: ${input.agent}`,\n `scopes: ${scopeField}`,\n `bond_sats: ${input.bond_sats}`,\n `bond_attestation: ${input.bond_attestation}`,\n `issued_at: ${input.issued_at}`,\n `expires_at: ${input.expires_at}`,\n `nonce: ${input.nonce}`,\n ].join('\\n');\n}\n\nexport function actionCanonicalMessage(input: ActionCanonicalInput): string {\n return [\n 'oc-agent:action:v1',\n `address: ${input.address}`,\n `content_hash: ${input.content_hash}`,\n `content_length: ${input.content_length}`,\n `content_mime: ${input.content_mime}`,\n `signed_at: ${input.signed_at}`,\n `delegation_id: ${input.delegation_id}`,\n `scope_exercised: ${input.scope_exercised}`,\n ].join('\\n');\n}\n\nexport function revocationCanonicalMessage(input: RevocationCanonicalInput): string {\n return [\n 'oc-agent:revocation:v1',\n `address: ${input.address}`,\n `delegation_id: ${input.delegation_id}`,\n `reason: ${input.reason}`,\n `signed_at: ${input.signed_at}`,\n ].join('\\n');\n}\n\nexport function subdelegationCanonicalMessage(input: SubdelegationCanonicalInput): string {\n const scopeField = input.scopes.join(',');\n return [\n 'oc-agent:subdelegation:v1',\n `parent_id: ${input.parent_id}`,\n `principal: ${input.principal}`,\n `agent: ${input.agent}`,\n `scopes: ${scopeField}`,\n `issued_at: ${input.issued_at}`,\n `expires_at: ${input.expires_at}`,\n `nonce: ${input.nonce}`,\n ].join('\\n');\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Bytes + ids\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport function delegationCanonicalBytes(input: DelegationCanonicalInput): Uint8Array {\n return new TextEncoder().encode(delegationCanonicalMessage(input));\n}\n\nexport function actionCanonicalBytes(input: ActionCanonicalInput): Uint8Array {\n return new TextEncoder().encode(actionCanonicalMessage(input));\n}\n\nexport function revocationCanonicalBytes(input: RevocationCanonicalInput): Uint8Array {\n return new TextEncoder().encode(revocationCanonicalMessage(input));\n}\n\nexport function subdelegationCanonicalBytes(input: SubdelegationCanonicalInput): Uint8Array {\n return new TextEncoder().encode(subdelegationCanonicalMessage(input));\n}\n\nexport function computeDelegationId(input: DelegationCanonicalInput): string {\n return hexEncode(sha256(delegationCanonicalBytes(input)));\n}\n\nexport function computeActionId(input: ActionCanonicalInput): string {\n return hexEncode(sha256(actionCanonicalBytes(input)));\n}\n\nexport function computeRevocationId(input: RevocationCanonicalInput): string {\n return hexEncode(sha256(revocationCanonicalBytes(input)));\n}\n\nexport function computeSubdelegationId(input: SubdelegationCanonicalInput): string {\n return hexEncode(sha256(subdelegationCanonicalBytes(input)));\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Envelope canonicalization (SPEC §6; RFC 8785 + scope-sorting)\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport function canonicalizeDelegation(env: DelegationEnvelope): string {\n return canonicalize(env as unknown as Parameters<typeof canonicalize>[0]);\n}\n\nexport function canonicalizeAction(env: ActionEnvelope): string {\n return canonicalize(env as unknown as Parameters<typeof canonicalize>[0]);\n}\n\nexport function canonicalizeRevocation(env: RevocationEnvelope): string {\n return canonicalize(env as unknown as Parameters<typeof canonicalize>[0]);\n}\n\nexport function canonicalDelegationBytes(env: DelegationEnvelope): Uint8Array {\n return new TextEncoder().encode(canonicalizeDelegation(env) + '\\n');\n}\n\nexport function canonicalActionBytes(env: ActionEnvelope): Uint8Array {\n return new TextEncoder().encode(canonicalizeAction(env) + '\\n');\n}\n\nexport function canonicalRevocationBytes(env: RevocationEnvelope): Uint8Array {\n return new TextEncoder().encode(canonicalizeRevocation(env) + '\\n');\n}\n\nexport function sha256Hex(bytes: Uint8Array): string {\n return hexEncode(sha256(bytes));\n}\n","// Private-scope helpers (PRIVATE-SCOPE.md, v1.2). Wrapping the OC Lock\n// `seal` and `unseal` primitives with the OC Agent-specific payload format\n// (canonical JSON array of scope strings, UTF-8 encoded).\n//\n// Why this lives in agent-core and not the consumer side: the canonical-\n// message commitment is the same across modes, so verifyDelegation needs to\n// be able to recover the plaintext. Centralizing the payload codec here\n// means every conformant verifier hashes the same bytes.\n\nimport { seal as lockSeal, unseal as lockUnseal } from '@orangecheck/lock-core';\nimport type {\n DeviceRecord,\n LockEnvelope,\n SealInput,\n UnsealInput,\n} from '@orangecheck/lock-core';\n\nimport { canonicalizeScopes } from './canonical.js';\nimport type { ScopesEncryptedEnvelope } from './types.js';\n\n/**\n * The plaintext payload sealed inside the OC Lock envelope. Canonical JSON\n * array of scope strings. Scopes are first put in canonical form (constraints\n * sorted by key) and the array is sorted lexicographically — same discipline\n * as v1.0 public-mode `scopes` field, so that the canonical-message bytes\n * match byte-for-byte across modes.\n */\nexport function encodeScopesPayload(scopes: string[]): Uint8Array {\n const canonical = canonicalizeScopes(scopes);\n const json = JSON.stringify(canonical);\n return new TextEncoder().encode(json);\n}\n\n/**\n * Inverse of `encodeScopesPayload`. Returns the canonicalized scope array.\n * Throws if the payload doesn't decode to a string array.\n */\nexport function decodeScopesPayload(bytes: Uint8Array): string[] {\n const json = new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n const parsed: unknown = JSON.parse(json);\n if (!Array.isArray(parsed) || !parsed.every((s) => typeof s === 'string')) {\n throw new Error('scopes payload must be a JSON array of strings');\n }\n return parsed as string[];\n}\n\nexport interface SealScopesInput {\n scopes: string[];\n /** Principal / sender — the same address that signs the OC Agent envelope. */\n sender: SealInput['sender'];\n /** Authorized decryptors. Must include at least the agent. */\n recipients: DeviceRecord[];\n /** Optional human hint stored in the OC Lock envelope. */\n hint?: string;\n /** Optional expiry on the OC Lock envelope itself. Independent of the\n * delegation's expires_at; usually left null. */\n expiresAt?: Date | null;\n}\n\n/**\n * Seal a scope list to one or more recipients. Returns the OC Lock envelope\n * to be embedded as `delegation.scopes_encrypted`.\n */\nexport async function sealScopes(\n input: SealScopesInput\n): Promise<ScopesEncryptedEnvelope> {\n const env = await lockSeal({\n kind: 'identity',\n payload: encodeScopesPayload(input.scopes),\n sender: input.sender,\n recipients: input.recipients,\n ...(input.hint !== undefined && { hint: input.hint }),\n ...(input.expiresAt !== undefined && { expiresAt: input.expiresAt }),\n });\n return env as unknown as ScopesEncryptedEnvelope;\n}\n\nexport interface UnsealScopesInput {\n envelope: ScopesEncryptedEnvelope;\n device: UnsealInput['device'];\n /** BIP-322 verifier callback. If omitted, the embedded LockEnvelope's\n * signature is NOT checked — useful for inspection or test paths. */\n verifyBip322?: UnsealInput['verifyBip322'];\n /** Skip the inner sender-signature check entirely. Default false. */\n skipSenderVerification?: boolean;\n}\n\n/** Result of unseal: decoded scope list plus the recovered sender address. */\nexport interface UnsealedScopes {\n scopes: string[];\n sender: { address: string; attestation_id?: string };\n matchedDeviceId: string;\n}\n\n/**\n * Decrypt an OC Agent v1.2 `scopes_encrypted` field with one of the\n * recipient device keys.\n */\nexport async function unsealScopes(\n input: UnsealScopesInput\n): Promise<UnsealedScopes> {\n const r = await lockUnseal({\n envelope: input.envelope as unknown as LockEnvelope,\n device: input.device,\n ...(input.verifyBip322 ? { verifyBip322: input.verifyBip322 } : {}),\n ...(input.skipSenderVerification !== undefined && {\n skipSenderVerification: input.skipSenderVerification,\n }),\n });\n return {\n scopes: decodeScopesPayload(r.payload),\n sender: r.sender,\n matchedDeviceId: r.matchedDeviceId,\n };\n}\n\n/** Convenience predicate. */\nexport function hasPrivateScopes<\n T extends { scopes?: string[]; scopes_encrypted?: ScopesEncryptedEnvelope }\n>(envelope: T): envelope is T & { scopes_encrypted: ScopesEncryptedEnvelope } {\n return !!envelope.scopes_encrypted;\n}\n","// verifyDelegation / verifyAction / verifyRevocation — reference implementation\n// of OC Agent v1 verification. SPEC §8.\n\nimport { sha256 } from '@noble/hashes/sha256';\n\nimport {\n actionCanonicalBytes,\n actionCanonicalMessage,\n canonicalizeScopes,\n computeSubdelegationId,\n delegationCanonicalBytes,\n delegationCanonicalMessage,\n hexEncode,\n revocationCanonicalBytes,\n revocationCanonicalMessage,\n} from './canonical.js';\nimport { unsealScopes } from './private-scope.js';\nimport {\n canonicalizeScope,\n isSubScope,\n parseScope,\n ScopeParseError,\n validateScope,\n type ValidationOptions,\n} from './scope.js';\nimport {\n ENVELOPE_VERSION,\n type ActionEnvelope,\n type AgentErrorCode,\n type ChainLink,\n type DelegationEnvelope,\n type RevocationEnvelope,\n type SubdelegationEnvelope,\n type VerifyActionResult,\n type VerifyDelegationResult,\n type VerifyRevocationResult,\n type VerifySubdelegationResult,\n} from './types.js';\n\n/** Default maximum chain depth, per SUB-DELEGATION.md §2.1. */\nexport const DEFAULT_MAX_CHAIN_DEPTH = 5;\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Shared options\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface VerifyBase {\n verifyBip322?: (msg: string, signatureB64: string, address: string) => Promise<boolean>;\n skipSignatureVerification?: boolean;\n scopeMode?: ValidationOptions['mode'];\n}\n\nexport class AgentError extends Error {\n code: AgentErrorCode;\n constructor(code: AgentErrorCode, message: string) {\n super(message);\n this.code = code;\n this.name = 'AgentError';\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Delegation (SPEC §8.1)\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface VerifyDelegationInput extends VerifyBase {\n envelope: DelegationEnvelope;\n /** Current time for temporal checks; defaults to new Date(). */\n now?: Date;\n /** Skip temporal checks entirely (useful for inspecting historical envelopes). */\n skipTemporalCheck?: boolean;\n /**\n * v1.2 private-scope decryption key. When the envelope carries\n * `scopes_encrypted`, the verifier MUST supply a device key matching one\n * of the recipient entries to recover the plaintext scope list. Without\n * this, verification returns `E_SCOPES_UNREADABLE`.\n */\n decryptScopesWith?: {\n device_id: string;\n secretKey: Uint8Array;\n };\n}\n\nexport async function verifyDelegation(input: VerifyDelegationInput): Promise<VerifyDelegationResult> {\n const env = input.envelope;\n\n if (env.v !== ENVELOPE_VERSION) {\n return err('E_UNSUPPORTED_VERSION', `delegation version ${env.v} not supported`);\n }\n\n const shape = checkDelegationShape(env);\n if (shape) return shape;\n\n // ─── v1.2 PRE-VERIFICATION (PRIVATE-SCOPE.md §2 steps P1–P6) ───────────\n // Steps P1 / P2: mutual exclusion + presence.\n if (env.scopes !== undefined && env.scopes_encrypted !== undefined) {\n return err(\n 'E_SCOPES_BOTH_PROVIDED',\n 'envelope carries both scopes and scopes_encrypted; pick one'\n );\n }\n if (env.scopes === undefined && env.scopes_encrypted === undefined) {\n return err(\n 'E_SCOPES_NEITHER_PROVIDED',\n 'envelope carries neither scopes nor scopes_encrypted'\n );\n }\n\n // The plaintext scope list. Either copied from env.scopes (public mode)\n // or recovered by decrypting env.scopes_encrypted (private mode).\n let workingScopes: string[];\n\n if (env.scopes_encrypted !== undefined) {\n // Step P3: issuer binding — the inner Lock envelope's `from.address`\n // must match the OC Agent envelope's principal.\n if (env.scopes_encrypted.from?.address !== env.principal.address) {\n return err(\n 'E_MALFORMED',\n `scopes_encrypted.from.address (${env.scopes_encrypted.from?.address}) does not match principal.address (${env.principal.address})`\n );\n }\n // Step P5: decryption capability.\n if (!input.decryptScopesWith) {\n return err(\n 'E_SCOPES_UNREADABLE',\n 'envelope carries scopes_encrypted; no decryption key provided'\n );\n }\n // Step P6: decrypt. Step P4 (inner-sig verify) is handled inside\n // unsealScopes via the same BIP-322 verifier — but only when\n // skipSignatureVerification is false.\n try {\n const r = await unsealScopes({\n envelope: env.scopes_encrypted,\n device: input.decryptScopesWith,\n ...(input.verifyBip322 ? { verifyBip322: input.verifyBip322 } : {}),\n skipSenderVerification: !!input.skipSignatureVerification,\n });\n workingScopes = r.scopes;\n } catch (e) {\n const msg = (e as Error).message ?? String(e);\n // Distinguish \"I had a key but the cryptographic operation failed\n // (bad envelope)\" from \"I had no matching recipient\" — the latter\n // is the more common case and gets E_SCOPES_UNREADABLE; the\n // former gets E_BAD_LOCK_ENVELOPE.\n if (/no matching recipient|no recipient|device_id/i.test(msg)) {\n return err('E_SCOPES_UNREADABLE', msg);\n }\n return err('E_BAD_LOCK_ENVELOPE', msg);\n }\n } else {\n workingScopes = env.scopes!;\n }\n\n // ─── Standard verification (SPEC.md §8.1) ──────────────────────────────\n // Scope grammar.\n let canonicalScopes: string[];\n try {\n for (const s of workingScopes) validateScope(parseScope(s), { mode: input.scopeMode ?? 'strict' });\n canonicalScopes = canonicalizeScopes(workingScopes);\n } catch (e) {\n const msg = e instanceof ScopeParseError ? e.message : (e as Error).message;\n return err('E_BAD_SCOPE_GRAMMAR', msg);\n }\n\n // In public mode the envelope's `scopes` array must already be in\n // canonical sorted order. (Private mode: the decrypted plaintext is\n // canonicalized at seal time, so this loop is a no-op for it.)\n for (let i = 0; i < canonicalScopes.length; i++) {\n if (workingScopes[i] !== canonicalScopes[i]) {\n return err(\n 'E_BAD_SCOPE_GRAMMAR',\n `scope at index ${i} not in canonical form; expected ${canonicalScopes[i]} got ${workingScopes[i]}`\n );\n }\n }\n\n // Canonical message reconstruction.\n const bondSats = env.bond?.sats ?? 0;\n const bondAttestation = env.bond?.attestation_id ?? 'none';\n const canonInput = {\n principal: env.principal.address,\n agent: env.agent.address,\n scopes: canonicalScopes,\n bond_sats: bondSats,\n bond_attestation: bondAttestation,\n issued_at: env.issued_at,\n expires_at: env.expires_at,\n nonce: env.nonce,\n };\n const reconstructedMessage = delegationCanonicalMessage(canonInput);\n const reconstructedId = hexEncode(sha256(delegationCanonicalBytes(canonInput)));\n if (reconstructedId !== env.id) {\n return err(\n 'E_BAD_ID',\n `reconstructed id (${reconstructedId}) does not match envelope.id (${env.id})`\n );\n }\n\n // Signature.\n if (!input.skipSignatureVerification) {\n if (!input.verifyBip322) return err('E_BAD_SIG', 'no BIP-322 verifier supplied');\n const ok = await input.verifyBip322(env.id, env.sig.value, env.principal.address);\n if (!ok) return err('E_BAD_SIG', 'BIP-322 signature did not verify');\n }\n\n // Temporal.\n if (!input.skipTemporalCheck) {\n const now = input.now ?? new Date();\n const issued = new Date(env.issued_at);\n const expires = new Date(env.expires_at);\n if (expires <= issued) return err('E_MALFORMED', 'expires_at <= issued_at');\n if (now < issued) return err('E_NOT_YET_VALID', `delegation not valid until ${env.issued_at}`);\n if (now >= expires) return err('E_EXPIRED', `delegation expired at ${env.expires_at}`);\n }\n\n // In private mode, return a hydrated envelope that includes the recovered\n // plaintext scopes so callers (verifyAction's chain walker, web-app\n // consumers) don't have to repeat the decryption.\n const returnedEnvelope: DelegationEnvelope =\n env.scopes_encrypted !== undefined\n ? { ...env, scopes: canonicalScopes }\n : env;\n\n return {\n ok: true,\n envelope: returnedEnvelope,\n canonicalMessage: reconstructedMessage,\n id: env.id,\n };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Action (SPEC §8.2–8.3)\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface VerifyActionInput extends VerifyBase {\n action: ActionEnvelope;\n /** The ROOT delegation rooting the authority chain. Always required. */\n delegation: DelegationEnvelope;\n /**\n * Optional v1.1 sub-delegation chain from S_1 (immediate child of `delegation`)\n * to S_leaf (the envelope `action.delegation_id` cites). When provided, the\n * verifier walks each link checking parent-id linkage, principal-equals-\n * parent-agent, scope containment, and temporal containment. The action's\n * delegation_id MUST equal the leaf's id; the action's signer MUST equal\n * the leaf's agent. See SUB-DELEGATION.md §2.2.\n */\n subdelegationChain?: SubdelegationEnvelope[];\n /**\n * Maximum permitted chain depth (number of subdelegations).\n * Default `DEFAULT_MAX_CHAIN_DEPTH` (5). Verifiers MAY lower; MUST NOT raise\n * silently above their advertised cap. Chains exceeding this fail with\n * E_SUBDELEGATION_DEPTH_EXCEEDED before any per-link work is performed.\n */\n maxChainDepth?: number;\n /**\n * Known revocations targeting any envelope in the chain (root + each\n * subdelegation). The verifier checks every link per SUB-DELEGATION.md §2.2\n * step 5 — a revocation against ANY link invalidates the action.\n */\n revocations?: RevocationEnvelope[];\n content?: Uint8Array;\n verifyOtsAnchor?: (proofB64: string, blockHeight: number, blockHash: string) => Promise<boolean>;\n /** If action and revocation are both OTS-anchored, pass a function that returns the comparable block height of each via proof parsing. Defaults: use envelope.ots.block_height. */\n resolveAnchorBlockHeight?: (env: ActionEnvelope | RevocationEnvelope) => number | null;\n /**\n * v1.2 private-scope decryption key. Applied to the root delegation AND\n * every subdelegation in the chain that carries `scopes_encrypted`. If a\n * link is private-mode and no key matches its recipients, verification\n * fails E_SCOPES_UNREADABLE — the chain's transitive narrowing cannot be\n * checked without the plaintext.\n */\n decryptScopesWith?: {\n device_id: string;\n secretKey: Uint8Array;\n };\n}\n\nexport async function verifyAction(input: VerifyActionInput): Promise<VerifyActionResult> {\n const a = input.action;\n const d = input.delegation;\n\n // 0. Chain-depth check (SUB-DELEGATION.md §2.1) — before any per-link work.\n const chain: SubdelegationEnvelope[] = input.subdelegationChain ?? [];\n const maxDepth = input.maxChainDepth ?? DEFAULT_MAX_CHAIN_DEPTH;\n if (chain.length > maxDepth) {\n return err(\n 'E_SUBDELEGATION_DEPTH_EXCEEDED',\n `chain depth ${chain.length} exceeds maximum ${maxDepth}`\n );\n }\n\n // 1. First verify the root delegation. verifyDelegation handles v1.2\n // private-scope hydration internally — when the root is private-mode,\n // the returned envelope already has `scopes` populated from the\n // decrypted plaintext.\n const dr = await verifyDelegation({\n envelope: d,\n verifyBip322: input.verifyBip322,\n skipSignatureVerification: input.skipSignatureVerification,\n scopeMode: input.scopeMode,\n skipTemporalCheck: true, // action window check dominates\n ...(input.decryptScopesWith ? { decryptScopesWith: input.decryptScopesWith } : {}),\n });\n if (!dr.ok) return dr;\n const rootHydrated: DelegationEnvelope = dr.envelope;\n\n // 1b. Walk the sub-delegation chain (SUB-DELEGATION.md §2.2 step 3).\n // Each link may independently be private-mode; we hydrate it before\n // handing it to verifyChainLink so the chain walker sees plaintext\n // scopes uniformly.\n let parent: ChainLink = rootHydrated;\n const hydratedChain: SubdelegationEnvelope[] = [];\n for (const sub of chain) {\n const hydrated = await hydrateSubdelegationScopes(sub, input);\n if (!hydrated.ok) return hydrated;\n const r = await verifyChainLink(hydrated.envelope, parent, input);\n if (!r.ok) return r;\n hydratedChain.push(hydrated.envelope);\n parent = hydrated.envelope;\n }\n /** The envelope `action.delegation_id` should cite (root if no chain, leaf otherwise). */\n const leaf: ChainLink =\n hydratedChain.length > 0 ? hydratedChain[hydratedChain.length - 1]! : rootHydrated;\n\n // 2. Core action checks.\n if (a.v !== ENVELOPE_VERSION) {\n return err('E_UNSUPPORTED_VERSION', `action version ${a.v} not supported`);\n }\n const shape = checkActionShape(a);\n if (shape) return shape;\n\n const canonInput = {\n address: a.signer.address,\n content_hash: a.content.hash,\n content_length: a.content.length,\n content_mime: a.content.mime,\n signed_at: a.signed_at,\n delegation_id: a.delegation_id,\n scope_exercised: a.scope_exercised,\n };\n const reconstructedMessage = actionCanonicalMessage(canonInput);\n const reconstructedId = hexEncode(sha256(actionCanonicalBytes(canonInput)));\n if (reconstructedId !== a.id) {\n return err('E_BAD_ID', `reconstructed id (${reconstructedId}) does not match action.id (${a.id})`);\n }\n\n if (!input.skipSignatureVerification) {\n if (!input.verifyBip322) return err('E_BAD_SIG', 'no BIP-322 verifier supplied');\n const ok = await input.verifyBip322(a.id, a.sig.value, a.signer.address);\n if (!ok) return err('E_BAD_ACTION_STAMP', 'action BIP-322 signature did not verify');\n }\n\n // 3. Authority chain — leaf-binding (action cites the leaf of the chain,\n // which is the root delegation when no subdelegation chain is present).\n if (a.delegation_id !== leaf.id) {\n return err('E_DELEGATION_MISMATCH', `action.delegation_id (${a.delegation_id}) != leaf.id (${leaf.id})`);\n }\n if (a.signer.address !== leaf.agent.address) {\n return err('E_AGENT_MISMATCH', `action signer (${a.signer.address}) != leaf.agent (${leaf.agent.address})`);\n }\n\n // 4. Window — against the leaf.\n const issued = new Date(leaf.issued_at).getTime();\n const expires = new Date(leaf.expires_at).getTime();\n const signed = new Date(a.signed_at).getTime();\n if (Number.isNaN(issued) || Number.isNaN(expires) || Number.isNaN(signed)) {\n return err('E_MALFORMED', 'unparseable ISO 8601 timestamp');\n }\n if (signed < issued || signed >= expires) {\n return err('E_OUT_OF_WINDOW', `action.signed_at ${a.signed_at} is outside leaf window [${leaf.issued_at}, ${leaf.expires_at})`);\n }\n\n // 5. Scope containment — against the leaf's granted set.\n // Leaf is post-hydration, so `scopes` is guaranteed populated. The\n // runtime guard satisfies the type checker and would only fire if a\n // caller bypassed the hydration path.\n if (!leaf.scopes) {\n return err('E_SCOPES_NEITHER_PROVIDED', 'leaf has no plaintext scopes after hydration');\n }\n let exercised, accepted;\n try {\n exercised = canonicalizeScope(parseScope(a.scope_exercised));\n const granted = leaf.scopes.map((s) => parseScope(s));\n const exercisedParsed = parseScope(a.scope_exercised);\n validateScope(exercisedParsed, { mode: input.scopeMode ?? 'strict' });\n accepted = granted.some((g) => isSubScope(exercisedParsed, g));\n } catch (e) {\n const msg = e instanceof ScopeParseError ? e.message : (e as Error).message;\n return err('E_BAD_SCOPE_GRAMMAR', msg);\n }\n if (!accepted) return err('E_SCOPE_DENIED', `scope_exercised (${exercised}) not a sub-scope of any granted scope`);\n\n // 6. Revocation check — applies per-link to ALL envelopes in the chain\n // (root + every subdelegation). Per SUB-DELEGATION.md §2.2 step 5, a\n // revocation against ANY link invalidates the action.\n if (input.revocations && input.revocations.length > 0) {\n const allLinks: ChainLink[] = [rootHydrated, ...hydratedChain];\n for (const link of allLinks) {\n for (const rev of input.revocations) {\n if (rev.delegation_id !== link.id) continue;\n // Verify the revocation itself (signature + canonical + signer\n // authorization). verifyRevocation accepts ChainLink, so the\n // call shape is identical for root vs sub.\n const rr = await verifyRevocation({\n envelope: rev,\n delegation: link,\n verifyBip322: input.verifyBip322,\n skipSignatureVerification: input.skipSignatureVerification,\n });\n if (!rr.ok) continue; // malformed revocations don't affect the action\n const effective = effectiveRevocationTime(rev, input.resolveAnchorBlockHeight);\n const actionTime = actionEffectiveTime(a, input.resolveAnchorBlockHeight);\n if (compareTimes(effective, actionTime) <= 0) {\n return err('E_REVOKED', `chain link ${link.id} was revoked by ${rev.id} before action was signed`);\n }\n }\n }\n }\n\n // 7. Content check.\n if (input.content) {\n const actualHash = 'sha256:' + hexEncode(sha256(input.content));\n if (actualHash !== a.content.hash) {\n return err('E_BAD_ACTION_STAMP', `content hash (${actualHash}) != action.content.hash (${a.content.hash})`);\n }\n }\n\n // 8. Anchor info.\n let anchor: VerifyActionResult extends infer R ? R extends { anchor: infer X } ? X : never : never;\n if (a.ots === null) {\n anchor = { status: 'none' } as typeof anchor;\n } else if (a.ots.status === 'pending') {\n anchor = { status: 'pending' } as typeof anchor;\n } else {\n const h = a.ots.block_height;\n const hash = a.ots.block_hash;\n if (h === null || hash === null) {\n return err('E_MALFORMED', 'confirmed OTS proof missing block_height or block_hash');\n }\n let verified = false;\n if (input.verifyOtsAnchor) {\n try {\n verified = await input.verifyOtsAnchor(a.ots.proof, h, hash);\n } catch (e) {\n return err('E_MALFORMED', `anchor verifier threw: ${(e as Error).message}`);\n }\n }\n anchor = { status: 'confirmed', blockHeight: h, blockHash: hash, verified } as typeof anchor;\n }\n\n return {\n ok: true,\n envelope: a,\n canonicalMessage: reconstructedMessage,\n id: a.id,\n delegation: rootHydrated,\n chain: hydratedChain,\n scopeExercised: exercised,\n anchor,\n };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// v1.2 chain-link hydration — decrypt scopes_encrypted on subdelegations\n// before passing them to the chain walker so all containment checks operate\n// on plaintext.\n// ─────────────────────────────────────────────────────────────────────────────\n\nasync function hydrateSubdelegationScopes(\n sub: SubdelegationEnvelope,\n input: VerifyBase & {\n decryptScopesWith?: { device_id: string; secretKey: Uint8Array };\n }\n): Promise<{ ok: true; envelope: SubdelegationEnvelope } | VerifyErrResult> {\n if (sub.scopes !== undefined && sub.scopes_encrypted !== undefined) {\n return err(\n 'E_SCOPES_BOTH_PROVIDED',\n 'subdelegation carries both scopes and scopes_encrypted'\n );\n }\n if (sub.scopes === undefined && sub.scopes_encrypted === undefined) {\n return err(\n 'E_SCOPES_NEITHER_PROVIDED',\n 'subdelegation carries neither scopes nor scopes_encrypted'\n );\n }\n if (sub.scopes_encrypted === undefined) {\n return { ok: true, envelope: sub };\n }\n if (sub.scopes_encrypted.from?.address !== sub.principal.address) {\n return err(\n 'E_MALFORMED',\n `subdelegation.scopes_encrypted.from.address (${sub.scopes_encrypted.from?.address}) does not match principal.address (${sub.principal.address})`\n );\n }\n if (!input.decryptScopesWith) {\n return err(\n 'E_SCOPES_UNREADABLE',\n 'subdelegation carries scopes_encrypted; no decryption key provided for the chain'\n );\n }\n try {\n const r = await unsealScopes({\n envelope: sub.scopes_encrypted,\n device: input.decryptScopesWith,\n ...(input.verifyBip322 ? { verifyBip322: input.verifyBip322 } : {}),\n skipSenderVerification: !!input.skipSignatureVerification,\n });\n return { ok: true, envelope: { ...sub, scopes: r.scopes } };\n } catch (e) {\n const msg = (e as Error).message ?? String(e);\n if (/no matching recipient|no recipient|device_id/i.test(msg)) {\n return err('E_SCOPES_UNREADABLE', msg);\n }\n return err('E_BAD_LOCK_ENVELOPE', msg);\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Revocation (SPEC §9, §8 transitive)\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface VerifyRevocationInput extends VerifyBase {\n envelope: RevocationEnvelope;\n /**\n * The envelope targeted by the revocation. Required to check signer is\n * authorized. May be a v1.0 root delegation OR a v1.1 sub-delegation —\n * both have identical `principal`, `agent`, `id`, and `revocation.holders`\n * field shapes per SUB-DELEGATION.md §3.\n */\n delegation: ChainLink;\n}\n\nexport async function verifyRevocation(input: VerifyRevocationInput): Promise<VerifyRevocationResult> {\n const env = input.envelope;\n const d = input.delegation;\n\n if (env.v !== ENVELOPE_VERSION) {\n return err('E_UNSUPPORTED_VERSION', `revocation version ${env.v} not supported`);\n }\n const shape = checkRevocationShape(env);\n if (shape) return shape;\n\n if (env.delegation_id !== d.id) {\n return err('E_DELEGATION_MISMATCH', `revocation.delegation_id (${env.delegation_id}) != delegation.id (${d.id})`);\n }\n\n // Signer must be authorized per delegation.revocation.holders.\n const holders = d.revocation?.holders ?? ['principal'];\n const holderAddrs = new Set<string>();\n if (holders.includes('principal')) holderAddrs.add(d.principal.address);\n if (holders.includes('agent')) holderAddrs.add(d.agent.address);\n if (!holderAddrs.has(env.signer.address)) {\n return err('E_REVOKER_UNAUTHORIZED', `revocation signer ${env.signer.address} not in delegation holders`);\n }\n\n const canonInput = {\n address: env.signer.address,\n delegation_id: env.delegation_id,\n reason: env.reason,\n signed_at: env.signed_at,\n };\n const reconstructedMessage = revocationCanonicalMessage(canonInput);\n const reconstructedId = hexEncode(sha256(revocationCanonicalBytes(canonInput)));\n if (reconstructedId !== env.id) {\n return err('E_BAD_ID', `reconstructed id (${reconstructedId}) does not match revocation.id (${env.id})`);\n }\n\n if (!input.skipSignatureVerification) {\n if (!input.verifyBip322) return err('E_BAD_SIG', 'no BIP-322 verifier supplied');\n const ok = await input.verifyBip322(env.id, env.sig.value, env.signer.address);\n if (!ok) return err('E_BAD_SIG', 'revocation BIP-322 signature did not verify');\n }\n\n return { ok: true, envelope: env, canonicalMessage: reconstructedMessage, id: env.id };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Shape checks\n// ─────────────────────────────────────────────────────────────────────────────\n\nfunction checkDelegationShape(env: DelegationEnvelope): VerifyDelegationResult | null {\n if (env.kind !== 'agent-delegation') return err('E_MALFORMED', 'kind must be \"agent-delegation\"');\n if (!isHex64(env.id)) return err('E_MALFORMED', 'id must be 64 lowercase hex chars');\n if (!env.principal?.address || env.principal.alg !== 'bip322') return err('E_MALFORMED', 'principal invalid');\n if (!env.agent?.address || env.agent.alg !== 'bip322') return err('E_MALFORMED', 'agent invalid');\n // v1.2: scopes OR scopes_encrypted (exactly one). Mutual exclusion +\n // presence checks are performed by the verify-time PRE-VERIFICATION block\n // (PRIVATE-SCOPE.md §2 steps P1–P2) so they can return their own error\n // codes (E_SCOPES_BOTH_PROVIDED / E_SCOPES_NEITHER_PROVIDED) rather than\n // collapsing into E_MALFORMED.\n if (env.scopes !== undefined) {\n if (!Array.isArray(env.scopes) || env.scopes.length === 0)\n return err('E_MALFORMED', 'scopes must be non-empty array');\n }\n if (env.bond !== null) {\n if (!Number.isInteger(env.bond.sats) || env.bond.sats < 0) return err('E_MALFORMED', 'bond.sats must be non-negative integer');\n if (!isHex64(env.bond.attestation_id)) return err('E_MALFORMED', 'bond.attestation_id must be 64-hex');\n }\n if (!isIsoUtc(env.issued_at)) return err('E_MALFORMED', 'issued_at must be ISO 8601 UTC');\n if (!isIsoUtc(env.expires_at)) return err('E_MALFORMED', 'expires_at must be ISO 8601 UTC');\n if (!/^[0-9a-f]{32}$/.test(env.nonce)) return err('E_MALFORMED', 'nonce must be 32 lowercase hex chars');\n if (env.sig?.alg !== 'bip322' || typeof env.sig.value !== 'string') return err('E_MALFORMED', 'sig invalid');\n if (env.sig.pubkey !== env.principal.address) return err('E_MALFORMED', 'sig.pubkey must equal principal.address');\n return null;\n}\n\nfunction checkActionShape(a: ActionEnvelope): VerifyActionResult | null {\n if (a.kind !== 'agent-action') return err('E_MALFORMED', 'kind must be \"agent-action\"');\n if (!isHex64(a.id)) return err('E_MALFORMED', 'id must be 64 lowercase hex chars');\n if (!a.content || typeof a.content.hash !== 'string' || !a.content.hash.startsWith('sha256:')) {\n return err('E_MALFORMED', 'content.hash must start with \"sha256:\"');\n }\n if (!Number.isInteger(a.content.length) || a.content.length < 0) return err('E_MALFORMED', 'content.length invalid');\n if (!a.signer?.address || a.signer.alg !== 'bip322') return err('E_MALFORMED', 'signer invalid');\n if (!isIsoUtc(a.signed_at)) return err('E_MALFORMED', 'signed_at must be ISO 8601 UTC');\n if (!isHex64(a.delegation_id)) return err('E_MALFORMED', 'delegation_id must be 64-hex');\n if (typeof a.scope_exercised !== 'string' || a.scope_exercised.length === 0) return err('E_MALFORMED', 'scope_exercised required');\n if (a.sig?.alg !== 'bip322' || typeof a.sig.value !== 'string') return err('E_MALFORMED', 'sig invalid');\n if (a.sig.pubkey !== a.signer.address) return err('E_MALFORMED', 'sig.pubkey must equal signer.address');\n return null;\n}\n\nfunction checkRevocationShape(env: RevocationEnvelope): VerifyRevocationResult | null {\n if (env.kind !== 'agent-revocation') return err('E_MALFORMED', 'kind must be \"agent-revocation\"');\n if (!isHex64(env.id)) return err('E_MALFORMED', 'id must be 64 lowercase hex chars');\n if (!isHex64(env.delegation_id)) return err('E_MALFORMED', 'delegation_id must be 64-hex');\n if (!env.signer?.address || env.signer.alg !== 'bip322') return err('E_MALFORMED', 'signer invalid');\n if (typeof env.reason !== 'string' || env.reason.length > 128) return err('E_MALFORMED', 'reason must be a string <=128 bytes');\n if (!isIsoUtc(env.signed_at)) return err('E_MALFORMED', 'signed_at must be ISO 8601 UTC');\n if (env.sig?.alg !== 'bip322' || typeof env.sig.value !== 'string') return err('E_MALFORMED', 'sig invalid');\n if (env.sig.pubkey !== env.signer.address) return err('E_MALFORMED', 'sig.pubkey must equal signer.address');\n return null;\n}\n\nfunction checkSubdelegationShape(env: SubdelegationEnvelope): VerifySubdelegationResult | null {\n if (env.kind !== 'agent-subdelegation') return err('E_MALFORMED', 'kind must be \"agent-subdelegation\"');\n if (!isHex64(env.id)) return err('E_MALFORMED', 'id must be 64 lowercase hex chars');\n if (!isHex64(env.parent_id)) return err('E_MALFORMED', 'parent_id must be 64-hex');\n if (!env.principal?.address || env.principal.alg !== 'bip322') return err('E_MALFORMED', 'principal invalid');\n if (!env.agent?.address || env.agent.alg !== 'bip322') return err('E_MALFORMED', 'agent invalid');\n // v1.2: scopes OR scopes_encrypted (post-hydration the chain walker\n // always sees `scopes` populated). Mutual exclusion + presence checked\n // by hydrateSubdelegationScopes.\n if (env.scopes !== undefined) {\n if (!Array.isArray(env.scopes) || env.scopes.length === 0)\n return err('E_MALFORMED', 'scopes must be non-empty array');\n }\n // Sub-delegations MUST NOT carry a bond field (SUB-DELEGATION.md §1.3).\n if ('bond' in env && (env as { bond?: unknown }).bond !== undefined) {\n return err('E_MALFORMED', 'sub-delegation envelopes MUST NOT carry a bond field');\n }\n if (!isIsoUtc(env.issued_at)) return err('E_MALFORMED', 'issued_at must be ISO 8601 UTC');\n if (!isIsoUtc(env.expires_at)) return err('E_MALFORMED', 'expires_at must be ISO 8601 UTC');\n if (!/^[0-9a-f]{32}$/.test(env.nonce)) return err('E_MALFORMED', 'nonce must be 32 lowercase hex chars');\n if (env.sig?.alg !== 'bip322' || typeof env.sig.value !== 'string') return err('E_MALFORMED', 'sig invalid');\n if (env.sig.pubkey !== env.principal.address) return err('E_MALFORMED', 'sig.pubkey must equal principal.address');\n return null;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Sub-delegation chain link (SUB-DELEGATION.md §2.2 step 3)\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Verify a single sub-delegation envelope as a chain link from `parent`.\n * Performs steps 3a–3g in order; returns the corresponding VerifyErr on\n * failure or `{ ok: true, envelope: s }` on success.\n *\n * Skips the standalone temporal-validity check (SUB-DELEGATION.md §2.2 step\n * 3d) — for action verification, the action-window check (step 4c) on the\n * leaf is the binding temporal constraint. Callers that want a current-time\n * \"is this subdelegation active right now\" check can use `verifySubdelegation`.\n */\nasync function verifyChainLink(\n s: SubdelegationEnvelope,\n parent: ChainLink,\n input: VerifyBase\n): Promise<VerifySubdelegationResult> {\n if (s.v !== ENVELOPE_VERSION) {\n return err('E_UNSUPPORTED_VERSION', `subdelegation version ${s.v} not supported`);\n }\n const shape = checkSubdelegationShape(s);\n if (shape) return shape;\n\n // verifyChainLink expects post-hydration scopes (callers run\n // hydrateSubdelegationScopes upfront). The runtime guard makes the\n // type-checker happy and protects against bypass.\n if (!s.scopes) {\n return err(\n 'E_SCOPES_NEITHER_PROVIDED',\n 'subdelegation has no plaintext scopes — caller must hydrate v1.2 envelopes before invoking verifyChainLink'\n );\n }\n\n // Step 3a: canonical id.\n let canonicalScopesList: string[];\n try {\n canonicalScopesList = canonicalizeScopes(s.scopes);\n } catch (e) {\n const msg = e instanceof ScopeParseError ? e.message : (e as Error).message;\n return err('E_BAD_SCOPE_GRAMMAR', msg);\n }\n const canonInput = {\n parent_id: s.parent_id,\n principal: s.principal.address,\n agent: s.agent.address,\n scopes: canonicalScopesList,\n issued_at: s.issued_at,\n expires_at: s.expires_at,\n nonce: s.nonce,\n };\n const reconstructedId = computeSubdelegationId(canonInput);\n if (reconstructedId !== s.id) {\n return err('E_BAD_ID', `reconstructed subdelegation id (${reconstructedId}) does not match envelope id (${s.id})`);\n }\n\n // Step 3b: scope grammar validation (registry-aware).\n let parsedScopes;\n try {\n parsedScopes = s.scopes.map((str) => parseScope(str));\n for (const p of parsedScopes) validateScope(p, { mode: input.scopeMode ?? 'strict' });\n } catch (e) {\n const msg = e instanceof ScopeParseError ? e.message : (e as Error).message;\n return err('E_BAD_SCOPE_GRAMMAR', msg);\n }\n\n // Step 3c: BIP-322 signature.\n if (!input.skipSignatureVerification) {\n if (!input.verifyBip322) return err('E_BAD_SIG', 'no BIP-322 verifier supplied for subdelegation');\n const ok = await input.verifyBip322(s.id, s.sig.value, s.principal.address);\n if (!ok) return err('E_BAD_SIG', 'subdelegation BIP-322 signature did not verify');\n }\n\n // Step 3e: linkage.\n if (s.parent_id !== parent.id) {\n return err(\n 'E_SUBDELEGATION_PRINCIPAL_MISMATCH',\n `subdelegation.parent_id (${s.parent_id}) does not match parent envelope id (${parent.id})`\n );\n }\n if (s.principal.address !== parent.agent.address) {\n return err(\n 'E_SUBDELEGATION_PRINCIPAL_MISMATCH',\n `subdelegation.principal (${s.principal.address}) does not match parent.agent (${parent.agent.address})`\n );\n }\n\n // Step 3f: temporal containment.\n const sIssued = new Date(s.issued_at).getTime();\n const sExpires = new Date(s.expires_at).getTime();\n const pIssued = new Date(parent.issued_at).getTime();\n const pExpires = new Date(parent.expires_at).getTime();\n if (Number.isNaN(sIssued) || Number.isNaN(sExpires) || Number.isNaN(pIssued) || Number.isNaN(pExpires)) {\n return err('E_MALFORMED', 'unparseable ISO 8601 timestamp in chain');\n }\n if (sExpires <= sIssued) {\n return err('E_MALFORMED', 'subdelegation expires_at must be > issued_at');\n }\n if (sIssued < pIssued || sExpires > pExpires) {\n return err(\n 'E_SUBDELEGATION_EXPIRES_EXTENDED',\n `subdelegation window [${s.issued_at}, ${s.expires_at}) is not contained in parent's [${parent.issued_at}, ${parent.expires_at})`\n );\n }\n\n // Step 3g: scope containment (transitive narrowing).\n if (!parent.scopes) {\n return err(\n 'E_SCOPES_NEITHER_PROVIDED',\n 'parent has no plaintext scopes — caller must hydrate v1.2 parents before invoking verifyChainLink'\n );\n }\n const parentScopesParsed = parent.scopes.map((str) => parseScope(str));\n for (let i = 0; i < parsedScopes.length; i++) {\n const childScope = parsedScopes[i]!;\n const containedBySomeParentScope = parentScopesParsed.some((p) => isSubScope(childScope, p));\n if (!containedBySomeParentScope) {\n return err(\n 'E_SUBDELEGATION_SCOPE_ESCALATED',\n `subdelegation scope ${canonicalizeScope(childScope)} is not a sub-scope of any granted scope on the parent`\n );\n }\n }\n\n return {\n ok: true,\n envelope: s,\n canonicalMessage: '', // not populated for chain links; computeSubdelegationId is the binding form\n id: s.id,\n };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Standalone subdelegation verification (no action context)\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface VerifySubdelegationInput extends VerifyBase {\n envelope: SubdelegationEnvelope;\n /**\n * The immediate parent envelope. Required for linkage / containment checks.\n * If the parent is itself v1.2 private-mode (`scopes_encrypted`) the caller\n * MUST pre-hydrate it (e.g., via verifyDelegation's returned envelope) —\n * the chain walker reads `parent.scopes` directly.\n */\n parent: ChainLink;\n /** Skip the \"now ∈ [issued, expires)\" check. Useful for inspection. */\n skipTemporalCheck?: boolean;\n /** Defaults to new Date(). */\n now?: Date;\n /**\n * v1.2 private-scope decryption key for the subdelegation envelope itself.\n * Not used for the parent — the caller hydrates the parent.\n */\n decryptScopesWith?: {\n device_id: string;\n secretKey: Uint8Array;\n };\n}\n\n/**\n * Verify a single sub-delegation envelope against its immediate parent.\n * Includes the standalone temporal-validity check (`now ∈ [issued, expires)`)\n * unless `skipTemporalCheck` is set. Useful for pre-flighting a chain link\n * outside of action verification.\n */\nexport async function verifySubdelegation(\n input: VerifySubdelegationInput\n): Promise<VerifySubdelegationResult> {\n // v1.2: hydrate private-mode envelopes before chain-link checks so\n // the walker uniformly reads plaintext scopes.\n const hydrated = await hydrateSubdelegationScopes(input.envelope, input);\n if (!hydrated.ok) return hydrated;\n const r = await verifyChainLink(hydrated.envelope, input.parent, input);\n if (!r.ok) return r;\n\n if (!input.skipTemporalCheck) {\n const now = (input.now ?? new Date()).getTime();\n const issued = new Date(input.envelope.issued_at).getTime();\n const expires = new Date(input.envelope.expires_at).getTime();\n if (now < issued) return err('E_NOT_YET_VALID', `subdelegation issued_at ${input.envelope.issued_at} is in the future`);\n if (now >= expires) return err('E_EXPIRED', `subdelegation expires_at ${input.envelope.expires_at} is past`);\n }\n\n return r;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Time comparison for revocation vs action (SPEC §9.3)\n// ─────────────────────────────────────────────────────────────────────────────\n\ntype EffectiveTime =\n | { kind: 'anchor'; blockHeight: number }\n | { kind: 'signed'; ms: number };\n\nfunction actionEffectiveTime(\n a: ActionEnvelope,\n resolve?: (env: ActionEnvelope | RevocationEnvelope) => number | null\n): EffectiveTime {\n if (a.ots?.status === 'confirmed') {\n const h = resolve ? resolve(a) : a.ots.block_height;\n if (h !== null && h !== undefined) return { kind: 'anchor', blockHeight: h };\n }\n return { kind: 'signed', ms: new Date(a.signed_at).getTime() };\n}\n\nfunction effectiveRevocationTime(\n r: RevocationEnvelope,\n resolve?: (env: ActionEnvelope | RevocationEnvelope) => number | null\n): EffectiveTime {\n if (r.ots?.status === 'confirmed') {\n const h = resolve ? resolve(r) : r.ots.block_height;\n if (h !== null && h !== undefined) return { kind: 'anchor', blockHeight: h };\n }\n return { kind: 'signed', ms: new Date(r.signed_at).getTime() };\n}\n\n/** Returns <0 if a < b, 0 if equal, >0 if a > b. Anchored always beats signed-only. */\nfunction compareTimes(a: EffectiveTime, b: EffectiveTime): number {\n if (a.kind === 'anchor' && b.kind === 'anchor') return a.blockHeight - b.blockHeight;\n // If only one anchored, the anchored one is authoritative: an unanchored action cannot\n // prove priority against an anchored revocation, so the anchored side is treated as \"earlier\".\n if (a.kind === 'anchor') return -1;\n if (b.kind === 'anchor') return 1;\n return a.ms - b.ms;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n\nfunction err(code: AgentErrorCode, message: string): VerifyErrResult {\n return { ok: false, code, message };\n}\n\ntype VerifyErrResult = { ok: false; code: AgentErrorCode; message: string };\n\nfunction isHex64(s: unknown): s is string {\n return typeof s === 'string' && /^[0-9a-f]{64}$/.test(s);\n}\n\nfunction isIsoUtc(s: unknown): s is string {\n return (\n typeof s === 'string' &&\n /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$/.test(s)\n );\n}\n","// OC Agent v1.2 — Federation Principal (FEDERATION.md).\n//\n// ADDITIVE module. Implements the federation-principal extension WITHOUT\n// touching the v1 single-address path (types.ts DelegationEnvelope, verify.ts\n// verifyDelegation are unchanged + byte-identical against their vectors). A\n// dispatcher routes by `principal.alg` / `signer.alg`:\n//\n// principal.alg === 'bip322' → verifyDelegation (v1, unchanged)\n// principal.alg === 'federation' → verifyFederationDelegation (this module)\n//\n// A federation principal is a content-addressed M-of-N guardian set. A\n// delegation / revocation under it is authentic iff M of N declared guardians\n// have BIP-322-signed the canonical message. The canonical-message + id rules\n// are unchanged — only the principal line (`federation:<descriptor_id>`) and the\n// signature block (`federation-bip322` with M-of-N) generalize. FEDERATION.md\n// §2 / §3 / §4.\n\nimport { sha256 } from '@noble/hashes/sha256';\n\nimport {\n canonicalizeScopes,\n computeDelegationId,\n computeRevocationId,\n delegationCanonicalMessage,\n hexEncode,\n revocationCanonicalMessage,\n} from './canonical.js';\nimport type { ActorRef, AgentErrorCode, DelegationBond, DelegationRevocationRef } from './types.js';\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Types (FEDERATION.md §2 / §3.2)\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface FederationGuardian {\n /** mainnet Bitcoin address (P2WPKH, P2TR, or P2PKH). */\n address: string;\n alg: 'bip322';\n /** Optional human label. NOT part of the cryptographic identity. */\n name?: string;\n}\n\nexport interface FederationDescriptor {\n v: 1;\n kind: 'agent-federation';\n /** \"M-of-N\", 1 ≤ M ≤ N, N === guardians.length. */\n threshold: string;\n guardians: FederationGuardian[];\n}\n\nexport interface FederationPrincipal {\n alg: 'federation';\n descriptor_id: string;\n descriptor: FederationDescriptor;\n}\n\nexport interface FederationSignature {\n alg: 'federation-bip322';\n threshold: string;\n signatures: Array<{ guardian_address: string; value: string }>;\n}\n\nexport interface FederationDelegationEnvelope {\n v: 1;\n kind: 'agent-delegation';\n id: string;\n principal: FederationPrincipal;\n agent: ActorRef;\n scopes: string[];\n bond: DelegationBond | null;\n issued_at: string;\n expires_at: string;\n nonce: string;\n revocation: DelegationRevocationRef;\n sig: FederationSignature;\n}\n\nexport interface FederationRevocationEnvelope {\n v: 1;\n kind: 'agent-revocation';\n id: string;\n delegation_id: string;\n /** Federation principal that authorizes the revocation (the guardian set). */\n signer: FederationPrincipal;\n reason: string;\n signed_at: string;\n ots?: unknown | null;\n sig: FederationSignature;\n}\n\nexport type FederationVerifyResult =\n | { ok: true; id: string; canonicalMessage: string }\n | { ok: false; code: AgentErrorCode; message: string };\n\nexport interface VerifyFederationBase {\n /** Injected BIP-322 verifier. Required unless `skipSignatureVerification`. */\n verifyBip322?: (msg: string, signatureB64: string, address: string) => Promise<boolean>;\n skipSignatureVerification?: boolean;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Descriptor canonicalization (FEDERATION.md §2.1 / §2.2)\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * The canonical, line-oriented descriptor message. Guardians are emitted in\n * lexicographic byte order of their address (NOT the JSON array order); the\n * `name` label is excluded — it is JSON-only metadata. No trailing LF.\n */\nexport function federationDescriptorCanonicalMessage(descriptor: FederationDescriptor): string {\n const addresses = descriptor.guardians\n .map((g) => g.address)\n .sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));\n return [\n 'oc-agent:federation:v1',\n `threshold: ${descriptor.threshold}`,\n ...addresses.map((a) => `guardian: ${a}`),\n ].join('\\n');\n}\n\n/** descriptor_id := H(canonical_descriptor_bytes). 64 lowercase hex. */\nexport function computeFederationDescriptorId(descriptor: FederationDescriptor): string {\n return hexEncode(sha256(new TextEncoder().encode(federationDescriptorCanonicalMessage(descriptor))));\n}\n\nfunction parseThreshold(t: unknown): { m: number; n: number } | null {\n if (typeof t !== 'string') return null;\n const m = /^(\\d+)-of-(\\d+)$/.exec(t);\n if (!m) return null;\n const mm = Number(m[1]);\n const nn = Number(m[2]);\n if (!Number.isInteger(mm) || !Number.isInteger(nn) || mm < 1 || mm > nn) return null;\n return { m: mm, n: nn };\n}\n\nconst HEX64 = /^[0-9a-f]{64}$/;\nconst ISO_UTC = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$/;\n\n/**\n * Shared descriptor + quorum validation (FEDERATION.md §3.3 checks 3–8 minus the\n * id check, plus BIP-322). `reconstructedId` is the already-computed envelope id.\n */\nasync function checkFederationQuorum(\n principal: FederationPrincipal,\n sig: FederationSignature,\n reconstructedId: string,\n input: VerifyFederationBase\n): Promise<{ ok: true } | { ok: false; code: AgentErrorCode; message: string }> {\n // §3.3.2 — principal alg.\n if (principal?.alg !== 'federation') {\n return fail('E_MALFORMED', 'principal.alg must be \"federation\"');\n }\n const descriptor = principal.descriptor;\n if (!descriptor || descriptor.kind !== 'agent-federation') {\n return fail('E_MALFORMED', 'principal.descriptor missing or wrong kind');\n }\n const parsed = parseThreshold(descriptor.threshold);\n if (!parsed) return fail('E_MALFORMED', `malformed threshold \"${descriptor.threshold}\"`);\n if (!Array.isArray(descriptor.guardians) || descriptor.guardians.length !== parsed.n) {\n return fail('E_MALFORMED', 'guardians length must equal N in M-of-N');\n }\n\n // §3.3.3 — descriptor_id matches the canonical hash of the inlined descriptor.\n const computedDescId = computeFederationDescriptorId(descriptor);\n if (principal.descriptor_id !== computedDescId) {\n return fail(\n 'E_BAD_FEDERATION_DESCRIPTOR',\n `declared descriptor_id (${principal.descriptor_id}) != canonical hash (${computedDescId})`\n );\n }\n\n // §3.3.4 — sig.threshold equals descriptor.threshold.\n if (sig?.alg !== 'federation-bip322') {\n return fail('E_MALFORMED', 'sig.alg must be \"federation-bip322\"');\n }\n if (sig.threshold !== descriptor.threshold) {\n return fail(\n 'E_THRESHOLD_MISMATCH',\n `sig.threshold (${sig.threshold}) != descriptor.threshold (${descriptor.threshold})`\n );\n }\n\n // §3.3.5 — at least M signatures.\n const sigs = sig.signatures;\n if (!Array.isArray(sigs)) return fail('E_MALFORMED', 'sig.signatures must be an array');\n if (sigs.length < parsed.m) {\n return fail(\n 'E_THRESHOLD_NOT_MET',\n `${sigs.length} signature(s) below threshold M=${parsed.m}`\n );\n }\n\n // §3.3.6 / §3.3.7 — every signer is a declared guardian; no duplicates.\n const guardianSet = new Set(descriptor.guardians.map((g) => g.address));\n const seen = new Set<string>();\n for (const s of sigs) {\n if (!guardianSet.has(s.guardian_address)) {\n return fail('E_UNKNOWN_GUARDIAN', `${s.guardian_address} is not a declared guardian`);\n }\n if (seen.has(s.guardian_address)) {\n return fail('E_DUPLICATE_GUARDIAN', `${s.guardian_address} signed more than once`);\n }\n seen.add(s.guardian_address);\n }\n\n // §3.3.8 — each signature verifies under BIP-322 over the hex-encoded id.\n if (!input.skipSignatureVerification) {\n if (!input.verifyBip322) return fail('E_BAD_SIG', 'no BIP-322 verifier supplied');\n for (const s of sigs) {\n const ok = await input.verifyBip322(reconstructedId, s.value, s.guardian_address);\n if (!ok) {\n return fail('E_BAD_SIG', `guardian ${s.guardian_address} signature did not verify`);\n }\n }\n }\n return { ok: true };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Delegation under a federation principal (FEDERATION.md §3)\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface VerifyFederationDelegationInput extends VerifyFederationBase {\n envelope: FederationDelegationEnvelope;\n now?: Date;\n skipTemporalCheck?: boolean;\n}\n\nexport async function verifyFederationDelegation(\n input: VerifyFederationDelegationInput\n): Promise<FederationVerifyResult> {\n const env = input.envelope;\n if (env?.kind !== 'agent-delegation') return fail('E_MALFORMED', 'kind must be \"agent-delegation\"');\n if (!HEX64.test(env.id ?? '')) return fail('E_MALFORMED', 'id must be 64 lowercase hex chars');\n if (!env.agent?.address || env.agent.alg !== 'bip322') return fail('E_MALFORMED', 'agent invalid');\n if (!Array.isArray(env.scopes) || env.scopes.length === 0) {\n return fail('E_MALFORMED', 'scopes must be a non-empty array');\n }\n if (!ISO_UTC.test(env.issued_at) || !ISO_UTC.test(env.expires_at)) {\n return fail('E_MALFORMED', 'issued_at / expires_at must be ISO 8601 UTC');\n }\n if (!/^[0-9a-f]{32}$/.test(env.nonce)) return fail('E_MALFORMED', 'nonce must be 32 hex chars');\n\n // Canonical scopes (identical rules to v1) must be sorted on the envelope.\n let canonicalScopes: string[];\n try {\n canonicalScopes = canonicalizeScopes(env.scopes);\n } catch (e) {\n return fail('E_BAD_SCOPE_GRAMMAR', (e as Error).message);\n }\n for (let i = 0; i < canonicalScopes.length; i++) {\n if (env.scopes[i] !== canonicalScopes[i]) {\n return fail('E_BAD_SCOPE_GRAMMAR', `scope index ${i} not in canonical order`);\n }\n }\n\n // §3.3.1 / §3.1 — reconstruct the id with the `federation:<descriptor_id>`\n // principal substitution. Everything else is the v1 canonical message.\n const canonInput = {\n principal: `federation:${env.principal?.descriptor_id ?? ''}`,\n agent: env.agent.address,\n scopes: canonicalScopes,\n bond_sats: env.bond?.sats ?? 0,\n bond_attestation: env.bond?.attestation_id ?? 'none',\n issued_at: env.issued_at,\n expires_at: env.expires_at,\n nonce: env.nonce,\n };\n const reconstructedId = computeDelegationId(canonInput);\n if (reconstructedId !== env.id) {\n return fail('E_BAD_ID', `reconstructed id (${reconstructedId}) != envelope.id (${env.id})`);\n }\n\n const quorum = await checkFederationQuorum(env.principal, env.sig, env.id, input);\n if (!quorum.ok) return quorum;\n\n if (!input.skipTemporalCheck) {\n const now = input.now ?? new Date();\n const issued = new Date(env.issued_at);\n const expires = new Date(env.expires_at);\n if (expires <= issued) return fail('E_MALFORMED', 'expires_at <= issued_at');\n if (now < issued) return fail('E_NOT_YET_VALID', `delegation not valid until ${env.issued_at}`);\n if (now >= expires) return fail('E_EXPIRED', `delegation expired at ${env.expires_at}`);\n }\n\n return { ok: true, id: env.id, canonicalMessage: delegationCanonicalMessage(canonInput) };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Revocation under a federation principal (FEDERATION.md §4)\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface VerifyFederationRevocationInput extends VerifyFederationBase {\n envelope: FederationRevocationEnvelope;\n}\n\nexport async function verifyFederationRevocation(\n input: VerifyFederationRevocationInput\n): Promise<FederationVerifyResult> {\n const env = input.envelope;\n if (env?.kind !== 'agent-revocation') return fail('E_MALFORMED', 'kind must be \"agent-revocation\"');\n if (!HEX64.test(env.id ?? '')) return fail('E_MALFORMED', 'id must be 64 lowercase hex chars');\n if (!HEX64.test(env.delegation_id ?? '')) return fail('E_MALFORMED', 'delegation_id must be 64-hex');\n if (typeof env.reason !== 'string' || env.reason.length > 128) {\n return fail('E_MALFORMED', 'reason must be a string ≤128 bytes');\n }\n if (!ISO_UTC.test(env.signed_at)) return fail('E_MALFORMED', 'signed_at must be ISO 8601 UTC');\n\n // §4 — the `address:` line carries the `federation:<descriptor_id>`\n // substitution; everything else is the v1 revocation canonical message.\n const canonInput = {\n address: `federation:${env.signer?.descriptor_id ?? ''}`,\n delegation_id: env.delegation_id,\n reason: env.reason,\n signed_at: env.signed_at,\n };\n const reconstructedId = computeRevocationId(canonInput);\n if (reconstructedId !== env.id) {\n return fail('E_BAD_ID', `reconstructed id (${reconstructedId}) != envelope.id (${env.id})`);\n }\n\n const quorum = await checkFederationQuorum(env.signer, env.sig, env.id, input);\n if (!quorum.ok) return quorum;\n\n return { ok: true, id: env.id, canonicalMessage: revocationCanonicalMessage(canonInput) };\n}\n\nfunction fail(code: AgentErrorCode, message: string): { ok: false; code: AgentErrorCode; message: string } {\n return { ok: false, code, message };\n}\n","import { hasPrivateScopes } from './private-scope.js';\nimport { isSubScope, parseScope } from './scope.js';\nimport type { ScopesEncryptedEnvelope } from './types.js';\n\n/**\n * The minimum an adapter needs to make the authorization decision. Kept\n * structural rather than importing `Delegation` so `stampX` helpers can accept\n * the narrower shapes they already declare.\n */\nexport interface ScopeBearingDelegation {\n scopes?: string[];\n scopes_encrypted?: ScopesEncryptedEnvelope;\n}\n\n/** Distinguishes the three reasons a stamp can be refused. */\nexport class ScopeNotGrantedError extends Error {\n readonly reason: 'not_subscope' | 'scopes_encrypted' | 'no_scopes';\n constructor(reason: ScopeNotGrantedError['reason'], message: string) {\n super(message);\n this.name = 'ScopeNotGrantedError';\n this.reason = reason;\n }\n}\n\n/**\n * Refuse unless `scopeExercised` is a sub-scope of something the delegation\n * actually grants. Every `agent-*` adapter's pre-flight check routes here.\n *\n * The check itself is unchanged and still fails closed. What this adds is\n * telling the caller WHICH of three things went wrong, because the five\n * adapters each open-coded `(delegation.scopes ?? []).map(parseScope)` and so\n * reported all three as the same thing:\n *\n * - **not_subscope** — scopes are readable and this one is not among them.\n * The integrator's own mistake, and the only case the old message fit.\n * - **scopes_encrypted** — v1.2 private mode. `scopes` is absent *because it\n * is sealed to a device key*, so the adapter cannot evaluate the request at\n * all. `?? []` collapsed this into \"not a sub-scope of any granted scope\",\n * which sends the integrator to audit a scope string that may well be\n * correct, when what they need is `decryptPrivateScopes` and to pass the\n * recovered list. Refusing is right; misnaming why is not.\n * - **no_scopes** — neither field present. A delegation granting nothing.\n *\n * Fail-closed is not a judgement call here: an over-broad stamp is a signed,\n * content-addressed authorization artifact that a verifier will accept.\n */\nexport function assertScopeGranted(\n delegation: ScopeBearingDelegation,\n scopeExercised: string,\n fnName: string\n): void {\n if (hasPrivateScopes(delegation)) {\n throw new ScopeNotGrantedError(\n 'scopes_encrypted',\n `${fnName}: this delegation uses v1.2 private scopes — \\`scopes_encrypted\\` is ` +\n `set and \\`scopes\\` is absent, so the granted set cannot be read here. ` +\n `Decrypt it with decryptPrivateScopes() using a matching device key and pass ` +\n `the recovered scopes as \\`delegation.scopes\\`. Refusing to stamp ` +\n `\\`${scopeExercised}\\` against an unreadable grant.`\n );\n }\n\n const scopes = delegation.scopes;\n if (scopes === undefined || scopes.length === 0) {\n throw new ScopeNotGrantedError(\n 'no_scopes',\n `${fnName}: delegation grants no scopes, so \\`${scopeExercised}\\` cannot be ` +\n `exercised. An absent or empty \\`scopes\\` means nothing is granted, never everything.`\n );\n }\n\n const exercised = parseScope(scopeExercised);\n if (!scopes.map(parseScope).some((g) => isSubScope(exercised, g))) {\n throw new ScopeNotGrantedError(\n 'not_subscope',\n `${fnName}: scope_exercised (${scopeExercised}) is not a sub-scope of any granted ` +\n `scope (${scopes.join(', ')})`\n );\n }\n}\n"]}