@peac/protocol 0.13.2 → 0.13.3

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/_internal/record-core/codec/types.ts","../src/_internal/record-core/codec/jws-jwt.ts","../src/type-extension-check.ts","../src/_internal/record-core/shadow-hook.ts","../src/_internal/record-core/validators/kernel-constraints.ts","../src/_internal/record-core/validators/type-extension-mapping.ts","../src/_internal/record-core/validators/jose-hardening.ts","../src/_internal/record-core/validators/issuer-form.ts","../src/_internal/record-core/validators/temporal.ts","../src/_internal/record-core/validators/extension-budget.ts","../src/_internal/record-core/bounded-validator.ts","../src/_internal/shadow-redact.ts","../src/_internal/shadow.ts","../src/_internal/shadow-observe.ts","../src/verify-local.ts"],"names":["signWire02","cryptoVerify","base64urlDecodeString","KERNEL_CONSTRAINTS","TYPE_TO_EXTENSION_MAP","REGISTERED_EXTENSION_GROUP_KEYS","REGISTERED_RECEIPT_TYPES","WARNING_TYPE_UNREGISTERED","isValidExtensionKey","WARNING_UNKNOWN_EXTENSION","WARNING_EXTENSION_GROUP_MISSING","WARNING_EXTENSION_GROUP_MISMATCH","ACCEPTED","ISS_CANONICAL","OCCURRED_AT_TOLERANCE_SECONDS","escapeJsonPointerSegment","EXTENSION_BUDGET","sha256Hex","base64urlEncode","WARNING_TYP_MISSING","validateKernelConstraints","parseReceiptClaims","checkOccurredAtSkew","HASH","verifyPolicyBinding","sortWarnings"],"mappings":";;;;;;;;;AAsCO,IAAM,UAAA,GAAN,cAAyB,KAAA,CAAM;AAAA,EACpC,WAAA,CACkB,MAChB,OAAA,EACA;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAHG,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAIhB,IAAA,IAAA,CAAK,IAAA,GAAO,YAAA;AAAA,EACd;AACF,CAAA;;;ACpBA,IAAM,cAAN,MAAyC;AAAA,EAC9B,IAAA,GAAO,SAAA;A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A,CAAI;AAAA,SACf;AAAA,MACF;AAAA,IACF;AAIA,IAAA,IACE,GAAA,KAAQ,QACR,OAAO,GAAA,KAAQ,YACf,MAAA,IAAU,GAAA,IACT,GAAA,CAA0B,IAAA,KAAS,aAAA,EACpC;AACA,MAAA,MAAM,aAAA,GACJ,aAAa,GAAA,IAAO,OAAQ,IAA6B,OAAA,KAAY,QAAA,GAChE,IAA4B,OAAA,GAC7B,cAAA;AACN,MAAA,OAAO;AAAA,QACL,KAAA,EAAO,KAAA;AAAA,QACP,IAAA,EAAM,kBAAA;AAAA,QACN,OAAA,EAAS,4BAA4B,aAAa,CAAA;AAAA,OACpD;AAAA,IACF;AAIA,IAAA,MAAM,UAAU,GAAA,YAAe,KAAA,GAAQ,GAAA,CAAI,OAAA,GAAU,OAAO,GAAG,CAAA;AAC/D,IAAA,OAAO;AAAA,MACL,KAAA,EAAO,KAAA;AAAA,MACP,IAAA,EAAM,YAAA;AAAA,MACN,OAAA,EAAS,kCAAkC,OAAO,CAAA;AAAA,KACpD;AAAA,EACF;AACF;AAMO,SAAS,iBACd,CAAA,EACkD;AAElD,EAAA,OAAO,KAAA;AACT;AAMO,SAAS,oBACd,CAAA,EACkD;AAElD,EAAA,OAAO,KAAA;AACT;AAQO,SAAS,eACd,CAAA,EACkD;AAClD,EAAA,OAAO,CAAA,CAAE,KAAA,KAAU,IAAA,IAAQ,CAAA,CAAE,OAAA,KAAY,SAAA;AAC3C","file":"verify-local.cjs","sourcesContent":["/**\n * Internal codec strategy types.\n *\n * @internal\n *\n * These types MUST NOT be re-exported from packages/protocol/src/index.ts.\n * The dist-leak gate (Tier 2) asserts that these names never appear in\n * @peac/protocol's public root declaration (dist/index.d.ts) or any\n * subpath in @peac/protocol/package.json `exports`.\n *\n * The canonical implementation of these types lives at\n * packages/protocol/src/_internal/record-core/codec/jws-jwt.ts and is\n * imported via RELATIVE paths from issue.ts / verify-local.ts.\n */\n\nimport type { VerifyResult } from '@peac/crypto';\n\n/**\n * Header view returned by codec.peekHeader().\n *\n * @internal\n */\nexport interface CodecHeader {\n /** JOSE typ value. Required at peek time; not defaulted. */\n readonly typ: string;\n /** Algorithm identifier. JWS string (e.g., 'EdDSA'). */\n readonly alg: string;\n /** Key identifier (when present). */\n readonly kid?: string;\n /** Full raw protected-header object for downstream policy inspection. */\n readonly raw: Readonly<Record<string, unknown>>;\n}\n\n/**\n * Codec error with a structured code.\n *\n * @internal\n */\nexport class CodecError extends Error {\n constructor(\n public readonly code: string,\n message: string\n ) {\n super(message);\n this.name = 'CodecError';\n }\n}\n\n/**\n * Internal codec strategy. v0.13.1 ships exactly one implementation:\n * jws-jwt. Signature mirrors @peac/crypto.signWire02 / verify exactly;\n * concrete Uint8Array keys (Ed25519 at this layer); parametric only on\n * the optional payload type T of VerifyResult<T>. Future codecs with\n * different key shapes register a different interface; they MAY NOT\n * shoehorn into this interface via parametric generics.\n *\n * @internal\n */\nexport interface RecordCodec {\n /** Codec name. Used for registry lookup. */\n readonly name: string;\n\n /**\n * Sign and serialize. Pure pass-through to the underlying signer; never\n * accepts a typ override (the signer hardcodes typ per the wire format).\n */\n encode(payload: unknown, privateKey: Uint8Array, kid: string): Promise<string>;\n\n /**\n * Verify and decode. Returns the underlying crypto verifier's result\n * unchanged. Throws structured CodecError on malformed input;\n * propagates the underlying CryptoError on signature mismatch.\n */\n decode<T = unknown>(serialized: string, publicKey: Uint8Array): Promise<VerifyResult<T>>;\n\n /**\n * Header-only decode. Structural strictness only: throws CodecError on\n * missing typ, missing alg, malformed protected header JSON, or\n * malformed compact JWS (must be exactly three non-empty\n * dot-separated segments). Does NOT enforce policy on crit / zip /\n * b64 / unsupported alg; those rejections are downstream JOSE-hardening\n * responsibilities and are surfaced via the raw header for inspection.\n *\n * Note: this codec is JWS/JWT string-based. The `serialized` parameter\n * is typed as `string` for that reason. Future codecs that operate on\n * binary inputs (e.g., COSE/CBOR over `Uint8Array`) MUST register a\n * different interface; do not generalize this one to imply binary\n * support that the JWS codec does not provide.\n */\n peekHeader(serialized: string): CodecHeader;\n}\n","/**\n * Default codec: pure pass-through to @peac/crypto.signWire02 / verify.\n *\n * @internal\n *\n * Byte-identical encode output to signWire02 is guaranteed by the\n * golden-vector test (codec-jws-jwt-byte-identical.test.ts). Decode\n * returns the underlying cryptoVerify result unchanged.\n *\n * peekHeader is structural-only: it requires typ + alg presence and a\n * structurally valid compact JWS, but does NOT enforce policy on\n * unsupported alg, crit, zip, or b64:false. Those rejections are\n * downstream responsibilities (kernel constraints, JOSE hardening).\n *\n * The canonical implementation lives here. Tests import via relative\n * paths from packages/protocol/__tests__/_internal/.\n */\n\nimport {\n signWire02,\n verify as cryptoVerify,\n base64urlDecodeString,\n type VerifyResult,\n} from '@peac/crypto';\nimport { CodecError, type CodecHeader, type RecordCodec } from './types.js';\n\nclass JwsJwtCodec implements RecordCodec {\n readonly name = 'jws-jwt' as const;\n\n async encode(payload: unknown, privateKey: Uint8Array, kid: string): Promise<string> {\n return signWire02(payload, privateKey, kid);\n }\n\n async decode<T = unknown>(serialized: string, publicKey: Uint8Array): Promise<VerifyResult<T>> {\n return cryptoVerify<T>(serialized, publicKey);\n }\n\n peekHeader(serialized: string): CodecHeader {\n // Structural compact-JWS shape: exactly three non-empty\n // dot-separated segments: header.payload.signature.\n const segments = serialized.split('.');\n if (segments.length !== 3) {\n throw new CodecError(\n 'CODEC_PEEK_MALFORMED',\n `jws-jwt: malformed compact JWS (expected 3 segments, got ${segments.length})`\n );\n }\n const [headerB64, payloadB64, signatureB64] = segments;\n if (headerB64.length === 0) {\n throw new CodecError(\n 'CODEC_PEEK_MALFORMED',\n 'jws-jwt: malformed compact JWS (empty header segment)'\n );\n }\n if (payloadB64.length === 0) {\n throw new CodecError(\n 'CODEC_PEEK_MALFORMED',\n 'jws-jwt: malformed compact JWS (empty payload segment)'\n );\n }\n if (signatureB64.length === 0) {\n throw new CodecError(\n 'CODEC_PEEK_MALFORMED',\n 'jws-jwt: malformed compact JWS (empty signature segment)'\n );\n }\n\n let header: Record<string, unknown>;\n try {\n // Runtime-neutral base64url -> UTF-8 string decode\n // (TextDecoder + Uint8Array via @peac/crypto.base64urlDecodeString;\n // no Node Buffer dependency: works in browser, edge worker, Deno).\n const headerJson = base64urlDecodeString(headerB64);\n header = JSON.parse(headerJson) as Record<string, unknown>;\n } catch (err) {\n throw new CodecError(\n 'CODEC_PEEK_INVALID_HEADER',\n `jws-jwt: protected header JSON parse failed: ${(err as Error).message}`\n );\n }\n\n if (typeof header.typ !== 'string') {\n throw new CodecError(\n 'CODEC_PEEK_MISSING_TYP',\n 'jws-jwt: protected header missing required field \"typ\" (string)'\n );\n }\n if (typeof header.alg !== 'string') {\n throw new CodecError(\n 'CODEC_PEEK_MISSING_ALG',\n 'jws-jwt: protected header missing required field \"alg\" (string)'\n );\n }\n\n return {\n typ: header.typ,\n alg: header.alg,\n kid: typeof header.kid === 'string' ? header.kid : undefined,\n raw: header,\n };\n }\n}\n\n/**\n * Default codec instance. Internal-only.\n *\n * @internal\n */\nexport const defaultCodec: RecordCodec = new JwsJwtCodec();\n","/**\n * Type-to-extension enforcement check (Layer 3)\n *\n * Pure helper: given a receipt kind, type, extensions record, and\n * registry data, determines whether the expected extension group is\n * present, absent, or replaced by a different registered group.\n *\n * This module has no side effects, no I/O, and no strictness logic.\n * Strictness (error vs warning) is decided by the caller (verifyLocal).\n *\n * Decision tree:\n * 1. challenge-kind receipt -> skip\n * 2. unmapped/custom type -> skip\n * 3. expected extension present -> ok\n * 4. expected absent + other registered present -> mismatch\n * 5. expected absent + none present -> missing\n *\n * Unknown third-party extension keys never count as mismatch.\n */\n\n/** Result of the type-to-extension mapping check */\nexport type TypeExtensionCheckResult =\n | { status: 'ok' }\n | { status: 'skip' }\n | {\n status: 'missing' | 'mismatch';\n expected_extension_group: string;\n present_registered_extension_groups: string[];\n };\n\n/**\n * Check whether a receipt's extensions match the expected extension\n * group for its registered type.\n *\n * Performance: O(1) lookup for the common ok/skip paths. Only iterates\n * extension keys when the expected group is absent (error path).\n *\n * @param kind - Receipt kind (evidence or challenge)\n * @param type - Receipt type value (e.g., org.peacprotocol/payment)\n * @param extensions - Extensions record from receipt claims (may be undefined)\n * @param typeToExtensionMap - Generated TYPE_TO_EXTENSION_MAP\n * @param registeredExtensionGroupKeys - Generated REGISTERED_EXTENSION_GROUP_KEYS set\n */\nexport function checkTypeExtensionMapping(\n kind: string,\n type: string,\n extensions: Record<string, unknown> | undefined,\n typeToExtensionMap: ReadonlyMap<string, string>,\n registeredExtensionGroupKeys: ReadonlySet<string>\n): TypeExtensionCheckResult {\n // Challenge-kind receipts skip: they indicate requirements, not evidence\n if (kind === 'challenge') {\n return { status: 'skip' };\n }\n\n const expectedGroup = typeToExtensionMap.get(type);\n\n // Unmapped/custom type: no check\n if (expectedGroup === undefined) {\n return { status: 'skip' };\n }\n\n // Expected group present: pass (O(1) check)\n if (extensions !== undefined && Object.prototype.hasOwnProperty.call(extensions, expectedGroup)) {\n return { status: 'ok' };\n }\n\n // Expected group absent: determine missing vs mismatch\n // Only build the present-registered list on this (uncommon) path\n const presentRegistered: string[] = [];\n if (extensions !== undefined) {\n for (const key of Object.keys(extensions)) {\n if (key !== expectedGroup && registeredExtensionGroupKeys.has(key)) {\n presentRegistered.push(key);\n }\n }\n }\n\n return {\n status: presentRegistered.length > 0 ? 'mismatch' : 'missing',\n expected_extension_group: expectedGroup,\n present_registered_extension_groups: presentRegistered,\n };\n}\n","/**\n * Inert shadow-call boundary for the bounded validator foundation.\n *\n * INTERNAL ONLY. This module is the call-site placeholder that PR D\n * will wire to the bounded validator pipeline behind an internal\n * feature flag. In v0.13.1 the boundary is INERT by construction:\n *\n * - the only declared mode is `'disabled'`\n * - the function body is a single early return on `'disabled'`\n * - it imports no bounded validators (zero runtime weight at\n * verify-local.ts cold-start, even though the call site exists)\n * - it never throws into verifyLocal()\n * - it never mutates the input claims object\n * - it never logs\n * - it never reads environment variables\n * - it never affects the canonical verify-local result\n *\n * The function returns `undefined` for every call. The call site in\n * verify-local.ts ignores the return value and never awaits any work.\n *\n * NOT re-exported from packages/protocol/src/index.ts. Public surface\n * is byte-stable. PR D may extend the input shape when wiring the\n * actual flag plumbing; that is a future-internal change, not a\n * public API change.\n */\n\n/**\n * The only declared shadow validation mode. Adding new modes requires\n * a deliberate future change in PR D where the actual flag is wired.\n */\nexport type ShadowValidationMode = 'disabled';\n\n/**\n * Input shape for the shadow-call boundary. `claims` is intentionally\n * `unknown` so callers may pass parsed Wire 0.2 claims without a\n * coupling to the schema's exported type from this internal helper.\n */\nexport interface ShadowValidationInput {\n readonly mode: ShadowValidationMode;\n readonly claims: unknown;\n}\n\n/**\n * Inert shadow-call hook. Always returns `undefined`. The signature\n * is stable enough for PR D to extend (e.g., adding a `header` or\n * `now` field) without breaking the disabled-default contract.\n */\nexport function maybeRunShadowValidation(input: ShadowValidationInput): undefined {\n if (input.mode === 'disabled') return undefined;\n return undefined;\n}\n","/**\n * Bounded internal kernel-constraints validator.\n *\n * INTERNAL ONLY. This is the parity-observed counterpart of\n * @peac/schema.validateKernelConstraints; both implementations consume\n * the same KERNEL_CONSTRAINTS constants from @peac/kernel and emit the\n * same ConstraintValidationResult shape. The differential parity test\n * asserts byte-identical equality between the two on every eligible\n * fixture; any divergence is stop-the-line.\n *\n * Existing validation in @peac/schema remains canonical. This module\n * is observational only; it is NOT re-exported from\n * packages/protocol/src/index.ts and is NOT wired into runtime paths\n * (issue.ts, verify-local.ts) in v0.13.1.\n *\n * Implementation invariants (must mirror @peac/schema/src/constraints.ts\n * verbatim; any drift fails the parity test):\n * - iterative stack-based traversal (stack-safe; no recursion)\n * - every value (primitives, arrays, objects) is pushed and counted as\n * a node when popped\n * - total-nodes check evaluated FIRST per pop; over-limit pushes the\n * violation with the current totalNodes count and breaks (preserves\n * first-violation semantics)\n * - depth check evaluated SECOND per pop; over-limit pushes a\n * violation and continues (no-op for primitives, prevents deeper\n * descent for containers)\n * - string-length check (primitives only) uses .length (code units)\n * - array-length and object-key-count checks pushed BEFORE descending\n * into children\n * - children pushed in reverse index/key order so traversal visits\n * them in original order (LIFO)\n * - empty path for root; bracket notation for arrays (`a[0]`); dot\n * notation for object keys (`a.b`)\n * - returns { valid: violations.length === 0, violations }\n * - never throws\n * - assumes acyclic input\n */\n\nimport { KERNEL_CONSTRAINTS } from '@peac/schema';\nimport type { ConstraintValidationResult, ConstraintViolation } from '@peac/schema';\n\n/**\n * Validate claims against structural kernel constraints. Mirrors the\n * canonical implementation in @peac/schema for parity.\n *\n * Distinct exported name (validateKernelConstraintsInternal) to avoid\n * collision with the canonical @peac/schema export when both are\n * imported into the same parity test file.\n */\nexport function validateKernelConstraintsInternal(claims: unknown): ConstraintValidationResult {\n const violations: ConstraintViolation[] = [];\n\n if (claims === null || claims === undefined || typeof claims !== 'object') {\n return { valid: true, violations };\n }\n\n let totalNodes = 0;\n const stack: Array<{ value: unknown; depth: number; path: string }> = [\n { value: claims, depth: 0, path: '' },\n ];\n\n while (stack.length > 0) {\n const item = stack.pop()!;\n totalNodes++;\n\n if (totalNodes > KERNEL_CONSTRAINTS.MAX_TOTAL_NODES) {\n violations.push({\n constraint: 'MAX_TOTAL_NODES',\n actual: totalNodes,\n limit: KERNEL_CONSTRAINTS.MAX_TOTAL_NODES,\n path: item.path,\n });\n break;\n }\n\n if (item.depth > KERNEL_CONSTRAINTS.MAX_NESTED_DEPTH) {\n violations.push({\n constraint: 'MAX_NESTED_DEPTH',\n actual: item.depth,\n limit: KERNEL_CONSTRAINTS.MAX_NESTED_DEPTH,\n path: item.path,\n });\n continue;\n }\n\n if (item.value === null || typeof item.value !== 'object') {\n if (typeof item.value === 'string') {\n if (item.value.length > KERNEL_CONSTRAINTS.MAX_STRING_LENGTH) {\n violations.push({\n constraint: 'MAX_STRING_LENGTH',\n actual: item.value.length,\n limit: KERNEL_CONSTRAINTS.MAX_STRING_LENGTH,\n path: item.path,\n });\n }\n }\n continue;\n }\n\n if (Array.isArray(item.value)) {\n if (item.value.length > KERNEL_CONSTRAINTS.MAX_ARRAY_LENGTH) {\n violations.push({\n constraint: 'MAX_ARRAY_LENGTH',\n actual: item.value.length,\n limit: KERNEL_CONSTRAINTS.MAX_ARRAY_LENGTH,\n path: item.path,\n });\n }\n for (let i = item.value.length - 1; i >= 0; i--) {\n stack.push({\n value: item.value[i],\n depth: item.depth + 1,\n path: `${item.path}[${i}]`,\n });\n }\n continue;\n }\n\n const keys = Object.keys(item.value as Record<string, unknown>);\n if (keys.length > KERNEL_CONSTRAINTS.MAX_OBJECT_KEYS) {\n violations.push({\n constraint: 'MAX_OBJECT_KEYS',\n actual: keys.length,\n limit: KERNEL_CONSTRAINTS.MAX_OBJECT_KEYS,\n path: item.path,\n });\n }\n for (let i = keys.length - 1; i >= 0; i--) {\n const key = keys[i];\n const childPath = item.path ? `${item.path}.${key}` : key;\n stack.push({\n value: (item.value as Record<string, unknown>)[key],\n depth: item.depth + 1,\n path: childPath,\n });\n }\n }\n\n return { valid: violations.length === 0, violations };\n}\n","/**\n * Bounded internal type-extension mapping validator.\n *\n * INTERNAL ONLY. This is the parity-observed counterpart of the\n * type/extension warning-emission block at verify-local.ts:477-540\n * (interop strictness branch). Both implementations consume the same\n * registries (REGISTERED_RECEIPT_TYPES, REGISTERED_EXTENSION_GROUP_KEYS,\n * TYPE_TO_EXTENSION_MAP) and the same warning-code constants from\n * @peac/schema; behavioral parity is proven byte-equal by the parity\n * tests, not by code copy.\n *\n * Existing canonical emission in @peac/protocol/verifyLocal remains\n * canonical. This module is observational only; it is NOT re-exported\n * from packages/protocol/src/index.ts and is NOT wired into runtime\n * paths (issue.ts, verify-local.ts) in v0.13.1.\n *\n * Output shape: a deterministically-ordered list of warning records,\n * each carrying only `code` and `pointer`. The canonical emission also\n * carries a `message` field; messages are intentionally omitted from\n * the parity comparison because the missing/mismatch messages embed\n * claim values (claims.type and the expected extension group), and\n * comparison on (code, pointer) is what the verifier output API\n * actually exposes to consumers via the warning code/pointer pair.\n *\n * Emission order (must mirror verify-local.ts exactly; tests assert):\n * 1. type_unregistered (when claims.type is not in REGISTERED_RECEIPT_TYPES)\n * 2. unknown_extension_preserved (one per unknown-but-well-formed\n * extension key, in Object.keys iteration order)\n * 3. extension_group_missing OR extension_group_mismatch (when\n * checkTypeExtensionMapping returns missing/mismatch; not emitted\n * for kind === 'challenge' or for unmapped/custom types)\n */\n\nimport {\n REGISTERED_EXTENSION_GROUP_KEYS,\n REGISTERED_RECEIPT_TYPES,\n WARNING_EXTENSION_GROUP_MISMATCH,\n WARNING_EXTENSION_GROUP_MISSING,\n WARNING_TYPE_UNREGISTERED,\n WARNING_UNKNOWN_EXTENSION,\n isValidExtensionKey,\n} from '@peac/schema';\nimport { TYPE_TO_EXTENSION_MAP } from '@peac/kernel';\n\n/** Minimal claims shape required by the type-extension warning surface. */\nexport interface TypeExtensionMappingInput {\n readonly kind: string;\n readonly type: string;\n readonly extensions?: Record<string, unknown>;\n}\n\n/** Normalized warning entry. Comparison shape; canonical messages omitted. */\nexport interface TypeExtensionMappingWarning {\n readonly code: string;\n readonly pointer: string;\n}\n\n/** Escape `~` and `/` per RFC 6901 for JSON Pointer fragments. */\nfunction escapeJsonPointerSegment(segment: string): string {\n return segment.replace(/~/g, '~0').replace(/\\//g, '~1');\n}\n\n/**\n * Mirror of @peac/protocol/src/type-extension-check.ts:checkTypeExtensionMapping.\n * Returns a status discriminator only; the bounded validator decides whether\n * the discriminator translates to a warning code.\n */\nfunction classifyExpectedGroup(\n kind: string,\n type: string,\n extensions: Record<string, unknown> | undefined\n): 'ok' | 'skip' | 'missing' | 'mismatch' {\n if (kind === 'challenge') return 'skip';\n const expectedGroup = TYPE_TO_EXTENSION_MAP.get(type);\n if (expectedGroup === undefined) return 'skip';\n if (extensions !== undefined && Object.prototype.hasOwnProperty.call(extensions, expectedGroup)) {\n return 'ok';\n }\n if (extensions !== undefined) {\n for (const key of Object.keys(extensions)) {\n if (key !== expectedGroup && REGISTERED_EXTENSION_GROUP_KEYS.has(key)) {\n return 'mismatch';\n }\n }\n }\n return 'missing';\n}\n\n/**\n * Evaluate the type-extension mapping warning surface for parsed Wire 0.2\n * claims. Returns warnings in canonical emission order; emits no warnings\n * when the claims are fully registered and the expected extension group\n * is present (or when no expected group exists for the given type).\n */\nexport function validateTypeExtensionMappingInternal(\n input: TypeExtensionMappingInput\n): TypeExtensionMappingWarning[] {\n const warnings: TypeExtensionMappingWarning[] = [];\n\n // Step 1: type_unregistered\n if (!REGISTERED_RECEIPT_TYPES.has(input.type)) {\n warnings.push({ code: WARNING_TYPE_UNREGISTERED, pointer: '/type' });\n }\n\n // Step 2: unknown_extension_preserved (one per unknown well-formed key)\n if (input.extensions !== undefined) {\n for (const key of Object.keys(input.extensions)) {\n if (!REGISTERED_EXTENSION_GROUP_KEYS.has(key) && isValidExtensionKey(key)) {\n warnings.push({\n code: WARNING_UNKNOWN_EXTENSION,\n pointer: `/extensions/${escapeJsonPointerSegment(key)}`,\n });\n }\n }\n }\n\n // Step 3: extension_group_missing | extension_group_mismatch\n const status = classifyExpectedGroup(input.kind, input.type, input.extensions);\n if (status === 'missing') {\n warnings.push({ code: WARNING_EXTENSION_GROUP_MISSING, pointer: '/type' });\n } else if (status === 'mismatch') {\n warnings.push({ code: WARNING_EXTENSION_GROUP_MISMATCH, pointer: '/type' });\n }\n\n return warnings;\n}\n","/**\n * Bounded internal JOSE header hardening validator.\n *\n * INTERNAL ONLY. This is the parity-observed counterpart of\n * @peac/crypto.validateWire02Header. Both implementations consume the\n * same JOSE protected-header object and apply the same five hardening\n * checks in the same order; behavioral parity is proven byte-equal by\n * the parity tests, not by code copy.\n *\n * Existing canonical hardening in @peac/crypto remains canonical. This\n * module is observational only; it is NOT re-exported from\n * packages/protocol/src/index.ts and is NOT wired into runtime paths\n * (issue.ts, verify-local.ts, peekHeader) in v0.13.1.\n *\n * Scope (must mirror validateWire02Header in packages/crypto/src/jws.ts):\n *\n * 1. kid presence and length:\n * - missing kid (undefined / non-string / empty) -> CRYPTO_JWS_MISSING_KID\n * - kid length > 256 chars -> CRYPTO_JWS_MISSING_KID\n *\n * 2. embedded key material (jwk, x5c, x5u, jku):\n * - any of the four set -> CRYPTO_JWS_EMBEDDED_KEY\n *\n * 3. crit header:\n * - any value (including null / empty array) -> CRYPTO_JWS_CRIT_REJECTED\n *\n * 4. b64: false (RFC 7797 unencoded payload):\n * - the only rejected value is the boolean false; other values pass through\n * - rejection -> CRYPTO_JWS_B64_REJECTED\n *\n * 5. zip header:\n * - any value -> CRYPTO_JWS_ZIP_REJECTED\n *\n * Out of scope for this module (mirroring validateWire02Header exactly):\n * - alg validation (lives in buildHeader, not validateWire02Header)\n * - typ validation (lives in buildHeader)\n * - signature verification\n * - compact-JWS shape / size checks\n *\n * Order is significant: the canonical function returns the FIRST\n * matching violation per call (it throws on the first hit). The\n * internal validator emits the same first-hit code.\n */\n\n/** Header input shape (matches the parsed JOSE protected header). */\nexport type JoseHardeningInput = Record<string, unknown>;\n\n/**\n * Normalized result. accepted=true means the header passes all five\n * hardening checks. accepted=false carries the canonical CryptoError\n * code emitted by the corresponding canonical check.\n */\nexport type JoseHardeningResult =\n | { readonly accepted: true }\n | { readonly accepted: false; readonly errorCode: string };\n\nconst KID_MAX_LENGTH = 256;\n\nconst ACCEPTED: JoseHardeningResult = { accepted: true } as const;\n\nfunction rejected(errorCode: string): JoseHardeningResult {\n return { accepted: false, errorCode };\n}\n\nexport function validateJoseHardeningInternal(header: JoseHardeningInput): JoseHardeningResult {\n // 1. kid presence and length\n if (\n !header.kid ||\n typeof header.kid !== 'string' ||\n header.kid.length === 0 ||\n header.kid.length > KID_MAX_LENGTH\n ) {\n return rejected('CRYPTO_JWS_MISSING_KID');\n }\n\n // 2. embedded key material\n if (\n header.jwk !== undefined ||\n header.x5c !== undefined ||\n header.x5u !== undefined ||\n header.jku !== undefined\n ) {\n return rejected('CRYPTO_JWS_EMBEDDED_KEY');\n }\n\n // 3. crit\n if (header.crit !== undefined) {\n return rejected('CRYPTO_JWS_CRIT_REJECTED');\n }\n\n // 4. b64: false (RFC 7797 unencoded payload)\n if (header.b64 === false) {\n return rejected('CRYPTO_JWS_B64_REJECTED');\n }\n\n // 5. zip\n if (header.zip !== undefined) {\n return rejected('CRYPTO_JWS_ZIP_REJECTED');\n }\n\n return ACCEPTED;\n}\n","/**\n * Bounded internal issuer-form validator.\n *\n * INTERNAL ONLY. This is the parity-observed counterpart of\n * @peac/schema.isCanonicalIss (referenced by Wire 0.2's CanonicalIssSchema\n * and by issue.ts pre-sign validation). Both implementations consume the\n * same ISS_CANONICAL.maxLength constant from @peac/kernel and apply the\n * same accept/reject rules in the same order; behavioral parity is proven\n * byte-equal by the parity tests, not by code copy.\n *\n * Existing canonical isCanonicalIss in @peac/schema remains canonical.\n * This module is observational only; it is NOT re-exported from\n * packages/protocol/src/index.ts and is NOT wired into runtime paths\n * (issue.ts, verify-local.ts) in v0.13.1.\n *\n * Scope (must mirror isCanonicalIss in packages/schema/src/wire-02-envelope.ts):\n *\n * 1. Type and length:\n * - Non-string iss -> rejected\n * - Empty string -> rejected\n * - Length > ISS_CANONICAL.maxLength (2048) -> rejected\n *\n * 2. did: branch (checked before URL parsing because did: is a valid\n * URL scheme in some parsers):\n * - Pattern: ^did:[a-z0-9]+:[^#?/]+$\n * - Method: lowercase letters and digits only, non-empty\n * - Method-specific-id: non-empty, no '/', '?', or '#'\n *\n * 3. https:// branch (URL-constructor based):\n * - new URL(iss) must succeed\n * - url.protocol === 'https:'\n * - Non-empty url.hostname\n * - No userinfo (url.username and url.password both empty)\n * - iss must equal the canonical reconstructed origin\n * ('https://${url.host}'). This rejects:\n * - uppercase host (URL spec lowercases hostname)\n * - explicit default port (:443 is dropped from url.host)\n * - trailing slash, path, query, fragment, userinfo\n * - raw Unicode hostname (URL emits punycode in url.host)\n *\n * 4. All other schemes -> rejected with E_ISS_NOT_CANONICAL.\n */\n\nimport { ISS_CANONICAL } from '@peac/kernel';\n\n/**\n * Normalized result. accepted=true means iss is in canonical form.\n * accepted=false carries the canonical error code E_ISS_NOT_CANONICAL.\n *\n * The canonical surface emits a single error code for any rejection;\n * no path field is attached, so the comparison is on (accepted, errorCode)\n * only.\n */\nexport type IssuerFormResult =\n | { readonly accepted: true }\n | { readonly accepted: false; readonly errorCode: string };\n\nconst ACCEPTED: IssuerFormResult = { accepted: true } as const;\nconst REJECTED: IssuerFormResult = { accepted: false, errorCode: 'E_ISS_NOT_CANONICAL' } as const;\n\n/** did:<method>:<method-specific-id> grammar (mirrors canonical regex). */\nconst DID_PATTERN = /^did:[a-z0-9]+:[^#?/]+$/;\n\nexport function validateIssuerFormInternal(iss: unknown): IssuerFormResult {\n // 1. Type and length\n if (typeof iss !== 'string' || iss.length === 0 || iss.length > ISS_CANONICAL.maxLength) {\n return REJECTED;\n }\n\n // 2. did: branch (check before URL parsing)\n if (iss.startsWith('did:')) {\n return DID_PATTERN.test(iss) ? ACCEPTED : REJECTED;\n }\n\n // 3. https:// branch (URL-constructor based)\n let url: URL;\n try {\n url = new URL(iss);\n } catch {\n return REJECTED;\n }\n\n if (url.protocol !== 'https:') return REJECTED;\n if (!url.hostname) return REJECTED;\n if (url.username !== '' || url.password !== '') return REJECTED;\n\n const origin = `${url.protocol}//${url.host}`;\n return iss === origin ? ACCEPTED : REJECTED;\n}\n","/**\n * Bounded internal temporal validator (occurred_at skew only).\n *\n * INTERNAL ONLY. This is the parity-observed counterpart of\n * @peac/schema.checkOccurredAtSkew (referenced by verify-local.ts when\n * claims.kind === 'evidence'). Both implementations consume the same\n * OCCURRED_AT_TOLERANCE_SECONDS constant from @peac/kernel and apply\n * the same skew classification rules in the same order; behavioral\n * parity is proven byte-equal by the parity tests, not by code copy.\n *\n * Existing canonical checkOccurredAtSkew in @peac/schema remains\n * canonical. This module is observational only; it is NOT re-exported\n * from packages/protocol/src/index.ts and is NOT wired into runtime\n * paths (issue.ts, verify-local.ts) in v0.13.1.\n *\n * SCOPE (deliberately narrow):\n * - occurred_at canonical skew classification ONLY\n * - the iat-not-yet-valid check (`iat > now + maxClockSkew`) lives\n * inline at verify-local.ts:454 with no helper to import; wrapping\n * it would make LEFT and RIGHT identical 1-line predicates that\n * prove nothing, so it is explicitly deferred to a later step\n * (extraction first, parity second)\n *\n * Rules (must mirror checkOccurredAtSkew exactly; evidence-kind-only\n * is the caller's responsibility):\n * 1. occurredAt undefined -> accepted, no warning\n * 2. parse occurredAt as ISO/RFC 3339; if NaN -> accepted, no warning\n * (the parse failure surfaces from schema validation elsewhere)\n * 3. ts > now + tolerance -> rejected with E_OCCURRED_AT_FUTURE\n * 4. ts > iat (within tolerance) -> accepted with occurred_at_skew\n * warning at pointer /occurred_at\n * 5. ts <= iat -> accepted, no warning\n *\n * The injected `now` parameter is required; this module never reads\n * Date.now() so tests are deterministic.\n */\n\nimport { OCCURRED_AT_TOLERANCE_SECONDS } from '@peac/kernel';\n\nexport interface TemporalWarning {\n readonly code: string;\n readonly pointer?: string;\n}\n\nexport type TemporalResult =\n | { readonly accepted: true; readonly warnings?: readonly TemporalWarning[] }\n | { readonly accepted: false; readonly errorCode: string; readonly pointer?: string };\n\nconst ACCEPTED: TemporalResult = { accepted: true } as const;\n\nexport function validateTemporalInternal(\n occurredAt: string | undefined,\n iat: number,\n now: number,\n tolerance: number = OCCURRED_AT_TOLERANCE_SECONDS\n): TemporalResult {\n if (occurredAt === undefined) return ACCEPTED;\n\n const ts = Date.parse(occurredAt) / 1000;\n if (isNaN(ts)) return ACCEPTED;\n\n if (ts > now + tolerance) {\n return {\n accepted: false,\n errorCode: 'E_OCCURRED_AT_FUTURE',\n pointer: '/occurred_at',\n };\n }\n\n if (ts > iat) {\n return {\n accepted: true,\n warnings: [{ code: 'occurred_at_skew', pointer: '/occurred_at' }],\n };\n }\n\n return ACCEPTED;\n}\n","/**\n * Bounded internal extension-budget validator.\n *\n * INTERNAL ONLY. This is the parity-observed counterpart of the\n * byte-budget portion (steps 4 + 5) of validateKnownExtensions in\n * @peac/schema/src/wire-02-extensions/validation.ts. Both sides import\n * EXTENSION_BUDGET from @peac/kernel; behavioral parity is proven\n * byte-equal by the parity tests, not by code copy.\n *\n * Existing canonical validateKnownExtensions in @peac/schema remains\n * canonical. This module is observational only; it is NOT re-exported\n * from packages/protocol/src/index.ts and is NOT wired into runtime\n * paths (issue.ts, verify-local.ts) in v0.13.1.\n *\n * SCOPE (deliberately narrow):\n * - byte-budget enforcement on the extensions record only\n * - the other three steps in validateKnownExtensions (key grammar,\n * plain-JSON guard, typed extension schema parse) are NOT in\n * scope here; they belong to other parity work and would require\n * their own validators\n *\n * Measurement basis (must mirror canonical exactly):\n * - bytes = TextEncoder.encode(JSON.stringify(value)).byteLength\n * (UTF-8 byte length of ECMAScript JSON.stringify output)\n * - serialization failure (circular references, BigInt, etc.) yields\n * Infinity, which the comparison treats as over-budget\n *\n * Order of checks (must mirror canonical exactly):\n * 1. Total: jsonUtf8ByteLength(extensions) > maxTotalBytes\n * -> violation at path '/extensions'; EARLY STOP (no per-group)\n * 2. Per-group, in Object.keys(extensions) iteration order:\n * jsonUtf8ByteLength(extensions[key]) > maxGroupBytes\n * -> violation at path '/extensions/<escaped-key>'\n *\n * Comparison uses '>' (strictly greater than), so values exactly equal\n * to the limit are accepted.\n */\n\nimport { EXTENSION_BUDGET } from '@peac/kernel';\n\nexport interface ExtensionBudgetViolation {\n readonly code: string;\n readonly path: string;\n}\n\nexport interface ExtensionBudgetResult {\n readonly accepted: boolean;\n readonly violations: readonly ExtensionBudgetViolation[];\n}\n\nconst ACCEPTED: ExtensionBudgetResult = { accepted: true, violations: [] } as const;\nconst SIZE_EXCEEDED = 'E_EXTENSION_SIZE_EXCEEDED' as const;\n\nconst textEncoder = new TextEncoder();\n\n/**\n * UTF-8 byte length of JSON.stringify(value). Returns Infinity if\n * serialization fails (circular references, BigInt, etc.); callers\n * treat Infinity as over-budget.\n */\nfunction jsonUtf8ByteLength(value: unknown): number {\n try {\n return textEncoder.encode(JSON.stringify(value)).byteLength;\n } catch {\n return Infinity;\n }\n}\n\n/** RFC 6901 JSON pointer segment escape: '~' -> '~0', '/' -> '~1'. */\nfunction escapeJsonPointerSegment(segment: string): string {\n return segment.replace(/~/g, '~0').replace(/\\//g, '~1');\n}\n\nexport function validateExtensionBudgetInternal(\n extensions: Record<string, unknown> | undefined\n): ExtensionBudgetResult {\n if (extensions === undefined) return ACCEPTED;\n\n const totalBytes = jsonUtf8ByteLength(extensions);\n if (totalBytes > EXTENSION_BUDGET.maxTotalBytes) {\n // Early stop: canonical returns immediately after pushing the\n // total-budget violation; per-group checks are not reached.\n return {\n accepted: false,\n violations: [{ code: SIZE_EXCEEDED, path: '/extensions' }],\n };\n }\n\n const violations: ExtensionBudgetViolation[] = [];\n for (const key of Object.keys(extensions)) {\n const groupBytes = jsonUtf8ByteLength(extensions[key]);\n if (groupBytes > EXTENSION_BUDGET.maxGroupBytes) {\n violations.push({\n code: SIZE_EXCEEDED,\n path: `/extensions/${escapeJsonPointerSegment(key)}`,\n });\n }\n }\n\n if (violations.length === 0) return ACCEPTED;\n return { accepted: false, violations };\n}\n","/**\n * Bounded observation subset: composition aggregator.\n *\n * INTERNAL ONLY. Composes the six proven layer validators introduced\n * across this PR (kernel constraints; type-extension mapping; JOSE\n * header hardening; issuer form; occurred_at temporal skew;\n * extension byte budget) into a single aggregated result. The\n * canonical-truth sanity test, layer-isolated parity tests, and\n * differential same-path proof have already established that each\n * underlying validator is byte-equal with the existing canonical\n * surface for the layer it covers.\n *\n * NOT WIRED. This module is NOT called from issue.ts, verify-local.ts,\n * or any runtime path in v0.13.1. It exists as a composition example\n * so PR D can wire the inert shadow-call hook to a real bounded\n * pipeline behind an internal feature flag without re-deriving the\n * composition shape.\n *\n * NOT FULL VALIDATION. The bounded subset deliberately EXCLUDES:\n * - full Wire 0.2 schema parsing (parseReceiptClaims; the canonical\n * parse continues to drive the runtime path)\n * - signature verification and full JWS decode (decodeWire02;\n * @peac/crypto remains canonical)\n * - iat-not-yet-valid temporal check (lives inline at\n * verify-local.ts:454 with no helper to import)\n * - typ_missing strictness handling\n * - policy binding verification\n * - unknown_extension key grammar / plain-JSON guard / typed\n * extension schema parse (only the byte-budget portion of\n * validateKnownExtensions is in scope)\n * - any control-plane behavior (issuer resolver, JWKS fetch, etc.)\n *\n * Public-facing wording for this module: \"bounded observation subset\",\n * never \"complete validator\" or \"primary validator\".\n */\n\nimport {\n validateExtensionBudgetInternal,\n validateIssuerFormInternal,\n validateJoseHardeningInternal,\n validateKernelConstraintsInternal,\n validateTemporalInternal,\n validateTypeExtensionMappingInternal,\n type ExtensionBudgetViolation,\n type TemporalWarning,\n type TypeExtensionMappingWarning,\n} from './validators/index.js';\n\n/** Minimal claims shape required by the bounded subset. */\nexport interface BoundedClaimsInput {\n readonly kind: string;\n readonly type: string;\n readonly iss: unknown;\n readonly iat: number;\n readonly occurred_at?: string;\n readonly extensions?: Record<string, unknown>;\n}\n\n/** Optional JOSE header (from the JWS protected header). */\nexport type BoundedHeaderInput = Record<string, unknown> | undefined;\n\n/** Aggregated input to the bounded observation subset. */\nexport interface BoundedValidationInput {\n readonly claims: BoundedClaimsInput;\n readonly header?: BoundedHeaderInput;\n /** Fixed Unix-second clock for temporal evaluation; required. */\n readonly now: number;\n}\n\n/**\n * Layer tag identifies which underlying validator emitted each entry.\n * Useful for downstream filtering (e.g., a future shadow-mode reporter\n * that ignores warning-class entries from one layer but not another).\n */\nexport type BoundedLayer =\n | 'kernel-constraints'\n | 'type-extension-mapping'\n | 'jose-header-hardening'\n | 'issuer-form'\n | 'temporal'\n | 'extension-budget';\n\nexport interface BoundedViolation {\n readonly layer: BoundedLayer;\n readonly code: string;\n readonly path?: string;\n}\n\nexport interface BoundedWarning {\n readonly layer: BoundedLayer;\n readonly code: string;\n readonly path?: string;\n}\n\nexport interface BoundedValidationResult {\n /** True iff every in-scope layer accepted the input. */\n readonly accepted: boolean;\n readonly violations: readonly BoundedViolation[];\n readonly warnings: readonly BoundedWarning[];\n}\n\n/**\n * Run the bounded observation subset. Composes the six layer\n * validators in a stable order; aggregates violations and warnings\n * with explicit layer tags; never throws. Pure: same input always\n * yields the same result.\n */\nexport function runBoundedValidatorShadow(input: BoundedValidationInput): BoundedValidationResult {\n const violations: BoundedViolation[] = [];\n const warnings: BoundedWarning[] = [];\n\n // 1. Kernel constraints (depth / array / keys / string / nodes).\n const kernelRes = validateKernelConstraintsInternal(input.claims);\n if (!kernelRes.valid) {\n for (const v of kernelRes.violations) {\n violations.push({\n layer: 'kernel-constraints',\n code: v.constraint,\n path: v.path || undefined,\n });\n }\n }\n\n // 2. Issuer form (canonical iss).\n const issRes = validateIssuerFormInternal(input.claims.iss);\n if (!issRes.accepted) {\n violations.push({ layer: 'issuer-form', code: issRes.errorCode });\n }\n\n // 3. JOSE header hardening (only when a header is supplied).\n if (input.header !== undefined) {\n const joseRes = validateJoseHardeningInternal(input.header);\n if (!joseRes.accepted) {\n violations.push({ layer: 'jose-header-hardening', code: joseRes.errorCode });\n }\n }\n\n // 4. Type-extension mapping warnings.\n const typeExtWarnings: readonly TypeExtensionMappingWarning[] =\n validateTypeExtensionMappingInternal({\n kind: input.claims.kind,\n type: input.claims.type,\n extensions: input.claims.extensions,\n });\n for (const w of typeExtWarnings) {\n warnings.push({ layer: 'type-extension-mapping', code: w.code, path: w.pointer });\n }\n\n // 5. Temporal occurred_at skew (evidence-kind-only is the caller's\n // responsibility; we mirror the canonical behavior of treating\n // non-evidence kinds as a no-op by skipping the call).\n if (input.claims.kind === 'evidence') {\n const temporalRes = validateTemporalInternal(\n input.claims.occurred_at,\n input.claims.iat,\n input.now\n );\n if (!temporalRes.accepted) {\n violations.push({\n layer: 'temporal',\n code: temporalRes.errorCode,\n path: temporalRes.pointer,\n });\n } else if (temporalRes.warnings) {\n const list: readonly TemporalWarning[] = temporalRes.warnings;\n for (const w of list) {\n warnings.push({ layer: 'temporal', code: w.code, path: w.pointer });\n }\n }\n }\n\n // 6. Extension byte budget.\n const budgetRes = validateExtensionBudgetInternal(input.claims.extensions);\n if (!budgetRes.accepted) {\n const list: readonly ExtensionBudgetViolation[] = budgetRes.violations;\n for (const v of list) {\n violations.push({ layer: 'extension-budget', code: v.code, path: v.path });\n }\n }\n\n return {\n accepted: violations.length === 0,\n violations,\n warnings,\n };\n}\n","/**\n * Shadow-mode telemetry redaction and canonical hashing.\n *\n * @internal\n *\n * INTERNAL ONLY. Not re-exported from packages/protocol/src/index.ts.\n *\n * Two responsibilities:\n *\n * 1. `redactNote(input, maxBytes)`: scrub known secret classes from\n * a free-form string and bound it to a UTF-8 byte ceiling. Used\n * for the `notes` field on every shadow divergence record so\n * that an accidental string concatenation cannot leak credential\n * material into the in-memory shadow log.\n *\n * 2. `canonicalHashOf(value)` / `hashJws(jws)`: produce a SHA-256\n * hex digest of a canonicalized representation. Used as the\n * comparison primitive between real-path and shadow-path results\n * so the divergence log never needs to store raw output.\n *\n * SECRET_PATTERNS is the ground-truth contract for what counts as a\n * leakable secret class. Adding a regex here REQUIRES a paired\n * adversarial test vector in shadow-redact-adversarial.test.ts (one\n * matching vector + one adjacent benign-not-matched vector). Removing\n * a regex here REQUIRES the same justification.\n *\n * Platform neutrality: this module avoids Node-only globals (`Buffer`,\n * `node:crypto`) so it can ship inside the platform-neutral\n * @peac/protocol bundle. UTF-8 byte work uses TextEncoder/TextDecoder;\n * SHA-256 hashing delegates to @peac/crypto.sha256Hex which uses the\n * Web Crypto API with a dynamic Node fallback.\n */\n\nimport { base64urlEncode, sha256Hex } from '@peac/crypto';\n\n/**\n * Known secret-class patterns. Order matters only for performance\n * (broader patterns first reduce the search space for narrower ones).\n *\n * @internal\n */\nconst SECRET_PATTERNS: readonly RegExp[] = [\n // Compact JWS / JWT (header.payload.signature with eyJ-prefixed header).\n /eyJ[A-Za-z0-9_-]{20,}\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+/g,\n\n // PEM-encoded blocks. Covers RSA / EC / OPENSSH / generic PRIVATE KEY\n // header variants in a single pattern.\n /-----BEGIN [A-Z0-9 ]+-----[\\s\\S]+?-----END [A-Z0-9 ]+-----/g,\n\n // Long base64 runs (>=40 chars). The character class is the standard\n // base64 alphabet only (no `_` or `-`) so that kebab-case and\n // snake_case identifier strings do not collateral-match. base64url\n // payloads carrying credentials are reached via more specific patterns\n // (compact JWS, Bearer, URL query token) and via the wrapper headers\n // they appear in.\n /\\b[A-Za-z0-9+/]{40,}={0,2}\\b/g,\n\n // Bearer token (Authorization header value with Bearer scheme).\n /Bearer\\s+[A-Za-z0-9._\\-/+=]+/gi,\n\n // Generic Authorization header line (any scheme, including Basic /\n // Digest / Negotiate). Multiline-anchored.\n /^authorization:\\s*[^\\r\\n]+/gim,\n\n // Generic auth-token header line (X-Auth-Token, X-API-Key).\n /^x-(?:auth-token|api-key):\\s*[^\\r\\n]+/gim,\n\n // Cookie request header line (raw client cookies).\n /^cookie:\\s*[^\\r\\n]+/gim,\n\n // Set-Cookie response header line (server-issued sessions).\n /^set-cookie:\\s*[^\\r\\n]+/gim,\n\n // URL query token / API key / secret / access_token.\n /[?&](?:token|key|secret|access_token|api_key|apikey)=[^&\\s#]+/gi,\n\n // AWS access key ID (AKIA + 16 alphanumeric).\n /\\bAKIA[0-9A-Z]{16}\\b/g,\n\n // Email address (PII).\n /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}/g,\n\n // Phone numbers. Three explicit forms (E.164 + parenthesized NA + dashed\n // NA / international) so plain consecutive-digit runs (sequence\n // numbers, hashes, identifiers) do not collateral-match.\n /\\+\\d[\\d\\s().-]{6,}\\d/g,\n /\\(\\d{3}\\)\\s*\\d{3}[\\s.-]?\\d{4}/g,\n /\\b\\d{3}[\\s.-]\\d{3}[\\s.-]\\d{4}\\b/g,\n];\n\n/**\n * Redaction marker used in place of any matched secret class.\n *\n * @internal\n */\nconst REDACTION_MARKER = '[REDACTED]';\n\nconst TEXT_ENCODER = /* @__PURE__ */ new TextEncoder();\nconst TEXT_DECODER = /* @__PURE__ */ new TextDecoder('utf-8', { fatal: false });\n\nconst REDACTION_MARKER_BYTES = TEXT_ENCODER.encode(REDACTION_MARKER).length;\n\n/**\n * UTF-8 byte length of a string. Platform-neutral replacement for\n * `Buffer.byteLength(s, 'utf8')`.\n *\n * @internal\n */\nexport function utf8ByteLength(value: string): number {\n return TEXT_ENCODER.encode(value).length;\n}\n\n/**\n * Redact known secret classes from `input` and bound the result to\n * `maxBytes` UTF-8 bytes. The output always either matches the input\n * (when no secret was found and the byte budget permits) or contains\n * the `[REDACTED]` marker.\n *\n * Truncation is byte-aware so multibyte UTF-8 sequences are not split\n * mid-character. When the redacted string exceeds `maxBytes`, the\n * tail is replaced with the marker.\n *\n * @internal\n */\nexport function redactNote(input: string, maxBytes: number): string {\n if (typeof input !== 'string') return REDACTION_MARKER;\n\n let redacted = input;\n for (const pattern of SECRET_PATTERNS) {\n redacted = redacted.replace(pattern, REDACTION_MARKER);\n }\n\n const bytes = TEXT_ENCODER.encode(redacted);\n if (bytes.length <= maxBytes) return redacted;\n\n if (maxBytes <= REDACTION_MARKER_BYTES) {\n return REDACTION_MARKER.slice(0, maxBytes);\n }\n\n const headBytes = maxBytes - REDACTION_MARKER_BYTES;\n return safeUtf8Slice(bytes, headBytes) + REDACTION_MARKER;\n}\n\n/**\n * SHA-256 hex digest of a canonical-stringified value. Used by the\n * shadow comparator to detect output-byte-diff WITHOUT logging raw\n * content. Object keys are sorted recursively so equivalent objects\n * with different key orders produce identical digests.\n *\n * Async because SHA-256 hashing in this codebase is platform-neutral\n * via @peac/crypto.sha256Hex (Web Crypto API with dynamic Node\n * fallback). Callers run inside the shadow scheduler's microtask /\n * macrotask boundary, so an additional await is free.\n *\n * @internal\n */\nexport async function canonicalHashOf(value: unknown): Promise<string> {\n return sha256Hex(canonicalStringify(value));\n}\n\n/**\n * SHA-256 hex digest of a JWS string. Used as the primary\n * `recordRefHash` input for divergence records.\n *\n * @internal\n */\nexport async function hashJws(jws: string): Promise<string> {\n return sha256Hex(jws);\n}\n\n/**\n * Canonical JSON serialization with stable key order. Internal helper\n * for `canonicalHashOf`. Not exported.\n */\nfunction canonicalStringify(value: unknown): string {\n if (value === null) return 'null';\n if (typeof value === 'undefined') return 'null';\n if (typeof value === 'string') return JSON.stringify(value);\n if (typeof value === 'number') {\n return Number.isFinite(value) ? String(value) : 'null';\n }\n if (typeof value === 'boolean') return String(value);\n if (typeof value === 'bigint') return String(value);\n if (Array.isArray(value)) {\n return '[' + value.map(canonicalStringify).join(',') + ']';\n }\n if (value instanceof Uint8Array) {\n return JSON.stringify(base64urlEncode(value));\n }\n if (typeof value === 'object') {\n const obj = value as Record<string, unknown>;\n const keys = Object.keys(obj).sort();\n return (\n '{' + keys.map((k) => JSON.stringify(k) + ':' + canonicalStringify(obj[k])).join(',') + '}'\n );\n }\n return 'null';\n}\n\n/**\n * Slice a UTF-8 byte buffer to at most `byteLen` bytes without\n * splitting a multi-byte sequence mid-character. Returns a decoded\n * string. Internal helper for `redactNote`. Not exported.\n */\nfunction safeUtf8Slice(bytes: Uint8Array, byteLen: number): string {\n if (byteLen <= 0) return '';\n if (bytes.length <= byteLen) return TEXT_DECODER.decode(bytes);\n\n let end = byteLen;\n // Walk back over UTF-8 continuation bytes (0b10xxxxxx) so the slice\n // ends on a complete code-point boundary.\n while (end > 0 && (bytes[end] & 0xc0) === 0x80) {\n end -= 1;\n }\n return TEXT_DECODER.decode(bytes.subarray(0, end));\n}\n","/**\n * Shadow-mode scheduler.\n *\n * @internal\n *\n * INTERNAL ONLY. Not re-exported from packages/protocol/src/index.ts.\n *\n * Schedules a shadow function to run AFTER the public-call boundary\n * has returned its real-path result to the caller. The shadow run:\n *\n * - is gated by `isShadowEnabled(options)` (env or programmatic);\n * - starts on a MACROTASK boundary (`setTimeout(..., 0)`), NOT on a\n * microtask, because microtasks can run before promise\n * continuations attached to the public async call and would still\n * add observable latency for CPU-heavy shadow work;\n * - has a bounded wall-clock REPORTING timeout (250ms by default;\n * see \"Timeout guarantee class\" below);\n * - reports comparison results into a bounded in-memory log;\n * - SWALLOWS every error, never propagating to the real-path return\n * value or surfacing as an unhandled-rejection event.\n *\n * The public function:\n *\n * - returns the real-path value FIRST (the macrotask boundary is\n * past every async continuation already attached to the call\n * site);\n * - never awaits shadow work;\n * - is byte-identical in its return value with shadow ON vs OFF.\n *\n * Timeout guarantee class. The 250ms timeout is a REPORTING bound,\n * not a hard preemption guarantee. Where the shadow function consults\n * the supplied `AbortSignal`, the runner aborts and bounds CPU; where\n * the shadow function is pure-CPU and ignores the signal (the v0.13.1\n * record-core validators are this shape), JavaScript cannot preempt\n * it. The runner stops awaiting and records `timing-diff`; the work\n * may continue to completion off the runner's await chain. Either\n * way, the public-call boundary returns its real-path value\n * immediately.\n *\n * Test-only helpers (`_peekShadowLog`, `_resetShadowLog`,\n * `_drainShadowQueueForTests`) are exposed for deterministic\n * assertions in vitest. Production code MUST NOT call them.\n *\n * Platform neutrality: this module avoids Node-only globals\n * (`Buffer`, `node:crypto`, unguarded `process`). Hashing delegates\n * to @peac/crypto; environment reads guard for the absence of\n * `process` so the module loads cleanly under browser / edge\n * runtimes.\n */\n\nimport type { ShadowCall, ShadowDivergence } from './shadow-types.js';\nimport { canonicalHashOf, hashJws, redactNote, utf8ByteLength } from './shadow-redact.js';\n\nconst MAX_LOG_ENTRIES = 1000;\nconst MAX_NOTE_BYTES = 128;\nconst RETENTION_MS = 7 * 24 * 60 * 60 * 1000; // 7 days\nconst SHADOW_TIMEOUT_MS = 250;\n\nconst SHADOW_LOG: ShadowDivergence[] = [];\nconst PENDING_SHADOW_TASKS: Set<Promise<void>> = new Set();\nlet pendingScheduleCount = 0;\n\n/**\n * Programmatic-flag shape. Internal-only; never appears in any\n * exported public option type.\n *\n * @internal\n */\nexport interface ShadowEnableOptions {\n readonly _internal?: {\n readonly shadowCore?: boolean;\n };\n}\n\n/**\n * Read the shadow-enable flag from environment or programmatic\n * options. Read once per call, NOT cached at module scope, so tests\n * can toggle the env var dynamically. Environment access is guarded\n * for browser / edge runtimes that do not expose `process`.\n *\n * @internal\n */\nexport function isShadowEnabled(options?: ShadowEnableOptions): boolean {\n if (options?._internal?.shadowCore === true) return true;\n return readEnvFlag();\n}\n\nfunction readEnvFlag(): boolean {\n if (typeof process === 'undefined' || process === null) return false;\n const env = (process as { env?: Record<string, string | undefined> }).env;\n return env?.PEAC_INTERNAL_SHADOW_CORE === '1';\n}\n\n/**\n * Inputs to `scheduleShadow`. The `shadowFn` factory receives an\n * `AbortSignal` so cancellable implementations can opt in. v0.13.1\n * shadow paths are pure-CPU and ignore the signal; the runner still\n * passes one for forward-compat.\n *\n * @internal\n */\nexport interface ScheduleShadowArgs<T> {\n readonly call: ShadowCall;\n readonly realResult: T | undefined;\n readonly realError: { code?: string } | undefined;\n readonly shadowFn: (signal?: AbortSignal) => Promise<T>;\n readonly recordRef: string;\n}\n\n/**\n * Schedule shadow work AFTER the real-path return.\n *\n * The shadow run starts on the next MACROTASK boundary (via\n * `setTimeout(..., 0)`). The public function returns its real-path\n * value before the macrotask fires, including for async callers\n * whose `.then` / `await` continuations execute on microtasks.\n * `queueMicrotask` would interleave with those continuations and is\n * intentionally avoided.\n *\n * Tasks are tracked internally so test helpers can drain them for\n * deterministic assertions; production callers ignore the (void)\n * return.\n *\n * Failures inside the shadow path are converted to divergence records\n * inside the task body. The outer `task.catch(() => {})` is defense\n * in depth: if anything inside `runShadowTask` throws after the inner\n * try/catch (e.g., a hash failure during canonical comparison), the\n * outer catch swallows the rejection so no unhandled-rejection event\n * fires.\n *\n * @internal\n */\nexport function scheduleShadow<T>(args: ScheduleShadowArgs<T>): void {\n pendingScheduleCount += 1;\n setTimeout(() => {\n pendingScheduleCount -= 1;\n const task = runShadowTask(args);\n PENDING_SHADOW_TASKS.add(task);\n // Cleanup runs on both fulfillment and rejection. Using\n // `task.then(remove, remove)` instead of `task.finally(remove)`\n // avoids creating a derived rejected promise that would surface\n // as an unhandled-rejection event when the inner task rejects.\n // The two-arg `then` form swallows any rejection and runs the\n // cleanup on either branch.\n const removeFromPending = (): void => {\n PENDING_SHADOW_TASKS.delete(task);\n };\n void task.then(removeFromPending, removeFromPending);\n }, 0);\n}\n\nasync function runShadowTask<T>(args: ScheduleShadowArgs<T>): Promise<void> {\n const recordRefHash = await hashJws(args.recordRef);\n let shadowResult: T | undefined;\n let shadowErrorCode: string | undefined;\n\n try {\n shadowResult = await runWithTimeout(args.shadowFn, SHADOW_TIMEOUT_MS);\n } catch (err) {\n shadowErrorCode = extractErrorCode(err);\n appendDivergence({\n kind: shadowErrorCode === 'SHADOW_TIMEOUT' ? 'timing-diff' : 'shadow-error',\n call: args.call,\n recordRefHash,\n realErrorCode: args.realError?.code,\n shadowErrorCode,\n notes: redactNote(`shadow threw ${shadowErrorCode}`, MAX_NOTE_BYTES),\n timestamp: new Date().toISOString(),\n });\n return;\n }\n\n const divergence = await compareResults(args, shadowResult, recordRefHash);\n if (divergence) appendDivergence(divergence);\n}\n\n/**\n * Bounded REPORTING timeout for shadow work. NOT a hard preemption\n * guarantee. See the module-level \"Timeout guarantee class\" comment.\n */\nfunction runWithTimeout<T>(fn: (signal?: AbortSignal) => Promise<T>, ms: number): Promise<T> {\n const controller = new AbortController();\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n controller.abort();\n reject(new Error('SHADOW_TIMEOUT'));\n }, ms);\n fn(controller.signal).then(\n (v) => {\n clearTimeout(timer);\n resolve(v);\n },\n (e) => {\n clearTimeout(timer);\n reject(e);\n }\n );\n });\n}\n\nasync function compareResults<T>(\n args: ScheduleShadowArgs<T>,\n shadowResult: T | undefined,\n recordRefHash: string\n): Promise<ShadowDivergence | null> {\n const ts = new Date().toISOString();\n\n // Both succeeded: compare canonical hashes.\n if (!args.realError && shadowResult !== undefined && args.realResult !== undefined) {\n const realHash = await canonicalHashOf(args.realResult);\n const shadowHash = await canonicalHashOf(shadowResult);\n if (realHash !== shadowHash) {\n return {\n kind: 'output-byte-diff',\n call: args.call,\n recordRefHash,\n realResultHash: realHash,\n shadowResultHash: shadowHash,\n realByteLen: byteLenOf(args.realResult),\n shadowByteLen: byteLenOf(shadowResult),\n notes: 'canonical-hash-mismatch',\n timestamp: ts,\n };\n }\n return null;\n }\n\n // Both errored: comparator already handled in catch path; no record here.\n if (args.realError && shadowResult === undefined) {\n return null;\n }\n\n // Asymmetric: one succeeded, one failed.\n return {\n kind: 'error-code-diff',\n call: args.call,\n recordRefHash,\n realErrorCode: args.realError?.code,\n notes: args.realError ? 'real-errored-shadow-succeeded' : 'real-succeeded-shadow-errored',\n timestamp: ts,\n };\n}\n\nfunction byteLenOf(value: unknown): number {\n if (typeof value === 'string') return utf8ByteLength(value);\n if (value instanceof Uint8Array) return value.byteLength;\n return utf8ByteLength(JSON.stringify(value) ?? '');\n}\n\nfunction extractErrorCode(err: unknown): string {\n if (err && typeof err === 'object') {\n const candidate = (err as { code?: unknown; message?: unknown }).code;\n if (typeof candidate === 'string' && candidate.length > 0) return candidate;\n const message = (err as { message?: unknown }).message;\n if (typeof message === 'string' && /^[A-Z_][A-Z0-9_]*$/.test(message)) return message;\n }\n return 'SHADOW_UNKNOWN_ERROR';\n}\n\nfunction appendDivergence(d: ShadowDivergence): void {\n pruneStale();\n if (SHADOW_LOG.length >= MAX_LOG_ENTRIES) SHADOW_LOG.shift();\n SHADOW_LOG.push(d);\n}\n\nfunction pruneStale(): void {\n const cutoffIso = new Date(Date.now() - RETENTION_MS).toISOString();\n while (SHADOW_LOG.length > 0 && SHADOW_LOG[0].timestamp < cutoffIso) SHADOW_LOG.shift();\n}\n\n/**\n * Read the in-memory shadow log without mutating it. TEST USE ONLY.\n *\n * @internal\n */\nexport function _peekShadowLog(): readonly ShadowDivergence[] {\n return SHADOW_LOG.slice();\n}\n\n/**\n * Clear the in-memory shadow log. TEST USE ONLY.\n *\n * @internal\n */\nexport function _resetShadowLog(): void {\n SHADOW_LOG.length = 0;\n}\n\n/**\n * Drain the pending-shadow-tasks set so deterministic assertions can\n * run after a sequence of shadow-enabled calls. Yields to the event\n * loop until every scheduled `setTimeout` has fired AND every\n * resulting task has settled. TEST USE ONLY. Production code MUST\n * NOT call this.\n *\n * @internal\n */\nexport async function _drainShadowQueueForTests(): Promise<void> {\n while (pendingScheduleCount > 0 || PENDING_SHADOW_TASKS.size > 0) {\n if (pendingScheduleCount > 0) {\n // Yield so any pending setTimeout(..., 0) fires.\n await new Promise<void>((resolve) => setTimeout(resolve, 0));\n }\n if (PENDING_SHADOW_TASKS.size > 0) {\n await Promise.allSettled(Array.from(PENDING_SHADOW_TASKS));\n }\n }\n}\n","/**\n * Normalized internal observation shape for shadow-vs-real comparison.\n *\n * @internal\n *\n * INTERNAL ONLY. Not re-exported from packages/protocol/src/index.ts.\n *\n * The shadow scheduler compares real-path and shadow-path results via\n * canonical hashes. To make that comparison meaningful (not just an\n * accept/reject boolean) and free of false positives, both sides\n * project onto the SAME stable normalized `ShadowObservation` shape\n * before the hash:\n *\n * - `accepted`: did the validator accept the input?\n * - `violationCodes`: sorted, deduplicated registered error codes.\n * - `warningCodes`: sorted, deduplicated registered warning codes.\n *\n * Layer-tag metadata is intentionally NOT part of the comparable\n * shape. The bounded validator emits per-layer tags; the canonical\n * Zod path does not. Including them would cause a hash divergence\n * even on full functional agreement, masking true divergence as\n * noise.\n *\n * Issue path projection:\n *\n * `IssueResult` does not expose warning codes; canonical issuance\n * either succeeds (and surfaces no warnings to the caller) or\n * throws. To prevent the bounded validator's warnings from\n * producing false `output-byte-diff` records on a successful\n * issuance, the issue-side comparison runs in ACCEPTED-ONLY mode:\n * `warningCodes` is projected to `[]` on BOTH sides.\n *\n * VerifyLocal success path projection:\n *\n * `VerifyLocalSuccess` exposes a `warnings` array of registered\n * warning codes. The verifyLocal-side comparison includes\n * `warningCodes` from both sides (canonical surfaces them\n * directly; the bounded validator's warningCodes are mapped from\n * `BoundedWarning.code`).\n */\n\nimport type { BoundedValidationResult } from './record-core/bounded-validator.js';\n\n/**\n * Canonical observation projected from either the real path or the\n * shadow path.\n *\n * @internal\n */\nexport interface ShadowObservation {\n readonly accepted: boolean;\n /** Registered error codes, sorted, deduplicated. */\n readonly violationCodes: readonly string[];\n /** Registered warning codes, sorted, deduplicated. */\n readonly warningCodes: readonly string[];\n}\n\n/**\n * Real-path observation for a successful `issue()` call. Always\n * projects to the empty accepted-only shape; canonical issuance\n * surfaces no warning codes through `IssueResult`.\n *\n * @internal\n */\nexport function realObservationForIssue(): ShadowObservation {\n return EMPTY_ACCEPTED;\n}\n\n/**\n * Real-path observation for a successful `verifyLocal()` call. Maps\n * the canonical `warnings: VerificationWarning[]` array onto the\n * normalized warningCodes set.\n *\n * @internal\n */\nexport function realObservationForVerifyLocalSuccess(\n warnings: readonly { code: string }[] | undefined\n): ShadowObservation {\n if (!warnings || warnings.length === 0) return EMPTY_ACCEPTED;\n return {\n accepted: true,\n violationCodes: [],\n warningCodes: sortedDedupedCodes(warnings.map((w) => w.code)),\n };\n}\n\n/**\n * Project a `BoundedValidationResult` into the shared observation\n * shape with full warning-code parity. Use on the verifyLocal path\n * where canonical exposes warning codes through\n * `VerifyLocalSuccess.warnings`.\n *\n * @internal\n */\nexport function shadowObservationFromBounded(bounded: BoundedValidationResult): ShadowObservation {\n return {\n accepted: bounded.accepted,\n violationCodes: sortedDedupedCodes(bounded.violations.map((v) => v.code)),\n warningCodes: sortedDedupedCodes(bounded.warnings.map((w) => w.code)),\n };\n}\n\n/**\n * Project a `BoundedValidationResult` into the shared observation\n * shape with `warningCodes` flattened to `[]`. Use on the issue path\n * where canonical issuance does not surface warning codes through\n * `IssueResult`. Without this projection the bounded validator's\n * type-extension or temporal warnings would create false\n * `output-byte-diff` records on every otherwise-successful issuance.\n *\n * @internal\n */\nexport function shadowObservationFromBoundedAcceptedOnly(\n bounded: BoundedValidationResult\n): ShadowObservation {\n return {\n accepted: bounded.accepted,\n violationCodes: sortedDedupedCodes(bounded.violations.map((v) => v.code)),\n warningCodes: [],\n };\n}\n\nconst EMPTY_ACCEPTED: ShadowObservation = Object.freeze({\n accepted: true,\n violationCodes: Object.freeze([]) as readonly string[],\n warningCodes: Object.freeze([]) as readonly string[],\n});\n\nfunction sortedDedupedCodes(codes: readonly string[]): readonly string[] {\n if (codes.length === 0) return [];\n return Array.from(new Set(codes)).sort();\n}\n","/**\n * Local receipt verification with schema validation\n *\n * Use this for verifying receipts when you have the public key locally,\n * without JWKS discovery.\n */\n\nimport { type VerificationStrictness, type VerificationWarning, HASH } from '@peac/kernel';\nimport { defaultCodec } from './_internal/record-core/codec/jws-jwt.js';\nimport {\n parseReceiptClaims,\n validateKernelConstraints,\n type Wire02Claims,\n checkOccurredAtSkew,\n sortWarnings,\n WARNING_TYP_MISSING,\n WARNING_TYPE_UNREGISTERED,\n WARNING_UNKNOWN_EXTENSION,\n WARNING_EXTENSION_GROUP_MISSING,\n WARNING_EXTENSION_GROUP_MISMATCH,\n REGISTERED_RECEIPT_TYPES,\n REGISTERED_EXTENSION_GROUP_KEYS,\n isValidExtensionKey,\n verifyPolicyBinding,\n} from '@peac/schema';\nimport { TYPE_TO_EXTENSION_MAP } from '@peac/kernel';\nimport { checkTypeExtensionMapping } from './type-extension-check';\nimport { maybeRunShadowValidation } from './_internal/record-core/shadow-hook';\nimport { runBoundedValidatorShadow } from './_internal/record-core/bounded-validator.js';\nimport { isShadowEnabled, scheduleShadow, type ShadowEnableOptions } from './_internal/shadow.js';\nimport {\n realObservationForVerifyLocalSuccess,\n shadowObservationFromBounded,\n type ShadowObservation,\n} from './_internal/shadow-observe.js';\nimport type { PolicyBindingStatus } from './verifier-types';\n\n/**\n * Structural type for CryptoError\n * Used instead of instanceof for robustness across ESM/CJS boundaries\n */\ninterface CryptoErrorLike {\n name: 'CryptoError';\n code: string;\n message: string;\n}\n\n/**\n * Structural check for CryptoError\n * More robust than instanceof across module boundaries (ESM/CJS, duplicate packages)\n */\nfunction isCryptoError(err: unknown): err is CryptoErrorLike {\n return (\n err !== null &&\n typeof err === 'object' &&\n 'name' in err &&\n err.name === 'CryptoError' &&\n 'code' in err &&\n typeof err.code === 'string' &&\n err.code.startsWith('CRYPTO_') &&\n 'message' in err &&\n typeof err.message === 'string'\n );\n}\n\n/**\n * Canonical error codes for local verification\n *\n * These map to E_* codes in specs/kernel/errors.json.\n * JOSE hardening codes (E_JWS_*) are distinct from generic E_INVALID_FORMAT\n * so callers can distinguish key-injection, compression, and crit attacks from\n * ordinary format errors (v0.12.0-preview.1).\n */\nexport type VerifyLocalErrorCode =\n | 'E_INVALID_SIGNATURE'\n | 'E_INVALID_FORMAT'\n | 'E_CONSTRAINT_VIOLATION'\n | 'E_EXPIRED'\n | 'E_NOT_YET_VALID'\n | 'E_INVALID_ISSUER'\n | 'E_INVALID_AUDIENCE'\n | 'E_INVALID_SUBJECT'\n | 'E_INVALID_RECEIPT_ID'\n | 'E_MISSING_EXP'\n | 'E_WIRE_VERSION_MISMATCH'\n | 'E_UNSUPPORTED_WIRE_VERSION'\n | 'E_OCCURRED_AT_FUTURE'\n // JOSE hardening codes (Wire 0.2, v0.12.0-preview.1)\n | 'E_JWS_EMBEDDED_KEY'\n | 'E_JWS_CRIT_REJECTED'\n | 'E_JWS_MISSING_KID'\n | 'E_JWS_B64_REJECTED'\n | 'E_JWS_ZIP_REJECTED'\n // Policy binding (Wire 0.2, v0.12.0-preview.1)\n | 'E_POLICY_BINDING_FAILED'\n // Type-to-extension enforcement (Wire 0.2, v0.12.2)\n | 'E_EXTENSION_GROUP_REQUIRED'\n | 'E_EXTENSION_GROUP_MISMATCH'\n | 'E_INTERNAL';\n\n/**\n * Options for local verification\n */\nexport interface VerifyLocalOptions {\n /**\n * Expected issuer URL\n *\n * If provided, verification fails if receipt.iss does not match.\n */\n issuer?: string;\n\n /**\n * @deprecated Wire 0.2 does not have an `aud` claim. This option is ignored.\n * Retained for source compatibility during migration; will be removed in v1.0.\n */\n audience?: string;\n\n /**\n * Expected subject URI\n *\n * If provided, verification fails if receipt.sub does not match.\n * Binds the receipt to a specific resource/interaction target.\n */\n subjectUri?: string;\n\n /**\n * @deprecated Wire 0.2 does not have a `rid` claim. Use `jti` for receipt identification.\n * This option is ignored. Retained for source compatibility; will be removed in v1.0.\n */\n rid?: string;\n\n /**\n * @deprecated Wire 0.2 receipts do not expire (permanent evidence by design).\n * This option is ignored. Retained for source compatibility; will be removed in v1.0.\n */\n requireExp?: boolean;\n\n /**\n * Current timestamp (Unix seconds)\n *\n * Defaults to Date.now() / 1000. Override for testing.\n */\n now?: number;\n\n /**\n * Maximum clock skew tolerance (seconds)\n *\n * Allows for clock drift between issuer and verifier.\n * Defaults to 300 (5 minutes).\n */\n maxClockSkew?: number;\n\n /**\n * Verification strictness profile (v0.12.0-preview.1).\n *\n * - 'strict' (default): missing typ is a hard error before schema validation.\n * - 'interop': missing typ emits a 'typ_missing' warning and routes by payload content.\n *\n * Strictness is EXCLUSIVELY controlled here (@peac/protocol). @peac/crypto has no strictness param.\n */\n strictness?: VerificationStrictness;\n\n /**\n * Pre-computed local policy digest for policy binding (Wire 0.2, v0.12.0-preview.1).\n *\n * Must be in 'sha256:<64 lowercase hex>' format, computed via computePolicyDigestJcs()\n * from @peac/protocol. When provided alongside a receipt that contains a policy block\n * (policy.digest), the binding check is performed:\n * - Match: policy_binding = 'verified'\n * - Mismatch: hard fail with E_POLICY_BINDING_FAILED\n * - Either absent: policy_binding = 'unavailable'\n *\n * Always 'unavailable' for Wire 0.1 receipts regardless of this option.\n */\n policyDigest?: string;\n\n /**\n * Pre-computed document-binding results for transaction-local terms\n * and any other referenced documents (v0.12.14).\n *\n * Per-representation envelope binding (status) and any optional\n * publisher-supplied canonical-JSON digest comparison are computed by\n * the caller using the helpers in `document-binding.ts`. `verifyLocal`\n * surfaces the results on the report's `bindings` field exactly as\n * supplied; it never synthesizes envelope or canonical-digest\n * comparisons internally.\n *\n * `bindings.policy` is populated by `verifyLocal` itself from the\n * receipt's `policy.digest` and the `policyDigest` option. `bindings.terms`\n * is populated from `terms` here. `bindings.documents` is populated from\n * `documents` here. None of these fields appear on the emitted record\n * or envelope; they are verifier-report-only.\n */\n bindings?: {\n terms?: import('./verifier-types.js').DocumentBindingResult;\n documents?: import('./verifier-types.js').DocumentBindingResult[];\n };\n}\n\n/**\n * Result of successful local verification (Wire 0.2 only)\n *\n * Wire 0.1 receipts are no longer accepted by verifyLocal() and return\n * E_UNSUPPORTED_WIRE_VERSION. Re-issue as Wire 0.2 using issue().\n */\nexport interface VerifyLocalSuccess {\n /** Verification succeeded */\n valid: true;\n /** Receipt variant (always 'wire-02') */\n variant: 'wire-02';\n /** Validated Wire 0.2 receipt claims */\n claims: Wire02Claims;\n /** Key ID from JWS header (for logging/indexing) */\n kid: string;\n /** Wire format version */\n wireVersion: '0.2';\n /** Verification warnings from schema parsing and strictness routing */\n warnings: VerificationWarning[];\n /**\n * Policy binding status.\n *\n * Three-state result:\n * - 'unavailable': either the receipt contains no policy block, or the\n * caller did not pass a policyDigest option to verifyLocal(). No check.\n * - 'verified': both digests present and match exactly.\n * - 'failed': not returned on success; verifyLocal() returns\n * E_POLICY_BINDING_FAILED (valid: false) before reaching this field.\n *\n * This field is the byte-stable legacy mirror of `bindings.policy`.\n */\n policy_binding: PolicyBindingStatus;\n\n /**\n * Top-level bindings object (v0.12.14).\n *\n * `bindings.policy` is always present and equal to `policy_binding`.\n * `bindings.terms` is present iff the caller supplied terms inputs.\n * `bindings.documents` is present iff the caller supplied a non-empty\n * `documentDigests` array. `bindings.terms` and `bindings.documents`\n * appear in verifier output only; they are NOT stamped into the\n * emitted record / envelope / artifact shape.\n */\n bindings: import('./verifier-types.js').VerifierBindings;\n}\n\n/**\n * Result of failed local verification\n */\nexport interface VerifyLocalFailure {\n /** Verification failed */\n valid: false;\n\n /** Canonical error code (maps to specs/kernel/errors.json) */\n code: VerifyLocalErrorCode;\n\n /** Human-readable error message */\n message: string;\n\n /** Structured details for debugging (stable error code preserved in `code`) */\n details?: {\n /** Precise parse error code from unified parser (e.g. E_PARSE_COMMERCE_INVALID) */\n parse_code?: string;\n /** Zod validation issues (bounded, stable shape; non-normative, may change) */\n issues?: ReadonlyArray<{ path: string; message: string }>;\n /**\n * Policy digest from the receipt (present when code is E_POLICY_BINDING_FAILED).\n * Both are SHA-256 hashes; safe to log without leaking policy content.\n */\n receipt_policy_digest?: string;\n /** Caller-supplied policy digest (present when code is E_POLICY_BINDING_FAILED). */\n local_policy_digest?: string;\n /** policy.uri hint from the receipt (present when code is E_POLICY_BINDING_FAILED and uri set). */\n policy_uri?: string;\n /** Receipt type value (present when code is E_EXTENSION_GROUP_REQUIRED or E_EXTENSION_GROUP_MISMATCH). */\n type?: string;\n /** Expected extension group key for the receipt type. */\n expected_extension_group?: string;\n /** Registered extension groups actually present in extensions. */\n present_registered_extension_groups?: string[];\n };\n}\n\n/**\n * Union type for local verification result\n */\nexport type VerifyLocalResult = VerifyLocalSuccess | VerifyLocalFailure;\n\n/**\n * Internal CRYPTO_* codes that map to generic E_INVALID_FORMAT.\n * These are format/encoding errors not security-specific.\n */\nconst FORMAT_ERROR_CODES = new Set([\n 'CRYPTO_INVALID_JWS_FORMAT',\n 'CRYPTO_INVALID_TYP',\n 'CRYPTO_INVALID_ALG',\n 'CRYPTO_INVALID_KEY_LENGTH',\n]);\n\n/**\n * JOSE hardening code mapping: CRYPTO_JWS_* → specific E_JWS_* (v0.12.0-preview.1).\n *\n * Each JOSE hazard code maps to its specific public E_JWS_* counterpart rather than\n * collapsing into the generic E_INVALID_FORMAT. This lets callers distinguish embedded-key\n * injection, crit-header abuse, and unencoded-payload attacks from ordinary format errors.\n */\nconst JOSE_CODE_MAP: Record<string, VerifyLocalErrorCode> = {\n CRYPTO_JWS_EMBEDDED_KEY: 'E_JWS_EMBEDDED_KEY',\n CRYPTO_JWS_CRIT_REJECTED: 'E_JWS_CRIT_REJECTED',\n CRYPTO_JWS_MISSING_KID: 'E_JWS_MISSING_KID',\n CRYPTO_JWS_B64_REJECTED: 'E_JWS_B64_REJECTED',\n CRYPTO_JWS_ZIP_REJECTED: 'E_JWS_ZIP_REJECTED',\n};\n\n/** Max parse issues to include in details (prevents log bloat) */\nconst MAX_PARSE_ISSUES = 25;\n\n/**\n * Sanitize Zod issues into a bounded, stable structure.\n * Avoids exposing raw Zod internals or unbounded arrays in the public API.\n */\nfunction sanitizeParseIssues(\n issues: unknown\n): ReadonlyArray<{ path: string; message: string }> | undefined {\n if (!Array.isArray(issues)) return undefined;\n return issues.slice(0, MAX_PARSE_ISSUES).map((issue) => ({\n path: Array.isArray(issue?.path) ? issue.path.join('.') : '',\n message: typeof issue?.message === 'string' ? issue.message : String(issue),\n }));\n}\n\n/**\n * Verify a Wire 0.2 PEAC receipt locally with a known public key.\n *\n * Wire 0.2 only: Wire 0.1 receipts return E_UNSUPPORTED_WIRE_VERSION.\n * Re-issue Wire 0.1 receipts as Wire 0.2 using issueWire02().\n *\n * This function:\n * 1. Verifies the Ed25519 signature and header (typ, alg)\n * 2. Applies strictness routing for missing typ (strict: hard error; interop: warning)\n * 3. Validates the receipt schema with Zod (Wire 0.2 only)\n * 4. Checks issuer/subject binding (if options provided)\n * 5. Checks time validity (iat with clock skew tolerance)\n * 6. Checks occurred_at skew and collects parse warnings\n *\n * @param jws - JWS compact serialization\n * @param publicKey - Ed25519 public key (32 bytes)\n * @param options - Optional verification options (issuer, subject, clock skew, strictness, policyDigest)\n * @returns Typed verification result\n *\n * @example\n * ```typescript\n * const result = await verifyLocal(jws, publicKey, {\n * issuer: 'https://api.example.com',\n * strictness: 'strict',\n * });\n * if (result.valid) {\n * console.log('Kind:', result.claims.kind);\n * console.log('Warnings:', result.warnings);\n * }\n * ```\n */\nexport async function verifyLocal(\n jws: string,\n publicKey: Uint8Array,\n options: VerifyLocalOptions = {}\n): Promise<VerifyLocalResult> {\n const {\n issuer,\n subjectUri,\n maxClockSkew = 300,\n strictness = 'strict',\n policyDigest,\n bindings: callerBindings,\n } = options;\n const now = options.now ?? Math.floor(Date.now() / 1000);\n\n try {\n // 1. Verify signature and header via the internal codec boundary\n // (typ, alg validated by @peac/crypto). Default codec is a pure\n // pass-through to @peac/crypto.verify; the returned VerifyResult is\n // byte-identical to the prior release for every fixture.\n const result = await defaultCodec.decode<unknown>(jws, publicKey);\n\n if (!result.valid) {\n return {\n valid: false,\n code: 'E_INVALID_SIGNATURE',\n message: 'Ed25519 signature verification failed',\n };\n }\n\n // Accumulated warnings for Wire 0.2 path\n const accumulatedWarnings: VerificationWarning[] = [];\n\n // 2. Strictness routing for missing typ (Correction 1)\n if (result.header.typ === undefined) {\n if (strictness === 'strict') {\n return {\n valid: false,\n code: 'E_INVALID_FORMAT',\n message: 'Missing JWS typ header: strict mode requires typ to be present',\n };\n }\n // interop mode: emit warning and continue\n accumulatedWarnings.push({\n code: WARNING_TYP_MISSING,\n message: 'JWS typ header is absent; accepted in interop mode',\n });\n }\n\n // 3. Validate structural kernel constraints (fail-closed)\n const constraintResult = validateKernelConstraints(result.payload);\n if (!constraintResult.valid) {\n const v = constraintResult.violations[0];\n return {\n valid: false,\n code: 'E_CONSTRAINT_VIOLATION',\n message: `Kernel constraint violated: ${v.constraint} (actual: ${v.actual}, limit: ${v.limit})`,\n };\n }\n\n // 4. Validate schema (unified parser supports Wire 0.1 and Wire 0.2)\n const pr = parseReceiptClaims(result.payload);\n\n if (!pr.ok) {\n return {\n valid: false,\n code: 'E_INVALID_FORMAT',\n message: `Receipt schema validation failed: ${pr.error.message}`,\n details: { parse_code: pr.error.code, issues: sanitizeParseIssues(pr.error.issues) },\n };\n }\n\n // 5. Collect parser warnings (Wire 0.2 parser may emit type/extension warnings)\n if (pr.wireVersion === '0.2') {\n accumulatedWarnings.push(...pr.warnings);\n }\n\n // Wire 0.2 path\n if (pr.wireVersion === '0.2') {\n const claims = pr.claims as Wire02Claims;\n\n // Inert shadow-call boundary (default disabled in v0.13.1; PR D\n // wires the actual flag plumbing). The hook returns undefined\n // and never affects control flow or result; this call is a\n // structural placeholder so PR D can extend the boundary\n // without touching this file again.\n maybeRunShadowValidation({ mode: 'disabled', claims });\n\n // Issuer check\n if (issuer !== undefined && claims.iss !== issuer) {\n return {\n valid: false,\n code: 'E_INVALID_ISSUER',\n message: `Issuer mismatch: expected \"${issuer}\", got \"${claims.iss}\"`,\n };\n }\n\n // Subject check\n if (subjectUri !== undefined && claims.sub !== subjectUri) {\n return {\n valid: false,\n code: 'E_INVALID_SUBJECT',\n message: `Subject mismatch: expected \"${subjectUri}\", got \"${claims.sub ?? 'undefined'}\"`,\n };\n }\n\n // iat: not-yet-valid check (with clock skew)\n if (claims.iat > now + maxClockSkew) {\n return {\n valid: false,\n code: 'E_NOT_YET_VALID',\n message: `Receipt not yet valid: issued at ${new Date(claims.iat * 1000).toISOString()}, now is ${new Date(now * 1000).toISOString()}`,\n };\n }\n\n // occurred_at skew check (evidence kind only)\n if (claims.kind === 'evidence') {\n const skewResult = checkOccurredAtSkew(claims.occurred_at, claims.iat, now, maxClockSkew);\n if (skewResult === 'future_error') {\n return {\n valid: false,\n code: 'E_OCCURRED_AT_FUTURE',\n message: `occurred_at is in the future beyond tolerance (${maxClockSkew}s)`,\n };\n }\n if (skewResult !== null) {\n accumulatedWarnings.push(skewResult);\n }\n }\n\n // Emit type_unregistered warning for valid-but-unregistered type values\n if (!REGISTERED_RECEIPT_TYPES.has(claims.type)) {\n accumulatedWarnings.push({\n code: WARNING_TYPE_UNREGISTERED,\n message: 'Receipt type is not in the recommended type registry',\n pointer: '/type',\n });\n }\n\n // Emit unknown_extension_preserved warnings for unrecognized-but-well-formed keys\n // Malformed keys are already hard errors (E_INVALID_EXTENSION_KEY) at schema layer.\n if (claims.extensions !== undefined) {\n for (const key of Object.keys(claims.extensions)) {\n if (!REGISTERED_EXTENSION_GROUP_KEYS.has(key) && isValidExtensionKey(key)) {\n // RFC 6901: '~' -> '~0', '/' -> '~1'\n const escapedKey = key.replace(/~/g, '~0').replace(/\\//g, '~1');\n accumulatedWarnings.push({\n code: WARNING_UNKNOWN_EXTENSION,\n message: 'Unknown extension key preserved without schema validation',\n pointer: `/extensions/${escapedKey}`,\n });\n }\n }\n }\n\n // Type-to-extension enforcement: check that the expected extension group is present\n const typeExtCheck = checkTypeExtensionMapping(\n claims.kind,\n claims.type,\n claims.extensions,\n TYPE_TO_EXTENSION_MAP,\n REGISTERED_EXTENSION_GROUP_KEYS\n );\n\n if (typeExtCheck.status === 'missing' || typeExtCheck.status === 'mismatch') {\n const warningCode =\n typeExtCheck.status === 'missing'\n ? WARNING_EXTENSION_GROUP_MISSING\n : WARNING_EXTENSION_GROUP_MISMATCH;\n const errorCode =\n typeExtCheck.status === 'missing'\n ? 'E_EXTENSION_GROUP_REQUIRED'\n : 'E_EXTENSION_GROUP_MISMATCH';\n\n if (strictness === 'strict') {\n return {\n valid: false,\n code: errorCode,\n message: `Type \"${claims.type}\" expects extension group \"${typeExtCheck.expected_extension_group}\" but it is ${typeExtCheck.status === 'mismatch' ? 'replaced by a different registered group' : 'absent'}`,\n details: {\n type: claims.type,\n expected_extension_group: typeExtCheck.expected_extension_group,\n present_registered_extension_groups: typeExtCheck.present_registered_extension_groups,\n },\n };\n }\n\n // Interop mode: emit warning, continue verification\n accumulatedWarnings.push({\n code: warningCode,\n message: `Type \"${claims.type}\" expects extension group \"${typeExtCheck.expected_extension_group}\"`,\n pointer: '/type',\n });\n }\n\n // Validate policyDigest option format: must be sha256:<64 lowercase hex> if provided.\n if (policyDigest !== undefined && !HASH.pattern.test(policyDigest)) {\n return {\n valid: false,\n code: 'E_INVALID_FORMAT',\n message: 'policyDigest option must be in sha256:<64 lowercase hex> format',\n };\n }\n\n // Policy binding check: 3-state result.\n // 'unavailable' when either receipt has no policy block or caller omitted policyDigest.\n // 'verified' / 'failed' when both are present; 'failed' is a hard verification error.\n const receiptPolicyDigest = claims.policy?.digest;\n const bindingStatus: PolicyBindingStatus =\n receiptPolicyDigest === undefined || policyDigest === undefined\n ? 'unavailable'\n : verifyPolicyBinding(receiptPolicyDigest, policyDigest);\n if (bindingStatus === 'failed') {\n return {\n valid: false,\n code: 'E_POLICY_BINDING_FAILED',\n message: 'Policy binding check failed: receipt policy digest does not match local policy',\n details: {\n receipt_policy_digest: receiptPolicyDigest,\n local_policy_digest: policyDigest,\n ...(claims.policy?.uri !== undefined && { policy_uri: claims.policy.uri }),\n },\n };\n }\n\n // Build the top-level `bindings` object. `policy` always present and\n // mirrors the legacy `policy_binding` field byte-stable. `terms` and\n // `documents` are surfaced from caller-supplied results; verifyLocal\n // does not synthesize envelope or canonical-digest comparisons here.\n // Report-only; never stamped into emitted record / envelope shape.\n const bindings: import('./verifier-types.js').VerifierBindings = {\n policy: bindingStatus,\n ...(callerBindings?.terms !== undefined && { terms: callerBindings.terms }),\n ...(callerBindings?.documents !== undefined &&\n callerBindings.documents.length > 0 && { documents: callerBindings.documents }),\n };\n\n const sortedWarnings = sortWarnings(accumulatedWarnings);\n\n if (isShadowEnabled(options as unknown as ShadowEnableOptions)) {\n const headerSnapshot = { ...result.header } as Record<string, unknown>;\n scheduleShadow<ShadowObservation>({\n call: 'verifyLocal',\n realResult: realObservationForVerifyLocalSuccess(sortedWarnings),\n realError: undefined,\n shadowFn: async () =>\n shadowObservationFromBounded(\n runBoundedValidatorShadow({\n claims: {\n kind: claims.kind,\n type: claims.type,\n iss: claims.iss,\n iat: claims.iat,\n occurred_at: claims.occurred_at,\n extensions: claims.extensions,\n },\n header: headerSnapshot,\n now,\n })\n ),\n recordRef: jws,\n });\n }\n\n return {\n valid: true,\n variant: 'wire-02',\n claims,\n kid: result.header.kid,\n wireVersion: '0.2',\n warnings: sortedWarnings,\n policy_binding: bindingStatus,\n bindings,\n };\n }\n\n // Wire 0.1 receipts: reject with E_UNSUPPORTED_WIRE_VERSION.\n return {\n valid: false,\n code: 'E_UNSUPPORTED_WIRE_VERSION',\n message: 'Wire 0.1 receipts are not supported. Re-issue as Wire 0.2 using issue().',\n };\n } catch (err) {\n // Handle typed CryptoError from @peac/crypto\n // Use structural check instead of instanceof for robustness across ESM/CJS boundaries\n // Map internal CRYPTO_* codes to canonical E_* codes.\n // JOSE hardening codes get specific E_JWS_* (not generic E_INVALID_FORMAT) so callers\n // can distinguish key-injection attacks from ordinary encoding errors.\n if (isCryptoError(err)) {\n // 1. JOSE hardening: specific E_JWS_* codes (checked first)\n if (Object.prototype.hasOwnProperty.call(JOSE_CODE_MAP, err.code)) {\n return {\n valid: false,\n code: JOSE_CODE_MAP[err.code]!,\n message: err.message,\n };\n }\n // 2. Generic format errors\n if (FORMAT_ERROR_CODES.has(err.code)) {\n return {\n valid: false,\n code: 'E_INVALID_FORMAT',\n message: err.message,\n };\n }\n if (err.code === 'CRYPTO_INVALID_SIGNATURE') {\n return {\n valid: false,\n code: 'E_INVALID_SIGNATURE',\n message: err.message,\n };\n }\n if (err.code === 'CRYPTO_WIRE_VERSION_MISMATCH') {\n return {\n valid: false,\n code: 'E_WIRE_VERSION_MISMATCH',\n message: err.message,\n };\n }\n }\n\n // Handle JSON parse errors from malformed payloads\n // Use structural check for cross-boundary robustness (consistent with isCryptoError pattern)\n if (\n err !== null &&\n typeof err === 'object' &&\n 'name' in err &&\n (err as { name: unknown }).name === 'SyntaxError'\n ) {\n const syntaxMessage =\n 'message' in err && typeof (err as { message: unknown }).message === 'string'\n ? (err as { message: string }).message\n : 'Invalid JSON';\n return {\n valid: false,\n code: 'E_INVALID_FORMAT',\n message: `Invalid receipt payload: ${syntaxMessage}`,\n };\n }\n\n // All other errors -> E_INTERNAL\n // No message parsing - code-based mapping only\n const message = err instanceof Error ? err.message : String(err);\n return {\n valid: false,\n code: 'E_INTERNAL',\n message: `Unexpected verification error: ${message}`,\n };\n }\n}\n\n/**\n * @deprecated Removed: verifyLocal() is Wire 0.2 only and always returns variant 'wire-02'.\n * This guard always returns false. Remove usage and use isWire02Result() instead.\n */\nexport function isCommerceResult(\n r: VerifyLocalResult\n): r is VerifyLocalSuccess & { variant: 'wire-02' } {\n // Always false: verifyLocal() only returns variant 'wire-02'\n return false;\n}\n\n/**\n * @deprecated Removed: verifyLocal() is Wire 0.2 only and always returns variant 'wire-02'.\n * This guard always returns false. Remove usage and use isWire02Result() instead.\n */\nexport function isAttestationResult(\n r: VerifyLocalResult\n): r is VerifyLocalSuccess & { variant: 'wire-02' } {\n // Always false: verifyLocal() only returns variant 'wire-02'\n return false;\n}\n\n/**\n * Type guard: narrows a VerifyLocalResult to a Wire 0.2 success (v0.12.0-preview.1).\n *\n * Use instead of manual `result.valid && result.variant === 'wire-02'` checks\n * to get proper claims narrowing to Wire02Claims.\n */\nexport function isWire02Result(\n r: VerifyLocalResult\n): r is VerifyLocalSuccess & { variant: 'wire-02' } {\n return r.valid === true && r.variant === 'wire-02';\n}\n"]}
1
+ {"version":3,"sources":["../src/_internal/record-core/codec/types.ts","../src/_internal/record-core/codec/jws-jwt.ts","../src/type-extension-check.ts","../src/_internal/record-core/shadow-hook.ts","../src/_internal/record-core/validators/kernel-constraints.ts","../src/_internal/record-core/validators/type-extension-mapping.ts","../src/_internal/record-core/validators/jose-hardening.ts","../src/_internal/record-core/validators/issuer-form.ts","../src/_internal/record-core/validators/temporal.ts","../src/_internal/record-core/validators/extension-budget.ts","../src/_internal/record-core/bounded-validator.ts","../src/_internal/shadow-redact.ts","../src/_internal/shadow.ts","../src/_internal/legacy-path.ts","../src/_internal/shadow-observe.ts","../src/verify-local.ts"],"names":["signWire02","cryptoVerify","base64urlDecodeString","KERNEL_CONSTRAINTS","TYPE_TO_EXTENSION_MAP","REGISTERED_EXTENSION_GROUP_KEYS","REGISTERED_RECEIPT_TYPES","WARNING_TYPE_UNREGISTERED","isValidExtensionKey","WARNING_UNKNOWN_EXTENSION","WARNING_EXTENSION_GROUP_MISSING","WARNING_EXTENSION_GROUP_MISMATCH","ACCEPTED","ISS_CANONICAL","OCCURRED_AT_TOLERANCE_SECONDS","escapeJsonPointerSegment","EXTENSION_BUDGET","sha256Hex","base64urlEncode","WARNING_TYP_MISSING","validateKernelConstraints","parseReceiptClaims","checkOccurredAtSkew","HASH","verifyPolicyBinding","sortWarnings"],"mappings":";;;;;;;;;AAsCO,IAAM,UAAA,GAAN,cAAyB,KAAA,CAAM;AAAA,EACpC,WAAA,CACkB,MAChB,OAAA,EACA;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAHG,IAAA,IAAA,CAAA,IAAA,GAAA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AACT;AAQO,SAAS,eACd,CAAA,EACkD;AAClD,EAAA,OAAO,CAAA,CAAE,KAAA,KAAU,IAAA,IAAQ,CAAA,CAAE,OAAA,KAAY,SAAA;AAC3C","file":"verify-local.cjs","sourcesContent":["/**\n * Internal codec strategy types.\n *\n * @internal\n *\n * These types MUST NOT be re-exported from packages/protocol/src/index.ts.\n * The dist-leak gate (Tier 2) asserts that these names never appear in\n * @peac/protocol's public root declaration (dist/index.d.ts) or any\n * subpath in @peac/protocol/package.json `exports`.\n *\n * The canonical implementation of these types lives at\n * packages/protocol/src/_internal/record-core/codec/jws-jwt.ts and is\n * imported via RELATIVE paths from issue.ts / verify-local.ts.\n */\n\nimport type { VerifyResult } from '@peac/crypto';\n\n/**\n * Header view returned by codec.peekHeader().\n *\n * @internal\n */\nexport interface CodecHeader {\n /** JOSE typ value. Required at peek time; not defaulted. */\n readonly typ: string;\n /** Algorithm identifier. JWS string (e.g., 'EdDSA'). */\n readonly alg: string;\n /** Key identifier (when present). */\n readonly kid?: string;\n /** Full raw protected-header object for downstream policy inspection. */\n readonly raw: Readonly<Record<string, unknown>>;\n}\n\n/**\n * Codec error with a structured code.\n *\n * @internal\n */\nexport class CodecError extends Error {\n constructor(\n public readonly code: string,\n message: string\n ) {\n super(message);\n this.name = 'CodecError';\n }\n}\n\n/**\n * Internal codec strategy. v0.13.1 ships exactly one implementation:\n * jws-jwt. Signature mirrors @peac/crypto.signWire02 / verify exactly;\n * concrete Uint8Array keys (Ed25519 at this layer); parametric only on\n * the optional payload type T of VerifyResult<T>. Future codecs with\n * different key shapes register a different interface; they MAY NOT\n * shoehorn into this interface via parametric generics.\n *\n * @internal\n */\nexport interface RecordCodec {\n /** Codec name. Used for registry lookup. */\n readonly name: string;\n\n /**\n * Sign and serialize. Pure pass-through to the underlying signer; never\n * accepts a typ override (the signer hardcodes typ per the wire format).\n */\n encode(payload: unknown, privateKey: Uint8Array, kid: string): Promise<string>;\n\n /**\n * Verify and decode. Returns the underlying crypto verifier's result\n * unchanged. Throws structured CodecError on malformed input;\n * propagates the underlying CryptoError on signature mismatch.\n */\n decode<T = unknown>(serialized: string, publicKey: Uint8Array): Promise<VerifyResult<T>>;\n\n /**\n * Header-only decode. Structural strictness only: throws CodecError on\n * missing typ, missing alg, malformed protected header JSON, or\n * malformed compact JWS (must be exactly three non-empty\n * dot-separated segments). Does NOT enforce policy on crit / zip /\n * b64 / unsupported alg; those rejections are downstream JOSE-hardening\n * responsibilities and are surfaced via the raw header for inspection.\n *\n * Note: this codec is JWS/JWT string-based. The `serialized` parameter\n * is typed as `string` for that reason. Future codecs that operate on\n * binary inputs (e.g., COSE/CBOR over `Uint8Array`) MUST register a\n * different interface; do not generalize this one to imply binary\n * support that the JWS codec does not provide.\n */\n peekHeader(serialized: string): CodecHeader;\n}\n","/**\n * Default codec: pure pass-through to @peac/crypto.signWire02 / verify.\n *\n * @internal\n *\n * Byte-identical encode output to signWire02 is guaranteed by the\n * golden-vector test (codec-jws-jwt-byte-identical.test.ts). Decode\n * returns the underlying cryptoVerify result unchanged.\n *\n * peekHeader is structural-only: it requires typ + alg presence and a\n * structurally valid compact JWS, but does NOT enforce policy on\n * unsupported alg, crit, zip, or b64:false. Those rejections are\n * downstream responsibilities (kernel constraints, JOSE hardening).\n *\n * The canonical implementation lives here. Tests import via relative\n * paths from packages/protocol/__tests__/_internal/.\n */\n\nimport {\n signWire02,\n verify as cryptoVerify,\n base64urlDecodeString,\n type VerifyResult,\n} from '@peac/crypto';\nimport { CodecError, type CodecHeader, type RecordCodec } from './types.js';\n\nclass JwsJwtCodec implements RecordCodec {\n readonly name = 'jws-jwt' as const;\n\n async encode(payload: unknown, privateKey: Uint8Array, kid: string): Promise<string> {\n return signWire02(payload, privateKey, kid);\n }\n\n async decode<T = unknown>(serialized: string, publicKey: Uint8Array): Promise<VerifyResult<T>> {\n return cryptoVerify<T>(serialized, publicKey);\n }\n\n peekHeader(serialized: string): CodecHeader {\n // Structural compact-JWS shape: exactly three non-empty\n // dot-separated segments: header.payload.signature.\n const segments = serialized.split('.');\n if (segments.length !== 3) {\n throw new CodecError(\n 'CODEC_PEEK_MALFORMED',\n `jws-jwt: malformed compact JWS (expected 3 segments, got ${segments.length})`\n );\n }\n const [headerB64, payloadB64, signatureB64] = segments;\n if (headerB64.length === 0) {\n throw new CodecError(\n 'CODEC_PEEK_MALFORMED',\n 'jws-jwt: malformed compact JWS (empty header segment)'\n );\n }\n if (payloadB64.length === 0) {\n throw new CodecError(\n 'CODEC_PEEK_MALFORMED',\n 'jws-jwt: malformed compact JWS (empty payload segment)'\n );\n }\n if (signatureB64.length === 0) {\n throw new CodecError(\n 'CODEC_PEEK_MALFORMED',\n 'jws-jwt: malformed compact JWS (empty signature segment)'\n );\n }\n\n let header: Record<string, unknown>;\n try {\n // Runtime-neutral base64url -> UTF-8 string decode\n // (TextDecoder + Uint8Array via @peac/crypto.base64urlDecodeString;\n // no Node Buffer dependency: works in browser, edge worker, Deno).\n const headerJson = base64urlDecodeString(headerB64);\n header = JSON.parse(headerJson) as Record<string, unknown>;\n } catch (err) {\n throw new CodecError(\n 'CODEC_PEEK_INVALID_HEADER',\n `jws-jwt: protected header JSON parse failed: ${(err as Error).message}`\n );\n }\n\n if (typeof header.typ !== 'string') {\n throw new CodecError(\n 'CODEC_PEEK_MISSING_TYP',\n 'jws-jwt: protected header missing required field \"typ\" (string)'\n );\n }\n if (typeof header.alg !== 'string') {\n throw new CodecError(\n 'CODEC_PEEK_MISSING_ALG',\n 'jws-jwt: protected header missing required field \"alg\" (string)'\n );\n }\n\n return {\n typ: header.typ,\n alg: header.alg,\n kid: typeof header.kid === 'string' ? header.kid : undefined,\n raw: header,\n };\n }\n}\n\n/**\n * Default codec instance. Internal-only.\n *\n * @internal\n */\nexport const defaultCodec: RecordCodec = new JwsJwtCodec();\n","/**\n * Type-to-extension enforcement check (Layer 3)\n *\n * Pure helper: given a receipt kind, type, extensions record, and\n * registry data, determines whether the expected extension group is\n * present, absent, or replaced by a different registered group.\n *\n * This module has no side effects, no I/O, and no strictness logic.\n * Strictness (error vs warning) is decided by the caller (verifyLocal).\n *\n * Decision tree:\n * 1. challenge-kind receipt -> skip\n * 2. unmapped/custom type -> skip\n * 3. expected extension present -> ok\n * 4. expected absent + other registered present -> mismatch\n * 5. expected absent + none present -> missing\n *\n * Unknown third-party extension keys never count as mismatch.\n */\n\n/** Result of the type-to-extension mapping check */\nexport type TypeExtensionCheckResult =\n | { status: 'ok' }\n | { status: 'skip' }\n | {\n status: 'missing' | 'mismatch';\n expected_extension_group: string;\n present_registered_extension_groups: string[];\n };\n\n/**\n * Check whether a receipt's extensions match the expected extension\n * group for its registered type.\n *\n * Performance: O(1) lookup for the common ok/skip paths. Only iterates\n * extension keys when the expected group is absent (error path).\n *\n * @param kind - Receipt kind (evidence or challenge)\n * @param type - Receipt type value (e.g., org.peacprotocol/payment)\n * @param extensions - Extensions record from receipt claims (may be undefined)\n * @param typeToExtensionMap - Generated TYPE_TO_EXTENSION_MAP\n * @param registeredExtensionGroupKeys - Generated REGISTERED_EXTENSION_GROUP_KEYS set\n */\nexport function checkTypeExtensionMapping(\n kind: string,\n type: string,\n extensions: Record<string, unknown> | undefined,\n typeToExtensionMap: ReadonlyMap<string, string>,\n registeredExtensionGroupKeys: ReadonlySet<string>\n): TypeExtensionCheckResult {\n // Challenge-kind receipts skip: they indicate requirements, not evidence\n if (kind === 'challenge') {\n return { status: 'skip' };\n }\n\n const expectedGroup = typeToExtensionMap.get(type);\n\n // Unmapped/custom type: no check\n if (expectedGroup === undefined) {\n return { status: 'skip' };\n }\n\n // Expected group present: pass (O(1) check)\n if (extensions !== undefined && Object.prototype.hasOwnProperty.call(extensions, expectedGroup)) {\n return { status: 'ok' };\n }\n\n // Expected group absent: determine missing vs mismatch\n // Only build the present-registered list on this (uncommon) path\n const presentRegistered: string[] = [];\n if (extensions !== undefined) {\n for (const key of Object.keys(extensions)) {\n if (key !== expectedGroup && registeredExtensionGroupKeys.has(key)) {\n presentRegistered.push(key);\n }\n }\n }\n\n return {\n status: presentRegistered.length > 0 ? 'mismatch' : 'missing',\n expected_extension_group: expectedGroup,\n present_registered_extension_groups: presentRegistered,\n };\n}\n","/**\n * Inert shadow-call boundary for the bounded validator foundation.\n *\n * INTERNAL ONLY. This module is the call-site placeholder that PR D\n * will wire to the bounded validator pipeline behind an internal\n * feature flag. In v0.13.1 the boundary is INERT by construction:\n *\n * - the only declared mode is `'disabled'`\n * - the function body is a single early return on `'disabled'`\n * - it imports no bounded validators (zero runtime weight at\n * verify-local.ts cold-start, even though the call site exists)\n * - it never throws into verifyLocal()\n * - it never mutates the input claims object\n * - it never logs\n * - it never reads environment variables\n * - it never affects the canonical verify-local result\n *\n * The function returns `undefined` for every call. The call site in\n * verify-local.ts ignores the return value and never awaits any work.\n *\n * NOT re-exported from packages/protocol/src/index.ts. Public surface\n * is byte-stable. PR D may extend the input shape when wiring the\n * actual flag plumbing; that is a future-internal change, not a\n * public API change.\n */\n\n/**\n * The only declared shadow validation mode. Adding new modes requires\n * a deliberate future change in PR D where the actual flag is wired.\n */\nexport type ShadowValidationMode = 'disabled';\n\n/**\n * Input shape for the shadow-call boundary. `claims` is intentionally\n * `unknown` so callers may pass parsed Wire 0.2 claims without a\n * coupling to the schema's exported type from this internal helper.\n */\nexport interface ShadowValidationInput {\n readonly mode: ShadowValidationMode;\n readonly claims: unknown;\n}\n\n/**\n * Inert shadow-call hook. Always returns `undefined`. The signature\n * is stable enough for PR D to extend (e.g., adding a `header` or\n * `now` field) without breaking the disabled-default contract.\n */\nexport function maybeRunShadowValidation(input: ShadowValidationInput): undefined {\n if (input.mode === 'disabled') return undefined;\n return undefined;\n}\n","/**\n * Bounded internal kernel-constraints validator.\n *\n * INTERNAL ONLY. This is the parity-observed counterpart of\n * @peac/schema.validateKernelConstraints; both implementations consume\n * the same KERNEL_CONSTRAINTS constants from @peac/kernel and emit the\n * same ConstraintValidationResult shape. The differential parity test\n * asserts byte-identical equality between the two on every eligible\n * fixture; any divergence is stop-the-line.\n *\n * Existing validation in @peac/schema remains canonical. This module\n * is observational only; it is NOT re-exported from\n * packages/protocol/src/index.ts and is NOT wired into runtime paths\n * (issue.ts, verify-local.ts) in v0.13.1.\n *\n * Implementation invariants (must mirror @peac/schema/src/constraints.ts\n * verbatim; any drift fails the parity test):\n * - iterative stack-based traversal (stack-safe; no recursion)\n * - every value (primitives, arrays, objects) is pushed and counted as\n * a node when popped\n * - total-nodes check evaluated FIRST per pop; over-limit pushes the\n * violation with the current totalNodes count and breaks (preserves\n * first-violation semantics)\n * - depth check evaluated SECOND per pop; over-limit pushes a\n * violation and continues (no-op for primitives, prevents deeper\n * descent for containers)\n * - string-length check (primitives only) uses .length (code units)\n * - array-length and object-key-count checks pushed BEFORE descending\n * into children\n * - children pushed in reverse index/key order so traversal visits\n * them in original order (LIFO)\n * - empty path for root; bracket notation for arrays (`a[0]`); dot\n * notation for object keys (`a.b`)\n * - returns { valid: violations.length === 0, violations }\n * - never throws\n * - assumes acyclic input\n */\n\nimport { KERNEL_CONSTRAINTS } from '@peac/schema';\nimport type { ConstraintValidationResult, ConstraintViolation } from '@peac/schema';\n\n/**\n * Validate claims against structural kernel constraints. Mirrors the\n * canonical implementation in @peac/schema for parity.\n *\n * Distinct exported name (validateKernelConstraintsInternal) to avoid\n * collision with the canonical @peac/schema export when both are\n * imported into the same parity test file.\n */\nexport function validateKernelConstraintsInternal(claims: unknown): ConstraintValidationResult {\n const violations: ConstraintViolation[] = [];\n\n if (claims === null || claims === undefined || typeof claims !== 'object') {\n return { valid: true, violations };\n }\n\n let totalNodes = 0;\n const stack: Array<{ value: unknown; depth: number; path: string }> = [\n { value: claims, depth: 0, path: '' },\n ];\n\n while (stack.length > 0) {\n const item = stack.pop()!;\n totalNodes++;\n\n if (totalNodes > KERNEL_CONSTRAINTS.MAX_TOTAL_NODES) {\n violations.push({\n constraint: 'MAX_TOTAL_NODES',\n actual: totalNodes,\n limit: KERNEL_CONSTRAINTS.MAX_TOTAL_NODES,\n path: item.path,\n });\n break;\n }\n\n if (item.depth > KERNEL_CONSTRAINTS.MAX_NESTED_DEPTH) {\n violations.push({\n constraint: 'MAX_NESTED_DEPTH',\n actual: item.depth,\n limit: KERNEL_CONSTRAINTS.MAX_NESTED_DEPTH,\n path: item.path,\n });\n continue;\n }\n\n if (item.value === null || typeof item.value !== 'object') {\n if (typeof item.value === 'string') {\n if (item.value.length > KERNEL_CONSTRAINTS.MAX_STRING_LENGTH) {\n violations.push({\n constraint: 'MAX_STRING_LENGTH',\n actual: item.value.length,\n limit: KERNEL_CONSTRAINTS.MAX_STRING_LENGTH,\n path: item.path,\n });\n }\n }\n continue;\n }\n\n if (Array.isArray(item.value)) {\n if (item.value.length > KERNEL_CONSTRAINTS.MAX_ARRAY_LENGTH) {\n violations.push({\n constraint: 'MAX_ARRAY_LENGTH',\n actual: item.value.length,\n limit: KERNEL_CONSTRAINTS.MAX_ARRAY_LENGTH,\n path: item.path,\n });\n }\n for (let i = item.value.length - 1; i >= 0; i--) {\n stack.push({\n value: item.value[i],\n depth: item.depth + 1,\n path: `${item.path}[${i}]`,\n });\n }\n continue;\n }\n\n const keys = Object.keys(item.value as Record<string, unknown>);\n if (keys.length > KERNEL_CONSTRAINTS.MAX_OBJECT_KEYS) {\n violations.push({\n constraint: 'MAX_OBJECT_KEYS',\n actual: keys.length,\n limit: KERNEL_CONSTRAINTS.MAX_OBJECT_KEYS,\n path: item.path,\n });\n }\n for (let i = keys.length - 1; i >= 0; i--) {\n const key = keys[i];\n const childPath = item.path ? `${item.path}.${key}` : key;\n stack.push({\n value: (item.value as Record<string, unknown>)[key],\n depth: item.depth + 1,\n path: childPath,\n });\n }\n }\n\n return { valid: violations.length === 0, violations };\n}\n","/**\n * Bounded internal type-extension mapping validator.\n *\n * INTERNAL ONLY. This is the parity-observed counterpart of the\n * type/extension warning-emission block at verify-local.ts:477-540\n * (interop strictness branch). Both implementations consume the same\n * registries (REGISTERED_RECEIPT_TYPES, REGISTERED_EXTENSION_GROUP_KEYS,\n * TYPE_TO_EXTENSION_MAP) and the same warning-code constants from\n * @peac/schema; behavioral parity is proven byte-equal by the parity\n * tests, not by code copy.\n *\n * Existing canonical emission in @peac/protocol/verifyLocal remains\n * canonical. This module is observational only; it is NOT re-exported\n * from packages/protocol/src/index.ts and is NOT wired into runtime\n * paths (issue.ts, verify-local.ts) in v0.13.1.\n *\n * Output shape: a deterministically-ordered list of warning records,\n * each carrying only `code` and `pointer`. The canonical emission also\n * carries a `message` field; messages are intentionally omitted from\n * the parity comparison because the missing/mismatch messages embed\n * claim values (claims.type and the expected extension group), and\n * comparison on (code, pointer) is what the verifier output API\n * actually exposes to consumers via the warning code/pointer pair.\n *\n * Emission order (must mirror verify-local.ts exactly; tests assert):\n * 1. type_unregistered (when claims.type is not in REGISTERED_RECEIPT_TYPES)\n * 2. unknown_extension_preserved (one per unknown-but-well-formed\n * extension key, in Object.keys iteration order)\n * 3. extension_group_missing OR extension_group_mismatch (when\n * checkTypeExtensionMapping returns missing/mismatch; not emitted\n * for kind === 'challenge' or for unmapped/custom types)\n */\n\nimport {\n REGISTERED_EXTENSION_GROUP_KEYS,\n REGISTERED_RECEIPT_TYPES,\n WARNING_EXTENSION_GROUP_MISMATCH,\n WARNING_EXTENSION_GROUP_MISSING,\n WARNING_TYPE_UNREGISTERED,\n WARNING_UNKNOWN_EXTENSION,\n isValidExtensionKey,\n} from '@peac/schema';\nimport { TYPE_TO_EXTENSION_MAP } from '@peac/kernel';\n\n/** Minimal claims shape required by the type-extension warning surface. */\nexport interface TypeExtensionMappingInput {\n readonly kind: string;\n readonly type: string;\n readonly extensions?: Record<string, unknown>;\n}\n\n/** Normalized warning entry. Comparison shape; canonical messages omitted. */\nexport interface TypeExtensionMappingWarning {\n readonly code: string;\n readonly pointer: string;\n}\n\n/** Escape `~` and `/` per RFC 6901 for JSON Pointer fragments. */\nfunction escapeJsonPointerSegment(segment: string): string {\n return segment.replace(/~/g, '~0').replace(/\\//g, '~1');\n}\n\n/**\n * Mirror of @peac/protocol/src/type-extension-check.ts:checkTypeExtensionMapping.\n * Returns a status discriminator only; the bounded validator decides whether\n * the discriminator translates to a warning code.\n */\nfunction classifyExpectedGroup(\n kind: string,\n type: string,\n extensions: Record<string, unknown> | undefined\n): 'ok' | 'skip' | 'missing' | 'mismatch' {\n if (kind === 'challenge') return 'skip';\n const expectedGroup = TYPE_TO_EXTENSION_MAP.get(type);\n if (expectedGroup === undefined) return 'skip';\n if (extensions !== undefined && Object.prototype.hasOwnProperty.call(extensions, expectedGroup)) {\n return 'ok';\n }\n if (extensions !== undefined) {\n for (const key of Object.keys(extensions)) {\n if (key !== expectedGroup && REGISTERED_EXTENSION_GROUP_KEYS.has(key)) {\n return 'mismatch';\n }\n }\n }\n return 'missing';\n}\n\n/**\n * Evaluate the type-extension mapping warning surface for parsed Wire 0.2\n * claims. Returns warnings in canonical emission order; emits no warnings\n * when the claims are fully registered and the expected extension group\n * is present (or when no expected group exists for the given type).\n */\nexport function validateTypeExtensionMappingInternal(\n input: TypeExtensionMappingInput\n): TypeExtensionMappingWarning[] {\n const warnings: TypeExtensionMappingWarning[] = [];\n\n // Step 1: type_unregistered\n if (!REGISTERED_RECEIPT_TYPES.has(input.type)) {\n warnings.push({ code: WARNING_TYPE_UNREGISTERED, pointer: '/type' });\n }\n\n // Step 2: unknown_extension_preserved (one per unknown well-formed key)\n if (input.extensions !== undefined) {\n for (const key of Object.keys(input.extensions)) {\n if (!REGISTERED_EXTENSION_GROUP_KEYS.has(key) && isValidExtensionKey(key)) {\n warnings.push({\n code: WARNING_UNKNOWN_EXTENSION,\n pointer: `/extensions/${escapeJsonPointerSegment(key)}`,\n });\n }\n }\n }\n\n // Step 3: extension_group_missing | extension_group_mismatch\n const status = classifyExpectedGroup(input.kind, input.type, input.extensions);\n if (status === 'missing') {\n warnings.push({ code: WARNING_EXTENSION_GROUP_MISSING, pointer: '/type' });\n } else if (status === 'mismatch') {\n warnings.push({ code: WARNING_EXTENSION_GROUP_MISMATCH, pointer: '/type' });\n }\n\n return warnings;\n}\n","/**\n * Bounded internal JOSE header hardening validator.\n *\n * INTERNAL ONLY. This is the parity-observed counterpart of\n * @peac/crypto.validateWire02Header. Both implementations consume the\n * same JOSE protected-header object and apply the same five hardening\n * checks in the same order; behavioral parity is proven byte-equal by\n * the parity tests, not by code copy.\n *\n * Existing canonical hardening in @peac/crypto remains canonical. This\n * module is observational only; it is NOT re-exported from\n * packages/protocol/src/index.ts and is NOT wired into runtime paths\n * (issue.ts, verify-local.ts, peekHeader) in v0.13.1.\n *\n * Scope (must mirror validateWire02Header in packages/crypto/src/jws.ts):\n *\n * 1. kid presence and length:\n * - missing kid (undefined / non-string / empty) -> CRYPTO_JWS_MISSING_KID\n * - kid length > 256 chars -> CRYPTO_JWS_MISSING_KID\n *\n * 2. embedded key material (jwk, x5c, x5u, jku):\n * - any of the four set -> CRYPTO_JWS_EMBEDDED_KEY\n *\n * 3. crit header:\n * - any value (including null / empty array) -> CRYPTO_JWS_CRIT_REJECTED\n *\n * 4. b64: false (RFC 7797 unencoded payload):\n * - the only rejected value is the boolean false; other values pass through\n * - rejection -> CRYPTO_JWS_B64_REJECTED\n *\n * 5. zip header:\n * - any value -> CRYPTO_JWS_ZIP_REJECTED\n *\n * Out of scope for this module (mirroring validateWire02Header exactly):\n * - alg validation (lives in buildHeader, not validateWire02Header)\n * - typ validation (lives in buildHeader)\n * - signature verification\n * - compact-JWS shape / size checks\n *\n * Order is significant: the canonical function returns the FIRST\n * matching violation per call (it throws on the first hit). The\n * internal validator emits the same first-hit code.\n */\n\n/** Header input shape (matches the parsed JOSE protected header). */\nexport type JoseHardeningInput = Record<string, unknown>;\n\n/**\n * Normalized result. accepted=true means the header passes all five\n * hardening checks. accepted=false carries the canonical CryptoError\n * code emitted by the corresponding canonical check.\n */\nexport type JoseHardeningResult =\n | { readonly accepted: true }\n | { readonly accepted: false; readonly errorCode: string };\n\nconst KID_MAX_LENGTH = 256;\n\nconst ACCEPTED: JoseHardeningResult = { accepted: true } as const;\n\nfunction rejected(errorCode: string): JoseHardeningResult {\n return { accepted: false, errorCode };\n}\n\nexport function validateJoseHardeningInternal(header: JoseHardeningInput): JoseHardeningResult {\n // 1. kid presence and length\n if (\n !header.kid ||\n typeof header.kid !== 'string' ||\n header.kid.length === 0 ||\n header.kid.length > KID_MAX_LENGTH\n ) {\n return rejected('CRYPTO_JWS_MISSING_KID');\n }\n\n // 2. embedded key material\n if (\n header.jwk !== undefined ||\n header.x5c !== undefined ||\n header.x5u !== undefined ||\n header.jku !== undefined\n ) {\n return rejected('CRYPTO_JWS_EMBEDDED_KEY');\n }\n\n // 3. crit\n if (header.crit !== undefined) {\n return rejected('CRYPTO_JWS_CRIT_REJECTED');\n }\n\n // 4. b64: false (RFC 7797 unencoded payload)\n if (header.b64 === false) {\n return rejected('CRYPTO_JWS_B64_REJECTED');\n }\n\n // 5. zip\n if (header.zip !== undefined) {\n return rejected('CRYPTO_JWS_ZIP_REJECTED');\n }\n\n return ACCEPTED;\n}\n","/**\n * Bounded internal issuer-form validator.\n *\n * INTERNAL ONLY. This is the parity-observed counterpart of\n * @peac/schema.isCanonicalIss (referenced by Wire 0.2's CanonicalIssSchema\n * and by issue.ts pre-sign validation). Both implementations consume the\n * same ISS_CANONICAL.maxLength constant from @peac/kernel and apply the\n * same accept/reject rules in the same order; behavioral parity is proven\n * byte-equal by the parity tests, not by code copy.\n *\n * Existing canonical isCanonicalIss in @peac/schema remains canonical.\n * This module is observational only; it is NOT re-exported from\n * packages/protocol/src/index.ts and is NOT wired into runtime paths\n * (issue.ts, verify-local.ts) in v0.13.1.\n *\n * Scope (must mirror isCanonicalIss in packages/schema/src/wire-02-envelope.ts):\n *\n * 1. Type and length:\n * - Non-string iss -> rejected\n * - Empty string -> rejected\n * - Length > ISS_CANONICAL.maxLength (2048) -> rejected\n *\n * 2. did: branch (checked before URL parsing because did: is a valid\n * URL scheme in some parsers):\n * - Pattern: ^did:[a-z0-9]+:[^#?/]+$\n * - Method: lowercase letters and digits only, non-empty\n * - Method-specific-id: non-empty, no '/', '?', or '#'\n *\n * 3. https:// branch (URL-constructor based):\n * - new URL(iss) must succeed\n * - url.protocol === 'https:'\n * - Non-empty url.hostname\n * - No userinfo (url.username and url.password both empty)\n * - iss must equal the canonical reconstructed origin\n * ('https://${url.host}'). This rejects:\n * - uppercase host (URL spec lowercases hostname)\n * - explicit default port (:443 is dropped from url.host)\n * - trailing slash, path, query, fragment, userinfo\n * - raw Unicode hostname (URL emits punycode in url.host)\n *\n * 4. All other schemes -> rejected with E_ISS_NOT_CANONICAL.\n */\n\nimport { ISS_CANONICAL } from '@peac/kernel';\n\n/**\n * Normalized result. accepted=true means iss is in canonical form.\n * accepted=false carries the canonical error code E_ISS_NOT_CANONICAL.\n *\n * The canonical surface emits a single error code for any rejection;\n * no path field is attached, so the comparison is on (accepted, errorCode)\n * only.\n */\nexport type IssuerFormResult =\n | { readonly accepted: true }\n | { readonly accepted: false; readonly errorCode: string };\n\nconst ACCEPTED: IssuerFormResult = { accepted: true } as const;\nconst REJECTED: IssuerFormResult = { accepted: false, errorCode: 'E_ISS_NOT_CANONICAL' } as const;\n\n/** did:<method>:<method-specific-id> grammar (mirrors canonical regex). */\nconst DID_PATTERN = /^did:[a-z0-9]+:[^#?/]+$/;\n\nexport function validateIssuerFormInternal(iss: unknown): IssuerFormResult {\n // 1. Type and length\n if (typeof iss !== 'string' || iss.length === 0 || iss.length > ISS_CANONICAL.maxLength) {\n return REJECTED;\n }\n\n // 2. did: branch (check before URL parsing)\n if (iss.startsWith('did:')) {\n return DID_PATTERN.test(iss) ? ACCEPTED : REJECTED;\n }\n\n // 3. https:// branch (URL-constructor based)\n let url: URL;\n try {\n url = new URL(iss);\n } catch {\n return REJECTED;\n }\n\n if (url.protocol !== 'https:') return REJECTED;\n if (!url.hostname) return REJECTED;\n if (url.username !== '' || url.password !== '') return REJECTED;\n\n const origin = `${url.protocol}//${url.host}`;\n return iss === origin ? ACCEPTED : REJECTED;\n}\n","/**\n * Bounded internal temporal validator (occurred_at skew only).\n *\n * INTERNAL ONLY. This is the parity-observed counterpart of\n * @peac/schema.checkOccurredAtSkew (referenced by verify-local.ts when\n * claims.kind === 'evidence'). Both implementations consume the same\n * OCCURRED_AT_TOLERANCE_SECONDS constant from @peac/kernel and apply\n * the same skew classification rules in the same order; behavioral\n * parity is proven byte-equal by the parity tests, not by code copy.\n *\n * Existing canonical checkOccurredAtSkew in @peac/schema remains\n * canonical. This module is observational only; it is NOT re-exported\n * from packages/protocol/src/index.ts and is NOT wired into runtime\n * paths (issue.ts, verify-local.ts) in v0.13.1.\n *\n * SCOPE (deliberately narrow):\n * - occurred_at canonical skew classification ONLY\n * - the iat-not-yet-valid check (`iat > now + maxClockSkew`) lives\n * inline at verify-local.ts:454 with no helper to import; wrapping\n * it would make LEFT and RIGHT identical 1-line predicates that\n * prove nothing, so it is explicitly deferred to a later step\n * (extraction first, parity second)\n *\n * Rules (must mirror checkOccurredAtSkew exactly; evidence-kind-only\n * is the caller's responsibility):\n * 1. occurredAt undefined -> accepted, no warning\n * 2. parse occurredAt as ISO/RFC 3339; if NaN -> accepted, no warning\n * (the parse failure surfaces from schema validation elsewhere)\n * 3. ts > now + tolerance -> rejected with E_OCCURRED_AT_FUTURE\n * 4. ts > iat (within tolerance) -> accepted with occurred_at_skew\n * warning at pointer /occurred_at\n * 5. ts <= iat -> accepted, no warning\n *\n * The injected `now` parameter is required; this module never reads\n * Date.now() so tests are deterministic.\n */\n\nimport { OCCURRED_AT_TOLERANCE_SECONDS } from '@peac/kernel';\n\nexport interface TemporalWarning {\n readonly code: string;\n readonly pointer?: string;\n}\n\nexport type TemporalResult =\n | { readonly accepted: true; readonly warnings?: readonly TemporalWarning[] }\n | { readonly accepted: false; readonly errorCode: string; readonly pointer?: string };\n\nconst ACCEPTED: TemporalResult = { accepted: true } as const;\n\nexport function validateTemporalInternal(\n occurredAt: string | undefined,\n iat: number,\n now: number,\n tolerance: number = OCCURRED_AT_TOLERANCE_SECONDS\n): TemporalResult {\n if (occurredAt === undefined) return ACCEPTED;\n\n const ts = Date.parse(occurredAt) / 1000;\n if (isNaN(ts)) return ACCEPTED;\n\n if (ts > now + tolerance) {\n return {\n accepted: false,\n errorCode: 'E_OCCURRED_AT_FUTURE',\n pointer: '/occurred_at',\n };\n }\n\n if (ts > iat) {\n return {\n accepted: true,\n warnings: [{ code: 'occurred_at_skew', pointer: '/occurred_at' }],\n };\n }\n\n return ACCEPTED;\n}\n","/**\n * Bounded internal extension-budget validator.\n *\n * INTERNAL ONLY. This is the parity-observed counterpart of the\n * byte-budget portion (steps 4 + 5) of validateKnownExtensions in\n * @peac/schema/src/wire-02-extensions/validation.ts. Both sides import\n * EXTENSION_BUDGET from @peac/kernel; behavioral parity is proven\n * byte-equal by the parity tests, not by code copy.\n *\n * Existing canonical validateKnownExtensions in @peac/schema remains\n * canonical. This module is observational only; it is NOT re-exported\n * from packages/protocol/src/index.ts and is NOT wired into runtime\n * paths (issue.ts, verify-local.ts) in v0.13.1.\n *\n * SCOPE (deliberately narrow):\n * - byte-budget enforcement on the extensions record only\n * - the other three steps in validateKnownExtensions (key grammar,\n * plain-JSON guard, typed extension schema parse) are NOT in\n * scope here; they belong to other parity work and would require\n * their own validators\n *\n * Measurement basis (must mirror canonical exactly):\n * - bytes = TextEncoder.encode(JSON.stringify(value)).byteLength\n * (UTF-8 byte length of ECMAScript JSON.stringify output)\n * - serialization failure (circular references, BigInt, etc.) yields\n * Infinity, which the comparison treats as over-budget\n *\n * Order of checks (must mirror canonical exactly):\n * 1. Total: jsonUtf8ByteLength(extensions) > maxTotalBytes\n * -> violation at path '/extensions'; EARLY STOP (no per-group)\n * 2. Per-group, in Object.keys(extensions) iteration order:\n * jsonUtf8ByteLength(extensions[key]) > maxGroupBytes\n * -> violation at path '/extensions/<escaped-key>'\n *\n * Comparison uses '>' (strictly greater than), so values exactly equal\n * to the limit are accepted.\n */\n\nimport { EXTENSION_BUDGET } from '@peac/kernel';\n\nexport interface ExtensionBudgetViolation {\n readonly code: string;\n readonly path: string;\n}\n\nexport interface ExtensionBudgetResult {\n readonly accepted: boolean;\n readonly violations: readonly ExtensionBudgetViolation[];\n}\n\nconst ACCEPTED: ExtensionBudgetResult = { accepted: true, violations: [] } as const;\nconst SIZE_EXCEEDED = 'E_EXTENSION_SIZE_EXCEEDED' as const;\n\nconst textEncoder = new TextEncoder();\n\n/**\n * UTF-8 byte length of JSON.stringify(value). Returns Infinity if\n * serialization fails (circular references, BigInt, etc.); callers\n * treat Infinity as over-budget.\n */\nfunction jsonUtf8ByteLength(value: unknown): number {\n try {\n return textEncoder.encode(JSON.stringify(value)).byteLength;\n } catch {\n return Infinity;\n }\n}\n\n/** RFC 6901 JSON pointer segment escape: '~' -> '~0', '/' -> '~1'. */\nfunction escapeJsonPointerSegment(segment: string): string {\n return segment.replace(/~/g, '~0').replace(/\\//g, '~1');\n}\n\nexport function validateExtensionBudgetInternal(\n extensions: Record<string, unknown> | undefined\n): ExtensionBudgetResult {\n if (extensions === undefined) return ACCEPTED;\n\n const totalBytes = jsonUtf8ByteLength(extensions);\n if (totalBytes > EXTENSION_BUDGET.maxTotalBytes) {\n // Early stop: canonical returns immediately after pushing the\n // total-budget violation; per-group checks are not reached.\n return {\n accepted: false,\n violations: [{ code: SIZE_EXCEEDED, path: '/extensions' }],\n };\n }\n\n const violations: ExtensionBudgetViolation[] = [];\n for (const key of Object.keys(extensions)) {\n const groupBytes = jsonUtf8ByteLength(extensions[key]);\n if (groupBytes > EXTENSION_BUDGET.maxGroupBytes) {\n violations.push({\n code: SIZE_EXCEEDED,\n path: `/extensions/${escapeJsonPointerSegment(key)}`,\n });\n }\n }\n\n if (violations.length === 0) return ACCEPTED;\n return { accepted: false, violations };\n}\n","/**\n * Bounded observation subset: composition aggregator.\n *\n * INTERNAL ONLY. Composes the six proven layer validators introduced\n * across this PR (kernel constraints; type-extension mapping; JOSE\n * header hardening; issuer form; occurred_at temporal skew;\n * extension byte budget) into a single aggregated result. The\n * canonical-truth sanity test, layer-isolated parity tests, and\n * differential same-path proof have already established that each\n * underlying validator is byte-equal with the existing canonical\n * surface for the layer it covers.\n *\n * NOT WIRED. This module is NOT called from issue.ts, verify-local.ts,\n * or any runtime path in v0.13.1. It exists as a composition example\n * so PR D can wire the inert shadow-call hook to a real bounded\n * pipeline behind an internal feature flag without re-deriving the\n * composition shape.\n *\n * NOT FULL VALIDATION. The bounded subset deliberately EXCLUDES:\n * - full Wire 0.2 schema parsing (parseReceiptClaims; the canonical\n * parse continues to drive the runtime path)\n * - signature verification and full JWS decode (decodeWire02;\n * @peac/crypto remains canonical)\n * - iat-not-yet-valid temporal check (lives inline at\n * verify-local.ts:454 with no helper to import)\n * - typ_missing strictness handling\n * - policy binding verification\n * - unknown_extension key grammar / plain-JSON guard / typed\n * extension schema parse (only the byte-budget portion of\n * validateKnownExtensions is in scope)\n * - any control-plane behavior (issuer resolver, JWKS fetch, etc.)\n *\n * Public-facing wording for this module: \"bounded observation subset\",\n * never \"complete validator\" or \"primary validator\".\n */\n\nimport {\n validateExtensionBudgetInternal,\n validateIssuerFormInternal,\n validateJoseHardeningInternal,\n validateKernelConstraintsInternal,\n validateTemporalInternal,\n validateTypeExtensionMappingInternal,\n type ExtensionBudgetViolation,\n type TemporalWarning,\n type TypeExtensionMappingWarning,\n} from './validators/index.js';\n\n/** Minimal claims shape required by the bounded subset. */\nexport interface BoundedClaimsInput {\n readonly kind: string;\n readonly type: string;\n readonly iss: unknown;\n readonly iat: number;\n readonly occurred_at?: string;\n readonly extensions?: Record<string, unknown>;\n}\n\n/** Optional JOSE header (from the JWS protected header). */\nexport type BoundedHeaderInput = Record<string, unknown> | undefined;\n\n/** Aggregated input to the bounded observation subset. */\nexport interface BoundedValidationInput {\n readonly claims: BoundedClaimsInput;\n readonly header?: BoundedHeaderInput;\n /** Fixed Unix-second clock for temporal evaluation; required. */\n readonly now: number;\n}\n\n/**\n * Layer tag identifies which underlying validator emitted each entry.\n * Useful for downstream filtering (e.g., a future shadow-mode reporter\n * that ignores warning-class entries from one layer but not another).\n */\nexport type BoundedLayer =\n | 'kernel-constraints'\n | 'type-extension-mapping'\n | 'jose-header-hardening'\n | 'issuer-form'\n | 'temporal'\n | 'extension-budget';\n\nexport interface BoundedViolation {\n readonly layer: BoundedLayer;\n readonly code: string;\n readonly path?: string;\n}\n\nexport interface BoundedWarning {\n readonly layer: BoundedLayer;\n readonly code: string;\n readonly path?: string;\n}\n\nexport interface BoundedValidationResult {\n /** True iff every in-scope layer accepted the input. */\n readonly accepted: boolean;\n readonly violations: readonly BoundedViolation[];\n readonly warnings: readonly BoundedWarning[];\n}\n\n/**\n * Run the bounded observation subset. Composes the six layer\n * validators in a stable order; aggregates violations and warnings\n * with explicit layer tags; never throws. Pure: same input always\n * yields the same result.\n */\nexport function runBoundedValidatorShadow(input: BoundedValidationInput): BoundedValidationResult {\n const violations: BoundedViolation[] = [];\n const warnings: BoundedWarning[] = [];\n\n // 1. Kernel constraints (depth / array / keys / string / nodes).\n const kernelRes = validateKernelConstraintsInternal(input.claims);\n if (!kernelRes.valid) {\n for (const v of kernelRes.violations) {\n violations.push({\n layer: 'kernel-constraints',\n code: v.constraint,\n path: v.path || undefined,\n });\n }\n }\n\n // 2. Issuer form (canonical iss).\n const issRes = validateIssuerFormInternal(input.claims.iss);\n if (!issRes.accepted) {\n violations.push({ layer: 'issuer-form', code: issRes.errorCode });\n }\n\n // 3. JOSE header hardening (only when a header is supplied).\n if (input.header !== undefined) {\n const joseRes = validateJoseHardeningInternal(input.header);\n if (!joseRes.accepted) {\n violations.push({ layer: 'jose-header-hardening', code: joseRes.errorCode });\n }\n }\n\n // 4. Type-extension mapping warnings.\n const typeExtWarnings: readonly TypeExtensionMappingWarning[] =\n validateTypeExtensionMappingInternal({\n kind: input.claims.kind,\n type: input.claims.type,\n extensions: input.claims.extensions,\n });\n for (const w of typeExtWarnings) {\n warnings.push({ layer: 'type-extension-mapping', code: w.code, path: w.pointer });\n }\n\n // 5. Temporal occurred_at skew (evidence-kind-only is the caller's\n // responsibility; we mirror the canonical behavior of treating\n // non-evidence kinds as a no-op by skipping the call).\n if (input.claims.kind === 'evidence') {\n const temporalRes = validateTemporalInternal(\n input.claims.occurred_at,\n input.claims.iat,\n input.now\n );\n if (!temporalRes.accepted) {\n violations.push({\n layer: 'temporal',\n code: temporalRes.errorCode,\n path: temporalRes.pointer,\n });\n } else if (temporalRes.warnings) {\n const list: readonly TemporalWarning[] = temporalRes.warnings;\n for (const w of list) {\n warnings.push({ layer: 'temporal', code: w.code, path: w.pointer });\n }\n }\n }\n\n // 6. Extension byte budget.\n const budgetRes = validateExtensionBudgetInternal(input.claims.extensions);\n if (!budgetRes.accepted) {\n const list: readonly ExtensionBudgetViolation[] = budgetRes.violations;\n for (const v of list) {\n violations.push({ layer: 'extension-budget', code: v.code, path: v.path });\n }\n }\n\n return {\n accepted: violations.length === 0,\n violations,\n warnings,\n };\n}\n","/**\n * Shadow-mode telemetry redaction and canonical hashing.\n *\n * @internal\n *\n * INTERNAL ONLY. Not re-exported from packages/protocol/src/index.ts.\n *\n * Two responsibilities:\n *\n * 1. `redactNote(input, maxBytes)`: scrub known secret classes from\n * a free-form string and bound it to a UTF-8 byte ceiling. Used\n * for the `notes` field on every shadow divergence record so\n * that an accidental string concatenation cannot leak credential\n * material into the in-memory shadow log.\n *\n * 2. `canonicalHashOf(value)` / `hashJws(jws)`: produce a SHA-256\n * hex digest of a canonicalized representation. Used as the\n * comparison primitive between real-path and shadow-path results\n * so the divergence log never needs to store raw output.\n *\n * SECRET_PATTERNS is the ground-truth contract for what counts as a\n * leakable secret class. Adding a regex here REQUIRES a paired\n * adversarial test vector in shadow-redact-adversarial.test.ts (one\n * matching vector + one adjacent benign-not-matched vector). Removing\n * a regex here REQUIRES the same justification.\n *\n * Platform neutrality: this module avoids Node-only globals (`Buffer`,\n * `node:crypto`) so it can ship inside the platform-neutral\n * @peac/protocol bundle. UTF-8 byte work uses TextEncoder/TextDecoder;\n * SHA-256 hashing delegates to @peac/crypto.sha256Hex which uses the\n * Web Crypto API with a dynamic Node fallback.\n */\n\nimport { base64urlEncode, sha256Hex } from '@peac/crypto';\n\n/**\n * Known secret-class patterns. Order matters only for performance\n * (broader patterns first reduce the search space for narrower ones).\n *\n * @internal\n */\nconst SECRET_PATTERNS: readonly RegExp[] = [\n // Compact JWS / JWT (header.payload.signature with eyJ-prefixed header).\n /eyJ[A-Za-z0-9_-]{20,}\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+/g,\n\n // PEM-encoded blocks. Covers RSA / EC / OPENSSH / generic PRIVATE KEY\n // header variants in a single pattern.\n /-----BEGIN [A-Z0-9 ]+-----[\\s\\S]+?-----END [A-Z0-9 ]+-----/g,\n\n // Long base64 runs (>=40 chars). The character class is the standard\n // base64 alphabet only (no `_` or `-`) so that kebab-case and\n // snake_case identifier strings do not collateral-match. base64url\n // payloads carrying credentials are reached via more specific patterns\n // (compact JWS, Bearer, URL query token) and via the wrapper headers\n // they appear in.\n /\\b[A-Za-z0-9+/]{40,}={0,2}\\b/g,\n\n // Bearer token (Authorization header value with Bearer scheme).\n /Bearer\\s+[A-Za-z0-9._\\-/+=]+/gi,\n\n // Generic Authorization header line (any scheme, including Basic /\n // Digest / Negotiate). Multiline-anchored.\n /^authorization:\\s*[^\\r\\n]+/gim,\n\n // Generic auth-token header line (X-Auth-Token, X-API-Key).\n /^x-(?:auth-token|api-key):\\s*[^\\r\\n]+/gim,\n\n // Cookie request header line (raw client cookies).\n /^cookie:\\s*[^\\r\\n]+/gim,\n\n // Set-Cookie response header line (server-issued sessions).\n /^set-cookie:\\s*[^\\r\\n]+/gim,\n\n // URL query token / API key / secret / access_token.\n /[?&](?:token|key|secret|access_token|api_key|apikey)=[^&\\s#]+/gi,\n\n // AWS access key ID (AKIA + 16 alphanumeric).\n /\\bAKIA[0-9A-Z]{16}\\b/g,\n\n // Email address (PII).\n /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}/g,\n\n // Phone numbers. Three explicit forms (E.164 + parenthesized NA + dashed\n // NA / international) so plain consecutive-digit runs (sequence\n // numbers, hashes, identifiers) do not collateral-match.\n /\\+\\d[\\d\\s().-]{6,}\\d/g,\n /\\(\\d{3}\\)\\s*\\d{3}[\\s.-]?\\d{4}/g,\n /\\b\\d{3}[\\s.-]\\d{3}[\\s.-]\\d{4}\\b/g,\n];\n\n/**\n * Redaction marker used in place of any matched secret class.\n *\n * @internal\n */\nconst REDACTION_MARKER = '[REDACTED]';\n\nconst TEXT_ENCODER = /* @__PURE__ */ new TextEncoder();\nconst TEXT_DECODER = /* @__PURE__ */ new TextDecoder('utf-8', { fatal: false });\n\nconst REDACTION_MARKER_BYTES = TEXT_ENCODER.encode(REDACTION_MARKER).length;\n\n/**\n * UTF-8 byte length of a string. Platform-neutral replacement for\n * `Buffer.byteLength(s, 'utf8')`.\n *\n * @internal\n */\nexport function utf8ByteLength(value: string): number {\n return TEXT_ENCODER.encode(value).length;\n}\n\n/**\n * Redact known secret classes from `input` and bound the result to\n * `maxBytes` UTF-8 bytes. The output always either matches the input\n * (when no secret was found and the byte budget permits) or contains\n * the `[REDACTED]` marker.\n *\n * Truncation is byte-aware so multibyte UTF-8 sequences are not split\n * mid-character. When the redacted string exceeds `maxBytes`, the\n * tail is replaced with the marker.\n *\n * @internal\n */\nexport function redactNote(input: string, maxBytes: number): string {\n if (typeof input !== 'string') return REDACTION_MARKER;\n\n let redacted = input;\n for (const pattern of SECRET_PATTERNS) {\n redacted = redacted.replace(pattern, REDACTION_MARKER);\n }\n\n const bytes = TEXT_ENCODER.encode(redacted);\n if (bytes.length <= maxBytes) return redacted;\n\n if (maxBytes <= REDACTION_MARKER_BYTES) {\n return REDACTION_MARKER.slice(0, maxBytes);\n }\n\n const headBytes = maxBytes - REDACTION_MARKER_BYTES;\n return safeUtf8Slice(bytes, headBytes) + REDACTION_MARKER;\n}\n\n/**\n * SHA-256 hex digest of a canonical-stringified value. Used by the\n * shadow comparator to detect output-byte-diff WITHOUT logging raw\n * content. Object keys are sorted recursively so equivalent objects\n * with different key orders produce identical digests.\n *\n * Async because SHA-256 hashing in this codebase is platform-neutral\n * via @peac/crypto.sha256Hex (Web Crypto API with dynamic Node\n * fallback). Callers run inside the shadow scheduler's microtask /\n * macrotask boundary, so an additional await is free.\n *\n * @internal\n */\nexport async function canonicalHashOf(value: unknown): Promise<string> {\n return sha256Hex(canonicalStringify(value));\n}\n\n/**\n * SHA-256 hex digest of a JWS string. Used as the primary\n * `recordRefHash` input for divergence records.\n *\n * @internal\n */\nexport async function hashJws(jws: string): Promise<string> {\n return sha256Hex(jws);\n}\n\n/**\n * Canonical JSON serialization with stable key order. Internal helper\n * for `canonicalHashOf`. Not exported.\n */\nfunction canonicalStringify(value: unknown): string {\n if (value === null) return 'null';\n if (typeof value === 'undefined') return 'null';\n if (typeof value === 'string') return JSON.stringify(value);\n if (typeof value === 'number') {\n return Number.isFinite(value) ? String(value) : 'null';\n }\n if (typeof value === 'boolean') return String(value);\n if (typeof value === 'bigint') return String(value);\n if (Array.isArray(value)) {\n return '[' + value.map(canonicalStringify).join(',') + ']';\n }\n if (value instanceof Uint8Array) {\n return JSON.stringify(base64urlEncode(value));\n }\n if (typeof value === 'object') {\n const obj = value as Record<string, unknown>;\n const keys = Object.keys(obj).sort();\n return (\n '{' + keys.map((k) => JSON.stringify(k) + ':' + canonicalStringify(obj[k])).join(',') + '}'\n );\n }\n return 'null';\n}\n\n/**\n * Slice a UTF-8 byte buffer to at most `byteLen` bytes without\n * splitting a multi-byte sequence mid-character. Returns a decoded\n * string. Internal helper for `redactNote`. Not exported.\n */\nfunction safeUtf8Slice(bytes: Uint8Array, byteLen: number): string {\n if (byteLen <= 0) return '';\n if (bytes.length <= byteLen) return TEXT_DECODER.decode(bytes);\n\n let end = byteLen;\n // Walk back over UTF-8 continuation bytes (0b10xxxxxx) so the slice\n // ends on a complete code-point boundary.\n while (end > 0 && (bytes[end] & 0xc0) === 0x80) {\n end -= 1;\n }\n return TEXT_DECODER.decode(bytes.subarray(0, end));\n}\n","/**\n * Shadow-mode scheduler.\n *\n * @internal\n *\n * INTERNAL ONLY. Not re-exported from packages/protocol/src/index.ts.\n *\n * Schedules a shadow function to run AFTER the public-call boundary\n * has returned its real-path result to the caller. The shadow run:\n *\n * - is gated by `isShadowEnabled(options)` (env or programmatic);\n * - starts on a MACROTASK boundary (`setTimeout(..., 0)`), NOT on a\n * microtask, because microtasks can run before promise\n * continuations attached to the public async call and would still\n * add observable latency for CPU-heavy shadow work;\n * - has a bounded wall-clock REPORTING timeout (250ms by default;\n * see \"Timeout guarantee class\" below);\n * - reports comparison results into a bounded in-memory log;\n * - SWALLOWS every error, never propagating to the real-path return\n * value or surfacing as an unhandled-rejection event.\n *\n * The public function:\n *\n * - returns the real-path value FIRST (the macrotask boundary is\n * past every async continuation already attached to the call\n * site);\n * - never awaits shadow work;\n * - is byte-identical in its return value with shadow ON vs OFF.\n *\n * Timeout guarantee class. The 250ms timeout is a REPORTING bound,\n * not a hard preemption guarantee. Where the shadow function consults\n * the supplied `AbortSignal`, the runner aborts and bounds CPU; where\n * the shadow function is pure-CPU and ignores the signal (the v0.13.1\n * record-core validators are this shape), JavaScript cannot preempt\n * it. The runner stops awaiting and records `timing-diff`; the work\n * may continue to completion off the runner's await chain. Either\n * way, the public-call boundary returns its real-path value\n * immediately.\n *\n * Test-only helpers (`_peekShadowLog`, `_resetShadowLog`,\n * `_drainShadowQueueForTests`) are exposed for deterministic\n * assertions in vitest. Production code MUST NOT call them.\n *\n * Platform neutrality: this module avoids Node-only globals\n * (`Buffer`, `node:crypto`, unguarded `process`). Hashing delegates\n * to @peac/crypto; environment reads guard for the absence of\n * `process` so the module loads cleanly under browser / edge\n * runtimes.\n */\n\nimport type { ShadowCall, ShadowDivergence } from './shadow-types.js';\nimport { canonicalHashOf, hashJws, redactNote, utf8ByteLength } from './shadow-redact.js';\n\nconst MAX_LOG_ENTRIES = 1000;\nconst MAX_NOTE_BYTES = 128;\nconst RETENTION_MS = 7 * 24 * 60 * 60 * 1000; // 7 days\nconst SHADOW_TIMEOUT_MS = 250;\n\nconst SHADOW_LOG: ShadowDivergence[] = [];\nconst PENDING_SHADOW_TASKS: Set<Promise<void>> = new Set();\nlet pendingScheduleCount = 0;\n\n/**\n * Programmatic-flag shape. Internal-only; never appears in any\n * exported public option type.\n *\n * @internal\n */\nexport interface ShadowEnableOptions {\n readonly _internal?: {\n readonly shadowCore?: boolean;\n };\n}\n\n/**\n * Read the shadow-enable flag from environment or programmatic\n * options. Read once per call, NOT cached at module scope, so tests\n * can toggle the env var dynamically. Environment access is guarded\n * for browser / edge runtimes that do not expose `process`.\n *\n * @internal\n */\nexport function isShadowEnabled(options?: ShadowEnableOptions): boolean {\n if (options?._internal?.shadowCore === true) return true;\n return readEnvFlag();\n}\n\nfunction readEnvFlag(): boolean {\n if (typeof process === 'undefined' || process === null) return false;\n const env = (process as { env?: Record<string, string | undefined> }).env;\n return env?.PEAC_INTERNAL_SHADOW_CORE === '1';\n}\n\n/**\n * Inputs to `scheduleShadow`. The `shadowFn` factory receives an\n * `AbortSignal` so cancellable implementations can opt in. v0.13.1\n * shadow paths are pure-CPU and ignore the signal; the runner still\n * passes one for forward-compat.\n *\n * @internal\n */\nexport interface ScheduleShadowArgs<T> {\n readonly call: ShadowCall;\n readonly realResult: T | undefined;\n readonly realError: { code?: string } | undefined;\n readonly shadowFn: (signal?: AbortSignal) => Promise<T>;\n readonly recordRef: string;\n}\n\n/**\n * Schedule shadow work AFTER the real-path return.\n *\n * The shadow run starts on the next MACROTASK boundary (via\n * `setTimeout(..., 0)`). The public function returns its real-path\n * value before the macrotask fires, including for async callers\n * whose `.then` / `await` continuations execute on microtasks.\n * `queueMicrotask` would interleave with those continuations and is\n * intentionally avoided.\n *\n * Tasks are tracked internally so test helpers can drain them for\n * deterministic assertions; production callers ignore the (void)\n * return.\n *\n * Failures inside the shadow path are converted to divergence records\n * inside the task body. The outer `task.catch(() => {})` is defense\n * in depth: if anything inside `runShadowTask` throws after the inner\n * try/catch (e.g., a hash failure during canonical comparison), the\n * outer catch swallows the rejection so no unhandled-rejection event\n * fires.\n *\n * @internal\n */\nexport function scheduleShadow<T>(args: ScheduleShadowArgs<T>): void {\n pendingScheduleCount += 1;\n setTimeout(() => {\n pendingScheduleCount -= 1;\n const task = runShadowTask(args);\n PENDING_SHADOW_TASKS.add(task);\n // Cleanup runs on both fulfillment and rejection. Using\n // `task.then(remove, remove)` instead of `task.finally(remove)`\n // avoids creating a derived rejected promise that would surface\n // as an unhandled-rejection event when the inner task rejects.\n // The two-arg `then` form swallows any rejection and runs the\n // cleanup on either branch.\n const removeFromPending = (): void => {\n PENDING_SHADOW_TASKS.delete(task);\n };\n void task.then(removeFromPending, removeFromPending);\n }, 0);\n}\n\nasync function runShadowTask<T>(args: ScheduleShadowArgs<T>): Promise<void> {\n const recordRefHash = await hashJws(args.recordRef);\n let shadowResult: T | undefined;\n let shadowErrorCode: string | undefined;\n\n try {\n shadowResult = await runWithTimeout(args.shadowFn, SHADOW_TIMEOUT_MS);\n } catch (err) {\n shadowErrorCode = extractErrorCode(err);\n appendDivergence({\n kind: shadowErrorCode === 'SHADOW_TIMEOUT' ? 'timing-diff' : 'shadow-error',\n call: args.call,\n recordRefHash,\n realErrorCode: args.realError?.code,\n shadowErrorCode,\n notes: redactNote(`shadow threw ${shadowErrorCode}`, MAX_NOTE_BYTES),\n timestamp: new Date().toISOString(),\n });\n return;\n }\n\n const divergence = await compareResults(args, shadowResult, recordRefHash);\n if (divergence) appendDivergence(divergence);\n}\n\n/**\n * Bounded REPORTING timeout for shadow work. NOT a hard preemption\n * guarantee. See the module-level \"Timeout guarantee class\" comment.\n */\nfunction runWithTimeout<T>(fn: (signal?: AbortSignal) => Promise<T>, ms: number): Promise<T> {\n const controller = new AbortController();\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n controller.abort();\n reject(new Error('SHADOW_TIMEOUT'));\n }, ms);\n fn(controller.signal).then(\n (v) => {\n clearTimeout(timer);\n resolve(v);\n },\n (e) => {\n clearTimeout(timer);\n reject(e);\n }\n );\n });\n}\n\nasync function compareResults<T>(\n args: ScheduleShadowArgs<T>,\n shadowResult: T | undefined,\n recordRefHash: string\n): Promise<ShadowDivergence | null> {\n const ts = new Date().toISOString();\n\n // Both succeeded: compare canonical hashes.\n if (!args.realError && shadowResult !== undefined && args.realResult !== undefined) {\n const realHash = await canonicalHashOf(args.realResult);\n const shadowHash = await canonicalHashOf(shadowResult);\n if (realHash !== shadowHash) {\n return {\n kind: 'output-byte-diff',\n call: args.call,\n recordRefHash,\n realResultHash: realHash,\n shadowResultHash: shadowHash,\n realByteLen: byteLenOf(args.realResult),\n shadowByteLen: byteLenOf(shadowResult),\n notes: 'canonical-hash-mismatch',\n timestamp: ts,\n };\n }\n return null;\n }\n\n // Both errored: comparator already handled in catch path; no record here.\n if (args.realError && shadowResult === undefined) {\n return null;\n }\n\n // Asymmetric: one succeeded, one failed.\n return {\n kind: 'error-code-diff',\n call: args.call,\n recordRefHash,\n realErrorCode: args.realError?.code,\n notes: args.realError ? 'real-errored-shadow-succeeded' : 'real-succeeded-shadow-errored',\n timestamp: ts,\n };\n}\n\nfunction byteLenOf(value: unknown): number {\n if (typeof value === 'string') return utf8ByteLength(value);\n if (value instanceof Uint8Array) return value.byteLength;\n return utf8ByteLength(JSON.stringify(value) ?? '');\n}\n\nfunction extractErrorCode(err: unknown): string {\n if (err && typeof err === 'object') {\n const candidate = (err as { code?: unknown; message?: unknown }).code;\n if (typeof candidate === 'string' && candidate.length > 0) return candidate;\n const message = (err as { message?: unknown }).message;\n if (typeof message === 'string' && /^[A-Z_][A-Z0-9_]*$/.test(message)) return message;\n }\n return 'SHADOW_UNKNOWN_ERROR';\n}\n\nfunction appendDivergence(d: ShadowDivergence): void {\n pruneStale();\n if (SHADOW_LOG.length >= MAX_LOG_ENTRIES) SHADOW_LOG.shift();\n SHADOW_LOG.push(d);\n}\n\nfunction pruneStale(): void {\n const cutoffIso = new Date(Date.now() - RETENTION_MS).toISOString();\n while (SHADOW_LOG.length > 0 && SHADOW_LOG[0].timestamp < cutoffIso) SHADOW_LOG.shift();\n}\n\n/**\n * Read the in-memory shadow log without mutating it. TEST USE ONLY.\n *\n * @internal\n */\nexport function _peekShadowLog(): readonly ShadowDivergence[] {\n return SHADOW_LOG.slice();\n}\n\n/**\n * Clear the in-memory shadow log. TEST USE ONLY.\n *\n * @internal\n */\nexport function _resetShadowLog(): void {\n SHADOW_LOG.length = 0;\n}\n\n/**\n * Drain the pending-shadow-tasks set so deterministic assertions can\n * run after a sequence of shadow-enabled calls. Yields to the event\n * loop until every scheduled `setTimeout` has fired AND every\n * resulting task has settled. TEST USE ONLY. Production code MUST\n * NOT call this.\n *\n * @internal\n */\nexport async function _drainShadowQueueForTests(): Promise<void> {\n while (pendingScheduleCount > 0 || PENDING_SHADOW_TASKS.size > 0) {\n if (pendingScheduleCount > 0) {\n // Yield so any pending setTimeout(..., 0) fires.\n await new Promise<void>((resolve) => setTimeout(resolve, 0));\n }\n if (PENDING_SHADOW_TASKS.size > 0) {\n await Promise.allSettled(Array.from(PENDING_SHADOW_TASKS));\n }\n }\n}\n","/**\n * Internal rollback-path flag.\n *\n * INTERNAL ONLY. Both flag values currently use the same protocol path.\n * The flag reader is exercised so rollback-path plumbing can be validated\n * without changing public behavior.\n *\n * Public option types MUST NOT declare `_internal.legacyPath`; callers\n * inside this package access the programmatic option only through\n * internal casts. Flag identifiers are forbidden on the public TypeScript\n * surface by `scripts/verify-dist-private-leaks.mjs` (Tier 1 + scoped\n * runtime allowlist for `@peac/protocol` runtime files only) and by\n * `scripts/verify-no-semantic-widening.mjs`.\n */\n\n/**\n * Programmatic-flag shape. Internal-only; never appears on any\n * exported public option type. Mirrors the existing shadow-flag\n * pattern at `_internal/shadow.ts` so the dist-leak gates and the\n * semantic-widening gates apply uniformly.\n *\n * @internal\n */\nexport interface LegacyPathOptions {\n readonly _internal?: {\n readonly legacyPath?: boolean;\n };\n}\n\n/**\n * Read the rollback-path flag from environment or programmatic\n * options. Read once per call, NOT cached at module scope, so tests\n * can toggle the env var dynamically. Strict semantics: only the\n * literal string `'1'` activates the flag, mirroring\n * `PEAC_INTERNAL_SHADOW_CORE`.\n *\n * Environment access is guarded for browser / edge runtimes that do\n * not expose `process`; the function never throws.\n *\n * Caller pattern at protocol hot paths:\n *\n * void readLegacyPathFlag(options as unknown as LegacyPathOptions);\n *\n * The `void` discards the returned boolean intentionally: both flag\n * values currently use the same protocol path, and the call exists\n * so the read path is exercised.\n *\n * @internal\n */\nexport function readLegacyPathFlag(options?: LegacyPathOptions): boolean {\n if (options?._internal?.legacyPath === true) return true;\n if (typeof process === 'undefined' || process === null) return false;\n const env = (process as { env?: Record<string, string | undefined> }).env;\n return env?.PEAC_INTERNAL_LEGACY_PATH === '1';\n}\n","/**\n * Normalized internal observation shape for shadow-vs-real comparison.\n *\n * @internal\n *\n * INTERNAL ONLY. Not re-exported from packages/protocol/src/index.ts.\n *\n * The shadow scheduler compares real-path and shadow-path results via\n * canonical hashes. To make that comparison meaningful (not just an\n * accept/reject boolean) and free of false positives, both sides\n * project onto the SAME stable normalized `ShadowObservation` shape\n * before the hash:\n *\n * - `accepted`: did the validator accept the input?\n * - `violationCodes`: sorted, deduplicated registered error codes.\n * - `warningCodes`: sorted, deduplicated registered warning codes.\n *\n * Layer-tag metadata is intentionally NOT part of the comparable\n * shape. The bounded validator emits per-layer tags; the canonical\n * Zod path does not. Including them would cause a hash divergence\n * even on full functional agreement, masking true divergence as\n * noise.\n *\n * Issue path projection:\n *\n * `IssueResult` does not expose warning codes; canonical issuance\n * either succeeds (and surfaces no warnings to the caller) or\n * throws. To prevent the bounded validator's warnings from\n * producing false `output-byte-diff` records on a successful\n * issuance, the issue-side comparison runs in ACCEPTED-ONLY mode:\n * `warningCodes` is projected to `[]` on BOTH sides.\n *\n * VerifyLocal success path projection:\n *\n * `VerifyLocalSuccess` exposes a `warnings` array of registered\n * warning codes. The verifyLocal-side comparison includes\n * `warningCodes` from both sides (canonical surfaces them\n * directly; the bounded validator's warningCodes are mapped from\n * `BoundedWarning.code`).\n */\n\nimport type { BoundedValidationResult } from './record-core/bounded-validator.js';\n\n/**\n * Canonical observation projected from either the real path or the\n * shadow path.\n *\n * @internal\n */\nexport interface ShadowObservation {\n readonly accepted: boolean;\n /** Registered error codes, sorted, deduplicated. */\n readonly violationCodes: readonly string[];\n /** Registered warning codes, sorted, deduplicated. */\n readonly warningCodes: readonly string[];\n}\n\n/**\n * Real-path observation for a successful `issue()` call. Always\n * projects to the empty accepted-only shape; canonical issuance\n * surfaces no warning codes through `IssueResult`.\n *\n * @internal\n */\nexport function realObservationForIssue(): ShadowObservation {\n return EMPTY_ACCEPTED;\n}\n\n/**\n * Real-path observation for a successful `verifyLocal()` call. Maps\n * the canonical `warnings: VerificationWarning[]` array onto the\n * normalized warningCodes set.\n *\n * @internal\n */\nexport function realObservationForVerifyLocalSuccess(\n warnings: readonly { code: string }[] | undefined\n): ShadowObservation {\n if (!warnings || warnings.length === 0) return EMPTY_ACCEPTED;\n return {\n accepted: true,\n violationCodes: [],\n warningCodes: sortedDedupedCodes(warnings.map((w) => w.code)),\n };\n}\n\n/**\n * Project a `BoundedValidationResult` into the shared observation\n * shape with full warning-code parity. Use on the verifyLocal path\n * where canonical exposes warning codes through\n * `VerifyLocalSuccess.warnings`.\n *\n * @internal\n */\nexport function shadowObservationFromBounded(bounded: BoundedValidationResult): ShadowObservation {\n return {\n accepted: bounded.accepted,\n violationCodes: sortedDedupedCodes(bounded.violations.map((v) => v.code)),\n warningCodes: sortedDedupedCodes(bounded.warnings.map((w) => w.code)),\n };\n}\n\n/**\n * Project a `BoundedValidationResult` into the shared observation\n * shape with `warningCodes` flattened to `[]`. Use on the issue path\n * where canonical issuance does not surface warning codes through\n * `IssueResult`. Without this projection the bounded validator's\n * type-extension or temporal warnings would create false\n * `output-byte-diff` records on every otherwise-successful issuance.\n *\n * @internal\n */\nexport function shadowObservationFromBoundedAcceptedOnly(\n bounded: BoundedValidationResult\n): ShadowObservation {\n return {\n accepted: bounded.accepted,\n violationCodes: sortedDedupedCodes(bounded.violations.map((v) => v.code)),\n warningCodes: [],\n };\n}\n\nconst EMPTY_ACCEPTED: ShadowObservation = Object.freeze({\n accepted: true,\n violationCodes: Object.freeze([]) as readonly string[],\n warningCodes: Object.freeze([]) as readonly string[],\n});\n\nfunction sortedDedupedCodes(codes: readonly string[]): readonly string[] {\n if (codes.length === 0) return [];\n return Array.from(new Set(codes)).sort();\n}\n","/**\n * Local receipt verification with schema validation\n *\n * Use this for verifying receipts when you have the public key locally,\n * without JWKS discovery.\n */\n\nimport { type VerificationStrictness, type VerificationWarning, HASH } from '@peac/kernel';\nimport { defaultCodec } from './_internal/record-core/codec/jws-jwt.js';\nimport {\n parseReceiptClaims,\n validateKernelConstraints,\n type Wire02Claims,\n checkOccurredAtSkew,\n sortWarnings,\n WARNING_TYP_MISSING,\n WARNING_TYPE_UNREGISTERED,\n WARNING_UNKNOWN_EXTENSION,\n WARNING_EXTENSION_GROUP_MISSING,\n WARNING_EXTENSION_GROUP_MISMATCH,\n REGISTERED_RECEIPT_TYPES,\n REGISTERED_EXTENSION_GROUP_KEYS,\n isValidExtensionKey,\n verifyPolicyBinding,\n} from '@peac/schema';\nimport { TYPE_TO_EXTENSION_MAP } from '@peac/kernel';\nimport { checkTypeExtensionMapping } from './type-extension-check';\nimport { maybeRunShadowValidation } from './_internal/record-core/shadow-hook';\nimport { runBoundedValidatorShadow } from './_internal/record-core/bounded-validator.js';\nimport { isShadowEnabled, scheduleShadow, type ShadowEnableOptions } from './_internal/shadow.js';\nimport { readLegacyPathFlag, type LegacyPathOptions } from './_internal/legacy-path.js';\nimport {\n realObservationForVerifyLocalSuccess,\n shadowObservationFromBounded,\n type ShadowObservation,\n} from './_internal/shadow-observe.js';\nimport type { PolicyBindingStatus } from './verifier-types';\n\n/**\n * Structural type for CryptoError\n * Used instead of instanceof for robustness across ESM/CJS boundaries\n */\ninterface CryptoErrorLike {\n name: 'CryptoError';\n code: string;\n message: string;\n}\n\n/**\n * Structural check for CryptoError\n * More robust than instanceof across module boundaries (ESM/CJS, duplicate packages)\n */\nfunction isCryptoError(err: unknown): err is CryptoErrorLike {\n return (\n err !== null &&\n typeof err === 'object' &&\n 'name' in err &&\n err.name === 'CryptoError' &&\n 'code' in err &&\n typeof err.code === 'string' &&\n err.code.startsWith('CRYPTO_') &&\n 'message' in err &&\n typeof err.message === 'string'\n );\n}\n\n/**\n * Canonical error codes for local verification\n *\n * These map to E_* codes in specs/kernel/errors.json.\n * JOSE hardening codes (E_JWS_*) are distinct from generic E_INVALID_FORMAT\n * so callers can distinguish key-injection, compression, and crit attacks from\n * ordinary format errors (v0.12.0-preview.1).\n */\nexport type VerifyLocalErrorCode =\n | 'E_INVALID_SIGNATURE'\n | 'E_INVALID_FORMAT'\n | 'E_CONSTRAINT_VIOLATION'\n | 'E_EXPIRED'\n | 'E_NOT_YET_VALID'\n | 'E_INVALID_ISSUER'\n | 'E_INVALID_AUDIENCE'\n | 'E_INVALID_SUBJECT'\n | 'E_INVALID_RECEIPT_ID'\n | 'E_MISSING_EXP'\n | 'E_WIRE_VERSION_MISMATCH'\n | 'E_UNSUPPORTED_WIRE_VERSION'\n | 'E_OCCURRED_AT_FUTURE'\n // JOSE hardening codes (Wire 0.2, v0.12.0-preview.1)\n | 'E_JWS_EMBEDDED_KEY'\n | 'E_JWS_CRIT_REJECTED'\n | 'E_JWS_MISSING_KID'\n | 'E_JWS_B64_REJECTED'\n | 'E_JWS_ZIP_REJECTED'\n // Policy binding (Wire 0.2, v0.12.0-preview.1)\n | 'E_POLICY_BINDING_FAILED'\n // Type-to-extension enforcement (Wire 0.2, v0.12.2)\n | 'E_EXTENSION_GROUP_REQUIRED'\n | 'E_EXTENSION_GROUP_MISMATCH'\n | 'E_INTERNAL';\n\n/**\n * Options for local verification\n */\nexport interface VerifyLocalOptions {\n /**\n * Expected issuer URL\n *\n * If provided, verification fails if receipt.iss does not match.\n */\n issuer?: string;\n\n /**\n * @deprecated Wire 0.2 does not have an `aud` claim. This option is ignored.\n * Retained for source compatibility during migration; will be removed in v1.0.\n */\n audience?: string;\n\n /**\n * Expected subject URI\n *\n * If provided, verification fails if receipt.sub does not match.\n * Binds the receipt to a specific resource/interaction target.\n */\n subjectUri?: string;\n\n /**\n * @deprecated Wire 0.2 does not have a `rid` claim. Use `jti` for receipt identification.\n * This option is ignored. Retained for source compatibility; will be removed in v1.0.\n */\n rid?: string;\n\n /**\n * @deprecated Wire 0.2 receipts do not expire (permanent evidence by design).\n * This option is ignored. Retained for source compatibility; will be removed in v1.0.\n */\n requireExp?: boolean;\n\n /**\n * Current timestamp (Unix seconds)\n *\n * Defaults to Date.now() / 1000. Override for testing.\n */\n now?: number;\n\n /**\n * Maximum clock skew tolerance (seconds)\n *\n * Allows for clock drift between issuer and verifier.\n * Defaults to 300 (5 minutes).\n */\n maxClockSkew?: number;\n\n /**\n * Verification strictness profile (v0.12.0-preview.1).\n *\n * - 'strict' (default): missing typ is a hard error before schema validation.\n * - 'interop': missing typ emits a 'typ_missing' warning and routes by payload content.\n *\n * Strictness is EXCLUSIVELY controlled here (@peac/protocol). @peac/crypto has no strictness param.\n */\n strictness?: VerificationStrictness;\n\n /**\n * Pre-computed local policy digest for policy binding (Wire 0.2, v0.12.0-preview.1).\n *\n * Must be in 'sha256:<64 lowercase hex>' format, computed via computePolicyDigestJcs()\n * from @peac/protocol. When provided alongside a receipt that contains a policy block\n * (policy.digest), the binding check is performed:\n * - Match: policy_binding = 'verified'\n * - Mismatch: hard fail with E_POLICY_BINDING_FAILED\n * - Either absent: policy_binding = 'unavailable'\n *\n * Always 'unavailable' for Wire 0.1 receipts regardless of this option.\n */\n policyDigest?: string;\n\n /**\n * Pre-computed document-binding results for transaction-local terms\n * and any other referenced documents (v0.12.14).\n *\n * Per-representation envelope binding (status) and any optional\n * publisher-supplied canonical-JSON digest comparison are computed by\n * the caller using the helpers in `document-binding.ts`. `verifyLocal`\n * surfaces the results on the report's `bindings` field exactly as\n * supplied; it never synthesizes envelope or canonical-digest\n * comparisons internally.\n *\n * `bindings.policy` is populated by `verifyLocal` itself from the\n * receipt's `policy.digest` and the `policyDigest` option. `bindings.terms`\n * is populated from `terms` here. `bindings.documents` is populated from\n * `documents` here. None of these fields appear on the emitted record\n * or envelope; they are verifier-report-only.\n */\n bindings?: {\n terms?: import('./verifier-types.js').DocumentBindingResult;\n documents?: import('./verifier-types.js').DocumentBindingResult[];\n };\n}\n\n/**\n * Result of successful local verification (Wire 0.2 only)\n *\n * Wire 0.1 receipts are no longer accepted by verifyLocal() and return\n * E_UNSUPPORTED_WIRE_VERSION. Re-issue as Wire 0.2 using issue().\n */\nexport interface VerifyLocalSuccess {\n /** Verification succeeded */\n valid: true;\n /** Receipt variant (always 'wire-02') */\n variant: 'wire-02';\n /** Validated Wire 0.2 receipt claims */\n claims: Wire02Claims;\n /** Key ID from JWS header (for logging/indexing) */\n kid: string;\n /** Wire format version */\n wireVersion: '0.2';\n /** Verification warnings from schema parsing and strictness routing */\n warnings: VerificationWarning[];\n /**\n * Policy binding status.\n *\n * Three-state result:\n * - 'unavailable': either the receipt contains no policy block, or the\n * caller did not pass a policyDigest option to verifyLocal(). No check.\n * - 'verified': both digests present and match exactly.\n * - 'failed': not returned on success; verifyLocal() returns\n * E_POLICY_BINDING_FAILED (valid: false) before reaching this field.\n *\n * This field is the byte-stable legacy mirror of `bindings.policy`.\n */\n policy_binding: PolicyBindingStatus;\n\n /**\n * Top-level bindings object (v0.12.14).\n *\n * `bindings.policy` is always present and equal to `policy_binding`.\n * `bindings.terms` is present iff the caller supplied terms inputs.\n * `bindings.documents` is present iff the caller supplied a non-empty\n * `documentDigests` array. `bindings.terms` and `bindings.documents`\n * appear in verifier output only; they are NOT stamped into the\n * emitted record / envelope / artifact shape.\n */\n bindings: import('./verifier-types.js').VerifierBindings;\n}\n\n/**\n * Result of failed local verification\n */\nexport interface VerifyLocalFailure {\n /** Verification failed */\n valid: false;\n\n /** Canonical error code (maps to specs/kernel/errors.json) */\n code: VerifyLocalErrorCode;\n\n /** Human-readable error message */\n message: string;\n\n /** Structured details for debugging (stable error code preserved in `code`) */\n details?: {\n /** Precise parse error code from unified parser (e.g. E_PARSE_COMMERCE_INVALID) */\n parse_code?: string;\n /** Zod validation issues (bounded, stable shape; non-normative, may change) */\n issues?: ReadonlyArray<{ path: string; message: string }>;\n /**\n * Policy digest from the receipt (present when code is E_POLICY_BINDING_FAILED).\n * Both are SHA-256 hashes; safe to log without leaking policy content.\n */\n receipt_policy_digest?: string;\n /** Caller-supplied policy digest (present when code is E_POLICY_BINDING_FAILED). */\n local_policy_digest?: string;\n /** policy.uri hint from the receipt (present when code is E_POLICY_BINDING_FAILED and uri set). */\n policy_uri?: string;\n /** Receipt type value (present when code is E_EXTENSION_GROUP_REQUIRED or E_EXTENSION_GROUP_MISMATCH). */\n type?: string;\n /** Expected extension group key for the receipt type. */\n expected_extension_group?: string;\n /** Registered extension groups actually present in extensions. */\n present_registered_extension_groups?: string[];\n };\n}\n\n/**\n * Union type for local verification result\n */\nexport type VerifyLocalResult = VerifyLocalSuccess | VerifyLocalFailure;\n\n/**\n * Internal CRYPTO_* codes that map to generic E_INVALID_FORMAT.\n * These are format/encoding errors not security-specific.\n */\nconst FORMAT_ERROR_CODES = new Set([\n 'CRYPTO_INVALID_JWS_FORMAT',\n 'CRYPTO_INVALID_TYP',\n 'CRYPTO_INVALID_ALG',\n 'CRYPTO_INVALID_KEY_LENGTH',\n]);\n\n/**\n * JOSE hardening code mapping: CRYPTO_JWS_* → specific E_JWS_* (v0.12.0-preview.1).\n *\n * Each JOSE hazard code maps to its specific public E_JWS_* counterpart rather than\n * collapsing into the generic E_INVALID_FORMAT. This lets callers distinguish embedded-key\n * injection, crit-header abuse, and unencoded-payload attacks from ordinary format errors.\n */\nconst JOSE_CODE_MAP: Record<string, VerifyLocalErrorCode> = {\n CRYPTO_JWS_EMBEDDED_KEY: 'E_JWS_EMBEDDED_KEY',\n CRYPTO_JWS_CRIT_REJECTED: 'E_JWS_CRIT_REJECTED',\n CRYPTO_JWS_MISSING_KID: 'E_JWS_MISSING_KID',\n CRYPTO_JWS_B64_REJECTED: 'E_JWS_B64_REJECTED',\n CRYPTO_JWS_ZIP_REJECTED: 'E_JWS_ZIP_REJECTED',\n};\n\n/** Max parse issues to include in details (prevents log bloat) */\nconst MAX_PARSE_ISSUES = 25;\n\n/**\n * Sanitize Zod issues into a bounded, stable structure.\n * Avoids exposing raw Zod internals or unbounded arrays in the public API.\n */\nfunction sanitizeParseIssues(\n issues: unknown\n): ReadonlyArray<{ path: string; message: string }> | undefined {\n if (!Array.isArray(issues)) return undefined;\n return issues.slice(0, MAX_PARSE_ISSUES).map((issue) => ({\n path: Array.isArray(issue?.path) ? issue.path.join('.') : '',\n message: typeof issue?.message === 'string' ? issue.message : String(issue),\n }));\n}\n\n/**\n * Verify a Wire 0.2 PEAC receipt locally with a known public key.\n *\n * Wire 0.2 only: Wire 0.1 receipts return E_UNSUPPORTED_WIRE_VERSION.\n * Re-issue Wire 0.1 receipts as Wire 0.2 using issueWire02().\n *\n * This function:\n * 1. Verifies the Ed25519 signature and header (typ, alg)\n * 2. Applies strictness routing for missing typ (strict: hard error; interop: warning)\n * 3. Validates the receipt schema with Zod (Wire 0.2 only)\n * 4. Checks issuer/subject binding (if options provided)\n * 5. Checks time validity (iat with clock skew tolerance)\n * 6. Checks occurred_at skew and collects parse warnings\n *\n * @param jws - JWS compact serialization\n * @param publicKey - Ed25519 public key (32 bytes)\n * @param options - Optional verification options (issuer, subject, clock skew, strictness, policyDigest)\n * @returns Typed verification result\n *\n * @example\n * ```typescript\n * const result = await verifyLocal(jws, publicKey, {\n * issuer: 'https://api.example.com',\n * strictness: 'strict',\n * });\n * if (result.valid) {\n * console.log('Kind:', result.claims.kind);\n * console.log('Warnings:', result.warnings);\n * }\n * ```\n */\nexport async function verifyLocal(\n jws: string,\n publicKey: Uint8Array,\n options: VerifyLocalOptions = {}\n): Promise<VerifyLocalResult> {\n // Internal rollback-path flag. See `_internal/legacy-path.ts` for\n // the full contract.\n void readLegacyPathFlag(options as unknown as LegacyPathOptions);\n\n const {\n issuer,\n subjectUri,\n maxClockSkew = 300,\n strictness = 'strict',\n policyDigest,\n bindings: callerBindings,\n } = options;\n const now = options.now ?? Math.floor(Date.now() / 1000);\n\n try {\n // 1. Verify signature and header via the internal codec boundary\n // (typ, alg validated by @peac/crypto). Default codec is a pure\n // pass-through to @peac/crypto.verify; the returned VerifyResult is\n // byte-identical to the prior release for every fixture.\n const result = await defaultCodec.decode<unknown>(jws, publicKey);\n\n if (!result.valid) {\n return {\n valid: false,\n code: 'E_INVALID_SIGNATURE',\n message: 'Ed25519 signature verification failed',\n };\n }\n\n // Accumulated warnings for Wire 0.2 path\n const accumulatedWarnings: VerificationWarning[] = [];\n\n // 2. Strictness routing for missing typ (Correction 1)\n if (result.header.typ === undefined) {\n if (strictness === 'strict') {\n return {\n valid: false,\n code: 'E_INVALID_FORMAT',\n message: 'Missing JWS typ header: strict mode requires typ to be present',\n };\n }\n // interop mode: emit warning and continue\n accumulatedWarnings.push({\n code: WARNING_TYP_MISSING,\n message: 'JWS typ header is absent; accepted in interop mode',\n });\n }\n\n // 3. Validate structural kernel constraints (fail-closed)\n const constraintResult = validateKernelConstraints(result.payload);\n if (!constraintResult.valid) {\n const v = constraintResult.violations[0];\n return {\n valid: false,\n code: 'E_CONSTRAINT_VIOLATION',\n message: `Kernel constraint violated: ${v.constraint} (actual: ${v.actual}, limit: ${v.limit})`,\n };\n }\n\n // 4. Validate schema (unified parser supports Wire 0.1 and Wire 0.2)\n const pr = parseReceiptClaims(result.payload);\n\n if (!pr.ok) {\n return {\n valid: false,\n code: 'E_INVALID_FORMAT',\n message: `Receipt schema validation failed: ${pr.error.message}`,\n details: { parse_code: pr.error.code, issues: sanitizeParseIssues(pr.error.issues) },\n };\n }\n\n // 5. Collect parser warnings (Wire 0.2 parser may emit type/extension warnings)\n if (pr.wireVersion === '0.2') {\n accumulatedWarnings.push(...pr.warnings);\n }\n\n // Wire 0.2 path\n if (pr.wireVersion === '0.2') {\n const claims = pr.claims as Wire02Claims;\n\n // Inert shadow-call boundary (default disabled in v0.13.1; PR D\n // wires the actual flag plumbing). The hook returns undefined\n // and never affects control flow or result; this call is a\n // structural placeholder so PR D can extend the boundary\n // without touching this file again.\n maybeRunShadowValidation({ mode: 'disabled', claims });\n\n // Issuer check\n if (issuer !== undefined && claims.iss !== issuer) {\n return {\n valid: false,\n code: 'E_INVALID_ISSUER',\n message: `Issuer mismatch: expected \"${issuer}\", got \"${claims.iss}\"`,\n };\n }\n\n // Subject check\n if (subjectUri !== undefined && claims.sub !== subjectUri) {\n return {\n valid: false,\n code: 'E_INVALID_SUBJECT',\n message: `Subject mismatch: expected \"${subjectUri}\", got \"${claims.sub ?? 'undefined'}\"`,\n };\n }\n\n // iat: not-yet-valid check (with clock skew)\n if (claims.iat > now + maxClockSkew) {\n return {\n valid: false,\n code: 'E_NOT_YET_VALID',\n message: `Receipt not yet valid: issued at ${new Date(claims.iat * 1000).toISOString()}, now is ${new Date(now * 1000).toISOString()}`,\n };\n }\n\n // occurred_at skew check (evidence kind only)\n if (claims.kind === 'evidence') {\n const skewResult = checkOccurredAtSkew(claims.occurred_at, claims.iat, now, maxClockSkew);\n if (skewResult === 'future_error') {\n return {\n valid: false,\n code: 'E_OCCURRED_AT_FUTURE',\n message: `occurred_at is in the future beyond tolerance (${maxClockSkew}s)`,\n };\n }\n if (skewResult !== null) {\n accumulatedWarnings.push(skewResult);\n }\n }\n\n // Emit type_unregistered warning for valid-but-unregistered type values\n if (!REGISTERED_RECEIPT_TYPES.has(claims.type)) {\n accumulatedWarnings.push({\n code: WARNING_TYPE_UNREGISTERED,\n message: 'Receipt type is not in the recommended type registry',\n pointer: '/type',\n });\n }\n\n // Emit unknown_extension_preserved warnings for unrecognized-but-well-formed keys\n // Malformed keys are already hard errors (E_INVALID_EXTENSION_KEY) at schema layer.\n if (claims.extensions !== undefined) {\n for (const key of Object.keys(claims.extensions)) {\n if (!REGISTERED_EXTENSION_GROUP_KEYS.has(key) && isValidExtensionKey(key)) {\n // RFC 6901: '~' -> '~0', '/' -> '~1'\n const escapedKey = key.replace(/~/g, '~0').replace(/\\//g, '~1');\n accumulatedWarnings.push({\n code: WARNING_UNKNOWN_EXTENSION,\n message: 'Unknown extension key preserved without schema validation',\n pointer: `/extensions/${escapedKey}`,\n });\n }\n }\n }\n\n // Type-to-extension enforcement: check that the expected extension group is present\n const typeExtCheck = checkTypeExtensionMapping(\n claims.kind,\n claims.type,\n claims.extensions,\n TYPE_TO_EXTENSION_MAP,\n REGISTERED_EXTENSION_GROUP_KEYS\n );\n\n if (typeExtCheck.status === 'missing' || typeExtCheck.status === 'mismatch') {\n const warningCode =\n typeExtCheck.status === 'missing'\n ? WARNING_EXTENSION_GROUP_MISSING\n : WARNING_EXTENSION_GROUP_MISMATCH;\n const errorCode =\n typeExtCheck.status === 'missing'\n ? 'E_EXTENSION_GROUP_REQUIRED'\n : 'E_EXTENSION_GROUP_MISMATCH';\n\n if (strictness === 'strict') {\n return {\n valid: false,\n code: errorCode,\n message: `Type \"${claims.type}\" expects extension group \"${typeExtCheck.expected_extension_group}\" but it is ${typeExtCheck.status === 'mismatch' ? 'replaced by a different registered group' : 'absent'}`,\n details: {\n type: claims.type,\n expected_extension_group: typeExtCheck.expected_extension_group,\n present_registered_extension_groups: typeExtCheck.present_registered_extension_groups,\n },\n };\n }\n\n // Interop mode: emit warning, continue verification\n accumulatedWarnings.push({\n code: warningCode,\n message: `Type \"${claims.type}\" expects extension group \"${typeExtCheck.expected_extension_group}\"`,\n pointer: '/type',\n });\n }\n\n // Validate policyDigest option format: must be sha256:<64 lowercase hex> if provided.\n if (policyDigest !== undefined && !HASH.pattern.test(policyDigest)) {\n return {\n valid: false,\n code: 'E_INVALID_FORMAT',\n message: 'policyDigest option must be in sha256:<64 lowercase hex> format',\n };\n }\n\n // Policy binding check: 3-state result.\n // 'unavailable' when either receipt has no policy block or caller omitted policyDigest.\n // 'verified' / 'failed' when both are present; 'failed' is a hard verification error.\n const receiptPolicyDigest = claims.policy?.digest;\n const bindingStatus: PolicyBindingStatus =\n receiptPolicyDigest === undefined || policyDigest === undefined\n ? 'unavailable'\n : verifyPolicyBinding(receiptPolicyDigest, policyDigest);\n if (bindingStatus === 'failed') {\n return {\n valid: false,\n code: 'E_POLICY_BINDING_FAILED',\n message: 'Policy binding check failed: receipt policy digest does not match local policy',\n details: {\n receipt_policy_digest: receiptPolicyDigest,\n local_policy_digest: policyDigest,\n ...(claims.policy?.uri !== undefined && { policy_uri: claims.policy.uri }),\n },\n };\n }\n\n // Build the top-level `bindings` object. `policy` always present and\n // mirrors the legacy `policy_binding` field byte-stable. `terms` and\n // `documents` are surfaced from caller-supplied results; verifyLocal\n // does not synthesize envelope or canonical-digest comparisons here.\n // Report-only; never stamped into emitted record / envelope shape.\n const bindings: import('./verifier-types.js').VerifierBindings = {\n policy: bindingStatus,\n ...(callerBindings?.terms !== undefined && { terms: callerBindings.terms }),\n ...(callerBindings?.documents !== undefined &&\n callerBindings.documents.length > 0 && { documents: callerBindings.documents }),\n };\n\n const sortedWarnings = sortWarnings(accumulatedWarnings);\n\n if (isShadowEnabled(options as unknown as ShadowEnableOptions)) {\n const headerSnapshot = { ...result.header } as Record<string, unknown>;\n scheduleShadow<ShadowObservation>({\n call: 'verifyLocal',\n realResult: realObservationForVerifyLocalSuccess(sortedWarnings),\n realError: undefined,\n shadowFn: async () =>\n shadowObservationFromBounded(\n runBoundedValidatorShadow({\n claims: {\n kind: claims.kind,\n type: claims.type,\n iss: claims.iss,\n iat: claims.iat,\n occurred_at: claims.occurred_at,\n extensions: claims.extensions,\n },\n header: headerSnapshot,\n now,\n })\n ),\n recordRef: jws,\n });\n }\n\n return {\n valid: true,\n variant: 'wire-02',\n claims,\n kid: result.header.kid,\n wireVersion: '0.2',\n warnings: sortedWarnings,\n policy_binding: bindingStatus,\n bindings,\n };\n }\n\n // Wire 0.1 receipts: reject with E_UNSUPPORTED_WIRE_VERSION.\n return {\n valid: false,\n code: 'E_UNSUPPORTED_WIRE_VERSION',\n message: 'Wire 0.1 receipts are not supported. Re-issue as Wire 0.2 using issue().',\n };\n } catch (err) {\n // Handle typed CryptoError from @peac/crypto\n // Use structural check instead of instanceof for robustness across ESM/CJS boundaries\n // Map internal CRYPTO_* codes to canonical E_* codes.\n // JOSE hardening codes get specific E_JWS_* (not generic E_INVALID_FORMAT) so callers\n // can distinguish key-injection attacks from ordinary encoding errors.\n if (isCryptoError(err)) {\n // 1. JOSE hardening: specific E_JWS_* codes (checked first)\n if (Object.prototype.hasOwnProperty.call(JOSE_CODE_MAP, err.code)) {\n return {\n valid: false,\n code: JOSE_CODE_MAP[err.code]!,\n message: err.message,\n };\n }\n // 2. Generic format errors\n if (FORMAT_ERROR_CODES.has(err.code)) {\n return {\n valid: false,\n code: 'E_INVALID_FORMAT',\n message: err.message,\n };\n }\n if (err.code === 'CRYPTO_INVALID_SIGNATURE') {\n return {\n valid: false,\n code: 'E_INVALID_SIGNATURE',\n message: err.message,\n };\n }\n if (err.code === 'CRYPTO_WIRE_VERSION_MISMATCH') {\n return {\n valid: false,\n code: 'E_WIRE_VERSION_MISMATCH',\n message: err.message,\n };\n }\n }\n\n // Handle JSON parse errors from malformed payloads\n // Use structural check for cross-boundary robustness (consistent with isCryptoError pattern)\n if (\n err !== null &&\n typeof err === 'object' &&\n 'name' in err &&\n (err as { name: unknown }).name === 'SyntaxError'\n ) {\n const syntaxMessage =\n 'message' in err && typeof (err as { message: unknown }).message === 'string'\n ? (err as { message: string }).message\n : 'Invalid JSON';\n return {\n valid: false,\n code: 'E_INVALID_FORMAT',\n message: `Invalid receipt payload: ${syntaxMessage}`,\n };\n }\n\n // All other errors -> E_INTERNAL\n // No message parsing - code-based mapping only\n const message = err instanceof Error ? err.message : String(err);\n return {\n valid: false,\n code: 'E_INTERNAL',\n message: `Unexpected verification error: ${message}`,\n };\n }\n}\n\n/**\n * @deprecated Removed: verifyLocal() is Wire 0.2 only and always returns variant 'wire-02'.\n * This guard always returns false. Remove usage and use isWire02Result() instead.\n */\nexport function isCommerceResult(\n r: VerifyLocalResult\n): r is VerifyLocalSuccess & { variant: 'wire-02' } {\n // Always false: verifyLocal() only returns variant 'wire-02'\n return false;\n}\n\n/**\n * @deprecated Removed: verifyLocal() is Wire 0.2 only and always returns variant 'wire-02'.\n * This guard always returns false. Remove usage and use isWire02Result() instead.\n */\nexport function isAttestationResult(\n r: VerifyLocalResult\n): r is VerifyLocalSuccess & { variant: 'wire-02' } {\n // Always false: verifyLocal() only returns variant 'wire-02'\n return false;\n}\n\n/**\n * Type guard: narrows a VerifyLocalResult to a Wire 0.2 success (v0.12.0-preview.1).\n *\n * Use instead of manual `result.valid && result.variant === 'wire-02'` checks\n * to get proper claims narrowing to Wire02Claims.\n */\nexport function isWire02Result(\n r: VerifyLocalResult\n): r is VerifyLocalSuccess & { variant: 'wire-02' } {\n return r.valid === true && r.variant === 'wire-02';\n}\n"]}