keymaster-connect 0.0.0-stage → 0.1.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/dist/server.js ADDED
@@ -0,0 +1,995 @@
1
+ import { PROTOCOL_VERSION, PROTOCOL_METHODS, validateNetworkIdentity, sameNetworkIdentity, STORAGE_MAX_PAYLOAD_BYTES, STORAGE_DEFAULT_LIST_LIMIT, STORAGE_MAX_LIST_LIMIT, isValidMsFileSourceId } from './chunk-AAVOIS5Q.js';
2
+ import { secp256k1 } from '@noble/curves/secp256k1.js';
3
+ import { sha256 } from '@noble/hashes/sha2.js';
4
+
5
+ var APP_IDENTITY_DOMAIN_V1 = "keymaster-app-identity:v1";
6
+ var AppIdentityValidationError = class extends Error {
7
+ constructor(message) {
8
+ super(message);
9
+ this.name = "AppIdentityValidationError";
10
+ }
11
+ };
12
+ function exact(value, keys, field) {
13
+ const actual = Object.keys(value).sort();
14
+ const expected = [...keys].sort();
15
+ if (actual.length !== expected.length || actual.some((key, i) => key !== expected[i])) {
16
+ throw new AppIdentityValidationError(`${field} has unexpected fields`);
17
+ }
18
+ }
19
+ function text(value, field, max) {
20
+ const invalidControl = (c) => {
21
+ const code = c.charCodeAt(0);
22
+ return code <= 31 || code >= 127 && code <= 159 || code === 65533;
23
+ };
24
+ if (typeof value !== "string" || !value.trim() || value !== value.trim() || [...value].length > max || [...value].some(invalidControl)) {
25
+ throw new AppIdentityValidationError(`${field} is invalid`);
26
+ }
27
+ }
28
+ function hex(value, field, length) {
29
+ if (typeof value !== "string" || value.length !== length || !/^[0-9a-f]+$/u.test(value)) {
30
+ throw new AppIdentityValidationError(`${field} must be hex`);
31
+ }
32
+ const out = new Uint8Array(length / 2);
33
+ for (let i = 0; i < out.length; i++) out[i] = Number.parseInt(value.slice(i * 2, i * 2 + 2), 16);
34
+ return out;
35
+ }
36
+ function canonicalizeJson(value) {
37
+ if (value === null || typeof value === "boolean" || typeof value === "string") {
38
+ return JSON.stringify(value);
39
+ }
40
+ if (typeof value === "number") {
41
+ if (!Number.isFinite(value)) {
42
+ throw new AppIdentityValidationError("identity payload contains a non-finite number");
43
+ }
44
+ return JSON.stringify(value);
45
+ }
46
+ if (Array.isArray(value)) {
47
+ return `[${value.map(canonicalizeJson).join(",")}]`;
48
+ }
49
+ if (typeof value === "object") {
50
+ const object = value;
51
+ const entries = Object.keys(object).sort().map((key) => `${JSON.stringify(key)}:${canonicalizeJson(object[key])}`);
52
+ return `{${entries.join(",")}}`;
53
+ }
54
+ throw new AppIdentityValidationError("identity payload contains an unsupported value");
55
+ }
56
+ function identityPayload(proof) {
57
+ return {
58
+ version: 1,
59
+ publisherPublicKey: proof.publisherPublicKey,
60
+ app: { ...proof.app },
61
+ requirements: [...proof.requirements]
62
+ };
63
+ }
64
+ function identityDigestBytes(proof) {
65
+ const payload = new TextEncoder().encode(canonicalizeJson(identityPayload(proof)));
66
+ const domain = new TextEncoder().encode(APP_IDENTITY_DOMAIN_V1);
67
+ const signed = new Uint8Array(domain.length + 1 + payload.length);
68
+ signed.set(domain);
69
+ signed[domain.length] = 0;
70
+ signed.set(payload, domain.length + 1);
71
+ return sha256(signed);
72
+ }
73
+ function verifyAppIdentityProof(raw) {
74
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
75
+ throw new AppIdentityValidationError("appIdentity must be an object");
76
+ }
77
+ const proof = raw;
78
+ exact(proof, ["version", "publisherPublicKey", "app", "requirements", "signature"], "appIdentity");
79
+ if (proof.version !== 1 || typeof proof.publisherPublicKey !== "string" || !/^(02|03)[0-9a-f]{64}$/u.test(proof.publisherPublicKey)) {
80
+ throw new AppIdentityValidationError("publisherPublicKey is invalid");
81
+ }
82
+ try {
83
+ if (!secp256k1.utils.isValidPublicKey(hex(proof.publisherPublicKey, "publisherPublicKey", 66))) throw new Error();
84
+ } catch {
85
+ throw new AppIdentityValidationError("publisherPublicKey is invalid");
86
+ }
87
+ if (!proof.app || typeof proof.app !== "object" || Array.isArray(proof.app)) {
88
+ throw new AppIdentityValidationError("app must be an object");
89
+ }
90
+ const app = proof.app;
91
+ exact(app, ["id", "name", "description"], "app");
92
+ text(app.id, "app.id", 63);
93
+ text(app.name, "app.name", 120);
94
+ text(app.description, "app.description", 500);
95
+ if (!/^[a-z0-9](?:[a-z0-9._-]{0,61}[a-z0-9])?$/u.test(app.id)) {
96
+ throw new AppIdentityValidationError("app.id is invalid");
97
+ }
98
+ if (!Array.isArray(proof.requirements)) {
99
+ throw new AppIdentityValidationError("requirements must be an array");
100
+ }
101
+ const requirements = proof.requirements;
102
+ const allowed = /* @__PURE__ */ new Set(["private-key", "storage"]);
103
+ 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))) {
104
+ throw new AppIdentityValidationError("requirements must be sorted and unique");
105
+ }
106
+ const signature = hex(proof.signature, "signature", 128);
107
+ const typed = {
108
+ version: 1,
109
+ publisherPublicKey: proof.publisherPublicKey,
110
+ app: { id: app.id, name: app.name, description: app.description },
111
+ requirements,
112
+ signature: proof.signature
113
+ };
114
+ try {
115
+ if (!secp256k1.verify(
116
+ signature,
117
+ identityDigestBytes(typed),
118
+ hex(proof.publisherPublicKey, "publisherPublicKey", 66),
119
+ { prehash: false, format: "compact" }
120
+ )) throw new Error();
121
+ } catch {
122
+ throw new AppIdentityValidationError("appIdentity signature is invalid");
123
+ }
124
+ const digest = identityDigestBytes(typed);
125
+ return {
126
+ version: 1,
127
+ publisherPublicKeyHex: typed.publisherPublicKey,
128
+ appId: typed.app.id,
129
+ appName: typed.app.name,
130
+ identityDigestHex: Array.from(digest, (b) => b.toString(16).padStart(2, "0")).join("")
131
+ };
132
+ }
133
+ function isVerifiedAppIdentitySnapshot(value) {
134
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
135
+ const snapshot = value;
136
+ 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)) {
137
+ return false;
138
+ }
139
+ try {
140
+ return secp256k1.utils.isValidPublicKey(
141
+ hex(snapshot.publisherPublicKeyHex, "publisherPublicKeyHex", 66)
142
+ );
143
+ } catch {
144
+ return false;
145
+ }
146
+ }
147
+
148
+ // src/validation.ts
149
+ var ProtocolValidationError = class extends Error {
150
+ code;
151
+ constructor(code, message) {
152
+ super(message);
153
+ this.code = code;
154
+ this.name = "ProtocolValidationError";
155
+ }
156
+ };
157
+ function validateIdentityGetParams(raw) {
158
+ const obj = expectObject(raw, "identity.get params");
159
+ const aud = expectString(obj.aud, "aud");
160
+ const iat = expectInteger(obj.iat, "iat");
161
+ const exp = expectInteger(obj.exp, "exp");
162
+ const text2 = expectString(obj.text, "text");
163
+ if (exp <= iat) {
164
+ throw new ProtocolValidationError("invalid_request", "exp must be greater than iat");
165
+ }
166
+ if (obj.claims !== void 0) {
167
+ if (!Array.isArray(obj.claims)) {
168
+ throw new ProtocolValidationError("invalid_request", "claims must be an array of strings");
169
+ }
170
+ for (const c of obj.claims) {
171
+ if (typeof c !== "string") {
172
+ throw new ProtocolValidationError("invalid_request", "claims entries must be strings");
173
+ }
174
+ }
175
+ }
176
+ return { aud, iat, exp, text: text2, claims: obj.claims };
177
+ }
178
+ function validateIntentSignParams(raw) {
179
+ const obj = expectObject(raw, "intent.sign params");
180
+ const aud = expectString(obj.aud, "aud");
181
+ const iat = expectInteger(obj.iat, "iat");
182
+ const exp = expectInteger(obj.exp, "exp");
183
+ const text2 = expectString(obj.text, "text");
184
+ const contentType = expectString(obj.contentType, "contentType");
185
+ if (exp <= iat) {
186
+ throw new ProtocolValidationError("invalid_request", "exp must be greater than iat");
187
+ }
188
+ const content = parseBinaryField(obj.content, "content");
189
+ return { aud, iat, exp, text: text2, contentType, content };
190
+ }
191
+ function validateCipherEncryptParams(raw) {
192
+ const obj = expectObject(raw, "cipher.encrypt params");
193
+ const text2 = expectString(obj.text, "text");
194
+ const contentType = expectString(obj.contentType, "contentType");
195
+ const content = parseBinaryField(obj.content, "content");
196
+ return { text: text2, contentType, content };
197
+ }
198
+ function validateCipherDecryptParams(raw) {
199
+ const obj = expectObject(raw, "cipher.decrypt params");
200
+ const text2 = expectString(obj.text, "text");
201
+ const nonce = parseBinaryField(obj.nonce, "nonce");
202
+ const cipherbytes = parseBinaryField(obj.cipherbytes, "cipherbytes");
203
+ return { text: text2, nonce, cipherbytes };
204
+ }
205
+ function assertOriginMatches(aud, eventOrigin) {
206
+ if (aud !== eventOrigin) {
207
+ throw new ProtocolValidationError("invalid_origin", "aud does not match event origin");
208
+ }
209
+ }
210
+ function validatePaymentPayParams(raw, network) {
211
+ const obj = expectObject(raw, "payment.pay params");
212
+ const allowed = ["channelId", "clientRequestId", "paymentType", "businessKind", "amountSatoshis", "feeRateSatoshisPerKb", "recipient"];
213
+ for (const key of Object.keys(obj))
214
+ if (!allowed.includes(key))
215
+ throw new ProtocolValidationError("invalid_request", "payment.pay contains an unsupported field");
216
+ const clientRequestId = expectNonEmptyString(obj.clientRequestId, "clientRequestId");
217
+ if (clientRequestId.length > 128 || !/^[A-Za-z0-9._:-]+$/u.test(clientRequestId))
218
+ throw new ProtocolValidationError("invalid_request", "clientRequestId is invalid");
219
+ const paymentType = obj.paymentType;
220
+ if (paymentType !== "p2pkh" && paymentType !== "p2pk")
221
+ throw new ProtocolValidationError("invalid_request", "paymentType is unsupported");
222
+ const businessKind = expectNonEmptyString(obj.businessKind, "businessKind");
223
+ if (businessKind.length > 64 || !/^[A-Za-z0-9][A-Za-z0-9._:-]*$/u.test(businessKind))
224
+ throw new ProtocolValidationError("invalid_request", "businessKind is invalid");
225
+ const recipient = expectObject(obj.recipient, "recipient");
226
+ if (paymentType === "p2pkh") {
227
+ if (recipient.type !== "p2pkh")
228
+ throw new ProtocolValidationError("invalid_request", "recipient.type must match paymentType");
229
+ for (const key of Object.keys(recipient))
230
+ if (key !== "type" && key !== "address")
231
+ throw new ProtocolValidationError("invalid_request", "recipient contains an unsupported field");
232
+ const address = expectString(recipient.address, "recipient.address");
233
+ const assetId = network === "test" ? "bsv-testnet" : "bsv-mainnet";
234
+ assertP2pkhAddressForAsset(address, assetId ?? "bsv-mainnet");
235
+ } else {
236
+ if (recipient.type !== "p2pk")
237
+ throw new ProtocolValidationError("invalid_request", "recipient.type must match paymentType");
238
+ for (const key of Object.keys(recipient))
239
+ if (key !== "type" && key !== "publicKeyHex")
240
+ throw new ProtocolValidationError("invalid_request", "recipient contains an unsupported field");
241
+ assertCompressedPubkeyHex(expectString(recipient.publicKeyHex, "recipient.publicKeyHex"));
242
+ }
243
+ const amountSatoshis = expectPositiveInteger(obj.amountSatoshis, "amountSatoshis");
244
+ let feeRateSatoshisPerKb;
245
+ if (obj.feeRateSatoshisPerKb !== void 0)
246
+ feeRateSatoshisPerKb = expectPositiveInteger(obj.feeRateSatoshisPerKb, "feeRateSatoshisPerKb");
247
+ const channelId = expectPaymentChannelId(obj.channelId);
248
+ return {
249
+ channelId,
250
+ clientRequestId,
251
+ paymentType,
252
+ businessKind,
253
+ amountSatoshis,
254
+ ...feeRateSatoshisPerKb === void 0 ? {} : { feeRateSatoshisPerKb },
255
+ recipient: paymentType === "p2pkh" ? { type: "p2pkh", address: expectString(recipient.address, "recipient.address") } : { type: "p2pk", publicKeyHex: expectString(recipient.publicKeyHex, "recipient.publicKeyHex").toLowerCase() }
256
+ };
257
+ }
258
+ function validatePaymentStatusParams(raw) {
259
+ const obj = expectObject(raw, "payment.status params");
260
+ for (const key of Object.keys(obj))
261
+ if (key !== "clientRequestId")
262
+ throw new ProtocolValidationError("invalid_request", "payment.status contains an unsupported field");
263
+ const clientRequestId = expectNonEmptyString(obj.clientRequestId, "clientRequestId");
264
+ if (clientRequestId.length > 128 || !/^[A-Za-z0-9._:-]+$/u.test(clientRequestId))
265
+ throw new ProtocolValidationError("invalid_request", "clientRequestId is invalid");
266
+ return { clientRequestId };
267
+ }
268
+ function expectPaymentChannelId(raw) {
269
+ const id = expectNonEmptyString(raw, "channelId");
270
+ if (id.length > 96 || !/^[a-z][a-z0-9.-]+$/.test(id))
271
+ throw new ProtocolValidationError("invalid_request", "Invalid payment channelId");
272
+ return id;
273
+ }
274
+ function validatePaymentChannelRegisterParams(raw) {
275
+ const obj = expectObject(raw, "payment.channel.register params");
276
+ const channelName = expectNonEmptyString(obj.channelName, "channelName");
277
+ if (!/^[a-z][a-z0-9.-]{0,31}$/.test(channelName))
278
+ throw new ProtocolValidationError("invalid_request", "Invalid channelName");
279
+ if (obj.paymentType !== "p2pkh" && obj.paymentType !== "p2pk")
280
+ throw new ProtocolValidationError("invalid_request", "Unsupported paymentType");
281
+ return { channelName, paymentType: obj.paymentType };
282
+ }
283
+ function validateConnectLoginParams(raw) {
284
+ const obj = expectObject(raw, "connect.login params");
285
+ for (const key of Object.keys(obj))
286
+ if (key !== "text" && key !== "claims" && key !== "appIdentity")
287
+ throw new ProtocolValidationError("invalid_request", "connect.login contains an unsupported field");
288
+ const text2 = expectString(obj.text, "text");
289
+ let claims;
290
+ if (obj.claims !== void 0) {
291
+ if (!Array.isArray(obj.claims)) {
292
+ throw new ProtocolValidationError("invalid_request", "claims must be an array of strings");
293
+ }
294
+ if (obj.claims.some((c) => typeof c !== "string"))
295
+ throw new ProtocolValidationError("invalid_request", "claims entries must be strings");
296
+ claims = [...obj.claims];
297
+ }
298
+ let appIdentity;
299
+ if (obj.appIdentity !== void 0) {
300
+ try {
301
+ verifyAppIdentityProof(obj.appIdentity);
302
+ appIdentity = obj.appIdentity;
303
+ } catch (error) {
304
+ throw new ProtocolValidationError("invalid_request", error instanceof AppIdentityValidationError ? error.message : "appIdentity is invalid");
305
+ }
306
+ }
307
+ return { text: text2, claims, ...appIdentity ? { appIdentity } : {} };
308
+ }
309
+ function validateConnectResumeParams(raw) {
310
+ const obj = expectObject(raw, "connect.resume params");
311
+ for (const field of Object.keys(obj))
312
+ if (field !== "appIdentity")
313
+ throw new ProtocolValidationError("invalid_request", "connect.resume contains an unsupported field");
314
+ let appIdentity;
315
+ if (obj.appIdentity !== void 0) {
316
+ try {
317
+ verifyAppIdentityProof(obj.appIdentity);
318
+ appIdentity = obj.appIdentity;
319
+ } catch (error) {
320
+ throw new ProtocolValidationError("invalid_request", error instanceof Error ? error.message : "appIdentity is invalid");
321
+ }
322
+ }
323
+ return { ...appIdentity ? { appIdentity } : {} };
324
+ }
325
+ function validateConnectLogoutParams(raw) {
326
+ expectObject(raw, "connect.logout params");
327
+ return {};
328
+ }
329
+ function validateConnectLaunchParams(raw) {
330
+ const obj = expectObject(raw, "connect.launch params");
331
+ if (Object.keys(obj).some((key) => key !== "launchToken" && key !== "appIdentity")) {
332
+ throw new ProtocolValidationError("invalid_request", "connect.launch contains an unsupported field");
333
+ }
334
+ const launchToken = expectNonEmptyString(obj.launchToken, "launchToken");
335
+ if (obj.appIdentity === void 0)
336
+ throw new ProtocolValidationError("invalid_request", "appIdentity is required");
337
+ let appIdentity;
338
+ try {
339
+ verifyAppIdentityProof(obj.appIdentity);
340
+ appIdentity = obj.appIdentity;
341
+ } catch (error) {
342
+ throw new ProtocolValidationError("invalid_request", error instanceof AppIdentityValidationError ? error.message : "appIdentity is invalid");
343
+ }
344
+ return { launchToken, appIdentity };
345
+ }
346
+ function validateChannelPublishParams(raw) {
347
+ const obj = expectObject(raw, "channel.publish params");
348
+ requireExactKeys(obj, ["channel", "content"], "channel.publish params");
349
+ const channel = validateExactChannel(obj.channel, "channel");
350
+ const content = validateJsonValue(obj.content, "content");
351
+ return { channel, content };
352
+ }
353
+ function validateChannelSubscriptionSetParams(raw) {
354
+ const obj = expectObject(raw, "channel.subscription_set params");
355
+ requireExactKeys(obj, ["channels"], "channel.subscription_set params");
356
+ if (!Array.isArray(obj.channels)) {
357
+ throw new ProtocolValidationError("invalid_request", "channels must be an array");
358
+ }
359
+ if (obj.channels.length > 64) {
360
+ throw new ProtocolValidationError("invalid_request", "channels must contain at most 64 entries");
361
+ }
362
+ const channels = obj.channels.map((value, index) => validateExactChannel(value, `channels[${index}]`));
363
+ if (new Set(channels).size !== channels.length) {
364
+ throw new ProtocolValidationError("invalid_request", "channels must not contain duplicates");
365
+ }
366
+ return { channels };
367
+ }
368
+ function validatePriceParams(raw) {
369
+ const obj = expectObject(raw, "price params");
370
+ requireExactKeys(obj, [], "price params");
371
+ return {};
372
+ }
373
+ function validateExactChannel(value, field = "channel") {
374
+ const channel = expectString(value, field);
375
+ if (channel.length === 0 || channel === "*") {
376
+ throw new ProtocolValidationError("invalid_request", `${field} must be a non-empty exact channel`);
377
+ }
378
+ if (new TextEncoder().encode(channel).byteLength > 256) {
379
+ throw new ProtocolValidationError("invalid_request", `${field} exceeds 256 UTF-8 bytes`);
380
+ }
381
+ for (const codePoint of channel) {
382
+ if (codePoint < " " || codePoint === "\x7F") {
383
+ throw new ProtocolValidationError("invalid_request", `${field} contains a control character`);
384
+ }
385
+ }
386
+ return channel;
387
+ }
388
+ function validateJsonValue(value, field, depth = 0) {
389
+ if (depth > 16)
390
+ throw new ProtocolValidationError("invalid_request", `${field} is too deeply nested`);
391
+ if (value === null || typeof value === "string" || typeof value === "boolean")
392
+ return value;
393
+ if (typeof value === "number") {
394
+ if (!Number.isFinite(value))
395
+ throw new ProtocolValidationError("invalid_request", `${field} contains a non-finite number`);
396
+ return value;
397
+ }
398
+ if (Array.isArray(value))
399
+ return value.map((item, index) => validateJsonValue(item, `${field}[${index}]`, depth + 1));
400
+ if (isPlainObject(value)) {
401
+ const output = {};
402
+ for (const [key, item] of Object.entries(value)) {
403
+ if (key.length > 256)
404
+ throw new ProtocolValidationError("invalid_request", `${field} contains an oversized object key`);
405
+ Object.defineProperty(output, key, { value: validateJsonValue(item, `${field}.${key}`, depth + 1), enumerable: true, writable: true, configurable: true });
406
+ }
407
+ return output;
408
+ }
409
+ throw new ProtocolValidationError("invalid_request", `${field} must be a JSON value`);
410
+ }
411
+ function requireExactKeys(obj, keys, name) {
412
+ const actual = Object.keys(obj).sort();
413
+ const expected = [...keys].sort();
414
+ if (actual.length !== expected.length || actual.some((key, index) => key !== expected[index])) {
415
+ throw new ProtocolValidationError("invalid_request", `${name} contains unsupported fields`);
416
+ }
417
+ }
418
+ var STORAGE_FORBIDDEN_FIELDS = [
419
+ "publisherPublicKeyHex",
420
+ "publisherPublicKey",
421
+ "appId",
422
+ "appName",
423
+ "appIdentity",
424
+ "namespaceRoot",
425
+ "bucket",
426
+ "endpoint",
427
+ "providerId",
428
+ "s3Key",
429
+ "s3UploadId",
430
+ "accessKeyId",
431
+ "secretAccessKey"
432
+ ];
433
+ function storageObject(raw, name) {
434
+ const obj = expectObject(raw, name);
435
+ for (const field of STORAGE_FORBIDDEN_FIELDS) {
436
+ if (Object.prototype.hasOwnProperty.call(obj, field))
437
+ throw new ProtocolValidationError("invalid_request", `${name} contains a forbidden field`);
438
+ }
439
+ return obj;
440
+ }
441
+ function storagePath(value, field, allowEmpty = false) {
442
+ const path = expectString(value, field);
443
+ if (!allowEmpty && path.length === 0)
444
+ throw new ProtocolValidationError("invalid_request", `${field} must not be empty`);
445
+ const withoutTrailingSlash = path.endsWith("/") ? path.slice(0, -1) : path;
446
+ if (path.length > 1024 || path.startsWith("/") || path.includes("\\") || path.includes("\0") || /[\u0000-\u001f\u007f]/u.test(path) || /[\u2044\u2215\u29f8\uff0f]/u.test(path)) {
447
+ throw new ProtocolValidationError("invalid_request", `${field} is not a valid relative path`);
448
+ }
449
+ const segments = withoutTrailingSlash.split("/");
450
+ if (!withoutTrailingSlash && !allowEmpty || withoutTrailingSlash && segments.some((segment) => !segment || segment === "." || segment === ".." || segment.length > 255)) {
451
+ throw new ProtocolValidationError("invalid_request", `${field} is not a valid relative path`);
452
+ }
453
+ return path;
454
+ }
455
+ function storageBinary(value, field) {
456
+ const binary = parseBinaryField(value, field);
457
+ if (binary.bytes.byteLength > STORAGE_MAX_PAYLOAD_BYTES) {
458
+ throw new ProtocolValidationError("storage_limit_exceeded", `${field} exceeds the maximum payload size`);
459
+ }
460
+ return binary;
461
+ }
462
+ function validateStorageListParams(raw) {
463
+ const obj = storageObject(raw, "storage.list params");
464
+ const prefix = obj.prefix === void 0 ? "" : storagePath(obj.prefix, "prefix", true);
465
+ const cursor = obj.cursor === void 0 ? void 0 : expectNonEmptyString(obj.cursor, "cursor");
466
+ const limit = obj.limit === void 0 ? STORAGE_DEFAULT_LIST_LIMIT : obj.limit;
467
+ if (typeof limit !== "number" || !Number.isInteger(limit) || limit < 1 || limit > STORAGE_MAX_LIST_LIMIT) {
468
+ throw new ProtocolValidationError("invalid_request", "limit must be between 1 and 1000");
469
+ }
470
+ return { prefix, cursor, limit };
471
+ }
472
+ function validateStorageDirectoryParams(raw, name, allowOverwrite) {
473
+ const obj = storageObject(raw, `${name} params`);
474
+ const path = storagePath(obj.path, "path");
475
+ const overwrite = obj.overwrite === void 0 ? void 0 : obj.overwrite;
476
+ if (overwrite !== void 0 && typeof overwrite !== "boolean")
477
+ throw new ProtocolValidationError("invalid_request", "overwrite must be boolean");
478
+ return allowOverwrite ? { path, overwrite } : { path };
479
+ }
480
+ function validateStoragePutParams(raw) {
481
+ const obj = storageObject(raw, "storage.put params");
482
+ const path = storagePath(obj.path, "path");
483
+ if (path.endsWith("/"))
484
+ throw new ProtocolValidationError("invalid_request", "object path must not end with '/'");
485
+ const content = storageBinary(obj.content, "content");
486
+ const contentType = obj.contentType === void 0 ? void 0 : expectString(obj.contentType, "contentType");
487
+ const overwrite = obj.overwrite === void 0 ? void 0 : obj.overwrite;
488
+ if (overwrite !== void 0 && typeof overwrite !== "boolean")
489
+ throw new ProtocolValidationError("invalid_request", "overwrite must be boolean");
490
+ return { path, content, contentType, overwrite };
491
+ }
492
+ function validateStorageGetParams(raw) {
493
+ const obj = storageObject(raw, "storage.get params");
494
+ const path = storagePath(obj.path, "path");
495
+ if (path.endsWith("/"))
496
+ throw new ProtocolValidationError("invalid_request", "object path must not end with '/'");
497
+ const offset = obj.offset === void 0 ? 0 : obj.offset;
498
+ const length = obj.length === void 0 ? STORAGE_MAX_PAYLOAD_BYTES : obj.length;
499
+ if (typeof offset !== "number" || !Number.isSafeInteger(offset) || offset < 0)
500
+ throw new ProtocolValidationError("invalid_request", "offset must be a non-negative safe integer");
501
+ if (typeof length !== "number" || !Number.isSafeInteger(length) || length < 1 || length > STORAGE_MAX_PAYLOAD_BYTES)
502
+ throw new ProtocolValidationError("storage_limit_exceeded", "length exceeds the maximum payload size");
503
+ if (offset > Number.MAX_SAFE_INTEGER - (length - 1))
504
+ throw new ProtocolValidationError("storage_limit_exceeded", "requested range exceeds safe integer bounds");
505
+ const ifMatch = obj.ifMatch === void 0 ? void 0 : expectString(obj.ifMatch, "ifMatch");
506
+ return { path, offset, length, ifMatch };
507
+ }
508
+ function validateStorageDeleteParams(raw) {
509
+ const obj = storageObject(raw, "storage.delete params");
510
+ const path = storagePath(obj.path, "path");
511
+ if (path.endsWith("/"))
512
+ throw new ProtocolValidationError("invalid_request", "object path must not end with '/'");
513
+ return { path };
514
+ }
515
+ var MSFILE_FORBIDDEN_FIELDS = [
516
+ "maxPriceSatoshis",
517
+ "contentKind",
518
+ "kind",
519
+ "fileId",
520
+ "accessId",
521
+ "seedAccessId",
522
+ "blockIndex",
523
+ "ownerPublicKeyHex",
524
+ "publisherPublicKeyHex",
525
+ "appId",
526
+ "appName",
527
+ "appIdentity",
528
+ "identityDigestHex"
529
+ ];
530
+ var MSFILE_HASH_HEX_PATTERN = /^[0-9a-f]{64}$/;
531
+ function msfileObject(raw, name) {
532
+ const obj = expectObject(raw, name);
533
+ for (const field of MSFILE_FORBIDDEN_FIELDS) {
534
+ if (Object.prototype.hasOwnProperty.call(obj, field)) {
535
+ throw new ProtocolValidationError("invalid_request", `${name} contains a forbidden field`);
536
+ }
537
+ }
538
+ return obj;
539
+ }
540
+ function msfileHash(value, field) {
541
+ const hash = expectString(value, field);
542
+ if (!MSFILE_HASH_HEX_PATTERN.test(hash)) {
543
+ throw new ProtocolValidationError("msfile_invalid_hash", `${field} must be 64 lower-case hex chars`);
544
+ }
545
+ return hash;
546
+ }
547
+ function msfileSourceId(obj, name) {
548
+ const sourceId = expectString(obj.sourceId, `${name}.sourceId`);
549
+ if (!isValidMsFileSourceId(sourceId))
550
+ throw new ProtocolValidationError("invalid_request", "sourceId must be a valid MSFile source route");
551
+ return sourceId;
552
+ }
553
+ function validateMsFileStatParams(raw) {
554
+ const obj = msfileObject(raw, "msfile.stat params");
555
+ return { seedHashHex: msfileHash(obj.seedHashHex, "seedHashHex") };
556
+ }
557
+ function validateMsFileSeedReadParams(raw) {
558
+ const obj = msfileObject(raw, "msfile.seed.read params");
559
+ return {
560
+ sourceId: msfileSourceId(obj, "msfile.seed.read"),
561
+ seedHashHex: msfileHash(obj.seedHashHex, "seedHashHex")
562
+ };
563
+ }
564
+ function validateMsFileBlockReadParams(raw) {
565
+ const obj = msfileObject(raw, "msfile.block.read params");
566
+ return {
567
+ sourceId: msfileSourceId(obj, "msfile.block.read"),
568
+ seedHashHex: msfileHash(obj.seedHashHex, "seedHashHex"),
569
+ blockHashHex: msfileHash(obj.blockHashHex, "blockHashHex")
570
+ };
571
+ }
572
+ function assertMainnetP2pkhAddress(addr) {
573
+ assertP2pkhAddressForAsset(addr, "bsv-mainnet");
574
+ }
575
+ function assertP2pkhAddressForAsset(addr, assetId) {
576
+ const expectedVersion = assetId === "bsv-testnet" ? 111 : 0;
577
+ const networkLabel = assetId === "bsv-testnet" ? "testnet" : "mainnet";
578
+ let decoded;
579
+ try {
580
+ decoded = base58Decode(addr);
581
+ } catch {
582
+ throw new ProtocolValidationError("invalid_request", "recipientAddress is not a valid P2PKH address");
583
+ }
584
+ if (decoded.length !== 25) {
585
+ throw new ProtocolValidationError("invalid_request", `recipientAddress must be a ${networkLabel} P2PKH address`);
586
+ }
587
+ if (decoded[0] !== expectedVersion) {
588
+ throw new ProtocolValidationError("invalid_request", `recipientAddress must be a ${networkLabel} P2PKH address`);
589
+ }
590
+ }
591
+ function assertCompressedPubkeyHex(hex2) {
592
+ if (hex2.length !== 66) {
593
+ throw new ProtocolValidationError("invalid_request", "counterpartyPublicKeyHex must be a 33-byte compressed public key hex");
594
+ }
595
+ if (!/^[0-9a-fA-F]+$/.test(hex2)) {
596
+ throw new ProtocolValidationError("invalid_request", "counterpartyPublicKeyHex must be hex");
597
+ }
598
+ }
599
+ function expectPositiveInteger(v, name) {
600
+ if (typeof v !== "number" || !Number.isInteger(v) || v <= 0) {
601
+ throw new ProtocolValidationError("invalid_request", `${name} must be a positive integer`);
602
+ }
603
+ return v;
604
+ }
605
+ function expectNonEmptyString(v, name) {
606
+ if (typeof v !== "string" || v.length === 0) {
607
+ throw new ProtocolValidationError("invalid_request", `${name} must be a non-empty string`);
608
+ }
609
+ return v;
610
+ }
611
+ var BASE58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
612
+ function base58Decode(input) {
613
+ if (input.length === 0)
614
+ return new Uint8Array(0);
615
+ const bytes = [0];
616
+ for (const ch of input) {
617
+ let carry = BASE58_ALPHABET.indexOf(ch);
618
+ if (carry < 0)
619
+ throw new Error("invalid base58");
620
+ for (let i = 0; i < bytes.length; i++) {
621
+ const v = bytes[i] * 58 + carry;
622
+ bytes[i] = v & 255;
623
+ carry = v / 256 | 0;
624
+ }
625
+ while (carry > 0) {
626
+ bytes.push(carry & 255);
627
+ carry = carry / 256 | 0;
628
+ }
629
+ }
630
+ let leadingZeros = 0;
631
+ for (const ch of input) {
632
+ if (ch === "1")
633
+ leadingZeros++;
634
+ else
635
+ break;
636
+ }
637
+ const out = new Uint8Array(leadingZeros + bytes.length);
638
+ for (let i = 0; i < bytes.length; i++) {
639
+ out[out.length - 1 - i] = bytes[i];
640
+ }
641
+ return out;
642
+ }
643
+ function isPlainObject(v) {
644
+ return typeof v === "object" && v !== null && !Array.isArray(v);
645
+ }
646
+ function expectObject(v, name) {
647
+ if (!isPlainObject(v)) {
648
+ throw new ProtocolValidationError("invalid_request", `${name} must be an object`);
649
+ }
650
+ return v;
651
+ }
652
+ function expectString(v, name) {
653
+ if (typeof v !== "string") {
654
+ throw new ProtocolValidationError("invalid_request", `${name} must be a string`);
655
+ }
656
+ return v;
657
+ }
658
+ function expectInteger(v, name) {
659
+ if (typeof v !== "number" || !Number.isInteger(v)) {
660
+ throw new ProtocolValidationError("invalid_request", `${name} must be an integer`);
661
+ }
662
+ return v;
663
+ }
664
+ function parseBinaryField(v, name) {
665
+ if (!isPlainObject(v)) {
666
+ throw new ProtocolValidationError("invalid_request", `${name} must be a BinaryField object`);
667
+ }
668
+ if (v.$type !== "binary") {
669
+ throw new ProtocolValidationError("invalid_request", `${name} must have $type="binary"`);
670
+ }
671
+ if (!(v.bytes instanceof ArrayBuffer)) {
672
+ throw new ProtocolValidationError("invalid_request", `${name}.bytes must be ArrayBuffer`);
673
+ }
674
+ if (v.mime !== void 0 && typeof v.mime !== "string") {
675
+ throw new ProtocolValidationError("invalid_request", `${name}.mime must be string when present`);
676
+ }
677
+ return { $type: "binary", bytes: v.bytes, mime: v.mime };
678
+ }
679
+ function isStructuredCloneRequestCandidate(v) {
680
+ if (!isPlainObject(v))
681
+ return false;
682
+ if (v.v !== PROTOCOL_VERSION)
683
+ return false;
684
+ if (v.type !== "request")
685
+ return false;
686
+ if (typeof v.id !== "string")
687
+ return false;
688
+ if (typeof v.method !== "string")
689
+ return false;
690
+ return true;
691
+ }
692
+ function parseCancelMessage(raw) {
693
+ if (!isPlainObject(raw)) {
694
+ throw new ProtocolValidationError("invalid_request", "Cancel must be a plain object");
695
+ }
696
+ if (raw.v !== PROTOCOL_VERSION) {
697
+ throw new ProtocolValidationError("invalid_request", "Unsupported protocol version");
698
+ }
699
+ if (raw.type !== "cancel") {
700
+ throw new ProtocolValidationError("invalid_request", "Message type must be 'cancel'");
701
+ }
702
+ if (typeof raw.id !== "string" || raw.id.length === 0) {
703
+ throw new ProtocolValidationError("invalid_request", "Cancel id is required");
704
+ }
705
+ return { id: raw.id };
706
+ }
707
+ function parseRequestMessage(raw, receiverIdentity) {
708
+ const value = expectObject(raw, "Request");
709
+ if (value.v !== PROTOCOL_VERSION) throw new ProtocolValidationError("invalid_request", "Unsupported protocol version; update Connect SDK");
710
+ if (value.type !== "request") throw new ProtocolValidationError("invalid_request", "Message type must be 'request'");
711
+ const id = expectNonEmptyString(value.id, "Request id");
712
+ if (["networkIdentity", "walletPublicKeyHex"].some((field) => field in value)) throw new ProtocolValidationError("invalid_request", "Wallet selectors have been removed");
713
+ if (typeof value.method !== "string") throw new ProtocolValidationError("invalid_request", "Unknown method");
714
+ if (value.method === "feepool.prepare" || value.method === "feepool.commit" || value.method === "p2pkh.transfer") throw new ProtocolValidationError("unsupported_scope", "Method is outside Connect v1 scope");
715
+ if (!PROTOCOL_METHODS.includes(value.method)) throw new ProtocolValidationError("invalid_request", "Unknown method");
716
+ const params = expectObject(value.params, "Params");
717
+ for (const field of ["walletPublicKeyHex", "networkIdentity", "bsvNetwork", "assetId"]) {
718
+ if (field in params) throw new ProtocolValidationError("invalid_request", `Removed wallet selector: ${field}`);
719
+ }
720
+ const method = value.method;
721
+ if (method === "payment.channel.register" && params.paymentType === "feepool.connect") throw new ProtocolValidationError("unsupported_scope", "Connect v1 does not create fee-pool channels");
722
+ const identity = validateNetworkIdentity(receiverIdentity);
723
+ let normalized;
724
+ switch (method) {
725
+ case "connect.login":
726
+ normalized = validateConnectLoginParams(params);
727
+ break;
728
+ case "connect.resume":
729
+ normalized = validateConnectResumeParams(params);
730
+ break;
731
+ case "connect.logout":
732
+ normalized = validateConnectLogoutParams(params);
733
+ break;
734
+ case "connect.launch":
735
+ normalized = validateConnectLaunchParams(params);
736
+ break;
737
+ case "identity.get":
738
+ normalized = validateIdentityGetParams(params);
739
+ break;
740
+ case "intent.sign":
741
+ normalized = validateIntentSignParams(params);
742
+ break;
743
+ case "cipher.encrypt":
744
+ normalized = validateCipherEncryptParams(params);
745
+ break;
746
+ case "cipher.decrypt":
747
+ normalized = validateCipherDecryptParams(params);
748
+ break;
749
+ case "payment.pay":
750
+ normalized = validatePaymentPayParams(params, identity.bsvNetwork);
751
+ break;
752
+ case "payment.status":
753
+ normalized = validatePaymentStatusParams(params);
754
+ break;
755
+ case "payment.channel.register":
756
+ normalized = validatePaymentChannelRegisterParams(params);
757
+ break;
758
+ case "channel.publish":
759
+ normalized = validateChannelPublishParams(params);
760
+ break;
761
+ case "channel.subscription_set":
762
+ normalized = validateChannelSubscriptionSetParams(params);
763
+ break;
764
+ case "price.get":
765
+ case "price.subscribe":
766
+ case "price.unsubscribe":
767
+ normalized = validatePriceParams(params);
768
+ break;
769
+ case "storage.list":
770
+ normalized = validateStorageListParams(params);
771
+ break;
772
+ case "storage.directory.create":
773
+ normalized = validateStorageDirectoryParams(params, method, true);
774
+ break;
775
+ case "storage.directory.delete":
776
+ normalized = validateStorageDirectoryParams(params, method, false);
777
+ break;
778
+ case "storage.put":
779
+ normalized = validateStoragePutParams(params);
780
+ break;
781
+ case "storage.get":
782
+ normalized = validateStorageGetParams(params);
783
+ break;
784
+ case "storage.delete":
785
+ normalized = validateStorageDeleteParams(params);
786
+ break;
787
+ case "msfile.stat":
788
+ normalized = validateMsFileStatParams(params);
789
+ break;
790
+ case "msfile.seed.read":
791
+ normalized = validateMsFileSeedReadParams(params);
792
+ break;
793
+ case "msfile.block.read":
794
+ normalized = validateMsFileBlockReadParams(params);
795
+ break;
796
+ default:
797
+ throw new ProtocolValidationError("unsupported_scope", "Method is outside Connect v1 scope");
798
+ }
799
+ return { id, method, params: normalized };
800
+ }
801
+
802
+ // src/server.ts
803
+ function isEstablishing(method) {
804
+ return ["connect.login", "connect.resume", "connect.launch"].includes(method);
805
+ }
806
+ var KeymasterConnectReceiver = class {
807
+ constructor(options) {
808
+ this.options = options;
809
+ }
810
+ options;
811
+ bindings = /* @__PURE__ */ new Map();
812
+ pending = /* @__PURE__ */ new Map();
813
+ appViewSource = null;
814
+ closingSent = false;
815
+ epoch = 0;
816
+ /** 每次从宿主读取来源策略;只接受 HTTP(S) 实际来源,拒绝 opaque origin。 */
817
+ isAllowedPeer(event, claim = false) {
818
+ if (!event.source) return false;
819
+ try {
820
+ const url = new URL(event.origin);
821
+ if (!["http:", "https:"].includes(url.protocol) || url.origin !== event.origin) return false;
822
+ } catch {
823
+ return false;
824
+ }
825
+ const policy = this.options.peer();
826
+ if (policy.mode === "popup") return !!policy.source && event.source === policy.source;
827
+ if (event.origin !== policy.origin) return false;
828
+ const expected = policy.source || this.appViewSource;
829
+ if (expected && event.source !== expected) return false;
830
+ if (claim) this.appViewSource = event.source;
831
+ return true;
832
+ }
833
+ /** appView 首条合法 ready 才认领来源;无效版本和外来窗口不改变绑定。 */
834
+ acceptReady(event) {
835
+ const data = event.data;
836
+ return this.options.peer().mode === "appView" && data?.v === PROTOCOL_VERSION && data.type === "ready" && this.isAllowedPeer(event, true);
837
+ }
838
+ /** 校验并签发请求上下文。重复在途 ID 被忽略;非法可信请求返回标准错误。 */
839
+ async accept(event) {
840
+ if (!this.isAllowedPeer(event)) return null;
841
+ const raw = event.data;
842
+ if (!raw || typeof raw !== "object" || raw.type !== "request") return null;
843
+ if (typeof raw.id === "string" && this.pending.get(event.source)?.has(raw.id)) return null;
844
+ try {
845
+ if (raw.v !== PROTOCOL_VERSION) throw new ProtocolValidationError("invalid_request", "Unsupported protocol version; update Connect SDK");
846
+ const receiverEpoch = this.epoch;
847
+ const before = this.options.lifecycle();
848
+ if (!before.walletGeneration || !before.runGeneration) throw new ProtocolValidationError("invalid_request", "Wallet is not initialized");
849
+ const establishing = typeof raw.method === "string" && isEstablishing(raw.method);
850
+ const binding = this.bindings.get(event.source);
851
+ if (!establishing && (!binding || binding.origin !== event.origin || raw.bindingId !== binding.id || binding.walletGeneration !== before.walletGeneration || binding.runGeneration !== before.runGeneration)) {
852
+ throw new ProtocolValidationError("connection_expired", "Wallet connection expired; reconnect explicitly");
853
+ }
854
+ if (establishing && raw.bindingId !== void 0) throw new ProtocolValidationError("invalid_request", "Establishment must not reuse a binding");
855
+ const identity = establishing ? validateNetworkIdentity(await this.options.identity()) : binding.identity;
856
+ const after = this.options.lifecycle();
857
+ if (receiverEpoch !== this.epoch || before.walletGeneration !== after.walletGeneration || before.runGeneration !== after.runGeneration || !this.isAllowedPeer(event)) throw new ProtocolValidationError("connection_expired", "Wallet changed during connection");
858
+ const parsed = parseRequestMessage(raw, identity);
859
+ if (parsed.method === "identity.get" || parsed.method === "intent.sign") assertOriginMatches(parsed.params.aud, event.origin);
860
+ let requests = this.pending.get(event.source);
861
+ if (requests?.has(parsed.id)) return null;
862
+ if (!requests) {
863
+ requests = /* @__PURE__ */ new Map();
864
+ this.pending.set(event.source, requests);
865
+ }
866
+ const abort = new AbortController();
867
+ const context = Object.freeze({
868
+ ...parsed,
869
+ source: event.source,
870
+ origin: event.origin,
871
+ networkIdentity: identity,
872
+ walletGeneration: before.walletGeneration,
873
+ runGeneration: before.runGeneration,
874
+ bindingId: establishing ? void 0 : binding.id,
875
+ signal: abort.signal
876
+ });
877
+ this.isAllowedPeer(event, true);
878
+ requests.set(parsed.id, { context, abort });
879
+ return context;
880
+ } catch (error) {
881
+ const failure = error instanceof ProtocolValidationError ? error : new ProtocolValidationError("internal_error", "Wallet identity could not be read");
882
+ if (typeof raw.id === "string" && raw.id && this.isAllowedPeer(event)) this.send(event.source, event.origin, { v: PROTOCOL_VERSION, type: "result", id: raw.id, ok: false, error: { code: failure.code, message: failure.message } });
883
+ return null;
884
+ }
885
+ }
886
+ /** 取消只通知宿主;宿主决定是否仍可取消,执行中的不可逆操作不能被协议回滚。 */
887
+ acceptCancel(event) {
888
+ if (!this.isAllowedPeer(event)) return null;
889
+ try {
890
+ const parsed = parseCancelMessage(event.data);
891
+ const pending = this.pending.get(event.source)?.get(parsed.id);
892
+ if (!pending || pending.context.origin !== event.origin) return null;
893
+ if (pending.context.bindingId && event.data.bindingId !== pending.context.bindingId) return null;
894
+ this.assertCurrent(pending.context);
895
+ pending.abort.abort();
896
+ return pending.context;
897
+ } catch {
898
+ return null;
899
+ }
900
+ }
901
+ /** 宿主在排队结束及不可逆业务前复核;这里只判断协议权威,不代替资金审批。 */
902
+ assertCurrent(context) {
903
+ if (this.pending.get(context.source)?.get(context.id)?.context !== context) throw new ProtocolValidationError("connection_expired", "Request authority is no longer active");
904
+ const lifecycle = this.options.lifecycle();
905
+ if (context.walletGeneration !== lifecycle.walletGeneration || context.runGeneration !== lifecycle.runGeneration || !this.isAllowedPeer({ ...context, data: null })) throw new ProtocolValidationError("connection_expired", "Wallet connection expired; reconnect explicitly");
906
+ if (!isEstablishing(context.method)) {
907
+ const binding = this.bindings.get(context.source);
908
+ if (!binding || binding.id !== context.bindingId || binding.origin !== context.origin || !sameNetworkIdentity(binding.identity, context.networkIdentity)) throw new ProtocolValidationError("connection_expired", "Connection binding was revoked");
909
+ }
910
+ }
911
+ /** 回复成功时才签发新的连接绑定;业务返回值必须已由宿主转换成公开 DTO。 */
912
+ replyResult(context, result) {
913
+ this.assertCurrent(context);
914
+ let bindingId = context.bindingId;
915
+ let publicResult = result;
916
+ if (isEstablishing(context.method)) {
917
+ const connected = result;
918
+ if (!sameNetworkIdentity(validateNetworkIdentity(connected.networkIdentity), context.networkIdentity) || "walletPublicKeyHex" in connected || "ownerPublicKeyHex" in connected) throw new ProtocolValidationError("invalid_request", "Invalid public connection result");
919
+ publicResult = { ...result, networkIdentity: context.networkIdentity };
920
+ bindingId = this.options.randomUUID?.() || crypto.randomUUID();
921
+ this.bindings.set(context.source, { id: bindingId, origin: context.origin, identity: context.networkIdentity, walletGeneration: context.walletGeneration, runGeneration: context.runGeneration });
922
+ }
923
+ this.finish(context);
924
+ if (context.method === "connect.logout") this.bindings.delete(context.source);
925
+ this.send(context.source, context.origin, { v: PROTOCOL_VERSION, type: "result", id: context.id, ok: true, networkIdentity: context.networkIdentity, bindingId, result: publicResult });
926
+ }
927
+ /** 失败仍属于原请求;不额外生成取消响应,不误撤销同窗口后来建立的新绑定。 */
928
+ replyError(context, error) {
929
+ if (this.pending.get(context.source)?.get(context.id)?.context !== context) return;
930
+ this.finish(context);
931
+ this.send(context.source, context.origin, { v: PROTOCOL_VERSION, type: "result", id: context.id, ok: false, networkIdentity: context.networkIdentity, error });
932
+ }
933
+ /** 事件只给当前有效绑定添加接收端上下文;业务发布者不能自报绑定/钱包身份。 */
934
+ sendEvent(target, origin, event) {
935
+ const binding = this.bindings.get(target);
936
+ const lifecycle = this.options.lifecycle();
937
+ if (!binding || binding.origin !== origin || binding.walletGeneration !== lifecycle.walletGeneration || binding.runGeneration !== lifecycle.runGeneration || !this.isAllowedPeer({ source: target, origin, data: null })) return;
938
+ try {
939
+ target.postMessage({ ...event, networkIdentity: binding.identity, bindingId: binding.id }, origin);
940
+ } catch {
941
+ }
942
+ }
943
+ /** ready/closing 只承载生命周期,不携带授权或业务结果。 */
944
+ sendReady(target) {
945
+ this.sendControl(target, "ready");
946
+ }
947
+ /** 同一运行期至多通知一次 closing,发送失败不重试。 */
948
+ sendClosing(target) {
949
+ if (this.closingSent) return;
950
+ this.closingSent = true;
951
+ this.sendControl(target, "closing");
952
+ }
953
+ /** 生命周期控制帧不包含敏感业务数据,未建绑定时也可以发送。 */
954
+ sendControl(target, type) {
955
+ try {
956
+ if (target.closed) return;
957
+ const message = { v: PROTOCOL_VERSION, type };
958
+ if (this.options.control) this.options.control(target, message);
959
+ else target.postMessage(message, "*");
960
+ } catch {
961
+ }
962
+ }
963
+ /** 开始新的 Session Window 运行期,才重置 closing 一次性通知。 */
964
+ reset() {
965
+ this.clear();
966
+ this.closingSent = false;
967
+ }
968
+ /** clear 仅清协议运行态;授权撤销和业务责任收尾必须由宿主另外执行。 */
969
+ clear() {
970
+ this.epoch++;
971
+ for (const requests of this.pending.values()) for (const pending of requests.values()) pending.abort.abort();
972
+ this.pending.clear();
973
+ this.bindings.clear();
974
+ this.appViewSource = null;
975
+ }
976
+ /** 终态释放请求关联,不保留业务结果或交易材料。 */
977
+ finish(context) {
978
+ const requests = this.pending.get(context.source);
979
+ requests?.delete(context.id);
980
+ if (!requests?.size) this.pending.delete(context.source);
981
+ }
982
+ /** 精确 origin 回复,窗口退出时不重试,不能据发送成功宣告业务提交成功。 */
983
+ send(target, origin, message) {
984
+ try {
985
+ if (target.closed) return;
986
+ if (this.options.send) this.options.send(target, origin, message);
987
+ else target.postMessage(message, origin);
988
+ } catch {
989
+ }
990
+ }
991
+ };
992
+
993
+ export { APP_IDENTITY_DOMAIN_V1, AppIdentityValidationError, KeymasterConnectReceiver, ProtocolValidationError, assertCompressedPubkeyHex, assertMainnetP2pkhAddress, assertOriginMatches, assertP2pkhAddressForAsset, canonicalizeJson, identityDigestBytes, identityPayload, isEstablishing, isStructuredCloneRequestCandidate, isVerifiedAppIdentitySnapshot, parseCancelMessage, parseRequestMessage, validateExactChannel, verifyAppIdentityProof };
994
+ //# sourceMappingURL=server.js.map
995
+ //# sourceMappingURL=server.js.map