@kya-os/checkpoint-shared 1.0.0 → 1.2.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.
@@ -0,0 +1,175 @@
1
+ import canonicalize from 'canonicalize';
2
+ import { getPublicKeyAsync, signAsync } from '@noble/ed25519';
3
+ import { base58btc } from 'multiformats/bases/base58';
4
+
5
+ // src/canonical-signer/payload.ts
6
+ function canonicalSigningPayload(payload) {
7
+ const json = canonicalize(payload);
8
+ if (json === void 0) {
9
+ throw new Error("canonicalSigningPayload: payload contains non-serializable values");
10
+ }
11
+ return new TextEncoder().encode(json);
12
+ }
13
+ var REQUIRED_STRING_FIELDS = [
14
+ "aud",
15
+ "iss",
16
+ "sub",
17
+ "nonce",
18
+ "sessionId",
19
+ "requestHash",
20
+ "responseHash"
21
+ ];
22
+ function validateMcpIPayload(value) {
23
+ if (value === null || typeof value !== "object") {
24
+ throw new Error(`expected JSON object, got ${value === null ? "null" : typeof value}`);
25
+ }
26
+ const obj = value;
27
+ for (const field of REQUIRED_STRING_FIELDS) {
28
+ if (typeof obj[field] !== "string") {
29
+ throw new Error(`missing or non-string required field "${field}" (got ${typeof obj[field]})`);
30
+ }
31
+ }
32
+ if (typeof obj.ts !== "number" || !Number.isFinite(obj.ts)) {
33
+ throw new Error(`missing or non-finite-number required field "ts" (got ${typeof obj.ts})`);
34
+ }
35
+ return obj;
36
+ }
37
+ var ED25519_MULTICODEC_PREFIX = new Uint8Array([237, 1]);
38
+ async function parseSigningKey(seed) {
39
+ if (seed.length !== 32) {
40
+ throw new Error(`parseSigningKey: expected 32-byte Ed25519 seed, got ${seed.length} bytes`);
41
+ }
42
+ const publicKey = await getPublicKeyAsync(seed);
43
+ const multibaseBytes = new Uint8Array(ED25519_MULTICODEC_PREFIX.length + publicKey.length);
44
+ multibaseBytes.set(ED25519_MULTICODEC_PREFIX, 0);
45
+ multibaseBytes.set(publicKey, ED25519_MULTICODEC_PREFIX.length);
46
+ const multibase = base58btc.encode(multibaseBytes);
47
+ const did = `did:key:${multibase}`;
48
+ return {
49
+ // Defensive copy — see KeyMaterial.signingKey docstring. The Sign-1
50
+ // tests assert that mutating the input seed after this call does NOT
51
+ // mutate the held key material.
52
+ signingKey: Uint8Array.from(seed),
53
+ publicKey,
54
+ did,
55
+ // mcp-i-core PR #16: the verification-method id is the multibase value
56
+ // as a fragment. Anything else (`#keys-1`, `#1`, etc.) breaks H-1's
57
+ // stage2_did_key_fragment_resolution.
58
+ kid: `${did}#${multibase}`
59
+ };
60
+ }
61
+ function base64UrlEncode(bytes) {
62
+ return Buffer.from(bytes).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
63
+ }
64
+ async function signMcpiEnvelope(payload, key) {
65
+ const header = { alg: "EdDSA", kid: key.kid };
66
+ const headerJson = JSON.stringify(header);
67
+ const headerB64 = base64UrlEncode(new TextEncoder().encode(headerJson));
68
+ const payloadB64 = base64UrlEncode(canonicalSigningPayload(payload));
69
+ const signingInput = new TextEncoder().encode(`${headerB64}.${payloadB64}`);
70
+ const signature = await signAsync(signingInput, key.signingKey);
71
+ const signatureB64 = base64UrlEncode(signature);
72
+ return `${headerB64}.${payloadB64}.${signatureB64}`;
73
+ }
74
+
75
+ // src/canonical-signer/parse.ts
76
+ var JwsParseError = class extends Error {
77
+ constructor(code, message) {
78
+ super(message);
79
+ this.code = code;
80
+ this.name = "JwsParseError";
81
+ }
82
+ };
83
+ function validateJwsHeader(value) {
84
+ if (value === null || typeof value !== "object") {
85
+ throw new Error(`expected JSON object, got ${value === null ? "null" : typeof value}`);
86
+ }
87
+ const obj = value;
88
+ if (typeof obj.alg !== "string" || obj.alg.length === 0) {
89
+ throw new Error(`missing or non-string required field "alg" (got ${typeof obj.alg})`);
90
+ }
91
+ if (typeof obj.kid !== "string" || obj.kid.length === 0) {
92
+ throw new Error(`missing or non-string required field "kid" (got ${typeof obj.kid})`);
93
+ }
94
+ if (obj.typ !== void 0 && typeof obj.typ !== "string") {
95
+ throw new Error(`optional field "typ" must be a string when present (got ${typeof obj.typ})`);
96
+ }
97
+ return obj;
98
+ }
99
+ function parseJwsCompact(jws) {
100
+ const parts = jws.split(".");
101
+ if (parts.length !== 3) {
102
+ throw new JwsParseError(
103
+ "WrongSegmentCount",
104
+ `Expected 3 dot-separated segments per RFC 7515 \xA7 3.1; got ${parts.length}`
105
+ );
106
+ }
107
+ const [headerB64, payloadB64, signatureB64] = parts;
108
+ let headerJson;
109
+ try {
110
+ headerJson = JSON.parse(base64UrlDecodeToString(headerB64));
111
+ } catch (cause) {
112
+ throw new JwsParseError("InvalidJson", `JWS header is not valid JSON: ${String(cause)}`);
113
+ }
114
+ let validatedHeader;
115
+ try {
116
+ validatedHeader = validateJwsHeader(headerJson);
117
+ } catch (cause) {
118
+ throw new JwsParseError(
119
+ "InvalidHeaderShape",
120
+ `JWS header does not match expected shape: ${cause.message}`
121
+ );
122
+ }
123
+ if (validatedHeader.alg !== "EdDSA") {
124
+ throw new JwsParseError(
125
+ "UnsupportedAlgorithm",
126
+ `Unsupported JWS alg "${validatedHeader.alg}"; Phase 1 only supports EdDSA`
127
+ );
128
+ }
129
+ const header = {
130
+ alg: "EdDSA",
131
+ kid: validatedHeader.kid,
132
+ ...validatedHeader.typ !== void 0 ? { typ: validatedHeader.typ } : {}
133
+ };
134
+ let payloadJson;
135
+ try {
136
+ payloadJson = JSON.parse(base64UrlDecodeToString(payloadB64));
137
+ } catch (cause) {
138
+ throw new JwsParseError("InvalidJson", `JWS payload is not valid JSON: ${String(cause)}`);
139
+ }
140
+ let payload;
141
+ try {
142
+ payload = validateMcpIPayload(payloadJson);
143
+ } catch (cause) {
144
+ throw new JwsParseError(
145
+ "InvalidPayloadShape",
146
+ `JWS payload does not match McpIPayload shape: ${cause.message}`
147
+ );
148
+ }
149
+ if (!BASE64URL_ALPHABET.test(signatureB64)) {
150
+ throw new JwsParseError(
151
+ "InvalidBase64",
152
+ `JWS signature segment contains characters outside the base64url alphabet (RFC 4648 \xA7 5)`
153
+ );
154
+ }
155
+ const signatureBytes = base64UrlDecodeToBytes(signatureB64);
156
+ if (signatureBytes.length !== 64) {
157
+ throw new JwsParseError(
158
+ "InvalidSignatureLength",
159
+ `Ed25519 signatures are 64 bytes (RFC 8032 \xA7 5.1.6); got ${signatureBytes.length}`
160
+ );
161
+ }
162
+ const signingInput = new TextEncoder().encode(`${headerB64}.${payloadB64}`);
163
+ return { header, payload, signatureBytes, signingInput };
164
+ }
165
+ var BASE64URL_ALPHABET = /^[A-Za-z0-9_-]+=*$/;
166
+ function base64UrlDecodeToBytes(s) {
167
+ const padded = s.replace(/-/g, "+").replace(/_/g, "/");
168
+ const padLen = padded.length % 4 === 0 ? 0 : 4 - padded.length % 4;
169
+ return new Uint8Array(Buffer.from(padded + "=".repeat(padLen), "base64"));
170
+ }
171
+ function base64UrlDecodeToString(s) {
172
+ return Buffer.from(base64UrlDecodeToBytes(s)).toString("utf-8");
173
+ }
174
+
175
+ export { JwsParseError, canonicalSigningPayload, parseJwsCompact, parseSigningKey, signMcpiEnvelope, validateMcpIPayload };