@kya-os/checkpoint-shared 1.4.0 → 1.5.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.
Files changed (161) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/dist/beacon-types/index.d.mts +448 -432
  3. package/dist/beacon-types/index.d.mts.map +1 -0
  4. package/dist/beacon-types/index.d.ts +448 -432
  5. package/dist/beacon-types/index.d.ts.map +1 -0
  6. package/dist/beacon-types/index.js +286 -182
  7. package/dist/beacon-types/index.mjs +284 -180
  8. package/dist/beacon-types/index.mjs.map +1 -0
  9. package/dist/browser-posture-cookie-Dmq9Brf_.d.mts +5 -0
  10. package/dist/browser-posture-cookie-Dmq9Brf_.d.mts.map +1 -0
  11. package/dist/browser-posture-cookie-Dmq9Brf_.d.ts +5 -0
  12. package/dist/browser-posture-cookie-Dmq9Brf_.d.ts.map +1 -0
  13. package/dist/browser-posture-cookie.d.mts +2 -0
  14. package/dist/browser-posture-cookie.d.ts +2 -0
  15. package/dist/browser-posture-cookie.js +1 -0
  16. package/dist/browser-posture-cookie.mjs +2 -0
  17. package/dist/browser-posture-cookie.mjs.map +1 -0
  18. package/dist/browser-posture-report.d.mts +48 -44
  19. package/dist/browser-posture-report.d.mts.map +1 -0
  20. package/dist/browser-posture-report.d.ts +48 -44
  21. package/dist/browser-posture-report.d.ts.map +1 -0
  22. package/dist/browser-posture-report.js +1 -1
  23. package/dist/browser-posture-report.mjs +2 -1
  24. package/dist/browser-posture-report.mjs.map +1 -0
  25. package/dist/browser-posture.d.mts +82 -75
  26. package/dist/browser-posture.d.mts.map +1 -0
  27. package/dist/browser-posture.d.ts +82 -75
  28. package/dist/browser-posture.d.ts.map +1 -0
  29. package/dist/browser-posture.js +167 -18993
  30. package/dist/browser-posture.mjs +166 -18990
  31. package/dist/browser-posture.mjs.map +1 -0
  32. package/dist/browser.d.mts +323 -316
  33. package/dist/browser.d.mts.map +1 -0
  34. package/dist/browser.d.ts +323 -316
  35. package/dist/browser.d.ts.map +1 -0
  36. package/dist/browser.js +1 -1
  37. package/dist/browser.mjs +2 -1
  38. package/dist/browser.mjs.map +1 -0
  39. package/dist/canonical-signer/index.d.mts +38 -33
  40. package/dist/canonical-signer/index.d.mts.map +1 -0
  41. package/dist/canonical-signer/index.d.ts +38 -33
  42. package/dist/canonical-signer/index.d.ts.map +1 -0
  43. package/dist/canonical-signer/index.js +411 -181
  44. package/dist/canonical-signer/index.mjs +383 -175
  45. package/dist/canonical-signer/index.mjs.map +1 -0
  46. package/dist/clearance.d.mts +30 -0
  47. package/dist/clearance.d.mts.map +1 -0
  48. package/dist/clearance.d.ts +30 -0
  49. package/dist/clearance.d.ts.map +1 -0
  50. package/dist/clearance.js +120 -0
  51. package/dist/clearance.mjs +112 -0
  52. package/dist/clearance.mjs.map +1 -0
  53. package/dist/client-ip-1y2iXAYW.js +237 -0
  54. package/dist/client-ip-HOfe6ucV.mjs +215 -0
  55. package/dist/client-ip-HOfe6ucV.mjs.map +1 -0
  56. package/dist/deploy/index.d.mts +339 -339
  57. package/dist/deploy/index.d.mts.map +1 -0
  58. package/dist/deploy/index.d.ts +339 -339
  59. package/dist/deploy/index.d.ts.map +1 -0
  60. package/dist/deploy/index.js +505 -413
  61. package/dist/deploy/index.mjs +504 -410
  62. package/dist/deploy/index.mjs.map +1 -0
  63. package/dist/errors/index.d.mts +101 -101
  64. package/dist/errors/index.d.mts.map +1 -0
  65. package/dist/errors/index.d.ts +101 -101
  66. package/dist/errors/index.d.ts.map +1 -0
  67. package/dist/errors/index.js +341 -314
  68. package/dist/errors/index.mjs +340 -311
  69. package/dist/errors/index.mjs.map +1 -0
  70. package/dist/external-jr_S4iSS.d.mts +4187 -0
  71. package/dist/external-jr_S4iSS.d.mts.map +1 -0
  72. package/dist/external-jr_S4iSS.d.ts +4187 -0
  73. package/dist/external-jr_S4iSS.d.ts.map +1 -0
  74. package/dist/gateway/index.d.mts +138 -132
  75. package/dist/gateway/index.d.mts.map +1 -0
  76. package/dist/gateway/index.d.ts +138 -132
  77. package/dist/gateway/index.d.ts.map +1 -0
  78. package/dist/gateway/index.js +117 -81
  79. package/dist/gateway/index.mjs +116 -78
  80. package/dist/gateway/index.mjs.map +1 -0
  81. package/dist/gateway-client-ip.d.mts +59 -0
  82. package/dist/gateway-client-ip.d.mts.map +1 -0
  83. package/dist/gateway-client-ip.d.ts +59 -0
  84. package/dist/gateway-client-ip.d.ts.map +1 -0
  85. package/dist/gateway-client-ip.js +149 -0
  86. package/dist/gateway-client-ip.mjs +139 -0
  87. package/dist/gateway-client-ip.mjs.map +1 -0
  88. package/dist/index.d.mts +14901 -14246
  89. package/dist/index.d.mts.map +1 -0
  90. package/dist/index.d.ts +14901 -14246
  91. package/dist/index.d.ts.map +1 -0
  92. package/dist/index.js +15180 -31025
  93. package/dist/index.mjs +15065 -30942
  94. package/dist/index.mjs.map +1 -0
  95. package/dist/mcpi/agentshield-api/index.d.mts +45 -44
  96. package/dist/mcpi/agentshield-api/index.d.mts.map +1 -0
  97. package/dist/mcpi/agentshield-api/index.d.ts +45 -44
  98. package/dist/mcpi/agentshield-api/index.d.ts.map +1 -0
  99. package/dist/mcpi/agentshield-api/index.js +0 -2
  100. package/dist/mcpi/agentshield-api/index.mjs +1 -1
  101. package/dist/mcpi/approval-grant/index.d.mts +63 -61
  102. package/dist/mcpi/approval-grant/index.d.mts.map +1 -0
  103. package/dist/mcpi/approval-grant/index.d.ts +63 -61
  104. package/dist/mcpi/approval-grant/index.d.ts.map +1 -0
  105. package/dist/mcpi/approval-grant/index.js +220 -140
  106. package/dist/mcpi/approval-grant/index.mjs +219 -137
  107. package/dist/mcpi/approval-grant/index.mjs.map +1 -0
  108. package/dist/mcpi/dashboard-config/index.d.mts +2323 -2318
  109. package/dist/mcpi/dashboard-config/index.d.mts.map +1 -0
  110. package/dist/mcpi/dashboard-config/index.d.ts +2323 -2318
  111. package/dist/mcpi/dashboard-config/index.d.ts.map +1 -0
  112. package/dist/mcpi/dashboard-config/index.js +605 -458
  113. package/dist/mcpi/dashboard-config/index.mjs +604 -455
  114. package/dist/mcpi/dashboard-config/index.mjs.map +1 -0
  115. package/dist/mcpi/multibase-ed25519.d.mts +10 -8
  116. package/dist/mcpi/multibase-ed25519.d.mts.map +1 -0
  117. package/dist/mcpi/multibase-ed25519.d.ts +10 -8
  118. package/dist/mcpi/multibase-ed25519.d.ts.map +1 -0
  119. package/dist/mcpi/multibase-ed25519.js +182 -106
  120. package/dist/mcpi/multibase-ed25519.mjs +181 -103
  121. package/dist/mcpi/multibase-ed25519.mjs.map +1 -0
  122. package/dist/patterns-CkRVOdtV.js +243 -0
  123. package/dist/patterns-DzkGy_qk.mjs +173 -0
  124. package/dist/patterns-DzkGy_qk.mjs.map +1 -0
  125. package/dist/project-verification-key-C3L5rd8a.js +41 -0
  126. package/dist/project-verification-key-CgSVX9_m.mjs +37 -0
  127. package/dist/project-verification-key-CgSVX9_m.mjs.map +1 -0
  128. package/dist/rolldown-runtime-iY2fYEqi.mjs +19 -0
  129. package/dist/schemas-BmjNLAE7.js +5677 -0
  130. package/dist/schemas-DxY-dk9y.mjs +5511 -0
  131. package/dist/schemas-DxY-dk9y.mjs.map +1 -0
  132. package/dist/signals/index.d.mts +125 -115
  133. package/dist/signals/index.d.mts.map +1 -0
  134. package/dist/signals/index.d.ts +125 -115
  135. package/dist/signals/index.d.ts.map +1 -0
  136. package/dist/signals/index.js +1693 -1536
  137. package/dist/signals/index.mjs +1692 -1533
  138. package/dist/signals/index.mjs.map +1 -0
  139. package/dist/test-fixtures/index.d.mts +124 -119
  140. package/dist/test-fixtures/index.d.mts.map +1 -0
  141. package/dist/test-fixtures/index.d.ts +124 -119
  142. package/dist/test-fixtures/index.d.ts.map +1 -0
  143. package/dist/test-fixtures/index.js +460 -228
  144. package/dist/test-fixtures/index.mjs +459 -225
  145. package/dist/test-fixtures/index.mjs.map +1 -0
  146. package/dist/tool-protection/index.d.mts +343 -343
  147. package/dist/tool-protection/index.d.mts.map +1 -0
  148. package/dist/tool-protection/index.d.ts +343 -343
  149. package/dist/tool-protection/index.d.ts.map +1 -0
  150. package/dist/tool-protection/index.js +366 -285
  151. package/dist/tool-protection/index.mjs +365 -282
  152. package/dist/tool-protection/index.mjs.map +1 -0
  153. package/fixtures/bot-signal-resolution.json +142 -0
  154. package/fixtures/browser-posture-claims.json +421 -0
  155. package/fixtures/browser-posture-headers.json +46 -0
  156. package/fixtures/detection/reason-codes.json +10 -1
  157. package/fixtures/kya-http/challenge.delegation.fetcher-200.json +9 -3
  158. package/fixtures/kya-http/challenge.delegation.full.json +9 -3
  159. package/fixtures/kya-http/challenge.delegation.minimal.json +9 -3
  160. package/fixtures/kya-http/error-codes.json +7 -2
  161. package/package.json +20 -6
