@peac/protocol 0.15.3 → 0.16.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +86 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.mjs +86 -3
- package/dist/index.mjs.map +1 -1
- package/dist/replay-guard.d.ts +55 -0
- package/dist/replay-guard.d.ts.map +1 -0
- package/dist/verify-local-wire01.d.ts.map +1 -1
- package/dist/verify-local.cjs +11 -2
- package/dist/verify-local.cjs.map +1 -1
- package/dist/verify-local.d.ts +1 -1
- package/dist/verify-local.d.ts.map +1 -1
- package/dist/verify-local.mjs +11 -2
- package/dist/verify-local.mjs.map +1 -1
- package/package.json +4 -4
|
@@ -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/validators/schema-parse.ts","../src/_internal/record-core/validators/jose-typ-strictness.ts","../src/_internal/record-core/validators/iat-not-yet-valid.ts","../src/_internal/record-core/validators/policy-binding.ts","../src/_internal/record-core/validators/unknown-extension-grammar.ts","../src/_internal/record-core/validators/type-extension-enforcement.ts","../src/_internal/record-core/bounded-validator.ts","../src/_internal/record-core/validation-gate.ts","../src/_internal/shadow-redact.ts","../src/_internal/shadow.ts","../src/_internal/legacy-path.ts","../src/_internal/signature.ts","../src/_internal/shadow-observe.ts","../src/verify-local.ts"],"names":["cryptoVerify","ACCEPTED","escapeJsonPointerSegment","REJECTED","REGISTERED_EXTENSION_GROUP_KEYS","isValidExtensionKey","ACCEPTED_NO_WARN","TYPE_TO_EXTENSION_MAP","validateKernelConstraints","parseReceiptClaims","REGISTERED_RECEIPT_TYPES","WARNING_TYPE_UNREGISTERED","WARNING_UNKNOWN_EXTENSION","WARNING_EXTENSION_GROUP_MISSING","WARNING_EXTENSION_GROUP_MISMATCH","verifyPolicyBinding"],"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;AAAA,EAEhB,MAAM,MAAA,CAAO,OAAA,EAAkB,UAAA,EAAwB,GAAA,EAA8B;AACnF,IAAA,OAAO,UAAA,CAAW,OAAA,EAAS,UAAA,EAAY,GAAG,CAAA;AAAA,EAC5C;AAAA,EAEA,MAAM,MAAA,CAAoB,UAAA,EAAoB,SAAA,EAAiD;AAC7F,IAAA,OAAOA,MAAA,CAAgB,YAAY,SAAS,CAAA;AAAA,EAC9C;AAAA,EAEA,WAAW,UAAA,EAAiC;AAG1C,IAAA,MAAM,QAAA,GAAW,UAAA,CAAW,KAAA,CAAM,GAAG,CAAA;AACrC,IAAA,IAAI,QAAA,CAAS,WAAW,CAAA,EAAG;AACzB,MAAA,MAAM,IAAI,UAAA;AAAA,QACR,sBAAA;AAAA,QACA,CAAA,yDAAA,EAA4D,SAAS,MAAM,CAAA,CAAA;AAAA,OAC7E;AAAA,IACF;AACA,IAAA,MAAM,CAAC,SAAA,EAAW,UAAA,EAAY,YAAY,CAAA,GAAI,QAAA;AAC9C,IAAA,IAAI,SAAA,CAAU,WAAW,CAAA,EAAG;AAC1B,MAAA,MAAM,IAAI,UAAA;AAAA,QACR,sBAAA;AA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AO,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;AAOA,IAAA,MAAM,cAAA,GAAiB,2BAA2B,GAAG,CAAA;AACrD,IAAA,IAAI,cAAA,KAAmB,IAAA,IAAQ,cAAA,KAAmB,uBAAA,EAAyB;AACzE,MAAA,OAAO;AAAA,QACL,KAAA,EAAO,KAAA;AAAA,QACP,IAAA,EAAM,qBAAA;AAAA,QACN,OAAA,EAAS;AAAA,OACX;AAAA,IACF;AAKA,IAAA,OAAO;AAAA,MACL,KAAA,EAAO,KAAA;AAAA,MACP,IAAA,EAAM,YAAA;AAAA,MACN,OAAA,EAAS;AAAA,KACX;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.mjs","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 internal schema-parse validator.\n *\n * INTERNAL ONLY. Thin wrapper around the canonical\n * `parseReceiptClaims` from `@peac/schema`. Projects the canonical\n * accept/reject signal plus the full canonical projection (parsed\n * claims, parser warnings, canonical error triple) so production\n * callers can reproduce the canonical surface byte-equally without\n * re-invoking `parseReceiptClaims`.\n *\n * Module is internal-only; not re-exported from\n * `packages/protocol/src/index.ts`.\n *\n * SCOPE:\n * - Run `parseReceiptClaims(payload)` and surface its accept/reject.\n * - On acceptance: surface `wireVersion`, parsed `claims`, and\n * parser `warnings` (e.g., `type_unregistered`,\n * `unknown_extension_preserved`). Higher-layer aggregation merges\n * these into the caller's warning array.\n * - On rejection: surface the canonical error triple\n * (`errorCode`, `errorMessage`, `errorIssues`) so callers can\n * project the canonical `details: { parse_code, issues }` and\n * `message: 'Receipt schema validation failed: <message>'`\n * surface byte-equally.\n */\n\nimport type { ZodError } from 'zod';\nimport type { VerificationWarning } from '@peac/kernel';\nimport { parseReceiptClaims } from '@peac/schema';\nimport type { Wire02Claims } from '@peac/schema';\n\nexport interface SchemaParseResult {\n readonly accepted: boolean;\n /**\n * Canonical parse-error code from `parseReceiptClaims` when the\n * parse rejects. Mirrors `pr.error.code`.\n */\n readonly errorCode?: string;\n /**\n * Canonical parse-error message from `parseReceiptClaims` when the\n * parse rejects. Mirrors `pr.error.message`. Required for callers\n * that reproduce the canonical surface message\n * `Receipt schema validation failed: <message>` byte-equally.\n */\n readonly errorMessage?: string;\n /**\n * Canonical parse-error issues from `parseReceiptClaims` when the\n * parse rejects. Mirrors `pr.error.issues`. Callers downstream\n * apply their own bounded sanitization (path-join, length cap)\n * before surfacing on a public verifier-result `details` payload.\n */\n readonly errorIssues?: ZodError['issues'];\n /**\n * Parsed Wire 0.2 claims when accepted. Internal-only; does not\n * appear on any emitted record or public surface.\n */\n readonly claims?: Wire02Claims;\n /**\n * Wire version surfaced from `parseReceiptClaims` on acceptance.\n * The bounded surface only admits `'0.2'`; Wire 0.1 acceptance from\n * the canonical parser is rejected at this layer with\n * `E_UNSUPPORTED_WIRE_VERSION` because the bounded composition is\n * keyed on Wire 0.2 claim shapes.\n */\n readonly wireVersion?: '0.2';\n /**\n * Parser warnings surfaced on acceptance. Mirrors `pr.warnings` for\n * Wire 0.2 acceptance. Callers that aggregate into a single\n * canonical warning array merge this list at the canonical-equivalent\n * flow position before the canonical sort.\n */\n readonly warnings?: readonly VerificationWarning[];\n}\n\nexport function validateSchemaParseInternal(payload: unknown): SchemaParseResult {\n const pr = parseReceiptClaims(payload);\n if (!pr.ok) {\n return {\n accepted: false,\n errorCode: pr.error.code,\n errorMessage: pr.error.message,\n ...(pr.error.issues !== undefined && { errorIssues: pr.error.issues }),\n };\n }\n if (pr.wireVersion !== '0.2') {\n return {\n accepted: false,\n errorCode: 'E_UNSUPPORTED_WIRE_VERSION',\n errorMessage: `Unsupported wire version: ${pr.wireVersion}`,\n };\n }\n return {\n accepted: true,\n claims: pr.claims as Wire02Claims,\n wireVersion: '0.2',\n warnings: pr.warnings,\n };\n}\n","/**\n * Bounded internal JOSE typ-strictness validator.\n *\n * INTERNAL ONLY. Parity-observed counterpart of the typ-strictness\n * routing in `verify-local.ts` (the block that rejects a missing typ\n * under `'strict'` mode and surfaces a `typ_missing` warning under\n * `'interop'` mode). Both implementations consume the same protected-\n * header `typ` value plus a `strictness` parameter and apply the same\n * accept/reject/warning rules.\n *\n * Existing canonical strictness routing in `verify-local.ts` remains\n * canonical. This module is observational only; not re-exported and\n * not wired into the public runtime path.\n *\n * SCOPE:\n * - typ present (any string) -> accepted, no warning.\n * - typ absent (undefined or non-string) and strictness === 'strict'\n * -> rejected with E_INVALID_FORMAT.\n * - typ absent and strictness === 'interop' -> accepted with\n * typ_missing warning.\n *\n * Out of scope:\n * - typ value validation (`'interaction-record+jwt'` enforcement lives\n * in `@peac/crypto.validateWire02Header` / the JOSE-hardening layer).\n * - alg / kid / crit / b64 / zip checks (handled by `jose-hardening.ts`).\n */\n\nexport type Strictness = 'strict' | 'interop';\n\nexport interface JoseTypStrictnessWarning {\n readonly code: string;\n}\n\nexport type JoseTypStrictnessResult =\n | { readonly accepted: true; readonly warnings?: readonly JoseTypStrictnessWarning[] }\n | { readonly accepted: false; readonly errorCode: string };\n\nconst ACCEPTED_NO_WARN: JoseTypStrictnessResult = { accepted: true } as const;\nconst ACCEPTED_TYP_MISSING: JoseTypStrictnessResult = {\n accepted: true,\n warnings: [{ code: 'typ_missing' }],\n} as const;\nconst REJECTED_INVALID_FORMAT: JoseTypStrictnessResult = {\n accepted: false,\n errorCode: 'E_INVALID_FORMAT',\n} as const;\n\nexport function validateJoseTypStrictnessInternal(\n typ: unknown,\n strictness: Strictness\n): JoseTypStrictnessResult {\n const present = typeof typ === 'string' && typ.length > 0;\n if (present) return ACCEPTED_NO_WARN;\n if (strictness === 'strict') return REJECTED_INVALID_FORMAT;\n return ACCEPTED_TYP_MISSING;\n}\n","/**\n * Bounded internal iat-not-yet-valid validator.\n *\n * INTERNAL ONLY. Parity-observed counterpart of the inline iat-not-yet-valid\n * check in `verify-local.ts` (`if (claims.iat > now + maxClockSkew) ...`).\n * Both implementations consume the same `iat`, `now`, and `maxClockSkew`\n * inputs and apply the same comparison; behavioral parity is proven\n * byte-equal by the parity tests.\n *\n * Existing canonical iat handling in `verify-local.ts` 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 the public\n * runtime path.\n *\n * SCOPE:\n * - Reject when `iat > now + maxClockSkew` (claim issued too far in the future).\n * - Accept when `iat <= now + maxClockSkew`.\n * - Never reads `Date.now()`; the caller injects `now` for determinism.\n *\n * Out of scope:\n * - `exp` / `nbf` checks (Wire 0.2 records do not expire and have no nbf).\n * - `occurred_at` skew (handled by `temporal.ts`).\n */\n\nexport interface IatNotYetValidResult {\n readonly accepted: boolean;\n readonly errorCode?: string;\n}\n\nconst ACCEPTED: IatNotYetValidResult = { accepted: true } as const;\nconst REJECTED: IatNotYetValidResult = {\n accepted: false,\n errorCode: 'E_NOT_YET_VALID',\n} as const;\n\nexport function validateIatNotYetValidInternal(\n iat: number,\n now: number,\n maxClockSkew: number\n): IatNotYetValidResult {\n if (iat > now + maxClockSkew) return REJECTED;\n return ACCEPTED;\n}\n","/**\n * Bounded internal policy-binding validator (canonical-composed).\n *\n * INTERNAL ONLY. Thin wrapper around `verifyPolicyBinding` from\n * `@peac/schema`. Surfaces the canonical three-state result\n * (`verified` / `failed` / `unavailable`) projected into the bounded\n * validator's accept/reject contract, where `failed` is the only\n * rejection.\n *\n * This is observational equivalence by construction, not a divergent\n * binding check. Module is observational only; not re-exported from\n * `packages/protocol/src/index.ts` and not wired into the public\n * runtime path.\n *\n * SCOPE:\n * - Both digests present and equal -> accepted (`verified`).\n * - Either digest absent -> accepted (`unavailable`); no policy\n * check is performed when the receipt or caller omits the digest.\n * - Both present but unequal -> rejected with E_POLICY_BINDING_FAILED.\n *\n * Out of scope:\n * - Policy-document fetch and digest computation (lives in\n * `verifyLocal()` / caller responsibility).\n * - Policy URI handling (`policy.uri` is informational only).\n */\n\nimport { verifyPolicyBinding } from '@peac/schema';\n\nexport interface PolicyBindingResult {\n readonly accepted: boolean;\n readonly errorCode?: string;\n /** 'verified' | 'failed' | 'unavailable'. Surfaced unchanged from canonical. */\n readonly status: 'verified' | 'failed' | 'unavailable';\n}\n\nexport function validatePolicyBindingInternal(\n receiptPolicyDigest: string | undefined,\n localPolicyDigest: string | undefined\n): PolicyBindingResult {\n if (receiptPolicyDigest === undefined || localPolicyDigest === undefined) {\n return { accepted: true, status: 'unavailable' };\n }\n const status = verifyPolicyBinding(receiptPolicyDigest, localPolicyDigest);\n if (status === 'failed') {\n return { accepted: false, errorCode: 'E_POLICY_BINDING_FAILED', status };\n }\n return { accepted: true, status };\n}\n","/**\n * Bounded internal unknown-extension-grammar validator (canonical-composed).\n *\n * INTERNAL ONLY. Thin wrapper around `isValidExtensionKey` and\n * `REGISTERED_EXTENSION_GROUP_KEYS` from `@peac/schema`. Identifies\n * unknown-but-well-formed extension keys and surfaces them as\n * non-blocking warnings, mirroring the canonical\n * `unknown_extension_preserved` warning emitted by `verifyLocal`.\n *\n * Malformed extension keys (failing `isValidExtensionKey`) are NOT\n * surfaced here as warnings; they are hard errors at the canonical\n * schema-parse layer (`E_INVALID_EXTENSION_KEY`) and therefore never\n * reach this layer on an accepted record.\n *\n * Module is observational only; not re-exported from\n * `packages/protocol/src/index.ts` and not wired into the public\n * runtime path.\n *\n * SCOPE:\n * - Walk `claims.extensions` keys.\n * - For every key that is well-formed but not registered, emit a\n * warning with code `unknown_extension_preserved` and an\n * RFC 6901 JSON-pointer-encoded path.\n * - Always accepted; this layer never rejects.\n *\n * Out of scope:\n * - Malformed-key rejection (canonical schema-parse owns this).\n * - Per-extension content validation (extension-specific schemas).\n */\n\nimport { REGISTERED_EXTENSION_GROUP_KEYS, isValidExtensionKey } from '@peac/schema';\n\nexport interface UnknownExtensionWarning {\n readonly code: string;\n readonly pointer: string;\n}\n\nexport interface UnknownExtensionGrammarResult {\n readonly accepted: true;\n readonly warnings: readonly UnknownExtensionWarning[];\n}\n\nconst ACCEPTED_EMPTY: UnknownExtensionGrammarResult = {\n accepted: true,\n warnings: [],\n} as const;\n\n/**\n * Encode a JSON-pointer reference token per RFC 6901: `~` -> `~0`,\n * `/` -> `~1`. Order matters: `~` must be replaced before `/`.\n */\nfunction escapeJsonPointer(token: string): string {\n return token.replace(/~/g, '~0').replace(/\\//g, '~1');\n}\n\nexport function validateUnknownExtensionGrammarInternal(\n extensions: Record<string, unknown> | undefined\n): UnknownExtensionGrammarResult {\n if (extensions === undefined) return ACCEPTED_EMPTY;\n const keys = Object.keys(extensions);\n if (keys.length === 0) return ACCEPTED_EMPTY;\n\n const warnings: UnknownExtensionWarning[] = [];\n for (const key of keys) {\n if (!REGISTERED_EXTENSION_GROUP_KEYS.has(key) && isValidExtensionKey(key)) {\n warnings.push({\n code: 'unknown_extension_preserved',\n pointer: `/extensions/${escapeJsonPointer(key)}`,\n });\n }\n }\n return { accepted: true, warnings };\n}\n","/**\n * Bounded internal type-extension-enforcement validator (canonical-composed).\n *\n * INTERNAL ONLY. Thin wrapper around `checkTypeExtensionMapping` from\n * `@peac/protocol/src/type-extension-check` plus the strictness-mode\n * routing performed by `verifyLocal`. Surfaces the canonical mapping\n * result projected into the bounded validator's accept/reject and\n * warning contract.\n *\n * Distinct from `type-extension-mapping.ts` (warnings-only) in this\n * module's directory: this layer covers the strictness-mode path that\n * promotes `missing` and `mismatch` to hard errors when\n * `strictness === 'strict'`. Both layers consume the same canonical\n * mapping result; they differ only in how they project it.\n *\n * Module is observational only; not re-exported from\n * `packages/protocol/src/index.ts` and not wired into the public\n * runtime path.\n *\n * SCOPE:\n * - `skip` -> accepted, no warning, no error.\n * - `ok` -> accepted, no warning, no error.\n * - `missing` + strict -> rejected with E_EXTENSION_GROUP_REQUIRED.\n * - `mismatch` + strict -> rejected with E_EXTENSION_GROUP_MISMATCH.\n * - `missing` + interop -> accepted with extension_group_missing warning at /type.\n * - `mismatch` + interop -> accepted with extension_group_mismatch warning at /type.\n */\n\nimport { TYPE_TO_EXTENSION_MAP } from '@peac/kernel';\nimport { REGISTERED_EXTENSION_GROUP_KEYS } from '@peac/schema';\nimport { checkTypeExtensionMapping } from '../../../type-extension-check.js';\nimport type { Strictness } from './jose-typ-strictness.js';\n\nexport interface TypeExtensionEnforcementWarning {\n readonly code: string;\n readonly pointer: string;\n}\n\nexport type TypeExtensionEnforcementResult =\n | { readonly accepted: true; readonly warnings?: readonly TypeExtensionEnforcementWarning[] }\n | { readonly accepted: false; readonly errorCode: string; readonly pointer?: string };\n\nconst ACCEPTED_NO_WARN: TypeExtensionEnforcementResult = { accepted: true } as const;\n\nexport function validateTypeExtensionEnforcementInternal(\n kind: string,\n type: string,\n extensions: Record<string, unknown> | undefined,\n strictness: Strictness\n): TypeExtensionEnforcementResult {\n const result = checkTypeExtensionMapping(\n kind,\n type,\n extensions,\n TYPE_TO_EXTENSION_MAP,\n REGISTERED_EXTENSION_GROUP_KEYS\n );\n\n if (result.status === 'ok' || result.status === 'skip') {\n return ACCEPTED_NO_WARN;\n }\n\n if (strictness === 'strict') {\n const errorCode =\n result.status === 'missing' ? 'E_EXTENSION_GROUP_REQUIRED' : 'E_EXTENSION_GROUP_MISMATCH';\n return { accepted: false, errorCode, pointer: '/type' };\n }\n\n // interop mode: surface as warning, accept the record.\n const warningCode =\n result.status === 'missing' ? 'extension_group_missing' : 'extension_group_mismatch';\n return {\n accepted: true,\n warnings: [{ code: warningCode, pointer: '/type' }],\n };\n}\n","/**\n * Canonical-composed shadow validation: composition aggregator.\n *\n * INTERNAL ONLY. Composes layer validators into a single aggregated\n * result. Each layer either delegates to a canonical helper from\n * `@peac/schema` / `@peac/crypto` / `@peac/protocol` (canonical-\n * composed wrapper pattern) or mirrors a canonical inline check\n * verbatim. The canonical-vs-candidate differential test asserts\n * byte-equality of the candidate verdict with the canonical verdict\n * on every eligible fixture; any divergence indicates a defect in\n * the projection logic.\n *\n * Always-on layers (run on every input):\n * - kernel-constraints (depth / array / keys / string / nodes)\n * - issuer-form (canonical iss)\n * - type-extension-mapping (warnings only)\n * - extension-byte-budget\n * - unknown-extension-grammar (warnings only)\n *\n * Optional-input layers (skip when their inputs are absent):\n * - jose-header-hardening (header)\n * - temporal occurred_at skew (evidence kind)\n * - schema-parse (fullClaims)\n * - jose-typ-strictness (header + strictness)\n * - iat-not-yet-valid (maxClockSkew)\n * - policy-binding (receiptPolicyDigest + localPolicyDigest)\n * - type-extension-enforcement (strictness)\n *\n * Out of scope:\n * - signature verification (the standalone `validateSignatureInternal`\n * export is async and is not composed here; callers that need it\n * invoke it directly with serialized + publicKey)\n * - any control-plane behavior (issuer resolver, JWKS fetch, etc.)\n *\n * Public-facing wording for this module: \"canonical-composed shadow\n * validation\" or \"observational equivalence harness\". Never\n * \"complete validator\", \"primary validator\", or \"divergent validator\".\n */\n\nimport {\n validateExtensionBudgetInternal,\n validateIatNotYetValidInternal,\n validateIssuerFormInternal,\n validateJoseHardeningInternal,\n validateJoseTypStrictnessInternal,\n validateKernelConstraintsInternal,\n validatePolicyBindingInternal,\n validateSchemaParseInternal,\n validateTemporalInternal,\n validateTypeExtensionEnforcementInternal,\n validateTypeExtensionMappingInternal,\n validateUnknownExtensionGrammarInternal,\n type ExtensionBudgetViolation,\n type Strictness,\n type TemporalWarning,\n type TypeExtensionEnforcementWarning,\n type TypeExtensionMappingWarning,\n type UnknownExtensionWarning,\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 * Strictness profile for layers that promote warnings to errors\n * under `'strict'` mode. When omitted, layers that consume\n * strictness skip (they do not run). Mirrors the canonical\n * `verifyLocal({ strictness })` option.\n */\n readonly strictness?: Strictness;\n /**\n * Maximum permitted clock skew in seconds for the iat-not-yet-valid\n * check. When omitted, the iat layer skips. Mirrors\n * `verifyLocal({ maxClockSkew })`; canonical default is 300.\n */\n readonly maxClockSkew?: number;\n /**\n * Receipt-side policy digest (`claims.policy.digest`). Used together\n * with `localPolicyDigest` by the policy-binding layer. Either\n * absent skips the layer.\n */\n readonly receiptPolicyDigest?: string;\n /**\n * Caller-supplied policy digest. Used together with\n * `receiptPolicyDigest`. Either absent skips the layer.\n */\n readonly localPolicyDigest?: string;\n /**\n * Full receipt-claims object for the schema-parse layer. When\n * omitted, the schema-parse layer falls back to running on the\n * minimal `BoundedClaimsInput` projection (which may not surface\n * field-level parse errors that depend on optional fields outside\n * the bounded subset).\n */\n readonly fullClaims?: Record<string, unknown>;\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 | 'schema-parse'\n | 'jose-typ-strictness'\n | 'iat-not-yet-valid'\n | 'policy-binding'\n | 'unknown-extension-grammar'\n | 'type-extension-enforcement';\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 // 7. Schema-parse projection (canonical-composed; delegates to\n // parseReceiptClaims). Skips when `fullClaims` is not supplied;\n // `BoundedClaimsInput` is a 6-field subset and would never satisfy\n // the canonical Wire 0.2 schema. Callers that want the schema-parse\n // layer to fire MUST pass the full claims object via `fullClaims`.\n if (input.fullClaims !== undefined) {\n const schemaRes = validateSchemaParseInternal(input.fullClaims);\n if (!schemaRes.accepted && schemaRes.errorCode !== undefined) {\n violations.push({ layer: 'schema-parse', code: schemaRes.errorCode });\n }\n }\n\n // 8. JOSE typ-strictness (canonical-composed; mirrors verify-local\n // strictness routing). Skip when no header or no strictness\n // supplied; canonical surface only routes typ-missing under a\n // declared strictness.\n if (input.header !== undefined && input.strictness !== undefined) {\n const typRes = validateJoseTypStrictnessInternal(input.header.typ, input.strictness);\n if (!typRes.accepted) {\n violations.push({ layer: 'jose-typ-strictness', code: typRes.errorCode });\n } else if (typRes.warnings) {\n for (const w of typRes.warnings) {\n warnings.push({ layer: 'jose-typ-strictness', code: w.code });\n }\n }\n }\n\n // 9. iat-not-yet-valid (mirrors the inline verify-local check).\n // Skip when no maxClockSkew supplied; canonical surface only runs\n // this check inside verifyLocal where maxClockSkew is bound.\n if (input.maxClockSkew !== undefined) {\n const iatRes = validateIatNotYetValidInternal(input.claims.iat, input.now, input.maxClockSkew);\n if (!iatRes.accepted && iatRes.errorCode !== undefined) {\n violations.push({ layer: 'iat-not-yet-valid', code: iatRes.errorCode });\n }\n }\n\n // 10. Policy-binding (canonical-composed; delegates to\n // verifyPolicyBinding). The `unavailable` projection (either\n // digest absent) is accepted with no surfacing; only `failed`\n // produces a violation.\n if (input.receiptPolicyDigest !== undefined && input.localPolicyDigest !== undefined) {\n const policyRes = validatePolicyBindingInternal(\n input.receiptPolicyDigest,\n input.localPolicyDigest\n );\n if (!policyRes.accepted && policyRes.errorCode !== undefined) {\n violations.push({ layer: 'policy-binding', code: policyRes.errorCode });\n }\n }\n\n // 11. Unknown-extension grammar (canonical-composed; warnings only).\n const unknownExtRes = validateUnknownExtensionGrammarInternal(input.claims.extensions);\n for (const w of unknownExtRes.warnings as readonly UnknownExtensionWarning[]) {\n warnings.push({\n layer: 'unknown-extension-grammar',\n code: w.code,\n path: w.pointer,\n });\n }\n\n // 12. Type-extension enforcement (canonical-composed; promotes\n // missing/mismatch to errors under strict mode, surfaces them as\n // warnings under interop). Skip when no strictness supplied.\n if (input.strictness !== undefined) {\n const enforceRes = validateTypeExtensionEnforcementInternal(\n input.claims.kind,\n input.claims.type,\n input.claims.extensions,\n input.strictness\n );\n if (!enforceRes.accepted) {\n violations.push({\n layer: 'type-extension-enforcement',\n code: enforceRes.errorCode,\n path: enforceRes.pointer,\n });\n } else if (enforceRes.warnings) {\n for (const w of enforceRes.warnings as readonly TypeExtensionEnforcementWarning[]) {\n warnings.push({\n layer: 'type-extension-enforcement',\n code: w.code,\n path: w.pointer,\n });\n }\n }\n }\n\n return {\n accepted: violations.length === 0,\n violations,\n warnings,\n };\n}\n","/**\n * Production-facing bounded validation gate.\n *\n * INTERNAL ONLY. Not re-exported from `packages/protocol/src/index.ts`.\n *\n * The gate is the only production wrapper for the bounded validation\n * path. The pre-existing `runBoundedValidatorShadow` from\n * `bounded-validator.ts` remains the entry point for shadow / corpus\n * / parity-harness consumers and is not the primary admission path\n * for the protocol entry points; the production-wrapper boundary is\n * enforced by `tests/tooling/production-gate-boundary.test.ts`.\n *\n * The gate is entrypoint-aware: callers identify themselves with a\n * `surface` discriminator, and the gate applies a per-surface\n * production projection allowlist. Layers in the bounded validator's\n * broader composition that fall outside the allowlist for a given\n * surface stay available to shadow / parity tests through\n * `runBoundedValidatorShadow` but are not surfaced as production\n * failure or production warning here.\n *\n * Allowlist for surface 'issueWire02':\n * - schema-parse only.\n *\n * Allowlist for surface 'verifyLocal':\n * - kernel-constraints (via canonical `validateKernelConstraints`).\n * - schema-parse (via the extended `validateSchemaParseInternal`).\n *\n * Out of scope here (kept inline-canonical on both branches by the\n * caller): caller-option-bearing checks (issuer mismatch, subjectUri\n * mismatch, policyDigest format), strictness routing for missing typ,\n * iat-not-yet-valid, occurred_at temporal, type-extension warnings,\n * type-extension enforcement, policy-binding compute, bindings\n * construction, sortWarnings.\n *\n * The canonical materializer (claim encoding, JWS signing, JWS\n * decoding, result-shape construction) is shared between the\n * bounded-default and rollback branches and is not touched by the\n * gate.\n */\n\nimport { validateKernelConstraints } from '@peac/schema';\nimport type { VerificationWarning } from '@peac/kernel';\nimport type { Wire02Claims } from '@peac/schema';\nimport { validateSchemaParseInternal } from './validators/schema-parse.js';\n\n/**\n * Discriminator identifying which protocol entry point invoked the\n * gate. Drives the production projection allowlist. Adding a third\n * surface requires a deliberate plan amendment, not an unannounced\n * source change.\n */\nexport type GateSurface = 'issueWire02' | 'verifyLocal';\n\n/** Sanitized parse-issue projection surfaced on rejection. */\nexport interface SanitizedParseIssue {\n readonly path: string;\n readonly message: string;\n}\n\n/** Parsed-claims projection surfaced on `verifyLocal` acceptance. */\nexport interface ValidationGateParsed {\n readonly wireVersion: '0.2';\n readonly claims: Wire02Claims;\n readonly parserWarnings: readonly VerificationWarning[];\n}\n\n/** Failure-detail projection. Smaller than the bounded layer set. */\nexport interface ValidationGateFailureDetails {\n readonly parse_code?: string;\n readonly issues?: readonly SanitizedParseIssue[];\n}\n\n/** Successful gate result. */\nexport interface ValidationGateSuccess {\n readonly ok: true;\n readonly parsed?: ValidationGateParsed;\n}\n\n/** Failed gate result. */\nexport interface ValidationGateFailure {\n readonly ok: false;\n readonly code: string;\n readonly message: string;\n readonly details?: ValidationGateFailureDetails;\n}\n\nexport type ValidationGateResult = ValidationGateSuccess | ValidationGateFailure;\n\n/** Inputs to the gate. Only `surface` and `payload` are required. */\nexport interface ValidationGateInput {\n readonly surface: GateSurface;\n /**\n * Full claims object. For surface 'issueWire02' this is the just-\n * constructed `Wire02Claims` cast to a plain record (the same\n * object that today flows through `Wire02ClaimsSchema.safeParse`).\n * For surface 'verifyLocal' this is the decoded JWS payload (the\n * same object that today flows through `validateKernelConstraints`\n * and `parseReceiptClaims`).\n */\n readonly payload: unknown;\n}\n\n/** Maximum sanitized-issue list length surfaced to a verifier report. */\nconst MAX_SANITIZED_ISSUES = 25;\n\nfunction sanitizeIssues(issues: unknown): readonly SanitizedParseIssue[] | undefined {\n if (!Array.isArray(issues)) return undefined;\n return issues.slice(0, MAX_SANITIZED_ISSUES).map((issue) => {\n const candidate = issue as { path?: unknown; message?: unknown };\n const path = Array.isArray(candidate.path)\n ? candidate.path\n .map((segment) =>\n typeof segment === 'string' || typeof segment === 'number' ? String(segment) : ''\n )\n .join('.')\n : '';\n const message =\n typeof candidate.message === 'string'\n ? candidate.message\n : String(candidate.message ?? issue);\n return { path, message };\n });\n}\n\n/**\n * Run the production projection of the bounded validation path.\n *\n * Behavior is byte-equivalent to the inline canonical sequences at\n * `issue.ts` and `verify-local.ts` for every input on the covered\n * runtime matrix. Any cross-branch divergence on JWS bytes, result\n * shape, error code, warning order, thrown error class, success /\n * failure classification, or observable default behavior is a\n * validation-equivalence regression.\n */\nexport function runBoundedValidationGate(input: ValidationGateInput): ValidationGateResult {\n if (input.surface === 'issueWire02') {\n return runIssueWire02(input.payload);\n }\n return runVerifyLocal(input.payload);\n}\n\nfunction runIssueWire02(payload: unknown): ValidationGateResult {\n // Issuance projection mirrors `issue.ts` Wire02ClaimsSchema.safeParse.\n // Today's canonical issuance reports the first Zod issue message in\n // the IssueError details. The gate reproduces that surface here.\n const schemaRes = validateSchemaParseInternal(payload);\n if (!schemaRes.accepted) {\n const firstIssueMessage = schemaRes.errorIssues?.[0]?.message;\n return {\n ok: false,\n code: 'E_INVALID_FORMAT',\n message: `Wire 0.2 claims schema validation failed: ${firstIssueMessage ?? 'unknown'}`,\n };\n }\n return { ok: true };\n}\n\nfunction runVerifyLocal(payload: unknown): ValidationGateResult {\n // Kernel constraints first (canonical-helper delegation preserves\n // the existing `Kernel constraint violated: <constraint>\n // (actual: <actual>, limit: <limit>)` message byte-equally).\n const kernelRes = validateKernelConstraints(payload);\n if (!kernelRes.valid) {\n const v = kernelRes.violations[0];\n return {\n ok: false,\n code: 'E_CONSTRAINT_VIOLATION',\n message: `Kernel constraint violated: ${v.constraint} (actual: ${v.actual}, limit: ${v.limit})`,\n };\n }\n\n // Schema parse next. Surface the canonical\n // `Receipt schema validation failed: <message>` shape with\n // `details: { parse_code, issues }` byte-equally.\n //\n // Wire 0.1 payloads parse successfully under the canonical parser\n // but are rejected at the bounded layer with errorCode\n // 'E_UNSUPPORTED_WIRE_VERSION'. The verify-local canonical surface\n // routes Wire 0.1 to a distinct error code (not E_INVALID_FORMAT)\n // and a distinct message; preserve that branch here.\n const schemaRes = validateSchemaParseInternal(payload);\n if (!schemaRes.accepted) {\n if (schemaRes.errorCode === 'E_UNSUPPORTED_WIRE_VERSION') {\n return {\n ok: 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 }\n const sanitized = sanitizeIssues(schemaRes.errorIssues);\n const details: ValidationGateFailureDetails = {};\n if (schemaRes.errorCode !== undefined) {\n Object.assign(details, { parse_code: schemaRes.errorCode });\n }\n if (sanitized !== undefined) {\n Object.assign(details, { issues: sanitized });\n }\n return {\n ok: false,\n code: 'E_INVALID_FORMAT',\n message: `Receipt schema validation failed: ${schemaRes.errorMessage ?? 'unknown'}`,\n ...(Object.keys(details).length > 0 && { details }),\n };\n }\n\n if (schemaRes.wireVersion !== '0.2' || schemaRes.claims === undefined) {\n return {\n ok: 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 }\n\n return {\n ok: true,\n parsed: {\n wireVersion: '0.2',\n claims: schemaRes.claims,\n parserWarnings: schemaRes.warnings ?? [],\n },\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 * Internal Ed25519 signature-width guard for the verification paths.\n *\n * NOT re-exported from the package barrel (`index.ts` does\n * `export * from './verify'` / `'./verify-local'`, so anything exported from\n * those modules becomes public API). Keep this helper in `_internal` so the\n * guard adds no public surface.\n */\n\nimport { base64urlDecode } from '@peac/crypto';\n\n/** Ed25519 signatures are fixed-width 64 bytes (RFC 8032 / RFC 8709). */\nexport const ED25519_SIGNATURE_BYTES = 64;\n\n/**\n * Return the decoded byte length of a compact JWS signature segment, or `null`\n * when the token is not a well-formed three-part compact JWS or the signature\n * segment is not decodable base64url. Those `null` cases are deliberately left\n * to the existing format/verification error paths (this guard does not change\n * their classification); only a well-formed token whose signature decodes to a\n * non-64-byte width is surfaced to the caller as a wrong-length signature.\n */\nexport function ed25519SignatureByteLength(jws: string): number | null {\n const parts = jws.split('.');\n if (parts.length !== 3) {\n return null;\n }\n try {\n return base64urlDecode(parts[2]).length;\n } catch {\n return null;\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 { runBoundedValidationGate } from './_internal/record-core/validation-gate.js';\nimport { isShadowEnabled, scheduleShadow, type ShadowEnableOptions } from './_internal/shadow.js';\nimport { readLegacyPathFlag, type LegacyPathOptions } from './_internal/legacy-path.js';\nimport { ED25519_SIGNATURE_BYTES, ed25519SignatureByteLength } from './_internal/signature.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. Selects the bounded validation\n // admission gate (default) or the inline canonical sequence\n // (rollback). Both branches share the post-admission flow: caller-\n // option binding, temporal checks, type-extension enforcement,\n // policy-binding compute, bindings construction, sortWarnings.\n const legacyPath = 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-5. Admission: kernel constraints, schema parse, parser warnings.\n //\n // The default branch routes through the bounded validation gate,\n // which surfaces canonical-equivalent E_CONSTRAINT_VIOLATION /\n // E_INVALID_FORMAT / E_UNSUPPORTED_WIRE_VERSION verdicts on\n // rejection and the parsed Wire 0.2 claims plus parser warnings\n // on acceptance. The rollback branch retains the inline canonical\n // sequence (validateKernelConstraints + parseReceiptClaims). Both\n // branches feed the same post-admission flow.\n type AdmittedClaims = {\n readonly ok: true;\n readonly wireVersion: '0.1' | '0.2';\n readonly warnings: readonly VerificationWarning[];\n readonly claims: unknown;\n };\n let pr: AdmittedClaims;\n\n if (legacyPath) {\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 const parsed = parseReceiptClaims(result.payload);\n if (!parsed.ok) {\n return {\n valid: false,\n code: 'E_INVALID_FORMAT',\n message: `Receipt schema validation failed: ${parsed.error.message}`,\n details: {\n parse_code: parsed.error.code,\n issues: sanitizeParseIssues(parsed.error.issues),\n },\n };\n }\n pr = parsed;\n } else {\n const gateResult = runBoundedValidationGate({\n surface: 'verifyLocal',\n payload: result.payload,\n });\n if (!gateResult.ok) {\n return {\n valid: false,\n code: gateResult.code as VerifyLocalErrorCode,\n message: gateResult.message,\n ...(gateResult.details !== undefined && { details: gateResult.details }),\n };\n }\n const parsedFromGate = gateResult.parsed;\n if (parsedFromGate === undefined) {\n return {\n valid: false,\n code: 'E_INTERNAL',\n message: 'Bounded validation gate accepted without surfacing parsed claims',\n };\n }\n pr = {\n ok: true,\n wireVersion: parsedFromGate.wireVersion,\n warnings: parsedFromGate.parserWarnings,\n claims: parsedFromGate.claims,\n };\n }\n\n // 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 // Shadow scheduling fires only on the rollback branch where the\n // bounded validator is genuinely a comparison path. Under the\n // default branch the gate runs as the production admission\n // path, so a duplicate shadow run would compare the same code\n // path against itself.\n if (legacyPath && 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 // A wrong-length Ed25519 signature throws an untyped error inside the\n // verifier (not a typed CryptoError, so it is not handled above). Classify\n // it deterministically as an invalid signature rather than letting it fall\n // through to E_INTERNAL. Typed format errors are handled earlier, so a\n // malformed header/payload still maps to E_INVALID_FORMAT (format-first).\n const signatureBytes = ed25519SignatureByteLength(jws);\n if (signatureBytes !== null && signatureBytes !== ED25519_SIGNATURE_BYTES) {\n return {\n valid: false,\n code: 'E_INVALID_SIGNATURE',\n message: 'Ed25519 signature has invalid length',\n };\n }\n\n // All other errors -> E_INTERNAL\n // No message parsing - code-based mapping only; do not surface raw\n // exception text to callers (avoids leaking internal paths/state).\n return {\n valid: false,\n code: 'E_INTERNAL',\n message: 'Unexpected verification error.',\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/validators/schema-parse.ts","../src/_internal/record-core/validators/jose-typ-strictness.ts","../src/_internal/record-core/validators/iat-not-yet-valid.ts","../src/_internal/record-core/validators/policy-binding.ts","../src/_internal/record-core/validators/unknown-extension-grammar.ts","../src/_internal/record-core/validators/type-extension-enforcement.ts","../src/_internal/record-core/bounded-validator.ts","../src/_internal/record-core/validation-gate.ts","../src/_internal/shadow-redact.ts","../src/_internal/shadow.ts","../src/_internal/legacy-path.ts","../src/_internal/signature.ts","../src/_internal/shadow-observe.ts","../src/verify-local.ts"],"names":["cryptoVerify","ACCEPTED","escapeJsonPointerSegment","REJECTED","REGISTERED_EXTENSION_GROUP_KEYS","isValidExtensionKey","ACCEPTED_NO_WARN","TYPE_TO_EXTENSION_MAP","validateKernelConstraints","parseReceiptClaims","REGISTERED_RECEIPT_TYPES","WARNING_TYPE_UNREGISTERED","WARNING_UNKNOWN_EXTENSION","WARNING_EXTENSION_GROUP_MISSING","WARNING_EXTENSION_GROUP_MISMATCH","verifyPolicyBinding"],"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;AAAA,EAEhB,MAAM,MAAA,CAAO,OAAA,EAAkB,UAAA,EAAwB,GAAA,EAA8B;AACnF,IAAA,OAAO,UAAA,CAAW,OAAA,EAAS,UAAA,EAAY,GAAG,CAAA;AAAA,EAC5C;AAAA,EAEA,MAAM,MAAA,CAAoB,UAAA,EAAoB,SAAA,EAAiD;AAC7F,IAAA,OAAOA,MAAA,CAAgB,YAAY,SAAS,CAAA;AAAA,EAC9C;AAAA,EAEA,WAAW,UAAA,EAAiC;AAG1C,IAAA,MAAM,QAAA,GAAW,UAAA,CAAW,KAAA,CAAM,GAAG,CAAA;AACrC,IAAA,IAAI,QAAA,CAAS,WAAW,CAAA,EAAG;AACzB,MAAA,MAAM,IAAI,UAAA;A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;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.mjs","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 internal schema-parse validator.\n *\n * INTERNAL ONLY. Thin wrapper around the canonical\n * `parseReceiptClaims` from `@peac/schema`. Projects the canonical\n * accept/reject signal plus the full canonical projection (parsed\n * claims, parser warnings, canonical error triple) so production\n * callers can reproduce the canonical surface byte-equally without\n * re-invoking `parseReceiptClaims`.\n *\n * Module is internal-only; not re-exported from\n * `packages/protocol/src/index.ts`.\n *\n * SCOPE:\n * - Run `parseReceiptClaims(payload)` and surface its accept/reject.\n * - On acceptance: surface `wireVersion`, parsed `claims`, and\n * parser `warnings` (e.g., `type_unregistered`,\n * `unknown_extension_preserved`). Higher-layer aggregation merges\n * these into the caller's warning array.\n * - On rejection: surface the canonical error triple\n * (`errorCode`, `errorMessage`, `errorIssues`) so callers can\n * project the canonical `details: { parse_code, issues }` and\n * `message: 'Receipt schema validation failed: <message>'`\n * surface byte-equally.\n */\n\nimport type { ZodError } from 'zod';\nimport type { VerificationWarning } from '@peac/kernel';\nimport { parseReceiptClaims } from '@peac/schema';\nimport type { Wire02Claims } from '@peac/schema';\n\nexport interface SchemaParseResult {\n readonly accepted: boolean;\n /**\n * Canonical parse-error code from `parseReceiptClaims` when the\n * parse rejects. Mirrors `pr.error.code`.\n */\n readonly errorCode?: string;\n /**\n * Canonical parse-error message from `parseReceiptClaims` when the\n * parse rejects. Mirrors `pr.error.message`. Required for callers\n * that reproduce the canonical surface message\n * `Receipt schema validation failed: <message>` byte-equally.\n */\n readonly errorMessage?: string;\n /**\n * Canonical parse-error issues from `parseReceiptClaims` when the\n * parse rejects. Mirrors `pr.error.issues`. Callers downstream\n * apply their own bounded sanitization (path-join, length cap)\n * before surfacing on a public verifier-result `details` payload.\n */\n readonly errorIssues?: ZodError['issues'];\n /**\n * Parsed Wire 0.2 claims when accepted. Internal-only; does not\n * appear on any emitted record or public surface.\n */\n readonly claims?: Wire02Claims;\n /**\n * Wire version surfaced from `parseReceiptClaims` on acceptance.\n * The bounded surface only admits `'0.2'`; Wire 0.1 acceptance from\n * the canonical parser is rejected at this layer with\n * `E_UNSUPPORTED_WIRE_VERSION` because the bounded composition is\n * keyed on Wire 0.2 claim shapes.\n */\n readonly wireVersion?: '0.2';\n /**\n * Parser warnings surfaced on acceptance. Mirrors `pr.warnings` for\n * Wire 0.2 acceptance. Callers that aggregate into a single\n * canonical warning array merge this list at the canonical-equivalent\n * flow position before the canonical sort.\n */\n readonly warnings?: readonly VerificationWarning[];\n}\n\nexport function validateSchemaParseInternal(payload: unknown): SchemaParseResult {\n const pr = parseReceiptClaims(payload);\n if (!pr.ok) {\n return {\n accepted: false,\n errorCode: pr.error.code,\n errorMessage: pr.error.message,\n ...(pr.error.issues !== undefined && { errorIssues: pr.error.issues }),\n };\n }\n if (pr.wireVersion !== '0.2') {\n return {\n accepted: false,\n errorCode: 'E_UNSUPPORTED_WIRE_VERSION',\n errorMessage: `Unsupported wire version: ${pr.wireVersion}`,\n };\n }\n return {\n accepted: true,\n claims: pr.claims as Wire02Claims,\n wireVersion: '0.2',\n warnings: pr.warnings,\n };\n}\n","/**\n * Bounded internal JOSE typ-strictness validator.\n *\n * INTERNAL ONLY. Parity-observed counterpart of the typ-strictness\n * routing in `verify-local.ts` (the block that rejects a missing typ\n * under `'strict'` mode and surfaces a `typ_missing` warning under\n * `'interop'` mode). Both implementations consume the same protected-\n * header `typ` value plus a `strictness` parameter and apply the same\n * accept/reject/warning rules.\n *\n * Existing canonical strictness routing in `verify-local.ts` remains\n * canonical. This module is observational only; not re-exported and\n * not wired into the public runtime path.\n *\n * SCOPE:\n * - typ present (any string) -> accepted, no warning.\n * - typ absent (undefined or non-string) and strictness === 'strict'\n * -> rejected with E_INVALID_FORMAT.\n * - typ absent and strictness === 'interop' -> accepted with\n * typ_missing warning.\n *\n * Out of scope:\n * - typ value validation (`'interaction-record+jwt'` enforcement lives\n * in `@peac/crypto.validateWire02Header` / the JOSE-hardening layer).\n * - alg / kid / crit / b64 / zip checks (handled by `jose-hardening.ts`).\n */\n\nexport type Strictness = 'strict' | 'interop';\n\nexport interface JoseTypStrictnessWarning {\n readonly code: string;\n}\n\nexport type JoseTypStrictnessResult =\n | { readonly accepted: true; readonly warnings?: readonly JoseTypStrictnessWarning[] }\n | { readonly accepted: false; readonly errorCode: string };\n\nconst ACCEPTED_NO_WARN: JoseTypStrictnessResult = { accepted: true } as const;\nconst ACCEPTED_TYP_MISSING: JoseTypStrictnessResult = {\n accepted: true,\n warnings: [{ code: 'typ_missing' }],\n} as const;\nconst REJECTED_INVALID_FORMAT: JoseTypStrictnessResult = {\n accepted: false,\n errorCode: 'E_INVALID_FORMAT',\n} as const;\n\nexport function validateJoseTypStrictnessInternal(\n typ: unknown,\n strictness: Strictness\n): JoseTypStrictnessResult {\n const present = typeof typ === 'string' && typ.length > 0;\n if (present) return ACCEPTED_NO_WARN;\n if (strictness === 'strict') return REJECTED_INVALID_FORMAT;\n return ACCEPTED_TYP_MISSING;\n}\n","/**\n * Bounded internal iat-not-yet-valid validator.\n *\n * INTERNAL ONLY. Parity-observed counterpart of the inline iat-not-yet-valid\n * check in `verify-local.ts` (`if (claims.iat > now + maxClockSkew) ...`).\n * Both implementations consume the same `iat`, `now`, and `maxClockSkew`\n * inputs and apply the same comparison; behavioral parity is proven\n * byte-equal by the parity tests.\n *\n * Existing canonical iat handling in `verify-local.ts` 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 the public\n * runtime path.\n *\n * SCOPE:\n * - Reject when `iat > now + maxClockSkew` (claim issued too far in the future).\n * - Accept when `iat <= now + maxClockSkew`.\n * - Never reads `Date.now()`; the caller injects `now` for determinism.\n *\n * Out of scope:\n * - `exp` / `nbf` checks (Wire 0.2 records do not expire and have no nbf).\n * - `occurred_at` skew (handled by `temporal.ts`).\n */\n\nexport interface IatNotYetValidResult {\n readonly accepted: boolean;\n readonly errorCode?: string;\n}\n\nconst ACCEPTED: IatNotYetValidResult = { accepted: true } as const;\nconst REJECTED: IatNotYetValidResult = {\n accepted: false,\n errorCode: 'E_NOT_YET_VALID',\n} as const;\n\nexport function validateIatNotYetValidInternal(\n iat: number,\n now: number,\n maxClockSkew: number\n): IatNotYetValidResult {\n if (iat > now + maxClockSkew) return REJECTED;\n return ACCEPTED;\n}\n","/**\n * Bounded internal policy-binding validator (canonical-composed).\n *\n * INTERNAL ONLY. Thin wrapper around `verifyPolicyBinding` from\n * `@peac/schema`. Surfaces the canonical three-state result\n * (`verified` / `failed` / `unavailable`) projected into the bounded\n * validator's accept/reject contract, where `failed` is the only\n * rejection.\n *\n * This is observational equivalence by construction, not a divergent\n * binding check. Module is observational only; not re-exported from\n * `packages/protocol/src/index.ts` and not wired into the public\n * runtime path.\n *\n * SCOPE:\n * - Both digests present and equal -> accepted (`verified`).\n * - Either digest absent -> accepted (`unavailable`); no policy\n * check is performed when the receipt or caller omits the digest.\n * - Both present but unequal -> rejected with E_POLICY_BINDING_FAILED.\n *\n * Out of scope:\n * - Policy-document fetch and digest computation (lives in\n * `verifyLocal()` / caller responsibility).\n * - Policy URI handling (`policy.uri` is informational only).\n */\n\nimport { verifyPolicyBinding } from '@peac/schema';\n\nexport interface PolicyBindingResult {\n readonly accepted: boolean;\n readonly errorCode?: string;\n /** 'verified' | 'failed' | 'unavailable'. Surfaced unchanged from canonical. */\n readonly status: 'verified' | 'failed' | 'unavailable';\n}\n\nexport function validatePolicyBindingInternal(\n receiptPolicyDigest: string | undefined,\n localPolicyDigest: string | undefined\n): PolicyBindingResult {\n if (receiptPolicyDigest === undefined || localPolicyDigest === undefined) {\n return { accepted: true, status: 'unavailable' };\n }\n const status = verifyPolicyBinding(receiptPolicyDigest, localPolicyDigest);\n if (status === 'failed') {\n return { accepted: false, errorCode: 'E_POLICY_BINDING_FAILED', status };\n }\n return { accepted: true, status };\n}\n","/**\n * Bounded internal unknown-extension-grammar validator (canonical-composed).\n *\n * INTERNAL ONLY. Thin wrapper around `isValidExtensionKey` and\n * `REGISTERED_EXTENSION_GROUP_KEYS` from `@peac/schema`. Identifies\n * unknown-but-well-formed extension keys and surfaces them as\n * non-blocking warnings, mirroring the canonical\n * `unknown_extension_preserved` warning emitted by `verifyLocal`.\n *\n * Malformed extension keys (failing `isValidExtensionKey`) are NOT\n * surfaced here as warnings; they are hard errors at the canonical\n * schema-parse layer (`E_INVALID_EXTENSION_KEY`) and therefore never\n * reach this layer on an accepted record.\n *\n * Module is observational only; not re-exported from\n * `packages/protocol/src/index.ts` and not wired into the public\n * runtime path.\n *\n * SCOPE:\n * - Walk `claims.extensions` keys.\n * - For every key that is well-formed but not registered, emit a\n * warning with code `unknown_extension_preserved` and an\n * RFC 6901 JSON-pointer-encoded path.\n * - Always accepted; this layer never rejects.\n *\n * Out of scope:\n * - Malformed-key rejection (canonical schema-parse owns this).\n * - Per-extension content validation (extension-specific schemas).\n */\n\nimport { REGISTERED_EXTENSION_GROUP_KEYS, isValidExtensionKey } from '@peac/schema';\n\nexport interface UnknownExtensionWarning {\n readonly code: string;\n readonly pointer: string;\n}\n\nexport interface UnknownExtensionGrammarResult {\n readonly accepted: true;\n readonly warnings: readonly UnknownExtensionWarning[];\n}\n\nconst ACCEPTED_EMPTY: UnknownExtensionGrammarResult = {\n accepted: true,\n warnings: [],\n} as const;\n\n/**\n * Encode a JSON-pointer reference token per RFC 6901: `~` -> `~0`,\n * `/` -> `~1`. Order matters: `~` must be replaced before `/`.\n */\nfunction escapeJsonPointer(token: string): string {\n return token.replace(/~/g, '~0').replace(/\\//g, '~1');\n}\n\nexport function validateUnknownExtensionGrammarInternal(\n extensions: Record<string, unknown> | undefined\n): UnknownExtensionGrammarResult {\n if (extensions === undefined) return ACCEPTED_EMPTY;\n const keys = Object.keys(extensions);\n if (keys.length === 0) return ACCEPTED_EMPTY;\n\n const warnings: UnknownExtensionWarning[] = [];\n for (const key of keys) {\n if (!REGISTERED_EXTENSION_GROUP_KEYS.has(key) && isValidExtensionKey(key)) {\n warnings.push({\n code: 'unknown_extension_preserved',\n pointer: `/extensions/${escapeJsonPointer(key)}`,\n });\n }\n }\n return { accepted: true, warnings };\n}\n","/**\n * Bounded internal type-extension-enforcement validator (canonical-composed).\n *\n * INTERNAL ONLY. Thin wrapper around `checkTypeExtensionMapping` from\n * `@peac/protocol/src/type-extension-check` plus the strictness-mode\n * routing performed by `verifyLocal`. Surfaces the canonical mapping\n * result projected into the bounded validator's accept/reject and\n * warning contract.\n *\n * Distinct from `type-extension-mapping.ts` (warnings-only) in this\n * module's directory: this layer covers the strictness-mode path that\n * promotes `missing` and `mismatch` to hard errors when\n * `strictness === 'strict'`. Both layers consume the same canonical\n * mapping result; they differ only in how they project it.\n *\n * Module is observational only; not re-exported from\n * `packages/protocol/src/index.ts` and not wired into the public\n * runtime path.\n *\n * SCOPE:\n * - `skip` -> accepted, no warning, no error.\n * - `ok` -> accepted, no warning, no error.\n * - `missing` + strict -> rejected with E_EXTENSION_GROUP_REQUIRED.\n * - `mismatch` + strict -> rejected with E_EXTENSION_GROUP_MISMATCH.\n * - `missing` + interop -> accepted with extension_group_missing warning at /type.\n * - `mismatch` + interop -> accepted with extension_group_mismatch warning at /type.\n */\n\nimport { TYPE_TO_EXTENSION_MAP } from '@peac/kernel';\nimport { REGISTERED_EXTENSION_GROUP_KEYS } from '@peac/schema';\nimport { checkTypeExtensionMapping } from '../../../type-extension-check.js';\nimport type { Strictness } from './jose-typ-strictness.js';\n\nexport interface TypeExtensionEnforcementWarning {\n readonly code: string;\n readonly pointer: string;\n}\n\nexport type TypeExtensionEnforcementResult =\n | { readonly accepted: true; readonly warnings?: readonly TypeExtensionEnforcementWarning[] }\n | { readonly accepted: false; readonly errorCode: string; readonly pointer?: string };\n\nconst ACCEPTED_NO_WARN: TypeExtensionEnforcementResult = { accepted: true } as const;\n\nexport function validateTypeExtensionEnforcementInternal(\n kind: string,\n type: string,\n extensions: Record<string, unknown> | undefined,\n strictness: Strictness\n): TypeExtensionEnforcementResult {\n const result = checkTypeExtensionMapping(\n kind,\n type,\n extensions,\n TYPE_TO_EXTENSION_MAP,\n REGISTERED_EXTENSION_GROUP_KEYS\n );\n\n if (result.status === 'ok' || result.status === 'skip') {\n return ACCEPTED_NO_WARN;\n }\n\n if (strictness === 'strict') {\n const errorCode =\n result.status === 'missing' ? 'E_EXTENSION_GROUP_REQUIRED' : 'E_EXTENSION_GROUP_MISMATCH';\n return { accepted: false, errorCode, pointer: '/type' };\n }\n\n // interop mode: surface as warning, accept the record.\n const warningCode =\n result.status === 'missing' ? 'extension_group_missing' : 'extension_group_mismatch';\n return {\n accepted: true,\n warnings: [{ code: warningCode, pointer: '/type' }],\n };\n}\n","/**\n * Canonical-composed shadow validation: composition aggregator.\n *\n * INTERNAL ONLY. Composes layer validators into a single aggregated\n * result. Each layer either delegates to a canonical helper from\n * `@peac/schema` / `@peac/crypto` / `@peac/protocol` (canonical-\n * composed wrapper pattern) or mirrors a canonical inline check\n * verbatim. The canonical-vs-candidate differential test asserts\n * byte-equality of the candidate verdict with the canonical verdict\n * on every eligible fixture; any divergence indicates a defect in\n * the projection logic.\n *\n * Always-on layers (run on every input):\n * - kernel-constraints (depth / array / keys / string / nodes)\n * - issuer-form (canonical iss)\n * - type-extension-mapping (warnings only)\n * - extension-byte-budget\n * - unknown-extension-grammar (warnings only)\n *\n * Optional-input layers (skip when their inputs are absent):\n * - jose-header-hardening (header)\n * - temporal occurred_at skew (evidence kind)\n * - schema-parse (fullClaims)\n * - jose-typ-strictness (header + strictness)\n * - iat-not-yet-valid (maxClockSkew)\n * - policy-binding (receiptPolicyDigest + localPolicyDigest)\n * - type-extension-enforcement (strictness)\n *\n * Out of scope:\n * - signature verification (the standalone `validateSignatureInternal`\n * export is async and is not composed here; callers that need it\n * invoke it directly with serialized + publicKey)\n * - any control-plane behavior (issuer resolver, JWKS fetch, etc.)\n *\n * Public-facing wording for this module: \"canonical-composed shadow\n * validation\" or \"observational equivalence harness\". Never\n * \"complete validator\", \"primary validator\", or \"divergent validator\".\n */\n\nimport {\n validateExtensionBudgetInternal,\n validateIatNotYetValidInternal,\n validateIssuerFormInternal,\n validateJoseHardeningInternal,\n validateJoseTypStrictnessInternal,\n validateKernelConstraintsInternal,\n validatePolicyBindingInternal,\n validateSchemaParseInternal,\n validateTemporalInternal,\n validateTypeExtensionEnforcementInternal,\n validateTypeExtensionMappingInternal,\n validateUnknownExtensionGrammarInternal,\n type ExtensionBudgetViolation,\n type Strictness,\n type TemporalWarning,\n type TypeExtensionEnforcementWarning,\n type TypeExtensionMappingWarning,\n type UnknownExtensionWarning,\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 * Strictness profile for layers that promote warnings to errors\n * under `'strict'` mode. When omitted, layers that consume\n * strictness skip (they do not run). Mirrors the canonical\n * `verifyLocal({ strictness })` option.\n */\n readonly strictness?: Strictness;\n /**\n * Maximum permitted clock skew in seconds for the iat-not-yet-valid\n * check. When omitted, the iat layer skips. Mirrors\n * `verifyLocal({ maxClockSkew })`; canonical default is 300.\n */\n readonly maxClockSkew?: number;\n /**\n * Receipt-side policy digest (`claims.policy.digest`). Used together\n * with `localPolicyDigest` by the policy-binding layer. Either\n * absent skips the layer.\n */\n readonly receiptPolicyDigest?: string;\n /**\n * Caller-supplied policy digest. Used together with\n * `receiptPolicyDigest`. Either absent skips the layer.\n */\n readonly localPolicyDigest?: string;\n /**\n * Full receipt-claims object for the schema-parse layer. When\n * omitted, the schema-parse layer falls back to running on the\n * minimal `BoundedClaimsInput` projection (which may not surface\n * field-level parse errors that depend on optional fields outside\n * the bounded subset).\n */\n readonly fullClaims?: Record<string, unknown>;\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 | 'schema-parse'\n | 'jose-typ-strictness'\n | 'iat-not-yet-valid'\n | 'policy-binding'\n | 'unknown-extension-grammar'\n | 'type-extension-enforcement';\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 // 7. Schema-parse projection (canonical-composed; delegates to\n // parseReceiptClaims). Skips when `fullClaims` is not supplied;\n // `BoundedClaimsInput` is a 6-field subset and would never satisfy\n // the canonical Wire 0.2 schema. Callers that want the schema-parse\n // layer to fire MUST pass the full claims object via `fullClaims`.\n if (input.fullClaims !== undefined) {\n const schemaRes = validateSchemaParseInternal(input.fullClaims);\n if (!schemaRes.accepted && schemaRes.errorCode !== undefined) {\n violations.push({ layer: 'schema-parse', code: schemaRes.errorCode });\n }\n }\n\n // 8. JOSE typ-strictness (canonical-composed; mirrors verify-local\n // strictness routing). Skip when no header or no strictness\n // supplied; canonical surface only routes typ-missing under a\n // declared strictness.\n if (input.header !== undefined && input.strictness !== undefined) {\n const typRes = validateJoseTypStrictnessInternal(input.header.typ, input.strictness);\n if (!typRes.accepted) {\n violations.push({ layer: 'jose-typ-strictness', code: typRes.errorCode });\n } else if (typRes.warnings) {\n for (const w of typRes.warnings) {\n warnings.push({ layer: 'jose-typ-strictness', code: w.code });\n }\n }\n }\n\n // 9. iat-not-yet-valid (mirrors the inline verify-local check).\n // Skip when no maxClockSkew supplied; canonical surface only runs\n // this check inside verifyLocal where maxClockSkew is bound.\n if (input.maxClockSkew !== undefined) {\n const iatRes = validateIatNotYetValidInternal(input.claims.iat, input.now, input.maxClockSkew);\n if (!iatRes.accepted && iatRes.errorCode !== undefined) {\n violations.push({ layer: 'iat-not-yet-valid', code: iatRes.errorCode });\n }\n }\n\n // 10. Policy-binding (canonical-composed; delegates to\n // verifyPolicyBinding). The `unavailable` projection (either\n // digest absent) is accepted with no surfacing; only `failed`\n // produces a violation.\n if (input.receiptPolicyDigest !== undefined && input.localPolicyDigest !== undefined) {\n const policyRes = validatePolicyBindingInternal(\n input.receiptPolicyDigest,\n input.localPolicyDigest\n );\n if (!policyRes.accepted && policyRes.errorCode !== undefined) {\n violations.push({ layer: 'policy-binding', code: policyRes.errorCode });\n }\n }\n\n // 11. Unknown-extension grammar (canonical-composed; warnings only).\n const unknownExtRes = validateUnknownExtensionGrammarInternal(input.claims.extensions);\n for (const w of unknownExtRes.warnings as readonly UnknownExtensionWarning[]) {\n warnings.push({\n layer: 'unknown-extension-grammar',\n code: w.code,\n path: w.pointer,\n });\n }\n\n // 12. Type-extension enforcement (canonical-composed; promotes\n // missing/mismatch to errors under strict mode, surfaces them as\n // warnings under interop). Skip when no strictness supplied.\n if (input.strictness !== undefined) {\n const enforceRes = validateTypeExtensionEnforcementInternal(\n input.claims.kind,\n input.claims.type,\n input.claims.extensions,\n input.strictness\n );\n if (!enforceRes.accepted) {\n violations.push({\n layer: 'type-extension-enforcement',\n code: enforceRes.errorCode,\n path: enforceRes.pointer,\n });\n } else if (enforceRes.warnings) {\n for (const w of enforceRes.warnings as readonly TypeExtensionEnforcementWarning[]) {\n warnings.push({\n layer: 'type-extension-enforcement',\n code: w.code,\n path: w.pointer,\n });\n }\n }\n }\n\n return {\n accepted: violations.length === 0,\n violations,\n warnings,\n };\n}\n","/**\n * Production-facing bounded validation gate.\n *\n * INTERNAL ONLY. Not re-exported from `packages/protocol/src/index.ts`.\n *\n * The gate is the only production wrapper for the bounded validation\n * path. The pre-existing `runBoundedValidatorShadow` from\n * `bounded-validator.ts` remains the entry point for shadow / corpus\n * / parity-harness consumers and is not the primary admission path\n * for the protocol entry points; the production-wrapper boundary is\n * enforced by `tests/tooling/production-gate-boundary.test.ts`.\n *\n * The gate is entrypoint-aware: callers identify themselves with a\n * `surface` discriminator, and the gate applies a per-surface\n * production projection allowlist. Layers in the bounded validator's\n * broader composition that fall outside the allowlist for a given\n * surface stay available to shadow / parity tests through\n * `runBoundedValidatorShadow` but are not surfaced as production\n * failure or production warning here.\n *\n * Allowlist for surface 'issueWire02':\n * - schema-parse only.\n *\n * Allowlist for surface 'verifyLocal':\n * - kernel-constraints (via canonical `validateKernelConstraints`).\n * - schema-parse (via the extended `validateSchemaParseInternal`).\n *\n * Out of scope here (kept inline-canonical on both branches by the\n * caller): caller-option-bearing checks (issuer mismatch, subjectUri\n * mismatch, policyDigest format), strictness routing for missing typ,\n * iat-not-yet-valid, occurred_at temporal, type-extension warnings,\n * type-extension enforcement, policy-binding compute, bindings\n * construction, sortWarnings.\n *\n * The canonical materializer (claim encoding, JWS signing, JWS\n * decoding, result-shape construction) is shared between the\n * bounded-default and rollback branches and is not touched by the\n * gate.\n */\n\nimport { validateKernelConstraints } from '@peac/schema';\nimport type { VerificationWarning } from '@peac/kernel';\nimport type { Wire02Claims } from '@peac/schema';\nimport { validateSchemaParseInternal } from './validators/schema-parse.js';\n\n/**\n * Discriminator identifying which protocol entry point invoked the\n * gate. Drives the production projection allowlist. Adding a third\n * surface requires a deliberate plan amendment, not an unannounced\n * source change.\n */\nexport type GateSurface = 'issueWire02' | 'verifyLocal';\n\n/** Sanitized parse-issue projection surfaced on rejection. */\nexport interface SanitizedParseIssue {\n readonly path: string;\n readonly message: string;\n}\n\n/** Parsed-claims projection surfaced on `verifyLocal` acceptance. */\nexport interface ValidationGateParsed {\n readonly wireVersion: '0.2';\n readonly claims: Wire02Claims;\n readonly parserWarnings: readonly VerificationWarning[];\n}\n\n/** Failure-detail projection. Smaller than the bounded layer set. */\nexport interface ValidationGateFailureDetails {\n readonly parse_code?: string;\n readonly issues?: readonly SanitizedParseIssue[];\n}\n\n/** Successful gate result. */\nexport interface ValidationGateSuccess {\n readonly ok: true;\n readonly parsed?: ValidationGateParsed;\n}\n\n/** Failed gate result. */\nexport interface ValidationGateFailure {\n readonly ok: false;\n readonly code: string;\n readonly message: string;\n readonly details?: ValidationGateFailureDetails;\n}\n\nexport type ValidationGateResult = ValidationGateSuccess | ValidationGateFailure;\n\n/** Inputs to the gate. Only `surface` and `payload` are required. */\nexport interface ValidationGateInput {\n readonly surface: GateSurface;\n /**\n * Full claims object. For surface 'issueWire02' this is the just-\n * constructed `Wire02Claims` cast to a plain record (the same\n * object that today flows through `Wire02ClaimsSchema.safeParse`).\n * For surface 'verifyLocal' this is the decoded JWS payload (the\n * same object that today flows through `validateKernelConstraints`\n * and `parseReceiptClaims`).\n */\n readonly payload: unknown;\n}\n\n/** Maximum sanitized-issue list length surfaced to a verifier report. */\nconst MAX_SANITIZED_ISSUES = 25;\n\nfunction sanitizeIssues(issues: unknown): readonly SanitizedParseIssue[] | undefined {\n if (!Array.isArray(issues)) return undefined;\n return issues.slice(0, MAX_SANITIZED_ISSUES).map((issue) => {\n const candidate = issue as { path?: unknown; message?: unknown };\n const path = Array.isArray(candidate.path)\n ? candidate.path\n .map((segment) =>\n typeof segment === 'string' || typeof segment === 'number' ? String(segment) : ''\n )\n .join('.')\n : '';\n const message =\n typeof candidate.message === 'string'\n ? candidate.message\n : String(candidate.message ?? issue);\n return { path, message };\n });\n}\n\n/**\n * Run the production projection of the bounded validation path.\n *\n * Behavior is byte-equivalent to the inline canonical sequences at\n * `issue.ts` and `verify-local.ts` for every input on the covered\n * runtime matrix. Any cross-branch divergence on JWS bytes, result\n * shape, error code, warning order, thrown error class, success /\n * failure classification, or observable default behavior is a\n * validation-equivalence regression.\n */\nexport function runBoundedValidationGate(input: ValidationGateInput): ValidationGateResult {\n if (input.surface === 'issueWire02') {\n return runIssueWire02(input.payload);\n }\n return runVerifyLocal(input.payload);\n}\n\nfunction runIssueWire02(payload: unknown): ValidationGateResult {\n // Issuance projection mirrors `issue.ts` Wire02ClaimsSchema.safeParse.\n // Today's canonical issuance reports the first Zod issue message in\n // the IssueError details. The gate reproduces that surface here.\n const schemaRes = validateSchemaParseInternal(payload);\n if (!schemaRes.accepted) {\n const firstIssueMessage = schemaRes.errorIssues?.[0]?.message;\n return {\n ok: false,\n code: 'E_INVALID_FORMAT',\n message: `Wire 0.2 claims schema validation failed: ${firstIssueMessage ?? 'unknown'}`,\n };\n }\n return { ok: true };\n}\n\nfunction runVerifyLocal(payload: unknown): ValidationGateResult {\n // Kernel constraints first (canonical-helper delegation preserves\n // the existing `Kernel constraint violated: <constraint>\n // (actual: <actual>, limit: <limit>)` message byte-equally).\n const kernelRes = validateKernelConstraints(payload);\n if (!kernelRes.valid) {\n const v = kernelRes.violations[0];\n return {\n ok: false,\n code: 'E_CONSTRAINT_VIOLATION',\n message: `Kernel constraint violated: ${v.constraint} (actual: ${v.actual}, limit: ${v.limit})`,\n };\n }\n\n // Schema parse next. Surface the canonical\n // `Receipt schema validation failed: <message>` shape with\n // `details: { parse_code, issues }` byte-equally.\n //\n // Wire 0.1 payloads parse successfully under the canonical parser\n // but are rejected at the bounded layer with errorCode\n // 'E_UNSUPPORTED_WIRE_VERSION'. The verify-local canonical surface\n // routes Wire 0.1 to a distinct error code (not E_INVALID_FORMAT)\n // and a distinct message; preserve that branch here.\n const schemaRes = validateSchemaParseInternal(payload);\n if (!schemaRes.accepted) {\n if (schemaRes.errorCode === 'E_UNSUPPORTED_WIRE_VERSION') {\n return {\n ok: 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 }\n const sanitized = sanitizeIssues(schemaRes.errorIssues);\n const details: ValidationGateFailureDetails = {};\n if (schemaRes.errorCode !== undefined) {\n Object.assign(details, { parse_code: schemaRes.errorCode });\n }\n if (sanitized !== undefined) {\n Object.assign(details, { issues: sanitized });\n }\n return {\n ok: false,\n code: 'E_INVALID_FORMAT',\n message: `Receipt schema validation failed: ${schemaRes.errorMessage ?? 'unknown'}`,\n ...(Object.keys(details).length > 0 && { details }),\n };\n }\n\n if (schemaRes.wireVersion !== '0.2' || schemaRes.claims === undefined) {\n return {\n ok: 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 }\n\n return {\n ok: true,\n parsed: {\n wireVersion: '0.2',\n claims: schemaRes.claims,\n parserWarnings: schemaRes.warnings ?? [],\n },\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 * Internal Ed25519 signature-width guard for the verification paths.\n *\n * NOT re-exported from the package barrel (`index.ts` does\n * `export * from './verify'` / `'./verify-local'`, so anything exported from\n * those modules becomes public API). Keep this helper in `_internal` so the\n * guard adds no public surface.\n */\n\nimport { base64urlDecode } from '@peac/crypto';\n\n/** Ed25519 signatures are fixed-width 64 bytes (RFC 8032 / RFC 8709). */\nexport const ED25519_SIGNATURE_BYTES = 64;\n\n/**\n * Return the decoded byte length of a compact JWS signature segment, or `null`\n * when the token is not a well-formed three-part compact JWS or the signature\n * segment is not decodable base64url. Those `null` cases are deliberately left\n * to the existing format/verification error paths (this guard does not change\n * their classification); only a well-formed token whose signature decodes to a\n * non-64-byte width is surfaced to the caller as a wrong-length signature.\n */\nexport function ed25519SignatureByteLength(jws: string): number | null {\n const parts = jws.split('.');\n if (parts.length !== 3) {\n return null;\n }\n try {\n return base64urlDecode(parts[2]).length;\n } catch {\n return null;\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 { runBoundedValidationGate } from './_internal/record-core/validation-gate.js';\nimport { isShadowEnabled, scheduleShadow, type ShadowEnableOptions } from './_internal/shadow.js';\nimport { readLegacyPathFlag, type LegacyPathOptions } from './_internal/legacy-path.js';\nimport { ED25519_SIGNATURE_BYTES, ed25519SignatureByteLength } from './_internal/signature.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 // Raw-input I-JSON gate (RFC 7493): runs on raw header/payload bytes before parse\n | 'E_IJSON_DUPLICATE_MEMBER_NAME'\n | 'E_IJSON_NUMBER_OUT_OF_RANGE'\n | 'E_IJSON_INVALID_STRING'\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 // Raw-input I-JSON gate (RFC 7493): specific E_IJSON_* codes so callers can\n // distinguish duplicate member names, out-of-range numbers, and invalid\n // strings from ordinary format errors. (Generic JSON syntax errors from the\n // gate use CRYPTO_INVALID_JWS_FORMAT -> E_INVALID_FORMAT via FORMAT_ERROR_CODES.)\n CRYPTO_IJSON_DUPLICATE_MEMBER_NAME: 'E_IJSON_DUPLICATE_MEMBER_NAME',\n CRYPTO_IJSON_NUMBER_OUT_OF_RANGE: 'E_IJSON_NUMBER_OUT_OF_RANGE',\n CRYPTO_IJSON_INVALID_STRING: 'E_IJSON_INVALID_STRING',\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. Selects the bounded validation\n // admission gate (default) or the inline canonical sequence\n // (rollback). Both branches share the post-admission flow: caller-\n // option binding, temporal checks, type-extension enforcement,\n // policy-binding compute, bindings construction, sortWarnings.\n const legacyPath = 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. Format errors\n // (bad typ/header/JSON) are thrown as typed CryptoErrors and handled in\n // the catch below (format-first), so the length discrimination here runs\n // only on a well-formed JWS whose signature simply failed to verify.\n const result = await defaultCodec.decode<unknown>(jws, publicKey);\n\n if (!result.valid) {\n // The Ed25519 verifier rejects a wrong-length signature by returning\n // false (it no longer throws); distinguish that specifically from a\n // genuine signature mismatch, matching verifyReceipt() in verify.ts.\n const signatureBytes = ed25519SignatureByteLength(jws);\n const invalidLength = signatureBytes !== null && signatureBytes !== ED25519_SIGNATURE_BYTES;\n return {\n valid: false,\n code: 'E_INVALID_SIGNATURE',\n message: invalidLength\n ? 'Ed25519 signature has invalid length'\n : '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-5. Admission: kernel constraints, schema parse, parser warnings.\n //\n // The default branch routes through the bounded validation gate,\n // which surfaces canonical-equivalent E_CONSTRAINT_VIOLATION /\n // E_INVALID_FORMAT / E_UNSUPPORTED_WIRE_VERSION verdicts on\n // rejection and the parsed Wire 0.2 claims plus parser warnings\n // on acceptance. The rollback branch retains the inline canonical\n // sequence (validateKernelConstraints + parseReceiptClaims). Both\n // branches feed the same post-admission flow.\n type AdmittedClaims = {\n readonly ok: true;\n readonly wireVersion: '0.1' | '0.2';\n readonly warnings: readonly VerificationWarning[];\n readonly claims: unknown;\n };\n let pr: AdmittedClaims;\n\n if (legacyPath) {\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 const parsed = parseReceiptClaims(result.payload);\n if (!parsed.ok) {\n return {\n valid: false,\n code: 'E_INVALID_FORMAT',\n message: `Receipt schema validation failed: ${parsed.error.message}`,\n details: {\n parse_code: parsed.error.code,\n issues: sanitizeParseIssues(parsed.error.issues),\n },\n };\n }\n pr = parsed;\n } else {\n const gateResult = runBoundedValidationGate({\n surface: 'verifyLocal',\n payload: result.payload,\n });\n if (!gateResult.ok) {\n return {\n valid: false,\n code: gateResult.code as VerifyLocalErrorCode,\n message: gateResult.message,\n ...(gateResult.details !== undefined && { details: gateResult.details }),\n };\n }\n const parsedFromGate = gateResult.parsed;\n if (parsedFromGate === undefined) {\n return {\n valid: false,\n code: 'E_INTERNAL',\n message: 'Bounded validation gate accepted without surfacing parsed claims',\n };\n }\n pr = {\n ok: true,\n wireVersion: parsedFromGate.wireVersion,\n warnings: parsedFromGate.parserWarnings,\n claims: parsedFromGate.claims,\n };\n }\n\n // 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 // Shadow scheduling fires only on the rollback branch where the\n // bounded validator is genuinely a comparison path. Under the\n // default branch the gate runs as the production admission\n // path, so a duplicate shadow run would compare the same code\n // path against itself.\n if (legacyPath && 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 // Defense in depth: a wrong-length Ed25519 signature is rejected on the\n // happy path (the verifier returns false and the !result.valid branch above\n // classifies it). Should any verifier error nonetheless reach here, classify\n // a wrong-length signature deterministically as an invalid signature rather\n // than letting it fall through to E_INTERNAL. Typed format errors are\n // handled earlier, so a malformed header/payload still maps to\n // E_INVALID_FORMAT (format-first).\n const signatureBytes = ed25519SignatureByteLength(jws);\n if (signatureBytes !== null && signatureBytes !== ED25519_SIGNATURE_BYTES) {\n return {\n valid: false,\n code: 'E_INVALID_SIGNATURE',\n message: 'Ed25519 signature has invalid length',\n };\n }\n\n // All other errors -> E_INTERNAL\n // No message parsing - code-based mapping only; do not surface raw\n // exception text to callers (avoids leaking internal paths/state).\n return {\n valid: false,\n code: 'E_INTERNAL',\n message: 'Unexpected verification error.',\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"]}
|