@kya-os/checkpoint-shared 1.5.2 → 1.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +98 -1
- package/dist/beacon-types/index.d.mts +12 -1
- package/dist/beacon-types/index.d.mts.map +1 -1
- package/dist/beacon-types/index.d.ts +12 -1
- package/dist/beacon-types/index.d.ts.map +1 -1
- package/dist/beacon-types/index.js +18 -1
- package/dist/beacon-types/index.mjs +18 -2
- package/dist/beacon-types/index.mjs.map +1 -1
- package/dist/{browser-posture-D4j2a5gi.d.ts → browser-posture-B8YiPa5c.d.ts} +6 -6
- package/dist/{browser-posture-D4j2a5gi.d.ts.map → browser-posture-B8YiPa5c.d.ts.map} +1 -1
- package/dist/{browser-posture-DVoHMHjY.d.mts → browser-posture-BLhw-MON.d.mts} +6 -6
- package/dist/{browser-posture-DVoHMHjY.d.mts.map → browser-posture-BLhw-MON.d.mts.map} +1 -1
- package/dist/browser-posture-cookie.js +1 -1
- package/dist/browser-posture-cookie.mjs +1 -1
- package/dist/browser-posture-cookie.mjs.map +1 -1
- package/dist/browser-posture-proof.d.mts +2 -2
- package/dist/browser-posture-proof.d.mts.map +1 -1
- package/dist/browser-posture-proof.d.ts +2 -2
- package/dist/browser-posture-proof.d.ts.map +1 -1
- package/dist/browser-posture-proof.js +43 -2
- package/dist/browser-posture-proof.mjs +43 -2
- package/dist/browser-posture-proof.mjs.map +1 -1
- package/dist/browser-posture.d.mts +1 -1
- package/dist/browser-posture.d.ts +1 -1
- package/dist/browser-posture.js +3 -3
- package/dist/browser-posture.mjs +3 -3
- package/dist/browser-posture.mjs.map +1 -1
- package/dist/canonical-signer/index.d.mts.map +1 -1
- package/dist/canonical-signer/index.d.ts.map +1 -1
- package/dist/canonical-signer/index.js +86 -51
- package/dist/canonical-signer/index.mjs +86 -51
- package/dist/canonical-signer/index.mjs.map +1 -1
- package/dist/clearance.d.mts +1 -1
- package/dist/clearance.d.ts +1 -1
- package/dist/clearance.js +2 -2
- package/dist/clearance.mjs +2 -2
- package/dist/client-ip-DFamiNoz.d.mts +34 -0
- package/dist/client-ip-DFamiNoz.d.mts.map +1 -0
- package/dist/client-ip-DFamiNoz.d.ts +34 -0
- package/dist/client-ip-DFamiNoz.d.ts.map +1 -0
- package/dist/client-ip.d.mts +2 -0
- package/dist/client-ip.d.ts +2 -0
- package/dist/client-ip.js +7 -0
- package/dist/client-ip.mjs +3 -0
- package/dist/errors/index.d.mts +17 -0
- package/dist/errors/index.d.mts.map +1 -1
- package/dist/errors/index.d.ts +17 -0
- package/dist/errors/index.d.ts.map +1 -1
- package/dist/errors/index.js +75 -3
- package/dist/errors/index.mjs +75 -3
- package/dist/errors/index.mjs.map +1 -1
- package/dist/{external-Ct8j_hto.d.ts → external-B7WI9FyQ.d.mts} +2 -2
- package/dist/{external-Ct8j_hto.d.mts.map → external-B7WI9FyQ.d.mts.map} +1 -1
- package/dist/{external-Ct8j_hto.d.mts → external-B7WI9FyQ.d.ts} +2 -2
- package/dist/{external-Ct8j_hto.d.ts.map → external-B7WI9FyQ.d.ts.map} +1 -1
- package/dist/gateway-client-ip.d.mts +1 -1
- package/dist/gateway-client-ip.d.ts +1 -1
- package/dist/gateway-client-ip.js +1 -1
- package/dist/gateway-client-ip.mjs +1 -1
- package/dist/host-adapter/index.d.mts +2 -0
- package/dist/host-adapter/index.d.ts +2 -0
- package/dist/host-adapter/index.js +23 -0
- package/dist/host-adapter/index.mjs +3 -0
- package/dist/host-adapter-C-4IxmqM.mjs +540 -0
- package/dist/host-adapter-C-4IxmqM.mjs.map +1 -0
- package/dist/host-adapter-CwW9YB0U.js +694 -0
- package/dist/index-B7rTovHa.d.mts +707 -0
- package/dist/index-B7rTovHa.d.mts.map +1 -0
- package/dist/index-HaqfPtaL.d.ts +707 -0
- package/dist/index-HaqfPtaL.d.ts.map +1 -0
- package/dist/index.d.mts +742 -937
- package/dist/index.d.mts.map +1 -1
- package/dist/index.d.ts +742 -937
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +758 -1193
- package/dist/index.mjs +659 -1148
- package/dist/index.mjs.map +1 -1
- package/dist/kya-http-error-codes-7ewV5RuK.d.mts +29 -0
- package/dist/kya-http-error-codes-7ewV5RuK.d.mts.map +1 -0
- package/dist/kya-http-error-codes-7ewV5RuK.d.ts +29 -0
- package/dist/kya-http-error-codes-7ewV5RuK.d.ts.map +1 -0
- package/dist/kya-http-error-codes-C2JiWPsi.mjs +73 -0
- package/dist/kya-http-error-codes-C2JiWPsi.mjs.map +1 -0
- package/dist/kya-http-error-codes-UYb1zpGM.js +83 -0
- package/dist/kya-http.d.mts +3 -0
- package/dist/kya-http.d.ts +3 -0
- package/dist/kya-http.js +11 -0
- package/dist/kya-http.mjs +4 -0
- package/dist/mcpi/approval-grant/index.d.mts.map +1 -1
- package/dist/mcpi/approval-grant/index.d.ts.map +1 -1
- package/dist/mcpi/approval-grant/index.js +10 -1
- package/dist/mcpi/approval-grant/index.mjs +10 -1
- package/dist/mcpi/approval-grant/index.mjs.map +1 -1
- package/dist/mcpi/dashboard-config/index.d.mts +3 -2
- package/dist/mcpi/dashboard-config/index.d.mts.map +1 -1
- package/dist/mcpi/dashboard-config/index.d.ts +3 -2
- package/dist/mcpi/dashboard-config/index.d.ts.map +1 -1
- package/dist/policy/enforcement.d.mts +2 -0
- package/dist/policy/enforcement.d.ts +2 -0
- package/dist/policy/enforcement.js +15 -0
- package/dist/policy/enforcement.mjs +3 -0
- package/dist/{posture-origins-Dl7i8j93.mjs → posture-origins-Ba83O0cD.mjs} +3 -3
- package/dist/posture-origins-Ba83O0cD.mjs.map +1 -0
- package/dist/{posture-origins-CEm83u4D.js → posture-origins-CdVOdiMT.js} +7 -1
- package/dist/{project-verification-key-CgSVX9_m.mjs → project-verification-key-66N4edKn.mjs} +2 -2
- package/dist/{project-verification-key-CgSVX9_m.mjs.map → project-verification-key-66N4edKn.mjs.map} +1 -1
- package/dist/{project-verification-key-C3L5rd8a.js → project-verification-key-BccT12tQ.js} +1 -1
- package/dist/registered-sid-D3g-gZQF.d.mts +11 -0
- package/dist/registered-sid-D3g-gZQF.d.mts.map +1 -0
- package/dist/registered-sid-D3g-gZQF.d.ts +11 -0
- package/dist/registered-sid-D3g-gZQF.d.ts.map +1 -0
- package/dist/registered-sid-eLCNZvIF.js +170 -0
- package/dist/registered-sid-hUl-bvM5.mjs +142 -0
- package/dist/registered-sid-hUl-bvM5.mjs.map +1 -0
- package/dist/{schemas-DxY-dk9y.mjs → schemas-7qodsG-Z.mjs} +49 -2
- package/dist/schemas-7qodsG-Z.mjs.map +1 -0
- package/dist/{schemas-BmjNLAE7.js → schemas-YhagYDx_.js} +59 -0
- package/dist/step-up-BjP--hG-.d.mts +114 -0
- package/dist/step-up-BjP--hG-.d.mts.map +1 -0
- package/dist/step-up-BjP--hG-.d.ts +114 -0
- package/dist/step-up-BjP--hG-.d.ts.map +1 -0
- package/dist/step-up-C2d8C20x.js +1697 -0
- package/dist/step-up-COlmWJN8.mjs +1513 -0
- package/dist/step-up-COlmWJN8.mjs.map +1 -0
- package/fixtures/cli-registration.v2.json +115 -0
- package/fixtures/detection/reason-codes.json +1 -1
- package/fixtures/kya-http/README.md +34 -26
- package/fixtures/kya-http/protected-resource-metadata.full.json +14 -5
- package/fixtures/kya-http/protected-resource-metadata.invalid-issuer.json +51 -0
- package/fixtures/kya-http/protected-resource-metadata.no-issuer.json +32 -0
- package/fixtures/reviewer-grant-revocation.v1.json +285 -0
- package/package.json +26 -4
- package/dist/posture-origins-Dl7i8j93.mjs.map +0 -1
- package/dist/schemas-DxY-dk9y.mjs.map +0 -1
- package/fixtures/kya-http/protected-resource-metadata.global.json +0 -28
|
@@ -235,6 +235,53 @@ async function parseSigningKey(seed) {
|
|
|
235
235
|
};
|
|
236
236
|
}
|
|
237
237
|
|
|
238
|
+
//#endregion
|
|
239
|
+
//#region src/utils/base64url.ts
|
|
240
|
+
/**
|
|
241
|
+
* Base64url (RFC 4648 § 5) built on `atob` and `btoa` rather than Node's
|
|
242
|
+
* buffer API, so it runs on every runtime the SDKs support, Cloudflare Workers
|
|
243
|
+
* without `nodejs_compat` included.
|
|
244
|
+
*/
|
|
245
|
+
const BASE64URL_UNPADDED = /^[A-Za-z0-9_-]*$/;
|
|
246
|
+
const PADDING = 61;
|
|
247
|
+
/**
|
|
248
|
+
* `text` without its trailing `=` padding. A backward scan, not
|
|
249
|
+
* `replace(/=+$/, '')`: that regex retries from every `=` in a long run that
|
|
250
|
+
* does not reach the end, which is quadratic on hostile input.
|
|
251
|
+
*/
|
|
252
|
+
function withoutPadding(text) {
|
|
253
|
+
let end = text.length;
|
|
254
|
+
while (end > 0 && text.charCodeAt(end - 1) === PADDING) end -= 1;
|
|
255
|
+
return text.slice(0, end);
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* Decode base64url, with or without `=` padding.
|
|
259
|
+
*
|
|
260
|
+
* Strict where Node's buffer decoder is lenient: a character outside the
|
|
261
|
+
* alphabet, or a length no encoder produces (one character past a multiple of
|
|
262
|
+
* four), throws a `TypeError` instead of being skipped or truncated. This
|
|
263
|
+
* matches the engine's decoder.
|
|
264
|
+
*/
|
|
265
|
+
function base64UrlToBytes(text) {
|
|
266
|
+
const unpadded = withoutPadding(text);
|
|
267
|
+
if (!BASE64URL_UNPADDED.test(unpadded) || unpadded.length % 4 === 1) throw new TypeError("not valid base64url (RFC 4648 § 5)");
|
|
268
|
+
const base64 = unpadded.replace(/-/g, "+").replace(/_/g, "/");
|
|
269
|
+
const binary = atob(base64 + "=".repeat((4 - base64.length % 4) % 4));
|
|
270
|
+
const bytes = new Uint8Array(binary.length);
|
|
271
|
+
for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
|
|
272
|
+
return bytes;
|
|
273
|
+
}
|
|
274
|
+
/** Decode base64url to a string as UTF-8, replacing invalid sequences with U+FFFD. */
|
|
275
|
+
function base64UrlToString(text) {
|
|
276
|
+
return new TextDecoder().decode(base64UrlToBytes(text));
|
|
277
|
+
}
|
|
278
|
+
/** Encode bytes as base64url without padding. */
|
|
279
|
+
function bytesToBase64Url(bytes) {
|
|
280
|
+
let binary = "";
|
|
281
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
282
|
+
return withoutPadding(btoa(binary).replace(/\+/g, "-").replace(/\//g, "_"));
|
|
283
|
+
}
|
|
284
|
+
|
|
238
285
|
//#endregion
|
|
239
286
|
//#region src/canonical-signer/envelope.ts
|
|
240
287
|
/**
|
|
@@ -254,22 +301,6 @@ async function parseSigningKey(seed) {
|
|
|
254
301
|
* Sites-4 parity drivers, the Adobe trial.
|
|
255
302
|
*/
|
|
256
303
|
/**
|
|
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
|
-
*/
|
|
269
|
-
function base64UrlEncode(bytes) {
|
|
270
|
-
return Buffer.from(bytes).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
271
|
-
}
|
|
272
|
-
/**
|
|
273
304
|
* Sign an `McpIPayload` and produce a compact-JWS envelope ready to drop
|
|
274
305
|
* into `_meta.proof.jws` of the request body per KYA-OS spec § 7.4.
|
|
275
306
|
*
|
|
@@ -290,15 +321,40 @@ async function signMcpiEnvelope(payload, key) {
|
|
|
290
321
|
kid: key.kid
|
|
291
322
|
};
|
|
292
323
|
const headerJson = JSON.stringify(header);
|
|
293
|
-
const headerB64 =
|
|
294
|
-
const payloadB64 =
|
|
324
|
+
const headerB64 = bytesToBase64Url(new TextEncoder().encode(headerJson));
|
|
325
|
+
const payloadB64 = bytesToBase64Url(canonicalSigningPayload(payload));
|
|
295
326
|
const signingInput = new TextEncoder().encode(`${headerB64}.${payloadB64}`);
|
|
296
|
-
|
|
327
|
+
const signature = await (0, _noble_ed25519.signAsync)(signingInput, key.signingKey);
|
|
328
|
+
return `${headerB64}.${payloadB64}.${bytesToBase64Url(signature)}`;
|
|
297
329
|
}
|
|
298
330
|
|
|
299
331
|
//#endregion
|
|
300
332
|
//#region src/canonical-signer/parse.ts
|
|
301
333
|
/**
|
|
334
|
+
* Compact-JWS parser for KYA-OS detached proofs.
|
|
335
|
+
*
|
|
336
|
+
* Producer-side counterpart to Sign-1's `signMcpiEnvelope`: takes the
|
|
337
|
+
* wire string the engine's H-1 parser would consume and decomposes it
|
|
338
|
+
* into the same logical pieces (header, payload, signature, signing
|
|
339
|
+
* input). Lives in `checkpoint-shared/canonical-signer/` so producer
|
|
340
|
+
* AND consumer share one wire-format implementation — the JCS / base64
|
|
341
|
+
* subtleties are handled in one place, not three.
|
|
342
|
+
*
|
|
343
|
+
* Consumed by:
|
|
344
|
+
* - `@kya-os/bouncer-middleware` (Envelope-1 / #2537)
|
|
345
|
+
* - any future TS host that needs to introspect a JWS without going
|
|
346
|
+
* through the WASM bridge
|
|
347
|
+
*
|
|
348
|
+
* The Rust engine's `jws::parse_jws_compact` is the structural mirror
|
|
349
|
+
* (`rust/crates/kya-os-engine/src/jws.rs`); this module produces the
|
|
350
|
+
* same logical decomposition. Cross-runtime parity here is implicit:
|
|
351
|
+
* if both parsers consume the same JWS string and disagree on what's
|
|
352
|
+
* inside, the H-1 fixtures would catch it.
|
|
353
|
+
*
|
|
354
|
+
* Sign-1 (#2500). Anti-pattern: don't write a parallel parser
|
|
355
|
+
* elsewhere in the org — import from here.
|
|
356
|
+
*/
|
|
357
|
+
/**
|
|
302
358
|
* Discriminated error type so consumers can map parse failures to
|
|
303
359
|
* appropriate response codes (400 for malformed shape, 422 for
|
|
304
360
|
* unsupported alg) without string-matching error messages.
|
|
@@ -364,7 +420,7 @@ function parseJwsCompact(jws) {
|
|
|
364
420
|
const [headerB64, payloadB64, signatureB64] = parts;
|
|
365
421
|
let headerJson;
|
|
366
422
|
try {
|
|
367
|
-
headerJson = JSON.parse(
|
|
423
|
+
headerJson = JSON.parse(base64UrlToString(headerB64));
|
|
368
424
|
} catch (cause) {
|
|
369
425
|
throw new JwsParseError("InvalidJson", `JWS header is not valid JSON: ${String(cause)}`);
|
|
370
426
|
}
|
|
@@ -382,7 +438,7 @@ function parseJwsCompact(jws) {
|
|
|
382
438
|
};
|
|
383
439
|
let payloadJson;
|
|
384
440
|
try {
|
|
385
|
-
payloadJson = JSON.parse(
|
|
441
|
+
payloadJson = JSON.parse(base64UrlToString(payloadB64));
|
|
386
442
|
} catch (cause) {
|
|
387
443
|
throw new JwsParseError("InvalidJson", `JWS payload is not valid JSON: ${String(cause)}`);
|
|
388
444
|
}
|
|
@@ -393,7 +449,12 @@ function parseJwsCompact(jws) {
|
|
|
393
449
|
throw new JwsParseError("InvalidPayloadShape", `JWS payload does not match McpIPayload shape: ${cause.message}`);
|
|
394
450
|
}
|
|
395
451
|
if (!BASE64URL_ALPHABET.test(signatureB64)) throw new JwsParseError("InvalidBase64", `JWS signature segment contains characters outside the base64url alphabet (RFC 4648 § 5)`);
|
|
396
|
-
|
|
452
|
+
let signatureBytes;
|
|
453
|
+
try {
|
|
454
|
+
signatureBytes = base64UrlToBytes(signatureB64);
|
|
455
|
+
} catch {
|
|
456
|
+
throw new JwsParseError("InvalidBase64", `JWS signature segment is not a valid base64url length (RFC 4648 § 5)`);
|
|
457
|
+
}
|
|
397
458
|
if (signatureBytes.length !== 64) throw new JwsParseError("InvalidSignatureLength", `Ed25519 signatures are 64 bytes (RFC 8032 § 5.1.6); got ${signatureBytes.length}`);
|
|
398
459
|
const signingInput = new TextEncoder().encode(`${headerB64}.${payloadB64}`);
|
|
399
460
|
return {
|
|
@@ -404,37 +465,11 @@ function parseJwsCompact(jws) {
|
|
|
404
465
|
};
|
|
405
466
|
}
|
|
406
467
|
/**
|
|
407
|
-
* Strict base64url alphabet check (RFC 4648 § 5)
|
|
408
|
-
*
|
|
409
|
-
*
|
|
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.
|
|
468
|
+
* Strict base64url alphabet check (RFC 4648 § 5): `A-Za-z0-9-_` plus optional
|
|
469
|
+
* `=` padding. The empty string fails it on purpose: an empty signature
|
|
470
|
+
* segment is reported as `InvalidBase64` too.
|
|
418
471
|
*/
|
|
419
472
|
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
|
-
*/
|
|
430
|
-
function base64UrlDecodeToBytes(s) {
|
|
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"));
|
|
434
|
-
}
|
|
435
|
-
function base64UrlDecodeToString(s) {
|
|
436
|
-
return Buffer.from(base64UrlDecodeToBytes(s)).toString("utf-8");
|
|
437
|
-
}
|
|
438
473
|
|
|
439
474
|
//#endregion
|
|
440
475
|
exports.JwsParseError = JwsParseError;
|
|
@@ -206,6 +206,53 @@ async function parseSigningKey(seed) {
|
|
|
206
206
|
};
|
|
207
207
|
}
|
|
208
208
|
|
|
209
|
+
//#endregion
|
|
210
|
+
//#region src/utils/base64url.ts
|
|
211
|
+
/**
|
|
212
|
+
* Base64url (RFC 4648 § 5) built on `atob` and `btoa` rather than Node's
|
|
213
|
+
* buffer API, so it runs on every runtime the SDKs support, Cloudflare Workers
|
|
214
|
+
* without `nodejs_compat` included.
|
|
215
|
+
*/
|
|
216
|
+
const BASE64URL_UNPADDED = /^[A-Za-z0-9_-]*$/;
|
|
217
|
+
const PADDING = 61;
|
|
218
|
+
/**
|
|
219
|
+
* `text` without its trailing `=` padding. A backward scan, not
|
|
220
|
+
* `replace(/=+$/, '')`: that regex retries from every `=` in a long run that
|
|
221
|
+
* does not reach the end, which is quadratic on hostile input.
|
|
222
|
+
*/
|
|
223
|
+
function withoutPadding(text) {
|
|
224
|
+
let end = text.length;
|
|
225
|
+
while (end > 0 && text.charCodeAt(end - 1) === PADDING) end -= 1;
|
|
226
|
+
return text.slice(0, end);
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* Decode base64url, with or without `=` padding.
|
|
230
|
+
*
|
|
231
|
+
* Strict where Node's buffer decoder is lenient: a character outside the
|
|
232
|
+
* alphabet, or a length no encoder produces (one character past a multiple of
|
|
233
|
+
* four), throws a `TypeError` instead of being skipped or truncated. This
|
|
234
|
+
* matches the engine's decoder.
|
|
235
|
+
*/
|
|
236
|
+
function base64UrlToBytes(text) {
|
|
237
|
+
const unpadded = withoutPadding(text);
|
|
238
|
+
if (!BASE64URL_UNPADDED.test(unpadded) || unpadded.length % 4 === 1) throw new TypeError("not valid base64url (RFC 4648 § 5)");
|
|
239
|
+
const base64 = unpadded.replace(/-/g, "+").replace(/_/g, "/");
|
|
240
|
+
const binary = atob(base64 + "=".repeat((4 - base64.length % 4) % 4));
|
|
241
|
+
const bytes = new Uint8Array(binary.length);
|
|
242
|
+
for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
|
|
243
|
+
return bytes;
|
|
244
|
+
}
|
|
245
|
+
/** Decode base64url to a string as UTF-8, replacing invalid sequences with U+FFFD. */
|
|
246
|
+
function base64UrlToString(text) {
|
|
247
|
+
return new TextDecoder().decode(base64UrlToBytes(text));
|
|
248
|
+
}
|
|
249
|
+
/** Encode bytes as base64url without padding. */
|
|
250
|
+
function bytesToBase64Url(bytes) {
|
|
251
|
+
let binary = "";
|
|
252
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
253
|
+
return withoutPadding(btoa(binary).replace(/\+/g, "-").replace(/\//g, "_"));
|
|
254
|
+
}
|
|
255
|
+
|
|
209
256
|
//#endregion
|
|
210
257
|
//#region src/canonical-signer/envelope.ts
|
|
211
258
|
/**
|
|
@@ -225,22 +272,6 @@ async function parseSigningKey(seed) {
|
|
|
225
272
|
* Sites-4 parity drivers, the Adobe trial.
|
|
226
273
|
*/
|
|
227
274
|
/**
|
|
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
|
-
*/
|
|
240
|
-
function base64UrlEncode(bytes) {
|
|
241
|
-
return Buffer.from(bytes).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
242
|
-
}
|
|
243
|
-
/**
|
|
244
275
|
* Sign an `McpIPayload` and produce a compact-JWS envelope ready to drop
|
|
245
276
|
* into `_meta.proof.jws` of the request body per KYA-OS spec § 7.4.
|
|
246
277
|
*
|
|
@@ -261,15 +292,40 @@ async function signMcpiEnvelope(payload, key) {
|
|
|
261
292
|
kid: key.kid
|
|
262
293
|
};
|
|
263
294
|
const headerJson = JSON.stringify(header);
|
|
264
|
-
const headerB64 =
|
|
265
|
-
const payloadB64 =
|
|
295
|
+
const headerB64 = bytesToBase64Url(new TextEncoder().encode(headerJson));
|
|
296
|
+
const payloadB64 = bytesToBase64Url(canonicalSigningPayload(payload));
|
|
266
297
|
const signingInput = new TextEncoder().encode(`${headerB64}.${payloadB64}`);
|
|
267
|
-
|
|
298
|
+
const signature = await signAsync(signingInput, key.signingKey);
|
|
299
|
+
return `${headerB64}.${payloadB64}.${bytesToBase64Url(signature)}`;
|
|
268
300
|
}
|
|
269
301
|
|
|
270
302
|
//#endregion
|
|
271
303
|
//#region src/canonical-signer/parse.ts
|
|
272
304
|
/**
|
|
305
|
+
* Compact-JWS parser for KYA-OS detached proofs.
|
|
306
|
+
*
|
|
307
|
+
* Producer-side counterpart to Sign-1's `signMcpiEnvelope`: takes the
|
|
308
|
+
* wire string the engine's H-1 parser would consume and decomposes it
|
|
309
|
+
* into the same logical pieces (header, payload, signature, signing
|
|
310
|
+
* input). Lives in `checkpoint-shared/canonical-signer/` so producer
|
|
311
|
+
* AND consumer share one wire-format implementation — the JCS / base64
|
|
312
|
+
* subtleties are handled in one place, not three.
|
|
313
|
+
*
|
|
314
|
+
* Consumed by:
|
|
315
|
+
* - `@kya-os/bouncer-middleware` (Envelope-1 / #2537)
|
|
316
|
+
* - any future TS host that needs to introspect a JWS without going
|
|
317
|
+
* through the WASM bridge
|
|
318
|
+
*
|
|
319
|
+
* The Rust engine's `jws::parse_jws_compact` is the structural mirror
|
|
320
|
+
* (`rust/crates/kya-os-engine/src/jws.rs`); this module produces the
|
|
321
|
+
* same logical decomposition. Cross-runtime parity here is implicit:
|
|
322
|
+
* if both parsers consume the same JWS string and disagree on what's
|
|
323
|
+
* inside, the H-1 fixtures would catch it.
|
|
324
|
+
*
|
|
325
|
+
* Sign-1 (#2500). Anti-pattern: don't write a parallel parser
|
|
326
|
+
* elsewhere in the org — import from here.
|
|
327
|
+
*/
|
|
328
|
+
/**
|
|
273
329
|
* Discriminated error type so consumers can map parse failures to
|
|
274
330
|
* appropriate response codes (400 for malformed shape, 422 for
|
|
275
331
|
* unsupported alg) without string-matching error messages.
|
|
@@ -335,7 +391,7 @@ function parseJwsCompact(jws) {
|
|
|
335
391
|
const [headerB64, payloadB64, signatureB64] = parts;
|
|
336
392
|
let headerJson;
|
|
337
393
|
try {
|
|
338
|
-
headerJson = JSON.parse(
|
|
394
|
+
headerJson = JSON.parse(base64UrlToString(headerB64));
|
|
339
395
|
} catch (cause) {
|
|
340
396
|
throw new JwsParseError("InvalidJson", `JWS header is not valid JSON: ${String(cause)}`);
|
|
341
397
|
}
|
|
@@ -353,7 +409,7 @@ function parseJwsCompact(jws) {
|
|
|
353
409
|
};
|
|
354
410
|
let payloadJson;
|
|
355
411
|
try {
|
|
356
|
-
payloadJson = JSON.parse(
|
|
412
|
+
payloadJson = JSON.parse(base64UrlToString(payloadB64));
|
|
357
413
|
} catch (cause) {
|
|
358
414
|
throw new JwsParseError("InvalidJson", `JWS payload is not valid JSON: ${String(cause)}`);
|
|
359
415
|
}
|
|
@@ -364,7 +420,12 @@ function parseJwsCompact(jws) {
|
|
|
364
420
|
throw new JwsParseError("InvalidPayloadShape", `JWS payload does not match McpIPayload shape: ${cause.message}`);
|
|
365
421
|
}
|
|
366
422
|
if (!BASE64URL_ALPHABET.test(signatureB64)) throw new JwsParseError("InvalidBase64", `JWS signature segment contains characters outside the base64url alphabet (RFC 4648 § 5)`);
|
|
367
|
-
|
|
423
|
+
let signatureBytes;
|
|
424
|
+
try {
|
|
425
|
+
signatureBytes = base64UrlToBytes(signatureB64);
|
|
426
|
+
} catch {
|
|
427
|
+
throw new JwsParseError("InvalidBase64", `JWS signature segment is not a valid base64url length (RFC 4648 § 5)`);
|
|
428
|
+
}
|
|
368
429
|
if (signatureBytes.length !== 64) throw new JwsParseError("InvalidSignatureLength", `Ed25519 signatures are 64 bytes (RFC 8032 § 5.1.6); got ${signatureBytes.length}`);
|
|
369
430
|
const signingInput = new TextEncoder().encode(`${headerB64}.${payloadB64}`);
|
|
370
431
|
return {
|
|
@@ -375,37 +436,11 @@ function parseJwsCompact(jws) {
|
|
|
375
436
|
};
|
|
376
437
|
}
|
|
377
438
|
/**
|
|
378
|
-
* Strict base64url alphabet check (RFC 4648 § 5)
|
|
379
|
-
*
|
|
380
|
-
*
|
|
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.
|
|
439
|
+
* Strict base64url alphabet check (RFC 4648 § 5): `A-Za-z0-9-_` plus optional
|
|
440
|
+
* `=` padding. The empty string fails it on purpose: an empty signature
|
|
441
|
+
* segment is reported as `InvalidBase64` too.
|
|
389
442
|
*/
|
|
390
443
|
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
|
-
*/
|
|
401
|
-
function base64UrlDecodeToBytes(s) {
|
|
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"));
|
|
405
|
-
}
|
|
406
|
-
function base64UrlDecodeToString(s) {
|
|
407
|
-
return Buffer.from(base64UrlDecodeToBytes(s)).toString("utf-8");
|
|
408
|
-
}
|
|
409
444
|
|
|
410
445
|
//#endregion
|
|
411
446
|
export { JwsParseError, canonicalSigningPayload, parseJwsCompact, parseSigningKey, signMcpiEnvelope, validateMcpIPayload };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/canonical-signer/payload.ts","../../src/mcpi/did-key.ts","../../src/canonical-signer/key.ts","../../src/canonical-signer/envelope.ts","../../src/canonical-signer/parse.ts"],"sourcesContent":["/**\n * Canonical KYA-OS signing payload (RFC 8785 / JCS).\n *\n * TS half of the cross-runtime parity contract pinned in\n * `rust/crates/kya-os-engine/src/signing.rs`. Same `McpIPayload` struct,\n * same JCS canonicalization, byte-identical output. The Rust engine's\n * `signing_payload` golden vector at `tests/fixtures/reference_payload.jcs`\n * is the firewall this module asserts against — if these bytes diverge,\n * every downstream signature verification claim is suspect.\n *\n * Field set is locked to KYA-OS spec § 7.4 (eight required claims) +\n * § 7.2 (ProofMeta). Wire format is camelCase per the KYA-OS JSON schema.\n *\n * Sign-1 (#2500). Do NOT extend without ratification through\n * mcp-i-core → D-design → here.\n *\n * @see rust/crates/kya-os-engine/src/signing.rs — Rust struct + JCS function\n * @see rust/crates/kya-os-engine/tests/fixtures/reference_payload.jcs — golden vector\n */\n\nimport canonicalize from 'canonicalize';\n\n/**\n * Structured KYA-OS payload signed by an Ed25519 key.\n *\n * Mirrors `kya_os_engine::signing::McpIPayload` field-for-field. Wire\n * format uses camelCase (matches Rust's `#[serde(rename_all = \"camelCase\")]`).\n *\n * Lexicographic key order on the wire (the JCS member-ordering rule):\n * `aud, iss, nonce, requestHash, responseHash, sessionId, sub, ts`\n */\nexport interface McpIPayload {\n /** Audience — the intended recipient DID or URL. */\n aud: string;\n /** Issuer — the signing principal's DID. */\n iss: string;\n /** Subject — the principal this proof is about (often equal to `iss`). */\n sub: string;\n /** Session nonce — binds the proof to the handshake that established the session. */\n nonce: string;\n /** Session identifier from the handshake response. */\n sessionId: string;\n /** Unix epoch seconds when the proof was generated. */\n ts: number;\n /** SHA-256 hash of the JCS-canonicalized request, formatted as `\"sha256:<64-lowercase-hex>\"`. */\n requestHash: string;\n /** SHA-256 hash of the JCS-canonicalized response, formatted as `\"sha256:<64-lowercase-hex>\"`. */\n responseHash: string;\n}\n\n/**\n * Canonicalize an `McpIPayload` into the byte sequence the Ed25519\n * signature is computed over.\n *\n * **Determinism contract.** Same input MUST produce byte-identical\n * output, every time, every runtime. This function is the cross-runtime\n * parity contract — TS, .NET, Go, Python, and Rust runtimes all\n * implement it independently and MUST agree on the golden vector\n * pinned at `rust/crates/kya-os-engine/tests/fixtures/reference_payload.jcs`.\n *\n * The output is RFC 8785 (JCS) canonical JSON: keys sorted\n * lexicographically by UTF-16 code units, integers serialized without\n * a decimal point, strings escaped only as required, no whitespace.\n *\n * Implementation note: `canonicalize` (npm) is Erdtman's RFC 8785\n * reference implementation. If a future TS host reaches for a\n * different library, the parity firewall test (`canonical-signer.parity.test.ts`)\n * will catch the byte drift before it reaches production.\n */\nexport function canonicalSigningPayload(payload: McpIPayload): Uint8Array {\n const json = canonicalize(payload);\n if (json === undefined) {\n // canonicalize returns undefined for non-serializable inputs\n // (functions, symbols, etc.). McpIPayload's typed fields preclude\n // this, but the runtime check guards against `as McpIPayload` casts\n // at consumer call-sites that bypass the type contract.\n throw new Error('canonicalSigningPayload: payload contains non-serializable values');\n }\n return new TextEncoder().encode(json);\n}\n\n/**\n * Field set that MUST be present for an `McpIPayload` to be valid.\n *\n * Source of truth for `validateMcpIPayload`. The list mirrors the TS\n * `McpIPayload` interface — adding a field there without adding it\n * here is a hidden bypass for the runtime contract. New required\n * fields land in lockstep; new optional fields (post-Scope-1) get\n * a sibling list with a `typeof === 'undefined' || ...` predicate.\n */\nconst REQUIRED_STRING_FIELDS = [\n 'aud',\n 'iss',\n 'sub',\n 'nonce',\n 'sessionId',\n 'requestHash',\n 'responseHash',\n] as const;\n\n/**\n * Runtime type guard: confirms a `JSON.parse` output actually matches\n * `McpIPayload`. Required because `JSON.parse` returns `unknown`, and\n * casting `as McpIPayload` is a *compile-time* assertion that the\n * runtime can't honor — a payload missing required fields silently\n * surfaces as `undefined` at consumer call-sites and bypasses field-\n * presence checks (e.g., the bouncer's replay-window comparison\n * `meta.ts < now - 300` evaluates `false` for `undefined`, skipping\n * the timestamp defense entirely).\n *\n * Throws on the FIRST missing or wrong-typed field — no error\n * accumulation, since one missing claim is enough to reject the\n * envelope and producers should re-issue the entire proof rather than\n * patch field-by-field.\n *\n * @throws Error with a descriptive message identifying the offending\n * field. `parseJwsCompact` translates this into a structured\n * `JwsParseError('InvalidPayloadShape', ...)` for consumers branching\n * on the discriminant.\n */\nexport function validateMcpIPayload(value: unknown): McpIPayload {\n if (value === null || typeof value !== 'object') {\n throw new Error(`expected JSON object, got ${value === null ? 'null' : typeof value}`);\n }\n const obj = value as Record<string, unknown>;\n\n for (const field of REQUIRED_STRING_FIELDS) {\n if (typeof obj[field] !== 'string') {\n throw new Error(`missing or non-string required field \"${field}\" (got ${typeof obj[field]})`);\n }\n }\n\n // ts is the load-bearing exception — number, not string. The bug\n // cursor-bot caught on PR #2546 (replay-window check silently\n // skipped on missing ts) lived on this exact field check.\n if (typeof obj.ts !== 'number' || !Number.isFinite(obj.ts)) {\n throw new Error(`missing or non-finite-number required field \"ts\" (got ${typeof obj.ts})`);\n }\n\n // Validated above: every required field is present and well-typed.\n // The double cast through `unknown` is the standard TS idiom for\n // returning a narrowed type from a `Record<string, unknown>` after\n // runtime checks — necessary because TS doesn't infer narrowing\n // across a for-of loop with dynamic keys.\n return obj as unknown as McpIPayload;\n}\n","/**\n * did:key (Ed25519 multikey) codec — draft-kya-http-02 / H1.2 (#3245).\n *\n * Format: `did:key:z<base58btc(0xed 0x01 || pubkey32)>`\n * The multicodec prefix `0xed 0x01` identifies `ed25519-pub`; the multibase\n * prefix `z` identifies base58btc. An Ed25519 public key is always 32 bytes,\n * so the decoded multikey is always 34 bytes and the did:key always begins\n * `z6Mk` (a fixed consequence of the `0xed01` prefix).\n *\n * This is a PURE-JS port of the base58btc decoder in\n * `apps/web/workers/gateway/src/detection/did-verifier.ts` (repeated-division\n * algorithm), lifted here so the H1.2 pickup endpoint — and future H2.x TS\n * PEPs — can recover the raw key for `node:crypto` Ed25519 verification with\n * zero crypto/runtime dependencies (it runs identically in Node, Cloudflare\n * Workers, and the browser). The encoder is the inverse, for tests and any\n * caller that emits a `did:key` from raw key bytes.\n */\n\nconst BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\nconst BASE58_INDEX: Record<string, number> = (() => {\n const idx: Record<string, number> = {};\n for (let i = 0; i < BASE58_ALPHABET.length; i++) idx[BASE58_ALPHABET[i]] = i;\n return idx;\n})();\n\nconst DID_KEY_PREFIX = 'did:key:';\nconst ED25519_MULTICODEC = [0xed, 0x01] as const; // ed25519-pub\nconst ED25519_PUBKEY_LENGTH = 32;\nconst ED25519_MULTIKEY_LENGTH = ED25519_MULTICODEC.length + ED25519_PUBKEY_LENGTH; // 34\n\n/**\n * Decode a base58btc string to bytes using the repeated-division algorithm.\n * Returns null if the string contains a character outside the base58btc\n * alphabet. Ported verbatim from the gateway worker's `did-verifier.ts`\n * (kept algorithm-identical to avoid cross-runtime drift).\n */\nexport function base58btcDecode(str: string): Uint8Array | null {\n if (str.length === 0) return new Uint8Array(0);\n\n let zeros = 0;\n while (zeros < str.length && str[zeros] === BASE58_ALPHABET[0]) zeros++;\n\n // Sentinel-seeded little-endian byte accumulator.\n const bytes: number[] = [0];\n for (let i = 0; i < str.length; i++) {\n const value = BASE58_INDEX[str[i]];\n if (value === undefined) return null;\n let carry = value;\n for (let j = 0; j < bytes.length; j++) {\n carry += bytes[j] * 58;\n bytes[j] = carry & 0xff;\n carry >>= 8;\n }\n while (carry > 0) {\n bytes.push(carry & 0xff);\n carry >>= 8;\n }\n }\n\n // Drop the trailing zero sentinel(s).\n let high = bytes.length;\n while (high > 0 && bytes[high - 1] === 0) high--;\n\n const out = new Uint8Array(zeros + high);\n for (let i = 0; i < high; i++) {\n out[zeros + high - 1 - i] = bytes[i];\n }\n return out;\n}\n\n/**\n * Encode bytes to a base58btc string — the exact inverse of\n * {@link base58btcDecode}. Leading zero bytes map to leading `1`s; the value\n * is accumulated as little-endian base58 digits (×256 + byte) and emitted\n * big-endian. The high-order zero sentinel is dropped the same way the decoder\n * drops its trailing zeros, so a single `0x00` byte encodes to `\"1\"`, not `\"11\"`.\n */\nexport function base58btcEncode(bytes: Uint8Array): string {\n if (bytes.length === 0) return '';\n\n let zeros = 0;\n while (zeros < bytes.length && bytes[zeros] === 0) zeros++;\n\n const digits: number[] = [0];\n for (let i = 0; i < bytes.length; i++) {\n let carry = bytes[i];\n for (let j = 0; j < digits.length; j++) {\n carry += digits[j] * 256;\n digits[j] = carry % 58;\n carry = Math.floor(carry / 58);\n }\n while (carry > 0) {\n digits.push(carry % 58);\n carry = Math.floor(carry / 58);\n }\n }\n\n // Drop the high-order zero sentinel(s); leading zero bytes become '1's.\n let high = digits.length;\n while (high > 0 && digits[high - 1] === 0) high--;\n\n let out = BASE58_ALPHABET[0].repeat(zeros);\n for (let i = high - 1; i >= 0; i--) {\n out += BASE58_ALPHABET[digits[i]];\n }\n return out;\n}\n\n/**\n * Recover the raw 32-byte Ed25519 public key from a `did:key:z6Mk…` string.\n * Returns null for any malformed input: wrong method, wrong multibase, invalid\n * base58, wrong decoded length, or a non-Ed25519 multicodec. Never throws —\n * callers treat null as \"not a verifiable Ed25519 did:key\".\n */\nexport function decodeDidKeyEd25519(did: string): Uint8Array | null {\n if (typeof did !== 'string' || !did.startsWith(DID_KEY_PREFIX)) return null;\n\n const suffix = did.slice(DID_KEY_PREFIX.length);\n if (!suffix.startsWith('z')) return null; // base58btc multibase prefix\n\n // A legit Ed25519 did:key body is fixed at 47 base58 chars. Cap the length\n // BEFORE the O(n^2) repeated-division decode: this keyid arrives from an\n // attacker-controlled Signature-Input header on the public pickup endpoint, so\n // an over-long body (which the 34-byte length check would reject anyway) must\n // not be allowed to burn quadratic event-loop CPU first.\n const body = suffix.slice(1);\n if (body.length > 64) return null;\n\n const decoded = base58btcDecode(body);\n if (!decoded || decoded.length !== ED25519_MULTIKEY_LENGTH) return null;\n if (decoded[0] !== ED25519_MULTICODEC[0] || decoded[1] !== ED25519_MULTICODEC[1]) return null;\n\n return decoded.slice(ED25519_MULTICODEC.length);\n}\n\n/** Recover the compressed SEC1 point from the HTTP profile's p256-pub\n * multicodec (0x1200). This runtime-independent codec validates carriage only;\n * the cryptographic consumer MUST validate that the point lies on P-256 before\n * trusting it or deriving a confirmation thumbprint. */\nexport function decodeDidKeyP256(did: string): Uint8Array | null {\n if (typeof did !== 'string' || !did.startsWith(`${DID_KEY_PREFIX}z`)) return null;\n const body = did.slice(DID_KEY_PREFIX.length + 1);\n // Bound the quadratic base58 decoder before processing untrusted keyids.\n if (body.length > 64) return null;\n const decoded = base58btcDecode(body);\n if (\n !decoded ||\n decoded.length !== 35 ||\n decoded[0] !== 0x80 ||\n decoded[1] !== 0x24 ||\n (decoded[2] !== 2 && decoded[2] !== 3)\n )\n return null;\n return decoded.slice(2);\n}\n\n/**\n * Encode a raw 32-byte Ed25519 public key as a `did:key:z6Mk…` string. Throws\n * if the key is not exactly 32 bytes — an emitter handing in the wrong length\n * is a programming error, not untrusted input (unlike {@link decodeDidKeyEd25519}).\n */\nexport function encodeDidKeyEd25519(publicKey: Uint8Array): string {\n if (!(publicKey instanceof Uint8Array) || publicKey.length !== ED25519_PUBKEY_LENGTH) {\n throw new Error(\n `encodeDidKeyEd25519: expected a ${ED25519_PUBKEY_LENGTH}-byte Ed25519 public key, got ${\n publicKey instanceof Uint8Array ? `${publicKey.length} bytes` : typeof publicKey\n }`\n );\n }\n\n const multikey = new Uint8Array(ED25519_MULTIKEY_LENGTH);\n multikey[0] = ED25519_MULTICODEC[0];\n multikey[1] = ED25519_MULTICODEC[1];\n multikey.set(publicKey, ED25519_MULTICODEC.length);\n\n return `${DID_KEY_PREFIX}z${base58btcEncode(multikey)}`;\n}\n","/**\n * Ed25519 keypair derivation for KYA-OS detached proofs.\n *\n * Derives a `KeyMaterial` bundle (signing key, public key, did:key, kid)\n * from a 32-byte seed. The derivation MUST agree byte-for-byte with\n * Rust's `ed25519_dalek::SigningKey::from_bytes` + did:key formatter so\n * H-1's committed test fixtures (`signer.seed` + `signer.public_key`)\n * derive identically across runtimes.\n *\n * `kid` form follows mcp-i-core PR #16 (multibase-as-fragment):\n * `did:key:z6Mk...#z6Mk...`. NOT `#keys-1`. NOT `#1`. The H-1\n * `stage2_did_key_fragment_resolution` test pins this on the verifier\n * side; this module pins it on the producer side.\n *\n * Sign-1 (#2500).\n */\n\nimport { getPublicKeyAsync } from '@noble/ed25519';\n// Pure-JS base58btc encode (not multiformats' `bases/base58` subpath):\n// that subpath's package.json `exports` map ships an `import` condition\n// only, no `require` — reaching it from this subpath's own CJS build\n// crashes with ERR_PACKAGE_PATH_NOT_EXPORTED before any application code\n// runs. `base58btcEncode` is the same dependency-free codec did:key\n// verification already uses elsewhere in this package.\nimport { base58btcEncode } from '../mcpi/did-key';\n\n/**\n * Multicodec prefix for Ed25519 verifying keys per the W3C did:key spec\n * (`0xed01` varint). Prepended to the 32-byte public key, base58btc-\n * encoded with the `z` multibase prefix to produce the did:key suffix.\n */\nconst ED25519_MULTICODEC_PREFIX = new Uint8Array([0xed, 0x01]);\n\n/**\n * Bundle of derived key material. Carries the signing key, the public\n * key, the canonical did:key DID, and the verification-method `kid`\n * (multibase-as-fragment per mcp-i-core PR #16).\n *\n * `signingKey` is a **copy** of the input seed, not a reference — see\n * `parseSigningKey` for the rationale. Treat the bundle as the owning\n * holder of the key material; the caller's original seed buffer is\n * safe to zero out after `parseSigningKey` returns.\n */\nexport interface KeyMaterial {\n /** The 32-byte Ed25519 secret seed (defensive copy of the input). */\n signingKey: Uint8Array;\n /** The 32-byte Ed25519 public verifying key. */\n publicKey: Uint8Array;\n /** The canonical did:key DID — `did:key:z6Mk...`. */\n did: string;\n /**\n * The verification-method id for this DID — multibase as fragment per\n * mcp-i-core PR #16 (`did:key:z6Mk...#z6Mk...`). Goes into the JWS\n * header `kid` field.\n */\n kid: string;\n}\n\n/**\n * Derive a `KeyMaterial` bundle from a 32-byte Ed25519 seed.\n *\n * The seed IS the signing key (per RFC 8032 § 5.1.5 — Ed25519 secret\n * keys are 32-byte seeds; the expanded scalar is computed at sign time).\n * Same seed → same `(publicKey, did, kid)` deterministically across\n * any RFC 8032 implementation.\n *\n * The input seed is **defensively copied** into the returned\n * `KeyMaterial.signingKey`. Subsequent mutations of the caller's\n * buffer (zeroization, key rotation, fixture reuse) do NOT affect\n * the key bundle. Callers that own the seed are free to scrub it\n * after this function returns.\n *\n * @throws if the seed is not exactly 32 bytes.\n */\nexport async function parseSigningKey(seed: Uint8Array): Promise<KeyMaterial> {\n if (seed.length !== 32) {\n throw new Error(`parseSigningKey: expected 32-byte Ed25519 seed, got ${seed.length} bytes`);\n }\n\n const publicKey = await getPublicKeyAsync(seed);\n\n // did:key z-encoded multibase per W3C spec: 0xed01 || pubkey, then\n // base58btc-encoded. The 'z' prefix is part of base58btc's multibase\n // alphabet; encode() returns it already prepended.\n const multibaseBytes = new Uint8Array(ED25519_MULTICODEC_PREFIX.length + publicKey.length);\n multibaseBytes.set(ED25519_MULTICODEC_PREFIX, 0);\n multibaseBytes.set(publicKey, ED25519_MULTICODEC_PREFIX.length);\n const multibase = `z${base58btcEncode(multibaseBytes)}`;\n const did = `did:key:${multibase}`;\n\n return {\n // Defensive copy — see KeyMaterial.signingKey docstring. The Sign-1\n // tests assert that mutating the input seed after this call does NOT\n // mutate the held key material.\n signingKey: Uint8Array.from(seed),\n publicKey,\n did,\n // mcp-i-core PR #16: the verification-method id is the multibase value\n // as a fragment. Anything else (`#keys-1`, `#1`, etc.) breaks H-1's\n // stage2_did_key_fragment_resolution.\n kid: `${did}#${multibase}`,\n };\n}\n","/**\n * JWS-compact envelope construction for KYA-OS detached proofs.\n *\n * Produces wire bytes the engine's H-1 parser (#2486) accepts:\n *\n * BASE64URL(header) \".\" BASE64URL(payload) \".\" BASE64URL(signature)\n *\n * where the header is `{ \"alg\": \"EdDSA\", \"kid\": \"<verification-method-id>\" }`,\n * the payload is the JCS-canonicalized `McpIPayload`, and the signature is\n * Ed25519 over `BASE64URL(header) || '.' || BASE64URL(payload)` per\n * RFC 7515 § 5.1.\n *\n * Sign-1 (#2500). Output of this function is what every TS producer in the\n * org emits — bouncer middleware (Envelope-1), Sites-1/2 e2e helpers, future\n * Sites-4 parity drivers, the Adobe trial.\n */\n\nimport { signAsync } from '@noble/ed25519';\nimport { canonicalSigningPayload, type McpIPayload } from './payload';\nimport type { KeyMaterial } from './key';\n\n/**\n * URL-safe base64 encoding without padding (RFC 4648 § 5).\n *\n * **Node-only.** Uses Node's `Buffer` API because every current consumer\n * of this module runs on Node (Vercel functions, Sites-1/2 Playwright\n * suites, future SDKs that bundle for Node + bundler-polyfilled runtimes\n * like Vercel Edge with `nodejs_compat`). If a future consumer needs a\n * pure-Web-API runtime (Cloudflare Workers without `nodejs_compat`,\n * Deno's stricter modes), swap to `Uint8Array.toBase64()` (Stage 4 as\n * of mid-2026) or a small inline encoder — but verify against the\n * envelope.test.ts round-trip first; the `base64url` character\n * substitution path is the part that has historically tripped polyfills.\n */\nfunction base64UrlEncode(bytes: Uint8Array): string {\n return Buffer.from(bytes)\n .toString('base64')\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=+$/, '');\n}\n\n/**\n * Sign an `McpIPayload` and produce a compact-JWS envelope ready to drop\n * into `_meta.proof.jws` of the request body per KYA-OS spec § 7.4.\n *\n * The signing input is `BASE64URL(header) || '.' || BASE64URL(payload)`,\n * NOT the canonical-JSON bytes. The canonicalization happens *inside* the\n * payload base64url segment; the Ed25519 signature happens *over* the dot-\n * separated structure. This is the RFC 7515 § 5.1 contract that H-1's\n * `verify_strict` checks against.\n *\n * @param payload — the structured KYA-OS claims (eight required fields).\n * @param key — derived via `parseSigningKey(seed)`. The header `kid` is\n * set from `key.kid` (multibase-as-fragment per mcp-i-core PR #16).\n * @returns the compact-JWS string `<headerB64>.<payloadB64>.<signatureB64>`.\n */\nexport async function signMcpiEnvelope(payload: McpIPayload, key: KeyMaterial): Promise<string> {\n const header = { alg: 'EdDSA', kid: key.kid };\n const headerJson = JSON.stringify(header);\n const headerB64 = base64UrlEncode(new TextEncoder().encode(headerJson));\n\n const payloadB64 = base64UrlEncode(canonicalSigningPayload(payload));\n\n // RFC 7515 § 5.1: signing input is the ASCII bytes of the dot-separated\n // header and payload. `TextEncoder` produces UTF-8, which is identical to\n // ASCII for the base64url alphabet (`A-Za-z0-9-_`) and the literal '.'.\n const signingInput = new TextEncoder().encode(`${headerB64}.${payloadB64}`);\n const signature = await signAsync(signingInput, key.signingKey);\n const signatureB64 = base64UrlEncode(signature);\n\n return `${headerB64}.${payloadB64}.${signatureB64}`;\n}\n","/**\n * Compact-JWS parser for KYA-OS detached proofs.\n *\n * Producer-side counterpart to Sign-1's `signMcpiEnvelope`: takes the\n * wire string the engine's H-1 parser would consume and decomposes it\n * into the same logical pieces (header, payload, signature, signing\n * input). Lives in `checkpoint-shared/canonical-signer/` so producer\n * AND consumer share one wire-format implementation — the JCS / base64\n * subtleties are handled in one place, not three.\n *\n * Consumed by:\n * - `@kya-os/bouncer-middleware` (Envelope-1 / #2537)\n * - any future TS host that needs to introspect a JWS without going\n * through the WASM bridge\n *\n * The Rust engine's `jws::parse_jws_compact` is the structural mirror\n * (`rust/crates/kya-os-engine/src/jws.rs`); this module produces the\n * same logical decomposition. Cross-runtime parity here is implicit:\n * if both parsers consume the same JWS string and disagree on what's\n * inside, the H-1 fixtures would catch it.\n *\n * Sign-1 (#2500). Anti-pattern: don't write a parallel parser\n * elsewhere in the org — import from here.\n */\n\nimport type { McpIPayload } from './payload';\nimport { validateMcpIPayload } from './payload';\n\n/**\n * The decomposed compact-JWS envelope.\n *\n * `signingInput` is stored separately so callers don't have to re-encode\n * the header + payload to verify the signature — re-encoding through a\n * different base64url implementation is a known source of \"should-be-\n * identical bytes drift differently\" canonicalization bugs (the same\n * class of risk that Sign-1's JCS parity firewall guards against on the\n * payload side).\n */\nexport interface ParsedJws {\n /** Decoded JWS Protected Header. Phase 1 only supports `alg: \"EdDSA\"`. */\n header: {\n alg: 'EdDSA';\n /** Verification-method id — multibase-as-fragment for did:key per\n * mcp-i-core PR #16 (`did:key:z...#z...`); whatever the DID\n * document declares for did:web (typically `#key-1`). */\n kid: string;\n /** Optional `typ` per RFC 7515. Bouncer ignores; preserved for\n * forward-compat with future header extensions. */\n typ?: string;\n };\n /** Decoded KYA-OS payload — the eight-field signing struct. */\n payload: McpIPayload;\n /** Raw 64-byte ed25519 signature segment. */\n signatureBytes: Uint8Array;\n /**\n * `header_b64 + \".\" + payload_b64` as ASCII bytes — the signing\n * input ed25519 verifies against per RFC 7515 § 5.1. Stored\n * verbatim from the input string (no re-encode round-trip).\n */\n signingInput: Uint8Array;\n}\n\n/**\n * Discriminated error type so consumers can map parse failures to\n * appropriate response codes (400 for malformed shape, 422 for\n * unsupported alg) without string-matching error messages.\n */\nexport class JwsParseError extends Error {\n constructor(\n /** Machine-readable failure category. */\n public readonly code:\n | 'WrongSegmentCount'\n | 'InvalidBase64'\n | 'InvalidJson'\n | 'InvalidHeaderShape'\n | 'InvalidPayloadShape'\n | 'UnsupportedAlgorithm'\n | 'InvalidSignatureLength',\n message: string\n ) {\n super(message);\n this.name = 'JwsParseError';\n }\n}\n\n/**\n * Wider intermediate shape returned by `validateJwsHeader`.\n *\n * Deliberately keeps `alg` as `string` (not `'EdDSA'`) — the validator\n * only proves it's a non-empty string, not that it's the supported\n * algorithm. Narrowing to the literal type happens at the alg-check\n * site in `parseJwsCompact`, where the failure can be surfaced under\n * the correct discriminant (`UnsupportedAlgorithm`, not\n * `InvalidHeaderShape`).\n *\n * Cursor-bot review on PR #2551: the previous version returned the\n * narrowed `ParsedJws['header']` via a double cast, which lied about\n * the runtime guarantee. Strict linters (`@typescript-eslint/no-\n * unnecessary-condition`) would have flagged the downstream\n * `header.alg !== 'EdDSA'` check as always-false and suggested\n * removing it — silently letting non-EdDSA algorithms through.\n */\ninterface ValidatedJwsHeaderShape {\n alg: string;\n kid: string;\n typ?: string;\n}\n\n/**\n * Runtime type guard for the JWS Protected Header (RFC 7515 § 4).\n *\n * Mirror of `validateMcpIPayload` for the header side of the envelope.\n * Cursor-bot review on PR #2546 caught two classes of bug the unguarded\n * `JSON.parse → cast` flow let through:\n *\n * 1. **Missing `kid`** — header parses, `header.kid === undefined`\n * typed as string, propagates into the bouncer's sidecar and gets\n * dropped by JSON.stringify → malformed payload at the remote.\n * 2. **Null JSON header** (`bnVsbA` base64url) — `JSON.parse` returns\n * `null`, `header.alg` access throws TypeError, escapes the\n * bouncer's `instanceof JwsParseError` guard → leaks as 500. Easy\n * DoS/probe vector.\n *\n * Both go away by validating before any property access. Throws plain\n * Error; `parseJwsCompact` translates into `JwsParseError('InvalidHeaderShape', …)`.\n *\n * Returns `ValidatedJwsHeaderShape` with `alg: string` (not `'EdDSA'`).\n * The literal-type narrowing is the caller's responsibility — keeping\n * the failure-category boundary clean: shape failures from this\n * validator surface as `InvalidHeaderShape`; algorithm-support failures\n * surface separately as `UnsupportedAlgorithm`.\n */\nfunction validateJwsHeader(value: unknown): ValidatedJwsHeaderShape {\n if (value === null || typeof value !== 'object') {\n throw new Error(`expected JSON object, got ${value === null ? 'null' : typeof value}`);\n }\n const obj = value as Record<string, unknown>;\n\n if (typeof obj.alg !== 'string' || obj.alg.length === 0) {\n throw new Error(`missing or non-string required field \"alg\" (got ${typeof obj.alg})`);\n }\n if (typeof obj.kid !== 'string' || obj.kid.length === 0) {\n throw new Error(`missing or non-string required field \"kid\" (got ${typeof obj.kid})`);\n }\n if (obj.typ !== undefined && typeof obj.typ !== 'string') {\n throw new Error(`optional field \"typ\" must be a string when present (got ${typeof obj.typ})`);\n }\n\n return obj as unknown as ValidatedJwsHeaderShape;\n}\n\n/**\n * Parse a compact-JWS string per RFC 7515 § 3.1 + § 5.1.\n *\n * Three segments separated by `.`, each base64url-encoded\n * (`A-Za-z0-9-_`, no padding). Header is JSON with at minimum\n * `alg: \"EdDSA\"` + `kid`. Payload is the JCS-canonicalized\n * `McpIPayload`. Signature segment decodes to exactly 64 bytes\n * (Ed25519 fixed-length per RFC 8032 § 5.1.6).\n *\n * @throws {@link JwsParseError} with a structured `code` for malformed\n * shape, invalid base64url, invalid JSON, unsupported algorithm, or\n * wrong signature length. Cryptographic verification is OUT of scope\n * — the engine (or `@noble/ed25519` round-trip) does that against\n * `signatureBytes` over `signingInput`.\n */\nexport function parseJwsCompact(jws: string): ParsedJws {\n const parts = jws.split('.');\n if (parts.length !== 3) {\n throw new JwsParseError(\n 'WrongSegmentCount',\n `Expected 3 dot-separated segments per RFC 7515 § 3.1; got ${parts.length}`\n );\n }\n const [headerB64, payloadB64, signatureB64] = parts;\n\n let headerJson: unknown;\n try {\n headerJson = JSON.parse(base64UrlDecodeToString(headerB64));\n } catch (cause) {\n throw new JwsParseError('InvalidJson', `JWS header is not valid JSON: ${String(cause)}`);\n }\n\n // Runtime shape validation for the header. Two cursor-bot findings on\n // PR #2546 motivate this:\n //\n // 1. A header with `{\"alg\":\"EdDSA\"}` (no `kid`) parsed successfully\n // and surfaced `header.kid === undefined` typed as string. The\n // bouncer's sidecar synthesis copied that into `meta.kid`, which\n // JSON.stringify silently drops, producing a malformed `{jws,\n // meta}` payload at the remote endpoint.\n //\n // 2. A header that decodes to JSON literal `null` (base64url of\n // `\"null\"` → `bnVsbA`) made `JSON.parse` succeed and assign\n // `null` to `header`. The subsequent `header.alg` access threw\n // a TypeError, which the bouncer's `instanceof JwsParseError`\n // guard let through — a 500 API_ERROR instead of a clean 401.\n // Trivially exploitable by an attacker.\n //\n // Both classes go away by validating the shape before any property\n // access. Same pattern as `validateMcpIPayload`.\n //\n // `validatedHeader` holds the wider `ValidatedJwsHeaderShape` (alg as\n // string) so the algorithm-support check below isn't redundant from\n // TS's perspective. After the check passes, we narrow to the final\n // `ParsedJws['header']` (alg as the 'EdDSA' literal). Cursor-bot\n // review on PR #2551: returning the narrowed type from the validator\n // would lie about the runtime guarantee and let strict linters\n // remove the alg check as \"always-false.\"\n let validatedHeader: ValidatedJwsHeaderShape;\n try {\n validatedHeader = validateJwsHeader(headerJson);\n } catch (cause) {\n throw new JwsParseError(\n 'InvalidHeaderShape',\n `JWS header does not match expected shape: ${(cause as Error).message}`\n );\n }\n if (validatedHeader.alg !== 'EdDSA') {\n throw new JwsParseError(\n 'UnsupportedAlgorithm',\n `Unsupported JWS alg \"${validatedHeader.alg}\"; Phase 1 only supports EdDSA`\n );\n }\n // Safe narrowing: alg has been runtime-checked === 'EdDSA' above.\n const header: ParsedJws['header'] = {\n alg: 'EdDSA',\n kid: validatedHeader.kid,\n ...(validatedHeader.typ !== undefined ? { typ: validatedHeader.typ } : {}),\n };\n\n let payloadJson: unknown;\n try {\n payloadJson = JSON.parse(base64UrlDecodeToString(payloadB64));\n } catch (cause) {\n throw new JwsParseError('InvalidJson', `JWS payload is not valid JSON: ${String(cause)}`);\n }\n\n // Runtime shape validation. Cursor-bot review on PR #2546: parsing\n // and casting `as McpIPayload` is a TS-only assertion the runtime\n // can't honor. A crafted JWS missing required fields (notably `ts`)\n // would surface as `undefined` at consumer call-sites and silently\n // skip field-presence checks (e.g., the bouncer's replay-window\n // comparison evaluates `false` on an undefined operand). Validating\n // here means every consumer of `parseJwsCompact` gets a payload\n // whose runtime guarantee matches its TypeScript guarantee.\n let payload: McpIPayload;\n try {\n payload = validateMcpIPayload(payloadJson);\n } catch (cause) {\n throw new JwsParseError(\n 'InvalidPayloadShape',\n `JWS payload does not match McpIPayload shape: ${(cause as Error).message}`\n );\n }\n\n // Validate the base64url alphabet on the signature segment BEFORE\n // decoding. Cursor-bot review on PR #2546: Node's `Buffer.from(s,\n // 'base64')` silently drops invalid characters rather than throwing,\n // so without this check `InvalidBase64` would be unreachable and a\n // signature with stray punctuation would surface as the wrong error\n // code (`InvalidSignatureLength` from the silent truncation). The\n // header/payload segments are validated implicitly by the JSON.parse\n // step that follows them, so they don't need their own alphabet check.\n if (!BASE64URL_ALPHABET.test(signatureB64)) {\n throw new JwsParseError(\n 'InvalidBase64',\n `JWS signature segment contains characters outside the base64url alphabet (RFC 4648 § 5)`\n );\n }\n const signatureBytes = base64UrlDecodeToBytes(signatureB64);\n if (signatureBytes.length !== 64) {\n throw new JwsParseError(\n 'InvalidSignatureLength',\n `Ed25519 signatures are 64 bytes (RFC 8032 § 5.1.6); got ${signatureBytes.length}`\n );\n }\n\n // Signing input is the ASCII bytes of the dot-separated header + payload.\n // Stored verbatim from the input string so callers don't have to re-encode\n // through a (potentially-different) base64url implementation to verify.\n const signingInput = new TextEncoder().encode(`${headerB64}.${payloadB64}`);\n\n return { header, payload, signatureBytes, signingInput };\n}\n\n/**\n * Strict base64url alphabet check (RFC 4648 § 5). The set is\n * `A-Za-z0-9-_` plus optional `=` padding. We use this to validate\n * input BEFORE handing to Node's `Buffer.from(s, 'base64')`, which\n * silently drops invalid characters rather than throwing — bypassing\n * the discriminated `InvalidBase64` error code consumers rely on for\n * HTTP-status mapping.\n *\n * The empty-string case is rejected by the regex (`+` requires ≥1\n * char), which is the desired behavior — an empty segment is a\n * different bug class from \"non-base64 characters in a non-empty\n * segment\" but both warrant the same `InvalidBase64` response.\n */\nconst BASE64URL_ALPHABET = /^[A-Za-z0-9_-]+=*$/;\n\n/**\n * Decode URL-safe base64 (with optional padding) to bytes. RFC 4648 § 5.\n * Tolerates the no-padding form Sign-1 produces AND the padded form\n * some external producers emit.\n *\n * **Caller must validate the input alphabet first** if they want\n * `InvalidBase64` reported as a distinct error class — Node's underlying\n * `Buffer.from(s, 'base64')` silently truncates on invalid characters\n * rather than throwing.\n */\nfunction base64UrlDecodeToBytes(s: string): Uint8Array {\n const padded = s.replace(/-/g, '+').replace(/_/g, '/');\n const padLen = padded.length % 4 === 0 ? 0 : 4 - (padded.length % 4);\n return new Uint8Array(Buffer.from(padded + '='.repeat(padLen), 'base64'));\n}\n\nfunction base64UrlDecodeToString(s: string): string {\n return Buffer.from(base64UrlDecodeToBytes(s)).toString('utf-8');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqEA,SAAgB,wBAAwB,SAAkC;CACxE,MAAM,OAAO,aAAa,OAAO;CACjC,IAAI,SAAS,QAKX,MAAM,IAAI,MAAM,mEAAmE;CAErF,OAAO,IAAI,YAAY,CAAC,CAAC,OAAO,IAAI;AACtC;;;;;;;;;;AAWA,MAAM,yBAAyB;CAC7B;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,oBAAoB,OAA6B;CAC/D,IAAI,UAAU,QAAQ,OAAO,UAAU,UACrC,MAAM,IAAI,MAAM,6BAA6B,UAAU,OAAO,SAAS,OAAO,OAAO;CAEvF,MAAM,MAAM;CAEZ,KAAK,MAAM,SAAS,wBAClB,IAAI,OAAO,IAAI,WAAW,UACxB,MAAM,IAAI,MAAM,yCAAyC,MAAM,SAAS,OAAO,IAAI,O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AgB,IAAI,IAAI,CAAC;CAC1E;CAEA,IAAI;CACJ,IAAI;EACF,cAAc,KAAK,MAAM,wBAAwB,UAAU,CAAC;CAC9D,SAAS,OAAO;EACd,MAAM,IAAI,cAAc,eAAe,kCAAkC,OAAO,KAAK,GAAG;CAC1F;CAUA,IAAI;CACJ,IAAI;EACF,UAAU,oBAAoB,WAAW;CAC3C,SAAS,OAAO;EACd,MAAM,IAAI,cACR,uBACA,iDAAkD,MAAgB,SACpE;CACF;CAUA,IAAI,CAAC,mBAAmB,KAAK,YAAY,GACvC,MAAM,IAAI,cACR,iBACA,yFACF;CAEF,MAAM,iBAAiB,uBAAuB,YAAY;CAC1D,IAAI,eAAe,WAAW,IAC5B,MAAM,IAAI,cACR,0BACA,2DAA2D,eAAe,QAC5E;CAMF,MAAM,eAAe,IAAI,YAAY,CAAC,CAAC,OAAO,GAAG,UAAU,GAAG,YAAY;CAE1E,OAAO;EAAE;EAAQ;EAAS;EAAgB;CAAa;AACzD;;;;;;;;;;;;;;AAeA,MAAM,qBAAqB;;;;;;;;;;;AAY3B,SAAS,uBAAuB,GAAuB;CACrD,MAAM,SAAS,EAAE,QAAQ,MAAM,GAAG,CAAC,CAAC,QAAQ,MAAM,GAAG;CACrD,MAAM,SAAS,OAAO,SAAS,MAAM,IAAI,IAAI,IAAK,OAAO,SAAS;CAClE,OAAO,IAAI,WAAW,OAAO,KAAK,SAAS,IAAI,OAAO,MAAM,GAAG,QAAQ,CAAC;AAC1E;AAEA,SAAS,wBAAwB,GAAmB;CAClD,OAAO,OAAO,KAAK,uBAAuB,CAAC,CAAC,CAAC,CAAC,SAAS,OAAO;AAChE"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/canonical-signer/payload.ts","../../src/mcpi/did-key.ts","../../src/canonical-signer/key.ts","../../src/utils/base64url.ts","../../src/canonical-signer/envelope.ts","../../src/canonical-signer/parse.ts"],"sourcesContent":["/**\n * Canonical KYA-OS signing payload (RFC 8785 / JCS).\n *\n * TS half of the cross-runtime parity contract pinned in\n * `rust/crates/kya-os-engine/src/signing.rs`. Same `McpIPayload` struct,\n * same JCS canonicalization, byte-identical output. The Rust engine's\n * `signing_payload` golden vector at `tests/fixtures/reference_payload.jcs`\n * is the firewall this module asserts against — if these bytes diverge,\n * every downstream signature verification claim is suspect.\n *\n * Field set is locked to KYA-OS spec § 7.4 (eight required claims) +\n * § 7.2 (ProofMeta). Wire format is camelCase per the KYA-OS JSON schema.\n *\n * Sign-1 (#2500). Do NOT extend without ratification through\n * mcp-i-core → D-design → here.\n *\n * @see rust/crates/kya-os-engine/src/signing.rs — Rust struct + JCS function\n * @see rust/crates/kya-os-engine/tests/fixtures/reference_payload.jcs — golden vector\n */\n\nimport canonicalize from 'canonicalize';\n\n/**\n * Structured KYA-OS payload signed by an Ed25519 key.\n *\n * Mirrors `kya_os_engine::signing::McpIPayload` field-for-field. Wire\n * format uses camelCase (matches Rust's `#[serde(rename_all = \"camelCase\")]`).\n *\n * Lexicographic key order on the wire (the JCS member-ordering rule):\n * `aud, iss, nonce, requestHash, responseHash, sessionId, sub, ts`\n */\nexport interface McpIPayload {\n /** Audience — the intended recipient DID or URL. */\n aud: string;\n /** Issuer — the signing principal's DID. */\n iss: string;\n /** Subject — the principal this proof is about (often equal to `iss`). */\n sub: string;\n /** Session nonce — binds the proof to the handshake that established the session. */\n nonce: string;\n /** Session identifier from the handshake response. */\n sessionId: string;\n /** Unix epoch seconds when the proof was generated. */\n ts: number;\n /** SHA-256 hash of the JCS-canonicalized request, formatted as `\"sha256:<64-lowercase-hex>\"`. */\n requestHash: string;\n /** SHA-256 hash of the JCS-canonicalized response, formatted as `\"sha256:<64-lowercase-hex>\"`. */\n responseHash: string;\n}\n\n/**\n * Canonicalize an `McpIPayload` into the byte sequence the Ed25519\n * signature is computed over.\n *\n * **Determinism contract.** Same input MUST produce byte-identical\n * output, every time, every runtime. This function is the cross-runtime\n * parity contract — TS, .NET, Go, Python, and Rust runtimes all\n * implement it independently and MUST agree on the golden vector\n * pinned at `rust/crates/kya-os-engine/tests/fixtures/reference_payload.jcs`.\n *\n * The output is RFC 8785 (JCS) canonical JSON: keys sorted\n * lexicographically by UTF-16 code units, integers serialized without\n * a decimal point, strings escaped only as required, no whitespace.\n *\n * Implementation note: `canonicalize` (npm) is Erdtman's RFC 8785\n * reference implementation. If a future TS host reaches for a\n * different library, the parity firewall test (`canonical-signer.parity.test.ts`)\n * will catch the byte drift before it reaches production.\n */\nexport function canonicalSigningPayload(payload: McpIPayload): Uint8Array {\n const json = canonicalize(payload);\n if (json === undefined) {\n // canonicalize returns undefined for non-serializable inputs\n // (functions, symbols, etc.). McpIPayload's typed fields preclude\n // this, but the runtime check guards against `as McpIPayload` casts\n // at consumer call-sites that bypass the type contract.\n throw new Error('canonicalSigningPayload: payload contains non-serializable values');\n }\n return new TextEncoder().encode(json);\n}\n\n/**\n * Field set that MUST be present for an `McpIPayload` to be valid.\n *\n * Source of truth for `validateMcpIPayload`. The list mirrors the TS\n * `McpIPayload` interface — adding a field there without adding it\n * here is a hidden bypass for the runtime contract. New required\n * fields land in lockstep; new optional fields (post-Scope-1) get\n * a sibling list with a `typeof === 'undefined' || ...` predicate.\n */\nconst REQUIRED_STRING_FIELDS = [\n 'aud',\n 'iss',\n 'sub',\n 'nonce',\n 'sessionId',\n 'requestHash',\n 'responseHash',\n] as const;\n\n/**\n * Runtime type guard: confirms a `JSON.parse` output actually matches\n * `McpIPayload`. Required because `JSON.parse` returns `unknown`, and\n * casting `as McpIPayload` is a *compile-time* assertion that the\n * runtime can't honor — a payload missing required fields silently\n * surfaces as `undefined` at consumer call-sites and bypasses field-\n * presence checks (e.g., the bouncer's replay-window comparison\n * `meta.ts < now - 300` evaluates `false` for `undefined`, skipping\n * the timestamp defense entirely).\n *\n * Throws on the FIRST missing or wrong-typed field — no error\n * accumulation, since one missing claim is enough to reject the\n * envelope and producers should re-issue the entire proof rather than\n * patch field-by-field.\n *\n * @throws Error with a descriptive message identifying the offending\n * field. `parseJwsCompact` translates this into a structured\n * `JwsParseError('InvalidPayloadShape', ...)` for consumers branching\n * on the discriminant.\n */\nexport function validateMcpIPayload(value: unknown): McpIPayload {\n if (value === null || typeof value !== 'object') {\n throw new Error(`expected JSON object, got ${value === null ? 'null' : typeof value}`);\n }\n const obj = value as Record<string, unknown>;\n\n for (const field of REQUIRED_STRING_FIELDS) {\n if (typeof obj[field] !== 'string') {\n throw new Error(`missing or non-string required field \"${field}\" (got ${typeof obj[field]})`);\n }\n }\n\n // ts is the load-bearing exception — number, not string. The bug\n // cursor-bot caught on PR #2546 (replay-window check silently\n // skipped on missing ts) lived on this exact field check.\n if (typeof obj.ts !== 'number' || !Number.isFinite(obj.ts)) {\n throw new Error(`missing or non-finite-number required field \"ts\" (got ${typeof obj.ts})`);\n }\n\n // Validated above: every required field is present and well-typed.\n // The double cast through `unknown` is the standard TS idiom for\n // returning a narrowed type from a `Record<string, unknown>` after\n // runtime checks — necessary because TS doesn't infer narrowing\n // across a for-of loop with dynamic keys.\n return obj as unknown as McpIPayload;\n}\n","/**\n * did:key (Ed25519 multikey) codec — draft-kya-http-02 / H1.2 (#3245).\n *\n * Format: `did:key:z<base58btc(0xed 0x01 || pubkey32)>`\n * The multicodec prefix `0xed 0x01` identifies `ed25519-pub`; the multibase\n * prefix `z` identifies base58btc. An Ed25519 public key is always 32 bytes,\n * so the decoded multikey is always 34 bytes and the did:key always begins\n * `z6Mk` (a fixed consequence of the `0xed01` prefix).\n *\n * This is a PURE-JS port of the base58btc decoder in\n * `apps/web/workers/gateway/src/detection/did-verifier.ts` (repeated-division\n * algorithm), lifted here so the H1.2 pickup endpoint — and future H2.x TS\n * PEPs — can recover the raw key for `node:crypto` Ed25519 verification with\n * zero crypto/runtime dependencies (it runs identically in Node, Cloudflare\n * Workers, and the browser). The encoder is the inverse, for tests and any\n * caller that emits a `did:key` from raw key bytes.\n */\n\nconst BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\nconst BASE58_INDEX: Record<string, number> = (() => {\n const idx: Record<string, number> = {};\n for (let i = 0; i < BASE58_ALPHABET.length; i++) idx[BASE58_ALPHABET[i]] = i;\n return idx;\n})();\n\nconst DID_KEY_PREFIX = 'did:key:';\nconst ED25519_MULTICODEC = [0xed, 0x01] as const; // ed25519-pub\nconst ED25519_PUBKEY_LENGTH = 32;\nconst ED25519_MULTIKEY_LENGTH = ED25519_MULTICODEC.length + ED25519_PUBKEY_LENGTH; // 34\n\n/**\n * Decode a base58btc string to bytes using the repeated-division algorithm.\n * Returns null if the string contains a character outside the base58btc\n * alphabet. Ported verbatim from the gateway worker's `did-verifier.ts`\n * (kept algorithm-identical to avoid cross-runtime drift).\n */\nexport function base58btcDecode(str: string): Uint8Array | null {\n if (str.length === 0) return new Uint8Array(0);\n\n let zeros = 0;\n while (zeros < str.length && str[zeros] === BASE58_ALPHABET[0]) zeros++;\n\n // Sentinel-seeded little-endian byte accumulator.\n const bytes: number[] = [0];\n for (let i = 0; i < str.length; i++) {\n const value = BASE58_INDEX[str[i]];\n if (value === undefined) return null;\n let carry = value;\n for (let j = 0; j < bytes.length; j++) {\n carry += bytes[j] * 58;\n bytes[j] = carry & 0xff;\n carry >>= 8;\n }\n while (carry > 0) {\n bytes.push(carry & 0xff);\n carry >>= 8;\n }\n }\n\n // Drop the trailing zero sentinel(s).\n let high = bytes.length;\n while (high > 0 && bytes[high - 1] === 0) high--;\n\n const out = new Uint8Array(zeros + high);\n for (let i = 0; i < high; i++) {\n out[zeros + high - 1 - i] = bytes[i];\n }\n return out;\n}\n\n/**\n * Encode bytes to a base58btc string — the exact inverse of\n * {@link base58btcDecode}. Leading zero bytes map to leading `1`s; the value\n * is accumulated as little-endian base58 digits (×256 + byte) and emitted\n * big-endian. The high-order zero sentinel is dropped the same way the decoder\n * drops its trailing zeros, so a single `0x00` byte encodes to `\"1\"`, not `\"11\"`.\n */\nexport function base58btcEncode(bytes: Uint8Array): string {\n if (bytes.length === 0) return '';\n\n let zeros = 0;\n while (zeros < bytes.length && bytes[zeros] === 0) zeros++;\n\n const digits: number[] = [0];\n for (let i = 0; i < bytes.length; i++) {\n let carry = bytes[i];\n for (let j = 0; j < digits.length; j++) {\n carry += digits[j] * 256;\n digits[j] = carry % 58;\n carry = Math.floor(carry / 58);\n }\n while (carry > 0) {\n digits.push(carry % 58);\n carry = Math.floor(carry / 58);\n }\n }\n\n // Drop the high-order zero sentinel(s); leading zero bytes become '1's.\n let high = digits.length;\n while (high > 0 && digits[high - 1] === 0) high--;\n\n let out = BASE58_ALPHABET[0].repeat(zeros);\n for (let i = high - 1; i >= 0; i--) {\n out += BASE58_ALPHABET[digits[i]];\n }\n return out;\n}\n\n/**\n * Recover the raw 32-byte Ed25519 public key from a `did:key:z6Mk…` string.\n * Returns null for any malformed input: wrong method, wrong multibase, invalid\n * base58, wrong decoded length, or a non-Ed25519 multicodec. Never throws —\n * callers treat null as \"not a verifiable Ed25519 did:key\".\n */\nexport function decodeDidKeyEd25519(did: string): Uint8Array | null {\n if (typeof did !== 'string' || !did.startsWith(DID_KEY_PREFIX)) return null;\n\n const suffix = did.slice(DID_KEY_PREFIX.length);\n if (!suffix.startsWith('z')) return null; // base58btc multibase prefix\n\n // A legit Ed25519 did:key body is fixed at 47 base58 chars. Cap the length\n // BEFORE the O(n^2) repeated-division decode: this keyid arrives from an\n // attacker-controlled Signature-Input header on the public pickup endpoint, so\n // an over-long body (which the 34-byte length check would reject anyway) must\n // not be allowed to burn quadratic event-loop CPU first.\n const body = suffix.slice(1);\n if (body.length > 64) return null;\n\n const decoded = base58btcDecode(body);\n if (!decoded || decoded.length !== ED25519_MULTIKEY_LENGTH) return null;\n if (decoded[0] !== ED25519_MULTICODEC[0] || decoded[1] !== ED25519_MULTICODEC[1]) return null;\n\n return decoded.slice(ED25519_MULTICODEC.length);\n}\n\n/** Recover the compressed SEC1 point from the HTTP profile's p256-pub\n * multicodec (0x1200). This runtime-independent codec validates carriage only;\n * the cryptographic consumer MUST validate that the point lies on P-256 before\n * trusting it or deriving a confirmation thumbprint. */\nexport function decodeDidKeyP256(did: string): Uint8Array | null {\n if (typeof did !== 'string' || !did.startsWith(`${DID_KEY_PREFIX}z`)) return null;\n const body = did.slice(DID_KEY_PREFIX.length + 1);\n // Bound the quadratic base58 decoder before processing untrusted keyids.\n if (body.length > 64) return null;\n const decoded = base58btcDecode(body);\n if (\n !decoded ||\n decoded.length !== 35 ||\n decoded[0] !== 0x80 ||\n decoded[1] !== 0x24 ||\n (decoded[2] !== 2 && decoded[2] !== 3)\n )\n return null;\n return decoded.slice(2);\n}\n\n/**\n * Encode a raw 32-byte Ed25519 public key as a `did:key:z6Mk…` string. Throws\n * if the key is not exactly 32 bytes — an emitter handing in the wrong length\n * is a programming error, not untrusted input (unlike {@link decodeDidKeyEd25519}).\n */\nexport function encodeDidKeyEd25519(publicKey: Uint8Array): string {\n if (!(publicKey instanceof Uint8Array) || publicKey.length !== ED25519_PUBKEY_LENGTH) {\n throw new Error(\n `encodeDidKeyEd25519: expected a ${ED25519_PUBKEY_LENGTH}-byte Ed25519 public key, got ${\n publicKey instanceof Uint8Array ? `${publicKey.length} bytes` : typeof publicKey\n }`\n );\n }\n\n const multikey = new Uint8Array(ED25519_MULTIKEY_LENGTH);\n multikey[0] = ED25519_MULTICODEC[0];\n multikey[1] = ED25519_MULTICODEC[1];\n multikey.set(publicKey, ED25519_MULTICODEC.length);\n\n return `${DID_KEY_PREFIX}z${base58btcEncode(multikey)}`;\n}\n","/**\n * Ed25519 keypair derivation for KYA-OS detached proofs.\n *\n * Derives a `KeyMaterial` bundle (signing key, public key, did:key, kid)\n * from a 32-byte seed. The derivation MUST agree byte-for-byte with\n * Rust's `ed25519_dalek::SigningKey::from_bytes` + did:key formatter so\n * H-1's committed test fixtures (`signer.seed` + `signer.public_key`)\n * derive identically across runtimes.\n *\n * `kid` form follows mcp-i-core PR #16 (multibase-as-fragment):\n * `did:key:z6Mk...#z6Mk...`. NOT `#keys-1`. NOT `#1`. The H-1\n * `stage2_did_key_fragment_resolution` test pins this on the verifier\n * side; this module pins it on the producer side.\n *\n * Sign-1 (#2500).\n */\n\nimport { getPublicKeyAsync } from '@noble/ed25519';\n// Pure-JS base58btc encode (not multiformats' `bases/base58` subpath):\n// that subpath's package.json `exports` map ships an `import` condition\n// only, no `require` — reaching it from this subpath's own CJS build\n// crashes with ERR_PACKAGE_PATH_NOT_EXPORTED before any application code\n// runs. `base58btcEncode` is the same dependency-free codec did:key\n// verification already uses elsewhere in this package.\nimport { base58btcEncode } from '../mcpi/did-key';\n\n/**\n * Multicodec prefix for Ed25519 verifying keys per the W3C did:key spec\n * (`0xed01` varint). Prepended to the 32-byte public key, base58btc-\n * encoded with the `z` multibase prefix to produce the did:key suffix.\n */\nconst ED25519_MULTICODEC_PREFIX = new Uint8Array([0xed, 0x01]);\n\n/**\n * Bundle of derived key material. Carries the signing key, the public\n * key, the canonical did:key DID, and the verification-method `kid`\n * (multibase-as-fragment per mcp-i-core PR #16).\n *\n * `signingKey` is a **copy** of the input seed, not a reference — see\n * `parseSigningKey` for the rationale. Treat the bundle as the owning\n * holder of the key material; the caller's original seed buffer is\n * safe to zero out after `parseSigningKey` returns.\n */\nexport interface KeyMaterial {\n /** The 32-byte Ed25519 secret seed (defensive copy of the input). */\n signingKey: Uint8Array;\n /** The 32-byte Ed25519 public verifying key. */\n publicKey: Uint8Array;\n /** The canonical did:key DID — `did:key:z6Mk...`. */\n did: string;\n /**\n * The verification-method id for this DID — multibase as fragment per\n * mcp-i-core PR #16 (`did:key:z6Mk...#z6Mk...`). Goes into the JWS\n * header `kid` field.\n */\n kid: string;\n}\n\n/**\n * Derive a `KeyMaterial` bundle from a 32-byte Ed25519 seed.\n *\n * The seed IS the signing key (per RFC 8032 § 5.1.5 — Ed25519 secret\n * keys are 32-byte seeds; the expanded scalar is computed at sign time).\n * Same seed → same `(publicKey, did, kid)` deterministically across\n * any RFC 8032 implementation.\n *\n * The input seed is **defensively copied** into the returned\n * `KeyMaterial.signingKey`. Subsequent mutations of the caller's\n * buffer (zeroization, key rotation, fixture reuse) do NOT affect\n * the key bundle. Callers that own the seed are free to scrub it\n * after this function returns.\n *\n * @throws if the seed is not exactly 32 bytes.\n */\nexport async function parseSigningKey(seed: Uint8Array): Promise<KeyMaterial> {\n if (seed.length !== 32) {\n throw new Error(`parseSigningKey: expected 32-byte Ed25519 seed, got ${seed.length} bytes`);\n }\n\n const publicKey = await getPublicKeyAsync(seed);\n\n // did:key z-encoded multibase per W3C spec: 0xed01 || pubkey, then\n // base58btc-encoded. The 'z' prefix is part of base58btc's multibase\n // alphabet; encode() returns it already prepended.\n const multibaseBytes = new Uint8Array(ED25519_MULTICODEC_PREFIX.length + publicKey.length);\n multibaseBytes.set(ED25519_MULTICODEC_PREFIX, 0);\n multibaseBytes.set(publicKey, ED25519_MULTICODEC_PREFIX.length);\n const multibase = `z${base58btcEncode(multibaseBytes)}`;\n const did = `did:key:${multibase}`;\n\n return {\n // Defensive copy — see KeyMaterial.signingKey docstring. The Sign-1\n // tests assert that mutating the input seed after this call does NOT\n // mutate the held key material.\n signingKey: Uint8Array.from(seed),\n publicKey,\n did,\n // mcp-i-core PR #16: the verification-method id is the multibase value\n // as a fragment. Anything else (`#keys-1`, `#1`, etc.) breaks H-1's\n // stage2_did_key_fragment_resolution.\n kid: `${did}#${multibase}`,\n };\n}\n","/**\n * Base64url (RFC 4648 § 5) built on `atob` and `btoa` rather than Node's\n * buffer API, so it runs on every runtime the SDKs support, Cloudflare Workers\n * without `nodejs_compat` included.\n */\n\nconst BASE64URL_UNPADDED = /^[A-Za-z0-9_-]*$/;\nconst PADDING = 61; // '='\n\n/**\n * `text` without its trailing `=` padding. A backward scan, not\n * `replace(/=+$/, '')`: that regex retries from every `=` in a long run that\n * does not reach the end, which is quadratic on hostile input.\n */\nfunction withoutPadding(text: string): string {\n let end = text.length;\n while (end > 0 && text.charCodeAt(end - 1) === PADDING) end -= 1;\n return text.slice(0, end);\n}\n\n/**\n * Decode base64url, with or without `=` padding.\n *\n * Strict where Node's buffer decoder is lenient: a character outside the\n * alphabet, or a length no encoder produces (one character past a multiple of\n * four), throws a `TypeError` instead of being skipped or truncated. This\n * matches the engine's decoder.\n */\nexport function base64UrlToBytes(text: string): Uint8Array {\n const unpadded = withoutPadding(text);\n if (!BASE64URL_UNPADDED.test(unpadded) || unpadded.length % 4 === 1) {\n throw new TypeError('not valid base64url (RFC 4648 § 5)');\n }\n const base64 = unpadded.replace(/-/g, '+').replace(/_/g, '/');\n const binary = atob(base64 + '='.repeat((4 - (base64.length % 4)) % 4));\n const bytes = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index += 1) {\n bytes[index] = binary.charCodeAt(index);\n }\n return bytes;\n}\n\n/** Decode base64url to a string as UTF-8, replacing invalid sequences with U+FFFD. */\nexport function base64UrlToString(text: string): string {\n return new TextDecoder().decode(base64UrlToBytes(text));\n}\n\n/** Encode bytes as base64url without padding. */\nexport function bytesToBase64Url(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return withoutPadding(btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_'));\n}\n","/**\n * JWS-compact envelope construction for KYA-OS detached proofs.\n *\n * Produces wire bytes the engine's H-1 parser (#2486) accepts:\n *\n * BASE64URL(header) \".\" BASE64URL(payload) \".\" BASE64URL(signature)\n *\n * where the header is `{ \"alg\": \"EdDSA\", \"kid\": \"<verification-method-id>\" }`,\n * the payload is the JCS-canonicalized `McpIPayload`, and the signature is\n * Ed25519 over `BASE64URL(header) || '.' || BASE64URL(payload)` per\n * RFC 7515 § 5.1.\n *\n * Sign-1 (#2500). Output of this function is what every TS producer in the\n * org emits — bouncer middleware (Envelope-1), Sites-1/2 e2e helpers, future\n * Sites-4 parity drivers, the Adobe trial.\n */\n\nimport { signAsync } from '@noble/ed25519';\nimport { canonicalSigningPayload, type McpIPayload } from './payload';\nimport type { KeyMaterial } from './key';\nimport { bytesToBase64Url } from '../utils/base64url';\n\n/**\n * Sign an `McpIPayload` and produce a compact-JWS envelope ready to drop\n * into `_meta.proof.jws` of the request body per KYA-OS spec § 7.4.\n *\n * The signing input is `BASE64URL(header) || '.' || BASE64URL(payload)`,\n * NOT the canonical-JSON bytes. The canonicalization happens *inside* the\n * payload base64url segment; the Ed25519 signature happens *over* the dot-\n * separated structure. This is the RFC 7515 § 5.1 contract that H-1's\n * `verify_strict` checks against.\n *\n * @param payload — the structured KYA-OS claims (eight required fields).\n * @param key — derived via `parseSigningKey(seed)`. The header `kid` is\n * set from `key.kid` (multibase-as-fragment per mcp-i-core PR #16).\n * @returns the compact-JWS string `<headerB64>.<payloadB64>.<signatureB64>`.\n */\nexport async function signMcpiEnvelope(payload: McpIPayload, key: KeyMaterial): Promise<string> {\n const header = { alg: 'EdDSA', kid: key.kid };\n const headerJson = JSON.stringify(header);\n const headerB64 = bytesToBase64Url(new TextEncoder().encode(headerJson));\n\n const payloadB64 = bytesToBase64Url(canonicalSigningPayload(payload));\n\n // RFC 7515 § 5.1: signing input is the ASCII bytes of the dot-separated\n // header and payload. `TextEncoder` produces UTF-8, which is identical to\n // ASCII for the base64url alphabet (`A-Za-z0-9-_`) and the literal '.'.\n const signingInput = new TextEncoder().encode(`${headerB64}.${payloadB64}`);\n const signature = await signAsync(signingInput, key.signingKey);\n const signatureB64 = bytesToBase64Url(signature);\n\n return `${headerB64}.${payloadB64}.${signatureB64}`;\n}\n","/**\n * Compact-JWS parser for KYA-OS detached proofs.\n *\n * Producer-side counterpart to Sign-1's `signMcpiEnvelope`: takes the\n * wire string the engine's H-1 parser would consume and decomposes it\n * into the same logical pieces (header, payload, signature, signing\n * input). Lives in `checkpoint-shared/canonical-signer/` so producer\n * AND consumer share one wire-format implementation — the JCS / base64\n * subtleties are handled in one place, not three.\n *\n * Consumed by:\n * - `@kya-os/bouncer-middleware` (Envelope-1 / #2537)\n * - any future TS host that needs to introspect a JWS without going\n * through the WASM bridge\n *\n * The Rust engine's `jws::parse_jws_compact` is the structural mirror\n * (`rust/crates/kya-os-engine/src/jws.rs`); this module produces the\n * same logical decomposition. Cross-runtime parity here is implicit:\n * if both parsers consume the same JWS string and disagree on what's\n * inside, the H-1 fixtures would catch it.\n *\n * Sign-1 (#2500). Anti-pattern: don't write a parallel parser\n * elsewhere in the org — import from here.\n */\n\nimport { base64UrlToBytes, base64UrlToString } from '../utils/base64url';\nimport type { McpIPayload } from './payload';\nimport { validateMcpIPayload } from './payload';\n\n/**\n * The decomposed compact-JWS envelope.\n *\n * `signingInput` is stored separately so callers don't have to re-encode\n * the header + payload to verify the signature — re-encoding through a\n * different base64url implementation is a known source of \"should-be-\n * identical bytes drift differently\" canonicalization bugs (the same\n * class of risk that Sign-1's JCS parity firewall guards against on the\n * payload side).\n */\nexport interface ParsedJws {\n /** Decoded JWS Protected Header. Phase 1 only supports `alg: \"EdDSA\"`. */\n header: {\n alg: 'EdDSA';\n /** Verification-method id — multibase-as-fragment for did:key per\n * mcp-i-core PR #16 (`did:key:z...#z...`); whatever the DID\n * document declares for did:web (typically `#key-1`). */\n kid: string;\n /** Optional `typ` per RFC 7515. Bouncer ignores; preserved for\n * forward-compat with future header extensions. */\n typ?: string;\n };\n /** Decoded KYA-OS payload — the eight-field signing struct. */\n payload: McpIPayload;\n /** Raw 64-byte ed25519 signature segment. */\n signatureBytes: Uint8Array;\n /**\n * `header_b64 + \".\" + payload_b64` as ASCII bytes — the signing\n * input ed25519 verifies against per RFC 7515 § 5.1. Stored\n * verbatim from the input string (no re-encode round-trip).\n */\n signingInput: Uint8Array;\n}\n\n/**\n * Discriminated error type so consumers can map parse failures to\n * appropriate response codes (400 for malformed shape, 422 for\n * unsupported alg) without string-matching error messages.\n */\nexport class JwsParseError extends Error {\n constructor(\n /** Machine-readable failure category. */\n public readonly code:\n | 'WrongSegmentCount'\n | 'InvalidBase64'\n | 'InvalidJson'\n | 'InvalidHeaderShape'\n | 'InvalidPayloadShape'\n | 'UnsupportedAlgorithm'\n | 'InvalidSignatureLength',\n message: string\n ) {\n super(message);\n this.name = 'JwsParseError';\n }\n}\n\n/**\n * Wider intermediate shape returned by `validateJwsHeader`.\n *\n * Deliberately keeps `alg` as `string` (not `'EdDSA'`) — the validator\n * only proves it's a non-empty string, not that it's the supported\n * algorithm. Narrowing to the literal type happens at the alg-check\n * site in `parseJwsCompact`, where the failure can be surfaced under\n * the correct discriminant (`UnsupportedAlgorithm`, not\n * `InvalidHeaderShape`).\n *\n * Cursor-bot review on PR #2551: the previous version returned the\n * narrowed `ParsedJws['header']` via a double cast, which lied about\n * the runtime guarantee. Strict linters (`@typescript-eslint/no-\n * unnecessary-condition`) would have flagged the downstream\n * `header.alg !== 'EdDSA'` check as always-false and suggested\n * removing it — silently letting non-EdDSA algorithms through.\n */\ninterface ValidatedJwsHeaderShape {\n alg: string;\n kid: string;\n typ?: string;\n}\n\n/**\n * Runtime type guard for the JWS Protected Header (RFC 7515 § 4).\n *\n * Mirror of `validateMcpIPayload` for the header side of the envelope.\n * Cursor-bot review on PR #2546 caught two classes of bug the unguarded\n * `JSON.parse → cast` flow let through:\n *\n * 1. **Missing `kid`** — header parses, `header.kid === undefined`\n * typed as string, propagates into the bouncer's sidecar and gets\n * dropped by JSON.stringify → malformed payload at the remote.\n * 2. **Null JSON header** (`bnVsbA` base64url) — `JSON.parse` returns\n * `null`, `header.alg` access throws TypeError, escapes the\n * bouncer's `instanceof JwsParseError` guard → leaks as 500. Easy\n * DoS/probe vector.\n *\n * Both go away by validating before any property access. Throws plain\n * Error; `parseJwsCompact` translates into `JwsParseError('InvalidHeaderShape', …)`.\n *\n * Returns `ValidatedJwsHeaderShape` with `alg: string` (not `'EdDSA'`).\n * The literal-type narrowing is the caller's responsibility — keeping\n * the failure-category boundary clean: shape failures from this\n * validator surface as `InvalidHeaderShape`; algorithm-support failures\n * surface separately as `UnsupportedAlgorithm`.\n */\nfunction validateJwsHeader(value: unknown): ValidatedJwsHeaderShape {\n if (value === null || typeof value !== 'object') {\n throw new Error(`expected JSON object, got ${value === null ? 'null' : typeof value}`);\n }\n const obj = value as Record<string, unknown>;\n\n if (typeof obj.alg !== 'string' || obj.alg.length === 0) {\n throw new Error(`missing or non-string required field \"alg\" (got ${typeof obj.alg})`);\n }\n if (typeof obj.kid !== 'string' || obj.kid.length === 0) {\n throw new Error(`missing or non-string required field \"kid\" (got ${typeof obj.kid})`);\n }\n if (obj.typ !== undefined && typeof obj.typ !== 'string') {\n throw new Error(`optional field \"typ\" must be a string when present (got ${typeof obj.typ})`);\n }\n\n return obj as unknown as ValidatedJwsHeaderShape;\n}\n\n/**\n * Parse a compact-JWS string per RFC 7515 § 3.1 + § 5.1.\n *\n * Three segments separated by `.`, each base64url-encoded\n * (`A-Za-z0-9-_`, no padding). Header is JSON with at minimum\n * `alg: \"EdDSA\"` + `kid`. Payload is the JCS-canonicalized\n * `McpIPayload`. Signature segment decodes to exactly 64 bytes\n * (Ed25519 fixed-length per RFC 8032 § 5.1.6).\n *\n * @throws {@link JwsParseError} with a structured `code` for malformed\n * shape, invalid base64url, invalid JSON, unsupported algorithm, or\n * wrong signature length. Cryptographic verification is OUT of scope\n * — the engine (or `@noble/ed25519` round-trip) does that against\n * `signatureBytes` over `signingInput`.\n */\nexport function parseJwsCompact(jws: string): ParsedJws {\n const parts = jws.split('.');\n if (parts.length !== 3) {\n throw new JwsParseError(\n 'WrongSegmentCount',\n `Expected 3 dot-separated segments per RFC 7515 § 3.1; got ${parts.length}`\n );\n }\n const [headerB64, payloadB64, signatureB64] = parts;\n\n let headerJson: unknown;\n try {\n headerJson = JSON.parse(base64UrlToString(headerB64));\n } catch (cause) {\n throw new JwsParseError('InvalidJson', `JWS header is not valid JSON: ${String(cause)}`);\n }\n\n // Runtime shape validation for the header. Two cursor-bot findings on\n // PR #2546 motivate this:\n //\n // 1. A header with `{\"alg\":\"EdDSA\"}` (no `kid`) parsed successfully\n // and surfaced `header.kid === undefined` typed as string. The\n // bouncer's sidecar synthesis copied that into `meta.kid`, which\n // JSON.stringify silently drops, producing a malformed `{jws,\n // meta}` payload at the remote endpoint.\n //\n // 2. A header that decodes to JSON literal `null` (base64url of\n // `\"null\"` → `bnVsbA`) made `JSON.parse` succeed and assign\n // `null` to `header`. The subsequent `header.alg` access threw\n // a TypeError, which the bouncer's `instanceof JwsParseError`\n // guard let through — a 500 API_ERROR instead of a clean 401.\n // Trivially exploitable by an attacker.\n //\n // Both classes go away by validating the shape before any property\n // access. Same pattern as `validateMcpIPayload`.\n //\n // `validatedHeader` holds the wider `ValidatedJwsHeaderShape` (alg as\n // string) so the algorithm-support check below isn't redundant from\n // TS's perspective. After the check passes, we narrow to the final\n // `ParsedJws['header']` (alg as the 'EdDSA' literal). Cursor-bot\n // review on PR #2551: returning the narrowed type from the validator\n // would lie about the runtime guarantee and let strict linters\n // remove the alg check as \"always-false.\"\n let validatedHeader: ValidatedJwsHeaderShape;\n try {\n validatedHeader = validateJwsHeader(headerJson);\n } catch (cause) {\n throw new JwsParseError(\n 'InvalidHeaderShape',\n `JWS header does not match expected shape: ${(cause as Error).message}`\n );\n }\n if (validatedHeader.alg !== 'EdDSA') {\n throw new JwsParseError(\n 'UnsupportedAlgorithm',\n `Unsupported JWS alg \"${validatedHeader.alg}\"; Phase 1 only supports EdDSA`\n );\n }\n // Safe narrowing: alg has been runtime-checked === 'EdDSA' above.\n const header: ParsedJws['header'] = {\n alg: 'EdDSA',\n kid: validatedHeader.kid,\n ...(validatedHeader.typ !== undefined ? { typ: validatedHeader.typ } : {}),\n };\n\n let payloadJson: unknown;\n try {\n payloadJson = JSON.parse(base64UrlToString(payloadB64));\n } catch (cause) {\n throw new JwsParseError('InvalidJson', `JWS payload is not valid JSON: ${String(cause)}`);\n }\n\n // Runtime shape validation. Cursor-bot review on PR #2546: parsing\n // and casting `as McpIPayload` is a TS-only assertion the runtime\n // can't honor. A crafted JWS missing required fields (notably `ts`)\n // would surface as `undefined` at consumer call-sites and silently\n // skip field-presence checks (e.g., the bouncer's replay-window\n // comparison evaluates `false` on an undefined operand). Validating\n // here means every consumer of `parseJwsCompact` gets a payload\n // whose runtime guarantee matches its TypeScript guarantee.\n let payload: McpIPayload;\n try {\n payload = validateMcpIPayload(payloadJson);\n } catch (cause) {\n throw new JwsParseError(\n 'InvalidPayloadShape',\n `JWS payload does not match McpIPayload shape: ${(cause as Error).message}`\n );\n }\n\n // A signature segment that is not base64url is `InvalidBase64`, never\n // `InvalidSignatureLength`: consumers map the codes to HTTP statuses.\n // The header/payload segments are covered by the JSON.parse step that\n // follows their decode, so they report `InvalidJson`.\n if (!BASE64URL_ALPHABET.test(signatureB64)) {\n throw new JwsParseError(\n 'InvalidBase64',\n `JWS signature segment contains characters outside the base64url alphabet (RFC 4648 § 5)`\n );\n }\n let signatureBytes: Uint8Array;\n try {\n signatureBytes = base64UrlToBytes(signatureB64);\n } catch {\n // In the alphabet but a length no encoder produces (one character past\n // a multiple of four). The engine's decoder rejects it the same way.\n throw new JwsParseError(\n 'InvalidBase64',\n `JWS signature segment is not a valid base64url length (RFC 4648 § 5)`\n );\n }\n if (signatureBytes.length !== 64) {\n throw new JwsParseError(\n 'InvalidSignatureLength',\n `Ed25519 signatures are 64 bytes (RFC 8032 § 5.1.6); got ${signatureBytes.length}`\n );\n }\n\n // Signing input is the ASCII bytes of the dot-separated header + payload.\n // Stored verbatim from the input string so callers don't have to re-encode\n // through a (potentially-different) base64url implementation to verify.\n const signingInput = new TextEncoder().encode(`${headerB64}.${payloadB64}`);\n\n return { header, payload, signatureBytes, signingInput };\n}\n\n/**\n * Strict base64url alphabet check (RFC 4648 § 5): `A-Za-z0-9-_` plus optional\n * `=` padding. The empty string fails it on purpose: an empty signature\n * segment is reported as `InvalidBase64` too.\n */\nconst BASE64URL_ALPHABET = /^[A-Za-z0-9_-]+=*$/;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqEA,SAAgB,wBAAwB,SAAkC;CACxE,MAAM,OAAO,aAAa,OAAO;CACjC,IAAI,SAAS,QAKX,MAAM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AAgB;EACrB,GAAI,gBAAgB,QAAQ,SAAY,EAAE,KAAK,gBAAgB,IAAI,IAAI,CAAC;CAC1E;CAEA,IAAI;CACJ,IAAI;EACF,cAAc,KAAK,MAAM,kBAAkB,UAAU,CAAC;CACxD,SAAS,OAAO;EACd,MAAM,IAAI,cAAc,eAAe,kCAAkC,OAAO,KAAK,GAAG;CAC1F;CAUA,IAAI;CACJ,IAAI;EACF,UAAU,oBAAoB,WAAW;CAC3C,SAAS,OAAO;EACd,MAAM,IAAI,cACR,uBACA,iDAAkD,MAAgB,SACpE;CACF;CAMA,IAAI,CAAC,mBAAmB,KAAK,YAAY,GACvC,MAAM,IAAI,cACR,iBACA,yFACF;CAEF,IAAI;CACJ,IAAI;EACF,iBAAiB,iBAAiB,YAAY;CAChD,QAAQ;EAGN,MAAM,IAAI,cACR,iBACA,sEACF;CACF;CACA,IAAI,eAAe,WAAW,IAC5B,MAAM,IAAI,cACR,0BACA,2DAA2D,eAAe,QAC5E;CAMF,MAAM,eAAe,IAAI,YAAY,CAAC,CAAC,OAAO,GAAG,UAAU,GAAG,YAAY;CAE1E,OAAO;EAAE;EAAQ;EAAS;EAAgB;CAAa;AACzD;;;;;;AAOA,MAAM,qBAAqB"}
|
package/dist/clearance.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { E as ZodObject, L as output, T as ZodNumber, V as $strip, j as ZodString, t as external_d_exports, x as ZodLiteral } from "./external-B7WI9FyQ.mjs";
|
|
2
2
|
import { JWK } from "jose";
|
|
3
3
|
//#region src/clearance.d.ts
|
|
4
4
|
export declare const CLEARANCE_TTL_SECONDS = 600;
|
package/dist/clearance.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { E as ZodObject, L as output, T as ZodNumber, V as $strip, j as ZodString, t as external_d_exports, x as ZodLiteral } from "./external-B7WI9FyQ.js";
|
|
2
2
|
import { JWK } from "jose";
|
|
3
3
|
//#region src/clearance.d.ts
|
|
4
4
|
export declare const CLEARANCE_TTL_SECONDS = 600;
|
package/dist/clearance.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
-
const require_schemas = require('./schemas-
|
|
3
|
-
const require_project_verification_key = require('./project-verification-key-
|
|
2
|
+
const require_schemas = require('./schemas-YhagYDx_.js');
|
|
3
|
+
const require_project_verification_key = require('./project-verification-key-BccT12tQ.js');
|
|
4
4
|
let jose = require("jose");
|
|
5
5
|
|
|
6
6
|
//#region src/clearance.ts
|
package/dist/clearance.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { t as projectVerificationKey } from "./project-verification-key-
|
|
1
|
+
import { C as string, g as literal, v as number, y as object } from "./schemas-7qodsG-Z.mjs";
|
|
2
|
+
import { t as projectVerificationKey } from "./project-verification-key-66N4edKn.mjs";
|
|
3
3
|
import { SignJWT, importJWK, jwtVerify } from "jose";
|
|
4
4
|
|
|
5
5
|
//#region src/clearance.ts
|