keymaster-connect 0.1.5 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.js CHANGED
@@ -1,151 +1,6 @@
1
- import { isAiToolMessage, parseToolDefinitions, validateToolArguments, assertToolPayload } from './chunk-VVOTW5ZT.js';
2
- export { AI_TOOLS_MAX_JSON_CHARS, assertToolJson, assertToolPayload, isAiToolMessage, parseToolDefinitions, validateToolArguments } from './chunk-VVOTW5ZT.js';
3
- import { PROTOCOL_VERSION, PROTOCOL_METHODS, validateNetworkIdentity, sameNetworkIdentity, STORAGE_MAX_PAYLOAD_BYTES, STORAGE_DEFAULT_LIST_LIMIT, STORAGE_MAX_LIST_LIMIT, isValidMsFileSourceId } from './chunk-ZDIFZJYD.js';
4
- import { secp256k1 } from '@noble/curves/secp256k1.js';
5
- import { sha256 } from '@noble/hashes/sha2.js';
6
-
7
- var APP_IDENTITY_DOMAIN_V1 = "keymaster-app-identity:v1";
8
- var AppIdentityValidationError = class extends Error {
9
- constructor(message) {
10
- super(message);
11
- this.name = "AppIdentityValidationError";
12
- }
13
- };
14
- function exact(value, keys, field) {
15
- const actual = Object.keys(value).sort();
16
- const expected = [...keys].sort();
17
- if (actual.length !== expected.length || actual.some((key, i) => key !== expected[i])) {
18
- throw new AppIdentityValidationError(`${field} has unexpected fields`);
19
- }
20
- }
21
- function text(value, field, max) {
22
- const invalidControl = (c) => {
23
- const code = c.charCodeAt(0);
24
- return code <= 31 || code >= 127 && code <= 159 || code === 65533;
25
- };
26
- if (typeof value !== "string" || !value.trim() || value !== value.trim() || [...value].length > max || [...value].some(invalidControl)) {
27
- throw new AppIdentityValidationError(`${field} is invalid`);
28
- }
29
- }
30
- function hex(value, field, length) {
31
- if (typeof value !== "string" || value.length !== length || !/^[0-9a-f]+$/u.test(value)) {
32
- throw new AppIdentityValidationError(`${field} must be hex`);
33
- }
34
- const out = new Uint8Array(length / 2);
35
- for (let i = 0; i < out.length; i++) out[i] = Number.parseInt(value.slice(i * 2, i * 2 + 2), 16);
36
- return out;
37
- }
38
- function canonicalizeJson(value) {
39
- if (value === null || typeof value === "boolean" || typeof value === "string") {
40
- return JSON.stringify(value);
41
- }
42
- if (typeof value === "number") {
43
- if (!Number.isFinite(value)) {
44
- throw new AppIdentityValidationError("identity payload contains a non-finite number");
45
- }
46
- return JSON.stringify(value);
47
- }
48
- if (Array.isArray(value)) {
49
- return `[${value.map(canonicalizeJson).join(",")}]`;
50
- }
51
- if (typeof value === "object") {
52
- const object = value;
53
- const entries = Object.keys(object).sort().map((key) => `${JSON.stringify(key)}:${canonicalizeJson(object[key])}`);
54
- return `{${entries.join(",")}}`;
55
- }
56
- throw new AppIdentityValidationError("identity payload contains an unsupported value");
57
- }
58
- function identityPayload(proof) {
59
- return {
60
- version: 1,
61
- publisherPublicKey: proof.publisherPublicKey,
62
- app: { ...proof.app },
63
- requirements: [...proof.requirements]
64
- };
65
- }
66
- function identityDigestBytes(proof) {
67
- const payload = new TextEncoder().encode(canonicalizeJson(identityPayload(proof)));
68
- const domain = new TextEncoder().encode(APP_IDENTITY_DOMAIN_V1);
69
- const signed = new Uint8Array(domain.length + 1 + payload.length);
70
- signed.set(domain);
71
- signed[domain.length] = 0;
72
- signed.set(payload, domain.length + 1);
73
- return sha256(signed);
74
- }
75
- function verifyAppIdentityProof(raw) {
76
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
77
- throw new AppIdentityValidationError("appIdentity must be an object");
78
- }
79
- const proof = raw;
80
- exact(proof, ["version", "publisherPublicKey", "app", "requirements", "signature"], "appIdentity");
81
- if (proof.version !== 1 || typeof proof.publisherPublicKey !== "string" || !/^(02|03)[0-9a-f]{64}$/u.test(proof.publisherPublicKey)) {
82
- throw new AppIdentityValidationError("publisherPublicKey is invalid");
83
- }
84
- try {
85
- if (!secp256k1.utils.isValidPublicKey(hex(proof.publisherPublicKey, "publisherPublicKey", 66))) throw new Error();
86
- } catch {
87
- throw new AppIdentityValidationError("publisherPublicKey is invalid");
88
- }
89
- if (!proof.app || typeof proof.app !== "object" || Array.isArray(proof.app)) {
90
- throw new AppIdentityValidationError("app must be an object");
91
- }
92
- const app = proof.app;
93
- exact(app, ["id", "name", "description"], "app");
94
- text(app.id, "app.id", 63);
95
- text(app.name, "app.name", 120);
96
- text(app.description, "app.description", 500);
97
- if (!/^[a-z0-9](?:[a-z0-9._-]{0,61}[a-z0-9])?$/u.test(app.id)) {
98
- throw new AppIdentityValidationError("app.id is invalid");
99
- }
100
- if (!Array.isArray(proof.requirements)) {
101
- throw new AppIdentityValidationError("requirements must be an array");
102
- }
103
- const requirements = proof.requirements;
104
- const allowed = /* @__PURE__ */ new Set(["private-key", "storage"]);
105
- if (requirements.some((r) => typeof r !== "string" || !allowed.has(r)) || new Set(requirements).size !== requirements.length || requirements.some((r, i) => i > 0 && String(requirements[i - 1]) >= String(r))) {
106
- throw new AppIdentityValidationError("requirements must be sorted and unique");
107
- }
108
- const signature = hex(proof.signature, "signature", 128);
109
- const typed = {
110
- version: 1,
111
- publisherPublicKey: proof.publisherPublicKey,
112
- app: { id: app.id, name: app.name, description: app.description },
113
- requirements,
114
- signature: proof.signature
115
- };
116
- try {
117
- if (!secp256k1.verify(
118
- signature,
119
- identityDigestBytes(typed),
120
- hex(proof.publisherPublicKey, "publisherPublicKey", 66),
121
- { prehash: false, format: "compact" }
122
- )) throw new Error();
123
- } catch {
124
- throw new AppIdentityValidationError("appIdentity signature is invalid");
125
- }
126
- const digest = identityDigestBytes(typed);
127
- return {
128
- version: 1,
129
- publisherPublicKeyHex: typed.publisherPublicKey,
130
- appId: typed.app.id,
131
- appName: typed.app.name,
132
- identityDigestHex: Array.from(digest, (b) => b.toString(16).padStart(2, "0")).join("")
133
- };
134
- }
135
- function isVerifiedAppIdentitySnapshot(value) {
136
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
137
- const snapshot = value;
138
- if (snapshot.version !== 1 || typeof snapshot.appId !== "string" || !/^[a-z0-9](?:[a-z0-9._-]{0,61}[a-z0-9])?$/u.test(snapshot.appId) || typeof snapshot.appName !== "string" || !snapshot.appName.trim() || snapshot.appName !== snapshot.appName.trim() || [...snapshot.appName].length > 120 || [...snapshot.appName].some((c) => /[\u0000-\u001f\u007f-\u009f\ufffd]/u.test(c)) || typeof snapshot.publisherPublicKeyHex !== "string" || !/^(02|03)[0-9a-f]{64}$/u.test(snapshot.publisherPublicKeyHex) || typeof snapshot.identityDigestHex !== "string" || !/^[0-9a-f]{64}$/u.test(snapshot.identityDigestHex)) {
139
- return false;
140
- }
141
- try {
142
- return secp256k1.utils.isValidPublicKey(
143
- hex(snapshot.publisherPublicKeyHex, "publisherPublicKeyHex", 66)
144
- );
145
- } catch {
146
- return false;
147
- }
148
- }
1
+ import { isAiToolMessage, parseToolDefinitions, validateToolArguments, assertToolPayload, validatePublicationProof } from './chunk-M2YEI4PG.js';
2
+ export { AI_TOOLS_MAX_JSON_CHARS, assertToolJson, assertToolPayload, isAiToolMessage, parseToolDefinitions, validateToolArguments } from './chunk-M2YEI4PG.js';
3
+ import { PROTOCOL_VERSION, PROTOCOL_METHODS, validateNetworkIdentity, sameNetworkIdentity, STORAGE_MAX_PAYLOAD_BYTES, STORAGE_DEFAULT_LIST_LIMIT, STORAGE_MAX_LIST_LIMIT, isValidMsFileSourceId } from './chunk-THT6XHHY.js';
149
4
 
