keymaster-connect 0.1.1 → 0.1.3

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 {
@@ -61,23 +59,24 @@ var KeymasterConnectClient = class {
61
59
  pending = /* @__PURE__ */ new Map();
62
60
  stateValue = "idle";
63
61
  sessionWindow = null;
64
- ownsSessionWindow = false;
65
62
  listenerInstalled = false;
66
63
  readyPromise = null;
67
64
  readyResolve = null;
68
65
  readyReject = null;
69
66
  readyTimer = null;
70
67
  closePoller = null;
68
+ authorizationId = null;
69
+ authorizedIdentity = null;
70
+ recoveryId = null;
71
+ recoveryWaiters = /* @__PURE__ */ new Set();
71
72
  constructor(options) {
72
73
  if ("networkIdentity" in options) throw new TypeError("networkIdentity option has been removed; read identity from the connection result");
73
74
  this.targetOrigin = normalizeHttpOrigin(options.targetOrigin);
74
75
  this.mode = options.mode ?? "popup";
76
+ if (!["iframe", "appView", "popup"].includes(this.mode)) throw new TypeError("Invalid Connect transport mode");
75
77
  this.options = {
76
78
  ...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"),
79
+ popupPath: options.popupPath ?? "/",
81
80
  readyTimeoutMs: positiveNumber(options.readyTimeoutMs ?? DEFAULT_READY_TIMEOUT_MS, "readyTimeoutMs"),
82
81
  requestTimeoutMs: positiveNumber(options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS, "requestTimeoutMs"),
83
82
  closePollMs: positiveNumber(options.closePollMs ?? DEFAULT_CLOSE_POLL_MS, "closePollMs")
@@ -95,14 +94,12 @@ var KeymasterConnectClient = class {
95
94
  /**
96
95
  * Establishes the browser transport.
97
96
  *
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.
97
+ * iframe / appView 绑定真实 parent / opener;popup 打开完整钱包等待 ready。
101
98
  *
102
99
  * @group Transport
103
100
  */
104
101
  connect() {
105
- return this.mode === "appView" ? this.connectAppView() : this.connectPopup();
102
+ return this.mode === "popup" ? this.connectPopup() : this.connectAppView();
106
103
  }
107
104
  /**
108
105
  * Sends any public Connect method with compile-time parameter and result
@@ -117,7 +114,9 @@ var KeymasterConnectClient = class {
117
114
  for (const field of ["walletPublicKeyHex", "networkIdentity", "bsvNetwork", "assetId"]) {
118
115
  if (field in params) throw new TypeError(`Removed wallet selector: ${field}`);
119
116
  }
117
+ if (method === "connect.resume" && this.authorizationId) return this.continueConnection(options);
120
118
  const establishing = ["connect.login", "connect.resume", "connect.launch"].includes(method);
119
+ if (!establishing && this.stateValue === "paused") throw new KeymasterTransportError("wallet_paused", "Wallet connection is paused; old business requests are never replayed");
121
120
  if (establishing && this.pending.size) throw new TypeError("Cannot establish a connection while requests are pending");
122
121
  if (!establishing && !this.bindingId) throw new KeymasterProtocolError("invalid_request", "Login, resume or launch before making business requests");
123
122
  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 +126,7 @@ var KeymasterConnectClient = class {
127
126
  if (options.signal?.aborted) throw abortReason(options.signal);
128
127
  const target = this.sessionWindow;
129
128
  if (!target || isWindowClosed(target)) {
130
- throw new KeymasterTransportError("popup_closed", "Keymaster Session Window is closed");
129
+ throw new KeymasterTransportError("wallet_closed", "Keymaster parent wallet is closed");
131
130
  }
132
131
  const requestId = options.requestId ?? this.environment.randomUUID();
133
132
  if (!requestId || this.pending.has(requestId)) {
@@ -202,9 +201,6 @@ var KeymasterConnectClient = class {
202
201
  * @group Connect
203
202
  */
204
203
  launch(params, options) {
205
- if (this.mode !== "appView") {
206
- return Promise.reject(new TypeError('connect.launch requires mode: "appView"'));
207
- }
208
204
  return this.request("connect.launch", params, options);
209
205
  }
210
206
  /**
@@ -380,6 +376,7 @@ var KeymasterConnectClient = class {
380
376
  * @group Transport
381
377
  */
382
378
  close() {
379
+ for (const id of this.pending.keys()) this.postCancel(id);
383
380
  this.identityValue = null;
384
381
  this.bindingId = null;
385
382
  const error = new KeymasterTransportError("client_closed", "Keymaster client was closed");
@@ -390,61 +387,80 @@ var KeymasterConnectClient = class {
390
387
  this.environment.removeMessageListener(this.handleMessage);
391
388
  this.listenerInstalled = false;
392
389
  }
393
- try {
394
- if (this.ownsSessionWindow && this.sessionWindow && !isWindowClosed(this.sessionWindow)) {
395
- this.sessionWindow.close();
390
+ if (!this.authorizationId) this.sessionWindow = null;
391
+ this.recoveryId = null;
392
+ this.finishRecovery(void 0, error);
393
+ this.setState(this.authorizationId ? "paused" : "disconnected");
394
+ }
395
+ /** 主动恢复可由 popup 重新打开钱包;后台恢复从不打开窗口或重放业务。 */
396
+ continueConnection(options) {
397
+ if (this.pending.size) return Promise.reject(new TypeError("Cannot resume while business requests are pending"));
398
+ this.installListener();
399
+ if (this.mode === "popup") {
400
+ if (!this.sessionWindow || isWindowClosed(this.sessionWindow)) {
401
+ const url = new URL(this.options.popupPath, `${this.targetOrigin}/`);
402
+ if (url.origin !== this.targetOrigin) return Promise.reject(new TypeError("popupPath must resolve inside targetOrigin"));
403
+ this.sessionWindow = this.environment.open(url.href, "_blank", "");
404
+ if (!this.sessionWindow) return Promise.reject(new KeymasterTransportError("popup_blocked", "Keymaster wallet window was blocked"));
396
405
  }
397
- } catch {
406
+ } else {
407
+ const launcher = this.mode === "iframe" ? this.environment.parent() : this.environment.opener();
408
+ if (!launcher || isWindowClosed(launcher)) return Promise.reject(new KeymasterTransportError("appview_session_lost", "Wallet launcher unavailable; relaunch from the wallet"));
409
+ this.sessionWindow = launcher;
398
410
  }
399
- this.sessionWindow = null;
400
- this.ownsSessionWindow = false;
401
- this.setState("disconnected");
411
+ this.pause(new KeymasterTransportError("wallet_paused", "Re-establishing the original wallet connection"));
412
+ this.startClosePolling();
413
+ return new Promise((resolve, reject) => {
414
+ const finish = (error, result) => {
415
+ this.environment.clearTimeout(timer);
416
+ options.signal?.removeEventListener("abort", aborted);
417
+ this.recoveryWaiters.delete(waiter);
418
+ if (error) reject(error);
419
+ else resolve(result);
420
+ };
421
+ const waiter = { resolve: (result) => finish(void 0, result), reject: (error) => finish(error) };
422
+ const aborted = () => finish(abortReason(options.signal));
423
+ const timer = this.environment.setTimeout(() => finish(new KeymasterTransportError("request_timeout", "Timed out restoring wallet connection")), positiveNumber(options.timeoutMs ?? this.options.readyTimeoutMs, "timeoutMs"));
424
+ this.recoveryWaiters.add(waiter);
425
+ options.signal?.addEventListener("abort", aborted, { once: true });
426
+ this.sendRecovery();
427
+ });
402
428
  }
403
429
  connectPopup() {
404
430
  if (this.isConnected()) return Promise.resolve();
405
431
  if (this.readyPromise) return this.readyPromise;
406
432
  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
- }
433
+ if (url.origin !== this.targetOrigin) return Promise.reject(new TypeError("popupPath must resolve inside targetOrigin"));
410
434
  this.installListener();
411
435
  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
- );
436
+ this.sessionWindow = this.environment.open(url.href, "_blank", "");
417
437
  if (!this.sessionWindow) {
418
438
  this.setState("disconnected");
419
- return Promise.reject(new KeymasterTransportError("popup_blocked", "Keymaster Session Window was blocked"));
439
+ return Promise.reject(new KeymasterTransportError("popup_blocked", "Keymaster wallet window was blocked"));
420
440
  }
421
- this.ownsSessionWindow = true;
422
441
  this.startClosePolling();
423
442
  this.readyPromise = new Promise((resolve, reject) => {
424
443
  this.readyResolve = resolve;
425
444
  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);
445
+ this.readyTimer = this.environment.setTimeout(() => this.disconnect(new KeymasterTransportError("ready_timeout", "Timed out waiting for the wallet to initialize or unlock")), this.options.readyTimeoutMs);
429
446
  });
430
447
  return this.readyPromise;
431
448
  }
432
449
  connectAppView() {
433
450
  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";
451
+ const parent = this.mode === "iframe" ? this.environment.parent() : this.environment.opener();
452
+ if (!parent || isWindowClosed(parent)) {
453
+ const code = this.stateValue === "idle" ? "not_embedded" : "appview_session_lost";
437
454
  this.setState("disconnected");
438
455
  return Promise.reject(new KeymasterTransportError(
439
456
  code,
440
- "No live Keymaster appView Session Window is available"
457
+ "Wallet launcher unavailable; launch the app from Keymaster"
441
458
  ));
442
459
  }
443
460
  this.installListener();
444
- this.sessionWindow = opener;
445
- this.ownsSessionWindow = false;
461
+ this.sessionWindow = parent;
446
462
  try {
447
- opener.postMessage({ v: PROTOCOL_VERSION, type: "ready" }, this.targetOrigin);
463
+ parent.postMessage({ v: PROTOCOL_VERSION, type: "ready" }, this.targetOrigin);
448
464
  } catch (cause) {
449
465
  this.sessionWindow = null;
450
466
  this.setState("disconnected");
@@ -462,12 +478,21 @@ var KeymasterConnectClient = class {
462
478
  if (value.type === "ready" || value.type === "result") this.disconnect(new KeymasterTransportError("unsupported_protocol", "Incompatible Keymaster protocol version"));
463
479
  return;
464
480
  }
465
- if (value.type === "ready" && this.mode === "popup") {
466
- this.finishReady();
481
+ if (value.type === "ready") {
482
+ if (this.mode === "popup" && this.readyPromise) this.finishReady();
467
483
  return;
468
484
  }
469
485
  if (value.type === "closing") {
470
- this.disconnect(new KeymasterTransportError("popup_closed", "Keymaster Session Window is closing"));
486
+ if (this.authorizationId) this.pause(new KeymasterTransportError("wallet_paused", "Wallet runtime is unavailable"));
487
+ else this.disconnect(new KeymasterTransportError("wallet_closed", "Keymaster wallet connection is closing"));
488
+ return;
489
+ }
490
+ if (value.type === "revoked" && value.authorizationId === this.authorizationId) {
491
+ this.authorizationId = null;
492
+ this.authorizedIdentity = null;
493
+ this.recoveryId = null;
494
+ this.finishRecovery(void 0, new KeymasterProtocolError("connection_expired", "Application connection authorization was revoked"));
495
+ this.disconnect(new KeymasterProtocolError("connection_expired", "Application connection authorization was revoked"));
471
496
  return;
472
497
  }
473
498
  if (value.type === "event") {
@@ -485,6 +510,27 @@ var KeymasterConnectClient = class {
485
510
  }
486
511
  if (value.type !== "result" || typeof value.id !== "string" || typeof value.ok !== "boolean") return;
487
512
  const result = event.data;
513
+ if (this.authorizationId && result.id === this.recoveryId) {
514
+ if (!result.ok) {
515
+ this.pause(new KeymasterProtocolError(result.error.code, result.error.message));
516
+ return;
517
+ }
518
+ try {
519
+ const identity = validateNetworkIdentity(value.networkIdentity);
520
+ const restored = result.result;
521
+ 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");
522
+ if (this.bindingId !== value.bindingId) this.pause(new KeymasterTransportError("wallet_paused", "Wallet runtime was replaced"));
523
+ this.identityValue = Object.freeze({ ...identity });
524
+ this.bindingId = value.bindingId;
525
+ this.recoveryId = null;
526
+ this.setState("connected");
527
+ this.finishRecovery(restored);
528
+ } catch (error) {
529
+ this.pause(error);
530
+ this.finishRecovery(void 0, error);
531
+ }
532
+ return;
533
+ }
488
534
  const pending = this.pending.get(result.id);
489
535
  if (!pending) return;
490
536
  this.deletePending(result.id);
@@ -494,8 +540,11 @@ var KeymasterConnectClient = class {
494
540
  return;
495
541
  }
496
542
  if (result.error.code === "connection_expired") {
497
- this.identityValue = null;
498
- this.bindingId = null;
543
+ if (this.authorizationId) this.pause(new KeymasterProtocolError(result.error.code, result.error.message));
544
+ else {
545
+ this.identityValue = null;
546
+ this.bindingId = null;
547
+ }
499
548
  }
500
549
  pending.reject(new KeymasterProtocolError(result.error.code, result.error.message));
501
550
  return;
@@ -504,8 +553,11 @@ var KeymasterConnectClient = class {
504
553
  const identity = validateNetworkIdentity(value.networkIdentity);
505
554
  if (["connect.login", "connect.resume", "connect.launch"].includes(pending.method)) {
506
555
  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");
556
+ 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
557
  this.identityValue = Object.freeze({ ...identity });
558
+ this.authorizedIdentity = this.identityValue;
559
+ this.authorizationId = connected.authorizationId;
560
+ this.recoveryId = null;
509
561
  this.bindingId = value.bindingId;
510
562
  } else if (!this.identityValue || value.bindingId !== this.bindingId || !sameNetworkIdentity(this.identityValue, identity)) {
511
563
  throw new Error("Keymaster connection identity mismatch");
@@ -513,6 +565,9 @@ var KeymasterConnectClient = class {
513
565
  if (pending.method === "connect.logout") {
514
566
  this.identityValue = null;
515
567
  this.bindingId = null;
568
+ this.authorizationId = null;
569
+ this.authorizedIdentity = null;
570
+ this.recoveryId = null;
516
571
  }
517
572
  pending.resolve(result.result);
518
573
  } catch (error) {
@@ -546,27 +601,46 @@ var KeymasterConnectClient = class {
546
601
  this.readyReject = null;
547
602
  }
548
603
  disconnect(reason) {
604
+ for (const id of this.pending.keys()) this.postCancel(id);
549
605
  this.identityValue = null;
550
606
  this.bindingId = null;
551
607
  this.rejectAll(reason);
552
608
  this.failReady(reason);
553
609
  this.stopClosePolling();
554
- try {
555
- if (this.ownsSessionWindow && this.sessionWindow && !isWindowClosed(this.sessionWindow)) {
556
- this.sessionWindow.close();
557
- }
558
- } catch {
559
- }
560
610
  this.sessionWindow = null;
561
- this.ownsSessionWindow = false;
562
611
  this.setState("disconnected");
563
612
  }
613
+ /** 暂停仅撤销瞬时绑定和旧请求,持久授权引用及原身份留作恢复校验。 */
614
+ pause(reason) {
615
+ this.identityValue = null;
616
+ this.bindingId = null;
617
+ this.rejectAll(reason);
618
+ this.failReady(reason);
619
+ this.setState("paused");
620
+ }
621
+ sendRecovery() {
622
+ if (!this.authorizationId || !this.sessionWindow || isWindowClosed(this.sessionWindow)) return;
623
+ this.recoveryId ??= this.environment.randomUUID();
624
+ try {
625
+ this.sessionWindow.postMessage({ v: PROTOCOL_VERSION, type: "reconnect", id: this.recoveryId, authorizationId: this.authorizationId, ...this.bindingId ? { bindingId: this.bindingId } : {} }, this.targetOrigin);
626
+ } catch (error) {
627
+ this.pause(error);
628
+ }
629
+ }
630
+ finishRecovery(result, error) {
631
+ for (const waiter of [...this.recoveryWaiters]) {
632
+ if (error) waiter.reject(error);
633
+ else if (result) waiter.resolve(result);
634
+ }
635
+ }
564
636
  startClosePolling() {
565
637
  this.stopClosePolling();
566
638
  this.closePoller = this.environment.setInterval(() => {
567
639
  if (this.sessionWindow && isWindowClosed(this.sessionWindow)) {
568
- this.disconnect(new KeymasterTransportError("popup_closed", "Keymaster Session Window was closed"));
569
- }
640
+ if (this.authorizationId) {
641
+ if (this.stateValue !== "paused") this.pause(new KeymasterTransportError("wallet_paused", "Wallet window is closed"));
642
+ } else this.disconnect(new KeymasterTransportError("wallet_closed", "Keymaster parent wallet was closed"));
643
+ } else this.sendRecovery();
570
644
  }, this.options.closePollMs);
571
645
  }
572
646
  stopClosePolling() {
@@ -613,6 +687,7 @@ function createBrowserEnvironment() {
613
687
  return {
614
688
  open: (url, target, features) => window.open(url, target, features),
615
689
  opener: () => window.opener,
690
+ parent: () => window.parent !== window ? window.parent : null,
616
691
  addMessageListener: (listener) => window.addEventListener("message", listener),
617
692
  removeMessageListener: (listener) => window.removeEventListener("message", listener),
618
693
  setTimeout: (handler, timeoutMs) => window.setTimeout(handler, timeoutMs),
@@ -629,9 +704,6 @@ function normalizeHttpOrigin(input) {
629
704
  }
630
705
  return url.origin;
631
706
  }
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
707
  function positiveNumber(value, name) {
636
708
  if (!Number.isFinite(value) || value <= 0) throw new TypeError(`${name} must be a positive number`);
637
709
  return value;