@@ -1,204 +1,412 @@
1
- import canonicalize from 'canonicalize';
2
- import { getPublicKeyAsync, signAsync } from '@noble/ed25519';
1
+ import canonicalize from "canonicalize";
2
+ import { getPublicKeyAsync, signAsync } from "@noble/ed25519";
3
3
 
4
- // src/canonical-signer/payload.ts
4
+ //#region src/canonical-signer/payload.ts
5
+ /**
6
+ * Canonical KYA-OS signing payload (RFC 8785 / JCS).
7
+ *
8
+ * TS half of the cross-runtime parity contract pinned in
9
+ * `rust/crates/kya-os-engine/src/signing.rs`. Same `McpIPayload` struct,
10
+ * same JCS canonicalization, byte-identical output. The Rust engine's
11
+ * `signing_payload` golden vector at `tests/fixtures/reference_payload.jcs`
12
+ * is the firewall this module asserts against — if these bytes diverge,
13
+ * every downstream signature verification claim is suspect.
14
+ *
15
+ * Field set is locked to KYA-OS spec § 7.4 (eight required claims) +
16
+ * § 7.2 (ProofMeta). Wire format is camelCase per the KYA-OS JSON schema.
17
+ *
18
+ * Sign-1 (#2500). Do NOT extend without ratification through
19
+ * mcp-i-core → D-design → here.
20
+ *
21
+ * @see rust/crates/kya-os-engine/src/signing.rs — Rust struct + JCS function
22
+ * @see rust/crates/kya-os-engine/tests/fixtures/reference_payload.jcs — golden vector
23
+ */
24
+ /**
25
+ * Canonicalize an `McpIPayload` into the byte sequence the Ed25519
26
+ * signature is computed over.
27
+ *
28
+ * **Determinism contract.** Same input MUST produce byte-identical
29
+ * output, every time, every runtime. This function is the cross-runtime
30
+ * parity contract — TS, .NET, Go, Python, and Rust runtimes all
31
+ * implement it independently and MUST agree on the golden vector
32
+ * pinned at `rust/crates/kya-os-engine/tests/fixtures/reference_payload.jcs`.
33
+ *
34
+ * The output is RFC 8785 (JCS) canonical JSON: keys sorted
35
+ * lexicographically by UTF-16 code units, integers serialized without
36
+ * a decimal point, strings escaped only as required, no whitespace.
37
+ *
38
+ * Implementation note: `canonicalize` (npm) is Erdtman's RFC 8785
39
+ * reference implementation. If a future TS host reaches for a
40
+ * different library, the parity firewall test (`canonical-signer.parity.test.ts`)
41
+ * will catch the byte drift before it reaches production.
42
+ */
5
43
  function canonicalSigningPayload(payload) {
6
- const json = canonicalize(payload);
7
- if (json === void 0) {
8
- throw new Error("canonicalSigningPayload: payload contains non-serializable values");
9
- }
10
- return new TextEncoder().encode(json);
44
+ const json = canonicalize(payload);
45
+ if (json === void 0) throw new Error("canonicalSigningPayload: payload contains non-serializable values");
46
+ return new TextEncoder().encode(json);
11
47
  }