150
5
  // src/validation.ts
151
6
  var ProtocolValidationError = class extends Error {
@@ -161,7 +16,7 @@ function validateIdentityGetParams(raw) {
161
16
  const aud = expectString(obj.aud, "aud");
162
17
  const iat = expectInteger(obj.iat, "iat");
163
18
  const exp = expectInteger(obj.exp, "exp");
164
- const text2 = expectString(obj.text, "text");
19
+ const text = expectString(obj.text, "text");
165
20
  if (exp <= iat) {
166
21
  throw new ProtocolValidationError("invalid_request", "exp must be greater than iat");
167
22
  }
@@ -175,34 +30,34 @@ function validateIdentityGetParams(raw) {
175
30
  }
176
31
  }
177
32
  }
178
- return { aud, iat, exp, text: text2, claims: obj.claims };
33
+ return { aud, iat, exp, text, claims: obj.claims };
179
34
  }
180
35
  function validateIntentSignParams(raw) {
181
36
  const obj = expectObject(raw, "intent.sign params");
182
37
  const aud = expectString(obj.aud, "aud");
183
38
  const iat = expectInteger(obj.iat, "iat");
184
39
  const exp = expectInteger(obj.exp, "exp");
185
- const text2 = expectString(obj.text, "text");
40
+ const text = expectString(obj.text, "text");
186
41
  const contentType = expectString(obj.contentType, "contentType");
187
42
  if (exp <= iat) {
188
43
  throw new ProtocolValidationError("invalid_request", "exp must be greater than iat");
189
44
  }
190
45
  const content = parseBinaryField(obj.content, "content");
191
- return { aud, iat, exp, text: text2, contentType, content };
46
+ return { aud, iat, exp, text, contentType, content };
192
47
  }
