keymaster-connect 0.1.1 → 0.1.2

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/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { PROTOCOL_METHODS, PROTOCOL_VERSION, sameNetworkIdentity, validateNetworkIdentity } from './chunk-JDAJD3SX.js';
2
- export { MSFILE_BLOCK_SIZE_BYTES, MSFILE_DIGEST_SIZE_BYTES, MSFILE_LOCAL_SOURCE_ID, MSFILE_MAX_BLOCK_BYTES, MSFILE_MAX_CONTENT_BYTES, MSFILE_MAX_ERROR_MESSAGE_BYTES, MSFILE_MAX_HEADER_BYTES, MSFILE_MAX_SEED_BYTES, MSFILE_PROTOCOL_ID, PROTOCOL_METHODS, PROTOCOL_VERSION, STORAGE_DEFAULT_LIST_LIMIT, STORAGE_MAX_LIST_LIMIT, STORAGE_MAX_PAYLOAD_BYTES, isValidMsFileSourceId, sameNetworkIdentity, validateBsvNetwork, validateNetworkIdentity } from './chunk-JDAJD3SX.js';
1
+ import { PROTOCOL_METHODS, PROTOCOL_VERSION, sameNetworkIdentity, validateNetworkIdentity } from './chunk-W2TNWBLP.js';
2
+ export { MSFILE_BLOCK_SIZE_BYTES, MSFILE_DIGEST_SIZE_BYTES, MSFILE_LOCAL_SOURCE_ID, MSFILE_MAX_BLOCK_BYTES, MSFILE_MAX_CONTENT_BYTES, MSFILE_MAX_ERROR_MESSAGE_BYTES, MSFILE_MAX_HEADER_BYTES, MSFILE_MAX_SEED_BYTES, MSFILE_PROTOCOL_ID, PROTOCOL_METHODS, PROTOCOL_VERSION, STORAGE_DEFAULT_LIST_LIMIT, STORAGE_MAX_LIST_LIMIT, STORAGE_MAX_PAYLOAD_BYTES, isValidMsFileSourceId, sameNetworkIdentity, validateBsvNetwork, validateNetworkIdentity } from './chunk-W2TNWBLP.js';
3
3
 
4
4
  // src/binary.ts
5
5
  function binary(bytes, mime) {
@@ -42,9 +42,7 @@ var KeymasterProtocolError = class extends Error {
42
42
  }
43
43
  code;
44
44
  };
45
- var DEFAULT_POPUP_PATH = "/protocol/v1/popup";
46
- var DEFAULT_POPUP_NAME = "keymaster-connect-v1";
47
- var DEFAULT_READY_TIMEOUT_MS = 3e4;
45
+ var DEFAULT_READY_TIMEOUT_MS = 12e4;
48
46
  var DEFAULT_REQUEST_TIMEOUT_MS = 12e4;
49
47
  var DEFAULT_CLOSE_POLL_MS = 500;
