@kya-os/checkpoint-shared 1.4.0 → 1.5.0

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