12
- var REQUIRED_STRING_FIELDS = [
13
- "aud",
14
- "iss",
15
- "sub",
16
- "nonce",
17
- "sessionId",
18
- "requestHash",
19
- "responseHash"
48
+ /**
49
+ * Field set that MUST be present for an `McpIPayload` to be valid.
50
+ *
51
+ * Source of truth for `validateMcpIPayload`. The list mirrors the TS
52
+ * `McpIPayload` interface — adding a field there without adding it
53
+ * here is a hidden bypass for the runtime contract. New required
54
+ * fields land in lockstep; new optional fields (post-Scope-1) get
55
+ * a sibling list with a `typeof === 'undefined' || ...` predicate.
56
+ */
57
+ const REQUIRED_STRING_FIELDS = [
58
+ "aud",
59
+ "iss",
60
+ "sub",
61
+ "nonce",
62
+ "sessionId",
63
+ "requestHash",
64
+ "responseHash"
20
65
  ];
66
+ /**
67
+ * Runtime type guard: confirms a `JSON.parse` output actually matches
68
+ * `McpIPayload`. Required because `JSON.parse` returns `unknown`, and
69
+ * casting `as McpIPayload` is a *compile-time* assertion that the
70
+ * runtime can't honor — a payload missing required fields silently
71
+ * surfaces as `undefined` at consumer call-sites and bypasses field-
72
+ * presence checks (e.g., the bouncer's replay-window comparison
73
+ * `meta.ts < now - 300` evaluates `false` for `undefined`, skipping
74
+ * the timestamp defense entirely).
75
+ *
76
+ * Throws on the FIRST missing or wrong-typed field — no error
77
+ * accumulation, since one missing claim is enough to reject the
78
+ * envelope and producers should re-issue the entire proof rather than
79
+ * patch field-by-field.
80
+ *
81
+ * @throws Error with a descriptive message identifying the offending
82
+ * field. `parseJwsCompact` translates this into a structured
83
+ * `JwsParseError('InvalidPayloadShape', ...)` for consumers branching
84
+ * on the discriminant.
85
+ */
21
86
  function validateMcpIPayload(value) {
22
- if (value === null || typeof value !== "object") {
23
- throw new Error(`expected JSON object, got ${value === null ? "null" : typeof value}`);
24
- }
25
- const obj = value;
26
- for (const field of REQUIRED_STRING_FIELDS) {
27
- if (typeof obj[field] !== "string") {
28
- throw new Error(`missing or non-string required field "${field}" (got ${typeof obj[field]})`);
29
- }
30
- }
31
- if (typeof obj.ts !== "number" || !Number.isFinite(obj.ts)) {
32
- throw new Error(`missing or non-finite-number required field "ts" (got ${typeof obj.ts})`);
33
- }
34
- return obj;
87
+ if (value === null || typeof value !== "object") throw new Error(`expected JSON object, got ${value === null ? "null" : typeof value}`);
88
+ const obj = value;
89
+ for (const field of REQUIRED_STRING_FIELDS) if (typeof obj[field] !== "string") throw new Error(`missing or non-string required field "${field}" (got ${typeof obj[field]})`);
90
+ if (typeof obj.ts !== "number" || !Number.isFinite(obj.ts)) throw new Error(`missing or non-finite-number required field "ts" (got ${typeof obj.ts})`);
91
+ return obj;
35
92
  }
36
93
 
37
- // src/mcpi/did-key.ts
38
- var BASE58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
94
+ //#endregion
95
+ //#region src/mcpi/did-key.ts
96
+ /**
97
+ * did:key (Ed25519 multikey) codec — draft-kya-http-02 / H1.2 (#3245).
98
+ *
99
+ * Format: `did:key:z<base58btc(0xed 0x01 || pubkey32)>`
100
+ * The multicodec prefix `0xed 0x01` identifies `ed25519-pub`; the multibase
101
+ * prefix `z` identifies base58btc. An Ed25519 public key is always 32 bytes,
102
+ * so the decoded multikey is always 34 bytes and the did:key always begins
103
+ * `z6Mk` (a fixed consequence of the `0xed01` prefix).
104
+ *
105
+ * This is a PURE-JS port of the base58btc decoder in
106
+ * `apps/web/workers/gateway/src/detection/did-verifier.ts` (repeated-division
107
+ * algorithm), lifted here so the H1.2 pickup endpoint — and future H2.x TS
108
+ * PEPs — can recover the raw key for `node:crypto` Ed25519 verification with
109
+ * zero crypto/runtime dependencies (it runs identically in Node, Cloudflare
110
+ * Workers, and the browser). The encoder is the inverse, for tests and any
111
+ * caller that emits a `did:key` from raw key bytes.
112
+ */
113
+ const BASE58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
114
+ const BASE58_INDEX = (() => {
115
+ const idx = {};
116
+ for (let i = 0; i < 58; i++) idx[BASE58_ALPHABET[i]] = i;
117
+ return idx;
118
+ })();
119
+ const ED25519_MULTICODEC = [237, 1];
120
+ const ED25519_PUBKEY_LENGTH = 32;
121
+ const ED25519_MULTIKEY_LENGTH = ED25519_MULTICODEC.length + ED25519_PUBKEY_LENGTH;
122
+ /**
123
+ * Encode bytes to a base58btc string — the exact inverse of
124
+ * {@link base58btcDecode}. Leading zero bytes map to leading `1`s; the value
125
+ * is accumulated as little-endian base58 digits (×256 + byte) and emitted
126
+ * big-endian. The high-order zero sentinel is dropped the same way the decoder
127
+ * drops its trailing zeros, so a single `0x00` byte encodes to `"1"`, not `"11"`.
128
+ */
39
129
  function base58btcEncode(bytes) {
40
- if (bytes.length === 0) return "";
41
- let zeros = 0;
42
- while (zeros < bytes.length && bytes[zeros] === 0) zeros++;
43
- const digits = [0];
44
- for (let i = 0; i < bytes.length; i++) {
45
- let carry = bytes[i];
46
- for (let j = 0; j < digits.length; j++) {
47
- carry += digits[j] * 256;
48
- digits[j] = carry % 58;
49
- carry = Math.floor(carry / 58);
50
- }
51
- while (carry > 0) {
52
- digits.push(carry % 58);
53
- carry = Math.floor(carry / 58);
54
- }
55
- }
56
- let high = digits.length;
57
- while (high > 0 && digits[high - 1] === 0) high--;
58
- let out = BASE58_ALPHABET[0].repeat(zeros);
59
- for (let i = high - 1; i >= 0; i--) {
60
- out += BASE58_ALPHABET[digits[i]];
61
- }
62
- return out;
130
+ if (bytes.length === 0) return "";
131
+ let zeros = 0;
132
+ while (zeros < bytes.length && bytes[zeros] === 0) zeros++;
133
+ const digits = [0];
134
+ for (let i = 0; i < bytes.length; i++) {
135
+ let carry = bytes[i];
136
+ for (let j = 0; j < digits.length; j++) {
137
+ carry += digits[j] * 256;
138
+ digits[j] = carry % 58;
139
+ carry = Math.floor(carry / 58);
140
+ }
141
+ while (carry > 0) {
142
+ digits.push(carry % 58);
143
+ carry = Math.floor(carry / 58);
144
+ }
145
+ }
146
+ let high = digits.length;
147
+ while (high > 0 && digits[high - 1] === 0) high--;
148
+ let out = BASE58_ALPHABET[0].repeat(zeros);
149
+ for (let i = high - 1; i >= 0; i--) out += BASE58_ALPHABET[digits[i]];
150
+ return out;
63
151
  }
64
152
 
65
- // src/canonical-signer/key.ts
66
- var ED25519_MULTICODEC_PREFIX = new Uint8Array([237, 1]);
153
+ //#endregion
154
+ //#region src/canonical-signer/key.ts
155
+ /**
156
+ * Ed25519 keypair derivation for KYA-OS detached proofs.
157
+ *
158
+ * Derives a `KeyMaterial` bundle (signing key, public key, did:key, kid)
159
+ * from a 32-byte seed. The derivation MUST agree byte-for-byte with
160
+ * Rust's `ed25519_dalek::SigningKey::from_bytes` + did:key formatter so
161
+ * H-1's committed test fixtures (`signer.seed` + `signer.public_key`)
162
+ * derive identically across runtimes.
163
+ *
164
+ * `kid` form follows mcp-i-core PR #16 (multibase-as-fragment):
165
+ * `did:key:z6Mk...#z6Mk...`. NOT `#keys-1`. NOT `#1`. The H-1
166
+ * `stage2_did_key_fragment_resolution` test pins this on the verifier
167
+ * side; this module pins it on the producer side.
168
+ *
169
+ * Sign-1 (#2500).
170
+ */
171
+ /**
172
+ * Multicodec prefix for Ed25519 verifying keys per the W3C did:key spec
173
+ * (`0xed01` varint). Prepended to the 32-byte public key, base58btc-
174
+ * encoded with the `z` multibase prefix to produce the did:key suffix.
175
+ */
176
+ const ED25519_MULTICODEC_PREFIX = new Uint8Array([237, 1]);
177
+ /**
178
+ * Derive a `KeyMaterial` bundle from a 32-byte Ed25519 seed.
179
+ *
180
+ * The seed IS the signing key (per RFC 8032 § 5.1.5 — Ed25519 secret
181
+ * keys are 32-byte seeds; the expanded scalar is computed at sign time).
182
+ * Same seed → same `(publicKey, did, kid)` deterministically across
183
+ * any RFC 8032 implementation.
184
+ *
185
+ * The input seed is **defensively copied** into the returned
186
+ * `KeyMaterial.signingKey`. Subsequent mutations of the caller's
187
+ * buffer (zeroization, key rotation, fixture reuse) do NOT affect
188
+ * the key bundle. Callers that own the seed are free to scrub it
189
+ * after this function returns.
190
+ *
191
+ * @throws if the seed is not exactly 32 bytes.
192
+ */
67
193
  async function parseSigningKey(seed) {
68
- if (seed.length !== 32) {
69
- throw new Error(`parseSigningKey: expected 32-byte Ed25519 seed, got ${seed.length} bytes`);
70
- }
71
- const publicKey = await getPublicKeyAsync(seed);
72
- const multibaseBytes = new Uint8Array(ED25519_MULTICODEC_PREFIX.length + publicKey.length);
73
- multibaseBytes.set(ED25519_MULTICODEC_PREFIX, 0);
74
- multibaseBytes.set(publicKey, ED25519_MULTICODEC_PREFIX.length);
75
- const multibase = `z${base58btcEncode(multibaseBytes)}`;
76
- const did = `did:key:${multibase}`;
77
- return {
78
- // Defensive copy — see KeyMaterial.signingKey docstring. The Sign-1
79
- // tests assert that mutating the input seed after this call does NOT
80
- // mutate the held key material.
81
- signingKey: Uint8Array.from(seed),
82
- publicKey,
83
- did,
84
- // mcp-i-core PR #16: the verification-method id is the multibase value
85
- // as a fragment. Anything else (`#keys-1`, `#1`, etc.) breaks H-1's
86
- // stage2_did_key_fragment_resolution.
87
- kid: `${did}#${multibase}`
88
- };
194
+ if (seed.length !== 32) throw new Error(`parseSigningKey: expected 32-byte Ed25519 seed, got ${seed.length} bytes`);
195
+ const publicKey = await getPublicKeyAsync(seed);
196
+ const multibaseBytes = new Uint8Array(ED25519_MULTICODEC_PREFIX.length + publicKey.length);
197
+ multibaseBytes.set(ED25519_MULTICODEC_PREFIX, 0);
198
+ multibaseBytes.set(publicKey, ED25519_MULTICODEC_PREFIX.length);
199
+ const multibase = `z${base58btcEncode(multibaseBytes)}`;
200
+ const did = `did:key:${multibase}`;
201
+ return {
202
+ signingKey: Uint8Array.from(seed),
203
+ publicKey,
204
+ did,
205
+ kid: `${did}#${multibase}`
206
+ };
89
207
  }
208
+
209
+ //#endregion
210
+ //#region src/canonical-signer/envelope.ts
211
+ /**
212
+ * JWS-compact envelope construction for KYA-OS detached proofs.
213
+ *
214
+ * Produces wire bytes the engine's H-1 parser (#2486) accepts:
215
+ *
216
+ * BASE64URL(header) "." BASE64URL(payload) "." BASE64URL(signature)
217
+ *
218
+ * where the header is `{ "alg": "EdDSA", "kid": "<verification-method-id>" }`,
219
+ * the payload is the JCS-canonicalized `McpIPayload`, and the signature is
220
+ * Ed25519 over `BASE64URL(header) || '.' || BASE64URL(payload)` per
221
+ * RFC 7515 § 5.1.
222
+ *
223
+ * Sign-1 (#2500). Output of this function is what every TS producer in the
224
+ * org emits — bouncer middleware (Envelope-1), Sites-1/2 e2e helpers, future
225
+ * Sites-4 parity drivers, the Adobe trial.
226
+ */
227
+ /**
228
+ * URL-safe base64 encoding without padding (RFC 4648 § 5).
229
+ *
230
+ * **Node-only.** Uses Node's `Buffer` API because every current consumer
231
+ * of this module runs on Node (Vercel functions, Sites-1/2 Playwright
232
+ * suites, future SDKs that bundle for Node + bundler-polyfilled runtimes
233
+ * like Vercel Edge with `nodejs_compat`). If a future consumer needs a
234
+ * pure-Web-API runtime (Cloudflare Workers without `nodejs_compat`,
235
+ * Deno's stricter modes), swap to `Uint8Array.toBase64()` (Stage 4 as
236
+ * of mid-2026) or a small inline encoder — but verify against the
237
+ * envelope.test.ts round-trip first; the `base64url` character
238
+ * substitution path is the part that has historically tripped polyfills.
239
+ */
90
240
  function base64UrlEncode(bytes) {
91
- return Buffer.from(bytes).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
241
+ return Buffer.from(bytes).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
92
242
  }
243
+ /**
244
+ * Sign an `McpIPayload` and produce a compact-JWS envelope ready to drop
245
+ * into `_meta.proof.jws` of the request body per KYA-OS spec § 7.4.
246
+ *
247
+ * The signing input is `BASE64URL(header) || '.' || BASE64URL(payload)`,
248
+ * NOT the canonical-JSON bytes. The canonicalization happens *inside* the
249
+ * payload base64url segment; the Ed25519 signature happens *over* the dot-
250
+ * separated structure. This is the RFC 7515 § 5.1 contract that H-1's
251
+ * `verify_strict` checks against.
252
+ *
253
+ * @param payload — the structured KYA-OS claims (eight required fields).
254
+ * @param key — derived via `parseSigningKey(seed)`. The header `kid` is
255
+ * set from `key.kid` (multibase-as-fragment per mcp-i-core PR #16).
256
+ * @returns the compact-JWS string `<headerB64>.<payloadB64>.<signatureB64>`.
257
+ */
93
258
  async function signMcpiEnvelope(payload, key) {
94
- const header = { alg: "EdDSA", kid: key.kid };
95
- const headerJson = JSON.stringify(header);
96
- const headerB64 = base64UrlEncode(new TextEncoder().encode(headerJson));
97
- const payloadB64 = base64UrlEncode(canonicalSigningPayload(payload));
98
- const signingInput = new TextEncoder().encode(`${headerB64}.${payloadB64}`);
99
- const signature = await signAsync(signingInput, key.signingKey);
100
- const signatureB64 = base64UrlEncode(signature);
101
- return `${headerB64}.${payloadB64}.${signatureB64}`;
259
+ const header = {
260
+ alg: "EdDSA",
261
+ kid: key.kid
262
+ };
263
+ const headerJson = JSON.stringify(header);
264
+ const headerB64 = base64UrlEncode(new TextEncoder().encode(headerJson));
265
+ const payloadB64 = base64UrlEncode(canonicalSigningPayload(payload));
266
+ const signingInput = new TextEncoder().encode(`${headerB64}.${payloadB64}`);
267
+ return `${headerB64}.${payloadB64}.${base64UrlEncode(await signAsync(signingInput, key.signingKey))}`;
102
268
  }
103
269
 
104
- // src/canonical-signer/parse.ts
270
+ //#endregion
271
+ //#region src/canonical-signer/parse.ts
272
+ /**
273
+ * Discriminated error type so consumers can map parse failures to
274
+ * appropriate response codes (400 for malformed shape, 422 for
275
+ * unsupported alg) without string-matching error messages.
276
+ */
105
277
  var JwsParseError = class extends Error {
106
- constructor(code, message) {
107
- super(message);
108
- this.code = code;
109
- this.name = "JwsParseError";
110
- }
278
+ code;
279
+ constructor(code, message) {
280
+ super(message);
281
+ this.code = code;
282
+ this.name = "JwsParseError";
283
+ }
111
284
  };
285
+ /**
286
+ * Runtime type guard for the JWS Protected Header (RFC 7515 § 4).
287
+ *
288
+ * Mirror of `validateMcpIPayload` for the header side of the envelope.
289
+ * Cursor-bot review on PR #2546 caught two classes of bug the unguarded
290
+ * `JSON.parse → cast` flow let through:
291
+ *
292
+ * 1. **Missing `kid`** — header parses, `header.kid === undefined`
293
+ * typed as string, propagates into the bouncer's sidecar and gets
294
+ * dropped by JSON.stringify → malformed payload at the remote.
295
+ * 2. **Null JSON header** (`bnVsbA` base64url) — `JSON.parse` returns
296
+ * `null`, `header.alg` access throws TypeError, escapes the
297
+ * bouncer's `instanceof JwsParseError` guard → leaks as 500. Easy
298
+ * DoS/probe vector.
299
+ *
300
+ * Both go away by validating before any property access. Throws plain
301
+ * Error; `parseJwsCompact` translates into `JwsParseError('InvalidHeaderShape', …)`.
302
+ *
303
+ * Returns `ValidatedJwsHeaderShape` with `alg: string` (not `'EdDSA'`).
304
+ * The literal-type narrowing is the caller's responsibility — keeping
305
+ * the failure-category boundary clean: shape failures from this
306
+ * validator surface as `InvalidHeaderShape`; algorithm-support failures
307
+ * surface separately as `UnsupportedAlgorithm`.
308
+ */
112
309
  function validateJwsHeader(value) {
113
- if (value === null || typeof value !== "object") {
114
- throw new Error(`expected JSON object, got ${value === null ? "null" : typeof value}`);
115
- }
116
- const obj = value;
117
- if (typeof obj.alg !== "string" || obj.alg.length === 0) {
118
- throw new Error(`missing or non-string required field "alg" (got ${typeof obj.alg})`);
119
- }
120
- if (typeof obj.kid !== "string" || obj.kid.length === 0) {
121
- throw new Error(`missing or non-string required field "kid" (got ${typeof obj.kid})`);
122
- }
123
- if (obj.typ !== void 0 && typeof obj.typ !== "string") {
124
- throw new Error(`optional field "typ" must be a string when present (got ${typeof obj.typ})`);
125
- }
126
- return obj;
310
+ if (value === null || typeof value !== "object") throw new Error(`expected JSON object, got ${value === null ? "null" : typeof value}`);
311
+ const obj = value;
312
+ if (typeof obj.alg !== "string" || obj.alg.length === 0) throw new Error(`missing or non-string required field "alg" (got ${typeof obj.alg})`);
313
+ if (typeof obj.kid !== "string" || obj.kid.length === 0) throw new Error(`missing or non-string required field "kid" (got ${typeof obj.kid})`);
314
+ if (obj.typ !== void 0 && typeof obj.typ !== "string") throw new Error(`optional field "typ" must be a string when present (got ${typeof obj.typ})`);
315
+ return obj;
127
316
  }
317
+ /**
318
+ * Parse a compact-JWS string per RFC 7515 § 3.1 + § 5.1.
319
+ *
320
+ * Three segments separated by `.`, each base64url-encoded
321
+ * (`A-Za-z0-9-_`, no padding). Header is JSON with at minimum
322
+ * `alg: "EdDSA"` + `kid`. Payload is the JCS-canonicalized
323
+ * `McpIPayload`. Signature segment decodes to exactly 64 bytes
324
+ * (Ed25519 fixed-length per RFC 8032 § 5.1.6).
325
+ *
326
+ * @throws {@link JwsParseError} with a structured `code` for malformed
327
+ * shape, invalid base64url, invalid JSON, unsupported algorithm, or
328
+ * wrong signature length. Cryptographic verification is OUT of scope
329
+ * — the engine (or `@noble/ed25519` round-trip) does that against
330
+ * `signatureBytes` over `signingInput`.
331
+ */
128
332
  function parseJwsCompact(jws) {
129
- const parts = jws.split(".");
130
- if (parts.length !== 3) {
131
- throw new JwsParseError(
132
- "WrongSegmentCount",
133
- `Expected 3 dot-separated segments per RFC 7515 \xA7 3.1; got ${parts.length}`
134
- );
135
- }
136
- const [headerB64, payloadB64, signatureB64] = parts;
137
- let headerJson;
138
- try {
139
- headerJson = JSON.parse(base64UrlDecodeToString(headerB64));
140
- } catch (cause) {
141
- throw new JwsParseError("InvalidJson", `JWS header is not valid JSON: ${String(cause)}`);
142
- }
143
- let validatedHeader;
144
- try {
145
- validatedHeader = validateJwsHeader(headerJson);
146
- } catch (cause) {
147
- throw new JwsParseError(
148
- "InvalidHeaderShape",
149
- `JWS header does not match expected shape: ${cause.message}`
150
- );
151
- }
152
- if (validatedHeader.alg !== "EdDSA") {
153
- throw new JwsParseError(
154
- "UnsupportedAlgorithm",
155
- `Unsupported JWS alg "${validatedHeader.alg}"; Phase 1 only supports EdDSA`
156
- );
157
- }
158
- const header = {
159
- alg: "EdDSA",
160
- kid: validatedHeader.kid,
161
- ...validatedHeader.typ !== void 0 ? { typ: validatedHeader.typ } : {}
162
- };
163
- let payloadJson;
164
- try {
165
- payloadJson = JSON.parse(base64UrlDecodeToString(payloadB64));
166
- } catch (cause) {
167
- throw new JwsParseError("InvalidJson", `JWS payload is not valid JSON: ${String(cause)}`);
168
- }
169
- let payload;
170
- try {
171
- payload = validateMcpIPayload(payloadJson);
172
- } catch (cause) {
173
- throw new JwsParseError(
174
- "InvalidPayloadShape",
175
- `JWS payload does not match McpIPayload shape: ${cause.message}`
176
- );
177
- }
178
- if (!BASE64URL_ALPHABET.test(signatureB64)) {
179
- throw new JwsParseError(
180
- "InvalidBase64",
181
- `JWS signature segment contains characters outside the base64url alphabet (RFC 4648 \xA7 5)`
182
- );
183
- }
184
- const signatureBytes = base64UrlDecodeToBytes(signatureB64);
185
- if (signatureBytes.length !== 64) {
186
- throw new JwsParseError(
187
- "InvalidSignatureLength",
188
- `Ed25519 signatures are 64 bytes (RFC 8032 \xA7 5.1.6); got ${signatureBytes.length}`
189
- );
190
- }
191
- const signingInput = new TextEncoder().encode(`${headerB64}.${payloadB64}`);
192
- return { header, payload, signatureBytes, signingInput };
333
+ const parts = jws.split(".");
334
+ if (parts.length !== 3) throw new JwsParseError("WrongSegmentCount", `Expected 3 dot-separated segments per RFC 7515 § 3.1; got ${parts.length}`);
335
+ const [headerB64, payloadB64, signatureB64] = parts;
336
+ let headerJson;
337
+ try {
338
+ headerJson = JSON.parse(base64UrlDecodeToString(headerB64));
339
+ } catch (cause) {
340
+ throw new JwsParseError("InvalidJson", `JWS header is not valid JSON: ${String(cause)}`);
341
+ }
342
+ let validatedHeader;
343
+ try {
344
+ validatedHeader = validateJwsHeader(headerJson);
345
+ } catch (cause) {
346
+ throw new JwsParseError("InvalidHeaderShape", `JWS header does not match expected shape: ${cause.message}`);
347
+ }
348
+ if (validatedHeader.alg !== "EdDSA") throw new JwsParseError("UnsupportedAlgorithm", `Unsupported JWS alg "${validatedHeader.alg}"; Phase 1 only supports EdDSA`);
349
+ const header = {
350
+ alg: "EdDSA",
351
+ kid: validatedHeader.kid,
352
+ ...validatedHeader.typ !== void 0 ? { typ: validatedHeader.typ } : {}
353
+ };
354
+ let payloadJson;
355
+ try {
356
+ payloadJson = JSON.parse(base64UrlDecodeToString(payloadB64));
357
+ } catch (cause) {
358
+ throw new JwsParseError("InvalidJson", `JWS payload is not valid JSON: ${String(cause)}`);
359
+ }
360
+ let payload;
361
+ try {
362
+ payload = validateMcpIPayload(payloadJson);
363
+ } catch (cause) {
364
+ throw new JwsParseError("InvalidPayloadShape", `JWS payload does not match McpIPayload shape: ${cause.message}`);
365
+ }
366
+ if (!BASE64URL_ALPHABET.test(signatureB64)) throw new JwsParseError("InvalidBase64", `JWS signature segment contains characters outside the base64url alphabet (RFC 4648 § 5)`);
367
+ const signatureBytes = base64UrlDecodeToBytes(signatureB64);
368
+ if (signatureBytes.length !== 64) throw new JwsParseError("InvalidSignatureLength", `Ed25519 signatures are 64 bytes (RFC 8032 § 5.1.6); got ${signatureBytes.length}`);
369
+ const signingInput = new TextEncoder().encode(`${headerB64}.${payloadB64}`);
370
+ return {
371
+ header,
372
+ payload,
373
+ signatureBytes,
374
+ signingInput
375
+ };
193
376
  }
194
- var BASE64URL_ALPHABET = /^[A-Za-z0-9_-]+=*$/;
377
+ /**
378
+ * Strict base64url alphabet check (RFC 4648 § 5). The set is
379
+ * `A-Za-z0-9-_` plus optional `=` padding. We use this to validate
380
+ * input BEFORE handing to Node's `Buffer.from(s, 'base64')`, which
381
+ * silently drops invalid characters rather than throwing — bypassing
382
+ * the discriminated `InvalidBase64` error code consumers rely on for
383
+ * HTTP-status mapping.
384
+ *
385
+ * The empty-string case is rejected by the regex (`+` requires ≥1
386
+ * char), which is the desired behavior — an empty segment is a
387
+ * different bug class from "non-base64 characters in a non-empty
388
+ * segment" but both warrant the same `InvalidBase64` response.
389
+ */
390
+ const BASE64URL_ALPHABET = /^[A-Za-z0-9_-]+=*$/;
391
+ /**
392
+ * Decode URL-safe base64 (with optional padding) to bytes. RFC 4648 § 5.
393
+ * Tolerates the no-padding form Sign-1 produces AND the padded form
394
+ * some external producers emit.
395
+ *
396
+ * **Caller must validate the input alphabet first** if they want
397
+ * `InvalidBase64` reported as a distinct error class — Node's underlying
398
+ * `Buffer.from(s, 'base64')` silently truncates on invalid characters
399
+ * rather than throwing.
400
+ */
195
401
  function base64UrlDecodeToBytes(s) {
196
- const padded = s.replace(/-/g, "+").replace(/_/g, "/");
197
- const padLen = padded.length % 4 === 0 ? 0 : 4 - padded.length % 4;
198
- return new Uint8Array(Buffer.from(padded + "=".repeat(padLen), "base64"));
402
+ const padded = s.replace(/-/g, "+").replace(/_/g, "/");
403
+ const padLen = padded.length % 4 === 0 ? 0 : 4 - padded.length % 4;
404
+ return new Uint8Array(Buffer.from(padded + "=".repeat(padLen), "base64"));
199
405
  }
200
406
  function base64UrlDecodeToString(s) {
201
- return Buffer.from(base64UrlDecodeToBytes(s)).toString("utf-8");
407
+ return Buffer.from(base64UrlDecodeToBytes(s)).toString("utf-8");
202
408
  }
203
409
 
410
+ //#endregion
204
411
  export { JwsParseError, canonicalSigningPayload, parseJwsCompact, parseSigningKey, signMcpiEnvelope, validateMcpIPayload };
412
+ //# sourceMappingURL=index.mjs.map