193
48
  function validateCipherEncryptParams(raw) {
194
49
  const obj = expectObject(raw, "cipher.encrypt params");
195
- const text2 = expectString(obj.text, "text");
50
+ const text = expectString(obj.text, "text");
196
51
  const contentType = expectString(obj.contentType, "contentType");
197
52
  const content = parseBinaryField(obj.content, "content");
198
- return { text: text2, contentType, content };
53
+ return { text, contentType, content };
199
54
  }
200
55
  function validateCipherDecryptParams(raw) {
201
56
  const obj = expectObject(raw, "cipher.decrypt params");
202
- const text2 = expectString(obj.text, "text");
57
+ const text = expectString(obj.text, "text");
203
58
  const nonce = parseBinaryField(obj.nonce, "nonce");
204
59
  const cipherbytes = parseBinaryField(obj.cipherbytes, "cipherbytes");
205
- return { text: text2, nonce, cipherbytes };
60
+ return { text, nonce, cipherbytes };
206
61
  }
207
62
  function assertOriginMatches(aud, eventOrigin) {
208
63
  if (aud !== eventOrigin) {
@@ -248,9 +103,9 @@ function validatePaymentStatusParams(raw) {
248
103
  function validateConnectLoginParams(raw) {
249
104
  const obj = expectObject(raw, "connect.login params");
250
105
  for (const key of Object.keys(obj))
251
- if (key !== "text" && key !== "claims" && key !== "appIdentity")
106
+ if (key !== "text" && key !== "claims" && key !== "publicationProof")
252
107
  throw new ProtocolValidationError("invalid_request", "connect.login contains an unsupported field");
253
- const text2 = expectString(obj.text, "text");
108
+ const text = expectString(obj.text, "text");
254
109
  let claims;
255
110
  if (obj.claims !== void 0) {
256
111
  if (!Array.isArray(obj.claims)) {
@@ -260,32 +115,21 @@ function validateConnectLoginParams(raw) {
260
115
  throw new ProtocolValidationError("invalid_request", "claims entries must be strings");
261
116
  claims = [...obj.claims];
262
117
  }
263
- let appIdentity;
264
- if (obj.appIdentity !== void 0) {
118
+ let publicationProof;
119
+ if (obj.publicationProof !== void 0) {
265
120
  try {
266
- verifyAppIdentityProof(obj.appIdentity);
267
- appIdentity = obj.appIdentity;
268
- } catch (error) {
269
- throw new ProtocolValidationError("invalid_request", error instanceof AppIdentityValidationError ? error.message : "appIdentity is invalid");
121
+ publicationProof = validatePublicationProof(obj.publicationProof);
122
+ } catch {
123
+ throw new ProtocolValidationError("invalid_request", "publicationProof is invalid");
270
124
  }
271
125
  }
272
- return { text: text2, claims, ...appIdentity ? { appIdentity } : {} };
126
+ return publicationProof === void 0 ? { text, claims } : { text, claims, publicationProof };
273
127
  }
274
128
  function validateConnectResumeParams(raw) {
275
129
  const obj = expectObject(raw, "connect.resume params");
276
130
  for (const field of Object.keys(obj))
277
- if (field !== "appIdentity")
278
- throw new ProtocolValidationError("invalid_request", "connect.resume contains an unsupported field");
279
- let appIdentity;
280
- if (obj.appIdentity !== void 0) {
281
- try {
282
- verifyAppIdentityProof(obj.appIdentity);
283
- appIdentity = obj.appIdentity;
284
- } catch (error) {
285
- throw new ProtocolValidationError("invalid_request", error instanceof Error ? error.message : "appIdentity is invalid");
286
- }
287
- }
288
- return { ...appIdentity ? { appIdentity } : {} };
131
+ throw new ProtocolValidationError("invalid_request", "connect.resume contains an unsupported field");
132
+ return {};
289
133
  }
290
134
  function validateConnectLogoutParams(raw) {
291
135
  expectObject(raw, "connect.logout params");
@@ -293,20 +137,17 @@ function validateConnectLogoutParams(raw) {
293
137
  }
294
138
  function validateConnectLaunchParams(raw) {
295
139
  const obj = expectObject(raw, "connect.launch params");
296
- if (Object.keys(obj).some((key) => key !== "launchToken" && key !== "appIdentity")) {
140
+ if (Object.keys(obj).some((key) => key !== "launchToken" && key !== "publicationProof")) {
297
141
  throw new ProtocolValidationError("invalid_request", "connect.launch contains an unsupported field");
298
142
  }
299
143
  const launchToken = expectNonEmptyString(obj.launchToken, "launchToken");
300
- if (obj.appIdentity === void 0)
301
- throw new ProtocolValidationError("invalid_request", "appIdentity is required");
302
- let appIdentity;
144
+ if (obj.publicationProof === void 0) return { launchToken };
303
145
  try {
304
- verifyAppIdentityProof(obj.appIdentity);
305
- appIdentity = obj.appIdentity;
306
- } catch (error) {
307
- throw new ProtocolValidationError("invalid_request", error instanceof AppIdentityValidationError ? error.message : "appIdentity is invalid");
146
+ const publicationProof = validatePublicationProof(obj.publicationProof);
147
+ return { launchToken, publicationProof };
148
+ } catch {
149
+ throw new ProtocolValidationError("invalid_request", "publicationProof is invalid");
308
150
  }
309
- return { launchToken, appIdentity };
310
151
  }
311
152
  function validateChannelPublishParams(raw) {
312
153
  const obj = expectObject(raw, "channel.publish params");
@@ -376,6 +217,10 @@ function requireExactKeys(obj, keys, name) {
376
217
  }
377
218
  }
378
219
  var STORAGE_FORBIDDEN_FIELDS = [
220
+ "appPublicKeyHex",
221
+ "appPublicKey",
222
+ "publicationProof",
223
+ "appProof",
379
224
  "publisherPublicKeyHex",
380
225
  "publisherPublicKey",
381
226
  "appId",
@@ -473,6 +318,10 @@ function validateStorageDeleteParams(raw) {
473
318
  return { path };
474
319
  }
475
320
  var MSFILE_FORBIDDEN_FIELDS = [
321
+ "appPublicKeyHex",
322
+ "appPublicKey",
323
+ "publicationProof",
324
+ "appProof",
476
325
  "maxPriceSatoshis",
477
326
  "contentKind",
478
327
  "kind",
@@ -548,11 +397,11 @@ function assertP2pkhAddressForAsset(addr, assetId) {
548
397
  throw new ProtocolValidationError("invalid_request", `recipientAddress must be a ${networkLabel} P2PKH address`);
549
398
  }
550
399
  }
551
- function assertCompressedPubkeyHex(hex2) {
552
- if (hex2.length !== 66) {
400
+ function assertCompressedPubkeyHex(hex) {
401
+ if (hex.length !== 66) {
553
402
  throw new ProtocolValidationError("invalid_request", "counterpartyPublicKeyHex must be a 33-byte compressed public key hex");
554
403
  }
555
- if (!/^[0-9a-fA-F]+$/.test(hex2)) {
404
+ if (!/^[0-9a-fA-F]+$/.test(hex)) {
556
405
  throw new ProtocolValidationError("invalid_request", "counterpartyPublicKeyHex must be hex");
557
406
  }
558
407
  }
@@ -746,6 +595,80 @@ function parseRequestMessage(raw, receiverIdentity) {
746
595
  return { id, method, params: normalized };
747
596
  }
748
597
 
598
+ // src/internal/origin.ts
599
+ var OriginValidationError = class extends Error {
600
+ constructor(message) {
601
+ super(message);
602
+ this.name = "OriginValidationError";
603
+ }
604
+ };
605
+ function canonicalizeJson(value) {
606
+ if (value === null || typeof value === "boolean" || typeof value === "string") {
607
+ return JSON.stringify(value);
608
+ }
609
+ if (typeof value === "number") {
610
+ if (!Number.isFinite(value)) {
611
+ throw new OriginValidationError("identity payload contains a non-finite number");
612
+ }
613
+ return JSON.stringify(value);
614
+ }
615
+ if (Array.isArray(value)) {
616
+ return `[${value.map(canonicalizeJson).join(",")}]`;
617
+ }
618
+ if (typeof value === "object") {
619
+ const object = value;
620
+ const entries = Object.keys(object).sort().map((key) => `${JSON.stringify(key)}:${canonicalizeJson(object[key])}`);
621
+ return `{${entries.join(",")}}`;
622
+ }
623
+ throw new OriginValidationError("identity payload contains an unsupported value");
624
+ }
625
+ function parseHttpUrl(input, field) {
626
+ if (typeof input !== "string" || !input) {
627
+ throw new OriginValidationError(`${field} must be a non-empty string`);
628
+ }
629
+ let url;
630
+ try {
631
+ url = new URL(input);
632
+ } catch {
633
+ throw new OriginValidationError(`${field} is not a valid URL`);
634
+ }
635
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
636
+ throw new OriginValidationError(`${field} must use http or https`);
637
+ }
638
+ if (url.username || url.password) {
639
+ throw new OriginValidationError(`${field} must not contain credentials`);
640
+ }
641
+ if (url.origin === "null" || url.origin === "") {
642
+ throw new OriginValidationError(`${field} has an opaque origin`);
643
+ }
644
+ if (!url.host) {
645
+ throw new OriginValidationError(`${field} is invalid`);
646
+ }
647
+ return url;
648
+ }
649
+ function parseEntryUrl(input) {
650
+ const url = parseHttpUrl(input, "url");
651
+ return { origin: url.origin, url: url.href };
652
+ }
653
+ function canonicalOrigin(input) {
654
+ const url = parseHttpUrl(input, "origin");
655
+ if (url.pathname !== "/" && url.pathname !== "") {
656
+ throw new OriginValidationError("origin must not contain a path");
657
+ }
658
+ if (url.search || url.hash) {
659
+ throw new OriginValidationError("origin must not contain query or fragment");
660
+ }
661
+ return url.origin;
662
+ }
663
+ function assertCanonicalOrigin(input, field = "origin") {
664
+ try {
665
+ return canonicalOrigin(input);
666
+ } catch (error) {
667
+ if (error instanceof OriginValidationError) throw error;
668
+ throw new OriginValidationError(`${field} is invalid`);
669
+ }
670
+ }
671
+
749
672
  // src/toolReceiver.ts
750
673
  var KeymasterAiToolReceiver = class {
751
674
  constructor(options) {
@@ -857,14 +780,7 @@ function isEstablishing(method) {
857
780
  function parseReconnectMessage(data) {
858
781
  if (!data || typeof data !== "object") return null;
859
782
  const value = data;
860
- if (value.v !== PROTOCOL_VERSION || value.type !== "reconnect" || typeof value.id !== "string" || !value.id || value.id.length > 128 || typeof value.authorizationId !== "string" || !value.authorizationId || value.authorizationId.length > 128 || value.bindingId !== void 0 && typeof value.bindingId !== "string" || Object.keys(value).some((key) => !["v", "type", "id", "authorizationId", "bindingId", "appIdentity"].includes(key))) return null;
861
- if (value.appIdentity !== void 0) {
862
- try {
863
- verifyAppIdentityProof(value.appIdentity);
864
- } catch {
865
- return null;
866
- }
867
- }
783
+ if (value.v !== PROTOCOL_VERSION || value.type !== "reconnect" || typeof value.id !== "string" || !value.id || value.id.length > 128 || typeof value.authorizationId !== "string" || !value.authorizationId || value.authorizationId.length > 128 || value.bindingId !== void 0 && typeof value.bindingId !== "string" || Object.keys(value).some((key) => !["v", "type", "id", "authorizationId", "bindingId"].includes(key))) return null;
868
784
  return value;
869
785
  }
870
786
  var KeymasterConnectReceiver = class {
@@ -903,7 +819,7 @@ var KeymasterConnectReceiver = class {
903
819
  async accept(event) {
904
820
  if (!this.isAllowedPeer(event)) return null;
905
821
  const reconnect = parseReconnectMessage(event.data);
906
- const raw = reconnect ? { v: PROTOCOL_VERSION, type: "request", id: reconnect.id, method: "connect.resume", params: reconnect.appIdentity ? { appIdentity: reconnect.appIdentity } : {} } : event.data;
822
+ const raw = reconnect ? { v: PROTOCOL_VERSION, type: "request", id: reconnect.id, method: "connect.resume", params: {} } : event.data;
907
823
  if (!raw || typeof raw !== "object" || raw.type !== "request") return null;
908
824
  if (typeof raw.id === "string" && this.pending.get(event.source)?.has(raw.id)) return null;
909
825
  try {
@@ -1067,6 +983,6 @@ var KeymasterConnectReceiver = class {
1067
983
  }
1068
984
  };
1069
985
 
1070
- export { APP_IDENTITY_DOMAIN_V1, AppIdentityValidationError, KeymasterAiToolReceiver, KeymasterConnectReceiver, ProtocolValidationError, assertCompressedPubkeyHex, assertMainnetP2pkhAddress, assertOriginMatches, assertP2pkhAddressForAsset, canonicalizeJson, identityDigestBytes, identityPayload, isEstablishing, isStructuredCloneRequestCandidate, isVerifiedAppIdentitySnapshot, parseCancelMessage, parseReconnectMessage, parseRequestMessage, validateExactChannel, verifyAppIdentityProof };
986
+ export { KeymasterAiToolReceiver, KeymasterConnectReceiver, OriginValidationError, ProtocolValidationError, assertCanonicalOrigin, assertCompressedPubkeyHex, assertMainnetP2pkhAddress, assertOriginMatches, assertP2pkhAddressForAsset, canonicalOrigin, canonicalizeJson, isEstablishing, isStructuredCloneRequestCandidate, parseCancelMessage, parseEntryUrl, parseReconnectMessage, parseRequestMessage, validateExactChannel };
1071
987
  //# sourceMappingURL=server.js.map
1072
988
  //# sourceMappingURL=server.js.map