50
48
  var KeymasterConnectClient = class {
@@ -55,29 +53,27 @@ var KeymasterConnectClient = class {
55
53
  return this.identityValue;
56
54
  }
57
55
  targetOrigin;
58
- mode;
59
56
  environment;
60
57
  options;
61
58
  pending = /* @__PURE__ */ new Map();
62
59
  stateValue = "idle";
63
60
  sessionWindow = null;
64
- ownsSessionWindow = false;
65
61
  listenerInstalled = false;
66
62
  readyPromise = null;
67
63
  readyResolve = null;
68
64
  readyReject = null;
69
65
  readyTimer = null;
70
66
  closePoller = null;
67
+ authorizationId = null;
68
+ authorizedIdentity = null;
69
+ recoveryId = null;
70
+ recoveryWaiters = /* @__PURE__ */ new Set();
71
71
  constructor(options) {
72
72
  if ("networkIdentity" in options) throw new TypeError("networkIdentity option has been removed; read identity from the connection result");
73
73
  this.targetOrigin = normalizeHttpOrigin(options.targetOrigin);
74
- this.mode = options.mode ?? "popup";
74
+ if (options.mode !== void 0 && options.mode !== "appView") throw new TypeError("Connect apps must be launched inside the wallet");
75
75
  this.options = {
76
76
  ...options,
77
- popupPath: options.popupPath ?? DEFAULT_POPUP_PATH,
78
- popupName: options.popupName ?? DEFAULT_POPUP_NAME,
79
- popupWidth: positiveNumber(options.popupWidth ?? 520, "popupWidth"),
80
- popupHeight: positiveNumber(options.popupHeight ?? 760, "popupHeight"),
81
77
  readyTimeoutMs: positiveNumber(options.readyTimeoutMs ?? DEFAULT_READY_TIMEOUT_MS, "readyTimeoutMs"),
82
78
  requestTimeoutMs: positiveNumber(options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS, "requestTimeoutMs"),
83
79
  closePollMs: positiveNumber(options.closePollMs ?? DEFAULT_CLOSE_POLL_MS, "closePollMs")
@@ -95,14 +91,12 @@ var KeymasterConnectClient = class {
95
91
  /**
96
92
  * Establishes the browser transport.
97
93
  *
98
- * Popup mode opens the Session Window and waits for `ready`. appView mode
99
- * adopts `window.opener`, installs the listener, and sends the child `ready`
100
- * message without ever opening a fallback popup.
94
+ * 绑定浏览器真实父页面,精确校验来源;独立页面直接失败,不打开钱包窗口。
101
95
  *
102
96
  * @group Transport
103
97
  */
104
98
  connect() {
105
- return this.mode === "appView" ? this.connectAppView() : this.connectPopup();
99
+ return this.connectAppView();
106
100
  }
107
101
  /**
108
102
  * Sends any public Connect method with compile-time parameter and result
@@ -117,7 +111,9 @@ var KeymasterConnectClient = class {
117
111
  for (const field of ["walletPublicKeyHex", "networkIdentity", "bsvNetwork", "assetId"]) {
118
112
  if (field in params) throw new TypeError(`Removed wallet selector: ${field}`);
119
113
  }
114
+ if (method === "connect.resume" && this.authorizationId) return this.continueConnection(options);
120
115
  const establishing = ["connect.login", "connect.resume", "connect.launch"].includes(method);
116
+ if (!establishing && this.stateValue === "paused") throw new KeymasterTransportError("wallet_paused", "Wallet connection is paused; old business requests are never replayed");
121
117
  if (establishing && this.pending.size) throw new TypeError("Cannot establish a connection while requests are pending");
122
118
  if (!establishing && !this.bindingId) throw new KeymasterProtocolError("invalid_request", "Login, resume or launch before making business requests");
123
119
  if ([...this.pending.values()].some((request) => ["connect.login", "connect.resume", "connect.launch"].includes(request.method))) throw new TypeError("Connection establishment is already pending");
@@ -127,7 +123,7 @@ var KeymasterConnectClient = class {
127
123
  if (options.signal?.aborted) throw abortReason(options.signal);
128
124
  const target = this.sessionWindow;
129
125
  if (!target || isWindowClosed(target)) {
130
- throw new KeymasterTransportError("popup_closed", "Keymaster Session Window is closed");
126
+ throw new KeymasterTransportError("wallet_closed", "Keymaster parent wallet is closed");
131
127
  }
132
128
  const requestId = options.requestId ?? this.environment.randomUUID();
133
129
  if (!requestId || this.pending.has(requestId)) {
@@ -202,9 +198,6 @@ var KeymasterConnectClient = class {
202
198
  * @group Connect
203
199
  */
204
200
  launch(params, options) {
205
- if (this.mode !== "appView") {
206
- return Promise.reject(new TypeError('connect.launch requires mode: "appView"'));
207
- }
208
201
  return this.request("connect.launch", params, options);
209
202
  }
210
203
  /**
@@ -380,6 +373,7 @@ var KeymasterConnectClient = class {
380
373
  * @group Transport
381
374
  */
382
375
  close() {
376
+ for (const id of this.pending.keys()) this.postCancel(id);
383
377
  this.identityValue = null;
384
378
  this.bindingId = null;
385
379
  const error = new KeymasterTransportError("client_closed", "Keymaster client was closed");
@@ -390,61 +384,51 @@ var KeymasterConnectClient = class {
390
384
  this.environment.removeMessageListener(this.handleMessage);
391
385
  this.listenerInstalled = false;
392
386
  }
393
- try {
394
- if (this.ownsSessionWindow && this.sessionWindow && !isWindowClosed(this.sessionWindow)) {
395
- this.sessionWindow.close();
396
- }
397
- } catch {
398
- }
399
- this.sessionWindow = null;
400
- this.ownsSessionWindow = false;
401
- this.setState("disconnected");
402
- }
403
- connectPopup() {
404
- if (this.isConnected()) return Promise.resolve();
405
- if (this.readyPromise) return this.readyPromise;
406
- const url = new URL(this.options.popupPath, `${this.targetOrigin}/`);
407
- if (url.origin !== this.targetOrigin) {
408
- return Promise.reject(new TypeError("popupPath must resolve inside targetOrigin"));
409
- }
387
+ if (!this.authorizationId) this.sessionWindow = null;
388
+ this.recoveryId = null;
389
+ this.finishRecovery(void 0, error);
390
+ this.setState(this.authorizationId ? "paused" : "disconnected");
391
+ }
392
+ /** 恢复原父钱包连接;任何情况下都不另开窗口或重放旧业务。 */
393
+ continueConnection(options) {
394
+ if (this.pending.size) return Promise.reject(new TypeError("Cannot resume while business requests are pending"));
410
395
  this.installListener();
411
- this.setState("opening");
412
- this.sessionWindow = this.environment.open(
413
- url.toString(),
414
- this.options.popupName,
415
- popupFeatures(this.options.popupWidth, this.options.popupHeight)
416
- );
417
- if (!this.sessionWindow) {
418
- this.setState("disconnected");
419
- return Promise.reject(new KeymasterTransportError("popup_blocked", "Keymaster Session Window was blocked"));
420
- }
421
- this.ownsSessionWindow = true;
396
+ const parent = this.environment.parent();
397
+ if (!parent || isWindowClosed(parent)) return Promise.reject(new KeymasterTransportError("appview_session_lost", "No wallet parent is available; relaunch from the wallet"));
398
+ this.sessionWindow = parent;
399
+ this.pause(new KeymasterTransportError("wallet_paused", "Re-establishing the original wallet connection"));
422
400
  this.startClosePolling();
423
- this.readyPromise = new Promise((resolve, reject) => {
424
- this.readyResolve = resolve;
425
- this.readyReject = reject;
426
- this.readyTimer = this.environment.setTimeout(() => {
427
- this.disconnect(new KeymasterTransportError("ready_timeout", "Timed out waiting for Keymaster ready"));
428
- }, this.options.readyTimeoutMs);
401
+ return new Promise((resolve, reject) => {
402
+ const finish = (error, result) => {
403
+ this.environment.clearTimeout(timer);
404
+ options.signal?.removeEventListener("abort", aborted);
405
+ this.recoveryWaiters.delete(waiter);
406
+ if (error) reject(error);
407
+ else resolve(result);
408
+ };
409
+ const waiter = { resolve: (result) => finish(void 0, result), reject: (error) => finish(error) };
410
+ const aborted = () => finish(abortReason(options.signal));
411
+ const timer = this.environment.setTimeout(() => finish(new KeymasterTransportError("request_timeout", "Timed out restoring wallet connection")), positiveNumber(options.timeoutMs ?? this.options.readyTimeoutMs, "timeoutMs"));
412
+ this.recoveryWaiters.add(waiter);
413
+ options.signal?.addEventListener("abort", aborted, { once: true });
414
+ this.sendRecovery();
429
415
  });
430
- return this.readyPromise;
431
416
  }
432
417
  connectAppView() {
433
418
  if (this.isConnected()) return Promise.resolve();
434
- const opener = this.environment.opener();
435
- if (!opener || isWindowClosed(opener)) {
436
- const code = this.stateValue === "idle" ? "no_opener" : "appview_session_lost";
419
+ const parent = this.environment.parent();
420
+ if (!parent || isWindowClosed(parent)) {
421
+ const code = this.stateValue === "idle" ? "not_embedded" : "appview_session_lost";
437
422
  this.setState("disconnected");
438
423
  return Promise.reject(new KeymasterTransportError(
439
424
  code,
440
- "No live Keymaster appView Session Window is available"
425
+ "No live wallet parent is available; launch the app from Keymaster"
441
426
  ));
442
427
  }
443
428
  this.installListener();
444
- this.sessionWindow = opener;
445
- this.ownsSessionWindow = false;
429
+ this.sessionWindow = parent;
446
430
  try {
447
- opener.postMessage({ v: PROTOCOL_VERSION, type: "ready" }, this.targetOrigin);
431
+ parent.postMessage({ v: PROTOCOL_VERSION, type: "ready" }, this.targetOrigin);
448
432
  } catch (cause) {
449
433
  this.sessionWindow = null;
450
434
  this.setState("disconnected");
@@ -462,12 +446,18 @@ var KeymasterConnectClient = class {
462
446
  if (value.type === "ready" || value.type === "result") this.disconnect(new KeymasterTransportError("unsupported_protocol", "Incompatible Keymaster protocol version"));
463
447
  return;
464
448
  }
465
- if (value.type === "ready" && this.mode === "popup") {
466
- this.finishReady();
449
+ if (value.type === "ready") return;
450
+ if (value.type === "closing") {
451
+ if (this.authorizationId) this.pause(new KeymasterTransportError("wallet_paused", "Wallet runtime is unavailable"));
452
+ else this.disconnect(new KeymasterTransportError("wallet_closed", "Keymaster wallet connection is closing"));
467
453
  return;
468
454
  }
469
- if (value.type === "closing") {
470
- this.disconnect(new KeymasterTransportError("popup_closed", "Keymaster Session Window is closing"));
455
+ if (value.type === "revoked" && value.authorizationId === this.authorizationId) {
456
+ this.authorizationId = null;
457
+ this.authorizedIdentity = null;
458
+ this.recoveryId = null;
459
+ this.finishRecovery(void 0, new KeymasterProtocolError("connection_expired", "Application connection authorization was revoked"));
460
+ this.disconnect(new KeymasterProtocolError("connection_expired", "Application connection authorization was revoked"));
471
461
  return;
472
462
  }
473
463
  if (value.type === "event") {
@@ -485,6 +475,27 @@ var KeymasterConnectClient = class {
485
475
  }
486
476
  if (value.type !== "result" || typeof value.id !== "string" || typeof value.ok !== "boolean") return;
487
477
  const result = event.data;
478
+ if (this.authorizationId && result.id === this.recoveryId) {
479
+ if (!result.ok) {
480
+ this.pause(new KeymasterProtocolError(result.error.code, result.error.message));
481
+ return;
482
+ }
483
+ try {
484
+ const identity = validateNetworkIdentity(value.networkIdentity);
485
+ const restored = result.result;
486
+ if (!this.authorizedIdentity || !sameNetworkIdentity(identity, this.authorizedIdentity) || !sameNetworkIdentity(identity, validateNetworkIdentity(restored.networkIdentity)) || restored.authorizationId !== this.authorizationId || typeof value.bindingId !== "string" || !value.bindingId) throw new Error("Recovery must retain the original wallet and authorization");
487
+ if (this.bindingId !== value.bindingId) this.pause(new KeymasterTransportError("wallet_paused", "Wallet runtime was replaced"));
488
+ this.identityValue = Object.freeze({ ...identity });
489
+ this.bindingId = value.bindingId;
490
+ this.recoveryId = null;
491
+ this.setState("connected");
492
+ this.finishRecovery(restored);
493
+ } catch (error) {
494
+ this.pause(error);
495
+ this.finishRecovery(void 0, error);
496
+ }
497
+ return;
498
+ }
488
499
  const pending = this.pending.get(result.id);
489
500
  if (!pending) return;
490
501
  this.deletePending(result.id);
@@ -494,8 +505,11 @@ var KeymasterConnectClient = class {
494
505
  return;
495
506
  }
496
507
  if (result.error.code === "connection_expired") {
497
- this.identityValue = null;
498
- this.bindingId = null;
508
+ if (this.authorizationId) this.pause(new KeymasterProtocolError(result.error.code, result.error.message));
509
+ else {
510
+ this.identityValue = null;
511
+ this.bindingId = null;
512
+ }
499
513
  }
500
514
  pending.reject(new KeymasterProtocolError(result.error.code, result.error.message));
501
515
  return;
@@ -504,8 +518,11 @@ var KeymasterConnectClient = class {
504
518
  const identity = validateNetworkIdentity(value.networkIdentity);
505
519
  if (["connect.login", "connect.resume", "connect.launch"].includes(pending.method)) {
506
520
  const connected = result.result;
507
- if (!sameNetworkIdentity(identity, validateNetworkIdentity(connected.networkIdentity)) || typeof value.bindingId !== "string" || !value.bindingId) throw new Error("Invalid connection identity or binding");
521
+ if (!sameNetworkIdentity(identity, validateNetworkIdentity(connected.networkIdentity)) || typeof value.bindingId !== "string" || !value.bindingId || typeof connected.authorizationId !== "string" || !connected.authorizationId) throw new Error("Invalid connection identity or binding");
508
522
  this.identityValue = Object.freeze({ ...identity });
523
+ this.authorizedIdentity = this.identityValue;
524
+ this.authorizationId = connected.authorizationId;
525
+ this.recoveryId = null;
509
526
  this.bindingId = value.bindingId;
510
527
  } else if (!this.identityValue || value.bindingId !== this.bindingId || !sameNetworkIdentity(this.identityValue, identity)) {
511
528
  throw new Error("Keymaster connection identity mismatch");
@@ -513,6 +530,9 @@ var KeymasterConnectClient = class {
513
530
  if (pending.method === "connect.logout") {
514
531
  this.identityValue = null;
515
532
  this.bindingId = null;
533
+ this.authorizationId = null;
534
+ this.authorizedIdentity = null;
535
+ this.recoveryId = null;
516
536
  }
517
537
  pending.resolve(result.result);
518
538
  } catch (error) {
@@ -546,27 +566,46 @@ var KeymasterConnectClient = class {
546
566
  this.readyReject = null;
547
567
  }
548
568
  disconnect(reason) {
569
+ for (const id of this.pending.keys()) this.postCancel(id);
549
570
  this.identityValue = null;
550
571
  this.bindingId = null;
551
572
  this.rejectAll(reason);
552
573
  this.failReady(reason);
553
574
  this.stopClosePolling();
554
- try {
555
- if (this.ownsSessionWindow && this.sessionWindow && !isWindowClosed(this.sessionWindow)) {
556
- this.sessionWindow.close();
557
- }
558
- } catch {
559
- }
560
575
  this.sessionWindow = null;
561
- this.ownsSessionWindow = false;
562
576
  this.setState("disconnected");
563
577
  }
578
+ /** 暂停仅撤销瞬时绑定和旧请求,持久授权引用及原身份留作恢复校验。 */
579
+ pause(reason) {
580
+ this.identityValue = null;
581
+ this.bindingId = null;
582
+ this.rejectAll(reason);
583
+ this.failReady(reason);
584
+ this.setState("paused");
585
+ }
586
+ sendRecovery() {
587
+ if (!this.authorizationId || !this.sessionWindow || isWindowClosed(this.sessionWindow)) return;
588
+ this.recoveryId ??= this.environment.randomUUID();
589
+ try {
590
+ this.sessionWindow.postMessage({ v: PROTOCOL_VERSION, type: "reconnect", id: this.recoveryId, authorizationId: this.authorizationId, ...this.bindingId ? { bindingId: this.bindingId } : {} }, this.targetOrigin);
591
+ } catch (error) {
592
+ this.pause(error);
593
+ }
594
+ }
595
+ finishRecovery(result, error) {
596
+ for (const waiter of [...this.recoveryWaiters]) {
597
+ if (error) waiter.reject(error);
598
+ else if (result) waiter.resolve(result);
599
+ }
600
+ }
564
601
  startClosePolling() {
565
602
  this.stopClosePolling();
566
603
  this.closePoller = this.environment.setInterval(() => {
567
604
  if (this.sessionWindow && isWindowClosed(this.sessionWindow)) {
568
- this.disconnect(new KeymasterTransportError("popup_closed", "Keymaster Session Window was closed"));
569
- }
605
+ if (this.authorizationId) {
606
+ if (this.stateValue !== "paused") this.pause(new KeymasterTransportError("wallet_paused", "Wallet window is closed"));
607
+ } else this.disconnect(new KeymasterTransportError("wallet_closed", "Keymaster parent wallet was closed"));
608
+ } else this.sendRecovery();
570
609
  }, this.options.closePollMs);
571
610
  }
572
611
  stopClosePolling() {
@@ -611,8 +650,7 @@ function createBrowserEnvironment() {
611
650
  throw new TypeError("keymaster-connect requires a browser Window or an explicit environment");
612
651
  }
613
652
  return {
614
- open: (url, target, features) => window.open(url, target, features),
615
- opener: () => window.opener,
653
+ parent: () => window.parent !== window ? window.parent : null,
616
654
  addMessageListener: (listener) => window.addEventListener("message", listener),
617
655
  removeMessageListener: (listener) => window.removeEventListener("message", listener),
618
656
  setTimeout: (handler, timeoutMs) => window.setTimeout(handler, timeoutMs),
@@ -629,9 +667,6 @@ function normalizeHttpOrigin(input) {
629
667
  }
630
668
  return url.origin;
631
669
  }
632
- function popupFeatures(width, height) {
633
- return `popup=yes,width=${Math.max(320, Math.trunc(width))},height=${Math.max(320, Math.trunc(height))}`;
634
- }
635
670
  function positiveNumber(value, name) {
636
671
  if (!Number.isFinite(value) || value <= 0) throw new TypeError(`${name} must be a positive number`);
637
672
  return value;