keymaster-connect 0.1.6 → 0.1.8

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,7 +1,7 @@
1
1
  import { readOwnPublicationProof, parseToolDefinitions, assertToolPayload, isAiToolMessage, validateToolArguments } from './chunk-M2YEI4PG.js';
2
2
  export { AI_TOOLS_MAX_JSON_CHARS, assertToolJson, assertToolPayload, isAiToolMessage, parseToolDefinitions, validateToolArguments } from './chunk-M2YEI4PG.js';
3
- import { PROTOCOL_METHODS, PROTOCOL_VERSION, sameNetworkIdentity, validateNetworkIdentity } from './chunk-THT6XHHY.js';
4
- 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-THT6XHHY.js';
3
+ import { PROTOCOL_METHODS, PROTOCOL_VERSION, sameNetworkIdentity, validateNetworkIdentity } from './chunk-D2RL3QGR.js';
4
+ 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, isValidMsFileSourceId, sameNetworkIdentity, validateBsvNetwork, validateNetworkIdentity } from './chunk-D2RL3QGR.js';
5
5
 
6
6
  // src/binary.ts
7
7
  function binary(bytes, mime) {
@@ -143,119 +143,6 @@ var AiToolClient = class {
143
143
  }
144
144
  };
145
145
 
146
- // src/recovery.ts
147
- var RECOVERY_STORAGE_KEY = "keymaster-connect:recovery:v1";
148
- function normalizeExactOrigin(input) {
149
- try {
150
- const url = new URL(input);
151
- if (url.protocol !== "http:" && url.protocol !== "https:") return null;
152
- if (url.origin !== input) return null;
153
- return url.origin;
154
- } catch {
155
- return null;
156
- }
157
- }
158
- function isMode(value) {
159
- return value === "iframe" || value === "appView" || value === "popup";
160
- }
161
- function parseRecord(raw) {
162
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
163
- const value = raw;
164
- if (value.version !== 1) return null;
165
- if (typeof value.targetOrigin !== "string" || normalizeExactOrigin(value.targetOrigin) === null) return null;
166
- if (!isMode(value.mode)) return null;
167
- if (typeof value.authorizationId !== "string" || !value.authorizationId || value.authorizationId.length > 128) return null;
168
- try {
169
- const identity = validateNetworkIdentity(value.networkIdentity);
170
- return {
171
- version: 1,
172
- targetOrigin: value.targetOrigin,
173
- mode: value.mode,
174
- authorizationId: value.authorizationId,
175
- networkIdentity: { ...identity }
176
- };
177
- } catch {
178
- return null;
179
- }
180
- }
181
- function resolveRecoveryStorage(explicit) {
182
- if (explicit) return explicit;
183
- try {
184
- if (typeof sessionStorage === "undefined") return null;
185
- sessionStorage.getItem(RECOVERY_STORAGE_KEY);
186
- return sessionStorage;
187
- } catch {
188
- return null;
189
- }
190
- }
191
- function isRecoveryStorageAvailable(storage) {
192
- return resolveRecoveryStorage(storage) !== null;
193
- }
194
- function readStoredRecord(storage) {
195
- if (!storage) return null;
196
- try {
197
- const raw = storage.getItem(RECOVERY_STORAGE_KEY);
198
- if (!raw) return null;
199
- return parseRecord(JSON.parse(raw));
200
- } catch {
201
- return null;
202
- }
203
- }
204
- function readConnectionRecovery(init) {
205
- const storage = resolveRecoveryStorage(init?.recoveryStorage);
206
- const record = readStoredRecord(storage);
207
- if (!record) return null;
208
- if (init?.targetOrigin !== void 0) {
209
- const expected = normalizeExactOrigin(init.targetOrigin);
210
- if (!expected || record.targetOrigin !== expected) return null;
211
- }
212
- if (init?.mode !== void 0 && record.mode !== init.mode) return null;
213
- return {
214
- version: 1,
215
- targetOrigin: record.targetOrigin,
216
- mode: record.mode,
217
- networkIdentity: { ...record.networkIdentity }
218
- };
219
- }
220
- function loadConnectionRecoveryRecord(init) {
221
- const expectedOrigin = normalizeExactOrigin(init.targetOrigin);
222
- if (!expectedOrigin || !isMode(init.mode)) return null;
223
- const storage = resolveRecoveryStorage(init.recoveryStorage);
224
- const record = readStoredRecord(storage);
225
- if (!record) return null;
226
- if (record.targetOrigin !== expectedOrigin || record.mode !== init.mode) return null;
227
- return record;
228
- }
229
- function saveConnectionRecoveryRecord(storage, record) {
230
- if (!storage) throw new Error("Recovery storage is unavailable");
231
- const parsed = parseRecord(record);
232
- if (!parsed) throw new TypeError("Invalid recovery record");
233
- storage.setItem(RECOVERY_STORAGE_KEY, JSON.stringify(parsed));
234
- }
235
- function clearConnectionRecovery(init) {
236
- const storage = resolveRecoveryStorage(init?.recoveryStorage);
237
- if (!storage) return false;
238
- try {
239
- const current = readStoredRecord(storage);
240
- if (!current) {
241
- try {
242
- storage.removeItem(RECOVERY_STORAGE_KEY);
243
- } catch {
244
- }
245
- return false;
246
- }
247
- if (init?.targetOrigin !== void 0) {
248
- const expected = normalizeExactOrigin(init.targetOrigin);
249
- if (!expected || current.targetOrigin !== expected) return false;
250
- }
251
- if (init?.authorizationId !== void 0 && current.authorizationId !== init.authorizationId) return false;
252
- storage.removeItem(RECOVERY_STORAGE_KEY);
253
- return true;
254
- } catch {
255
- return false;
256
- }
257
- }
258
-
259
146
  // src/client.ts
260
147
  var KeymasterTransportError = class extends Error {
261
148
  constructor(code, message) {
@@ -295,14 +182,6 @@ var KeymasterConnectClient = class {
295
182
  get networkIdentity() {
296
183
  return this.identityValue;
297
184
  }
298
- /** 最近一次持久化失败的原因;成功后清零。登录成功不受写入失败影响。 */
299
- get recoverySaveError() {
300
- return this.recoverySaveErrorValue;
301
- }
302
- /** 刷新恢复存储是否可用;不可用时仍可登录,但刷新后需重新登录。 */
303
- get recoveryStorageAvailable() {
304
- return this.recoveryStorage !== null;
305
- }
306
185
  targetOrigin;
307
186
  mode;
308
187
  environment;
@@ -317,19 +196,8 @@ var KeymasterConnectClient = class {
317
196
  readyTimer = null;
318
197
  closePoller = null;
319
198
  authorizationId = null;
320
- authorizedIdentity = null;
321
- recoveryId = null;
322
- recoveryStorage;
323
- recoverySaveErrorValue = null;
324
- /** 显式恢复期间暂停后台心跳;结束(成功/失败/取消/超时)后恢复。 */
325
- explicitRecoveryActive = false;
326
- /** 内存授权是否已验证:login/launch/恢复成功置 true;仅从存储装载的待验证凭据为 false。 */
327
- authorizationVerified = false;
328
- /** 当前传输窗口是否已可信就绪(收到过匹配来源与窗口的 ready);新开窗口后重置,存在≠就绪。 */
329
- sessionWindowReady = false;
330
- /** 新 popup 首发前等待可信窗口 ready 的一次性继续函数;超时/结束时清空。 */
331
- recoveryReadyContinue = null;
332
- recoveryWaiters = /* @__PURE__ */ new Set();
199
+ /** 等待 ready 与授权响应共用一个建连位置,取消不能影响其他调用。 */
200
+ establishmentActive = false;
333
201
  constructor(options) {
334
202
  if ("networkIdentity" in options) throw new TypeError("networkIdentity option has been removed; read identity from the connection result");
335
203
  this.targetOrigin = normalizeHttpOrigin(options.targetOrigin);
@@ -343,7 +211,6 @@ var KeymasterConnectClient = class {
343
211
  closePollMs: positiveNumber(options.closePollMs ?? DEFAULT_CLOSE_POLL_MS, "closePollMs")
344
212
  };
345
213
  this.environment = options.environment ?? createBrowserEnvironment();
346
- this.recoveryStorage = resolveRecoveryStorage(options.recoveryStorage);
347
214
  }
348
215
  /**
349
216
  * Current browser transport state.
@@ -356,15 +223,9 @@ var KeymasterConnectClient = class {
356
223
  /**
357
224
  * Establishes the browser transport.
358
225
  *
359
- * 只建立传输,不恢复授权:iframe / appView 绑定真实 parent / opener;
360
- * popup 打开完整钱包等待 ready。刷新后的授权恢复请使用 `resume()`,
361
- * 它会先装载本地恢复记录再复用 `continueConnection()`;`connect()` 本身
362
- * 不读取恢复记录、不自动恢复。
363
- *
364
226
  * @group Transport
365
227
  */
366
228
  connect() {
367
- if (this.explicitRecoveryActive) return Promise.reject(new TypeError("Connection recovery is already in progress"));
368
229
  return this.mode === "popup" ? this.connectPopup() : this.connectAppView();
369
230
  }
370
231
  /**
@@ -380,67 +241,82 @@ var KeymasterConnectClient = class {
380
241
  for (const field of ["walletPublicKeyHex", "networkIdentity", "bsvNetwork", "assetId"]) {
381
242
  if (field in params) throw new TypeError(`Removed wallet selector: ${field}`);
382
243
  }
383
- if (method === "connect.resume" && this.authorizationId) {
384
- return this.continueConnection(options);
385
- }
386
- const establishing = ["connect.login", "connect.resume", "connect.launch"].includes(method);
387
- let effectiveParams = params;
388
- if ((method === "connect.login" || method === "connect.launch") && !("publicationProof" in params)) {
389
- effectiveParams = withOwnPublicationProof(params);
390
- }
391
- if (!establishing && this.stateValue === "paused") throw new KeymasterTransportError("wallet_paused", "Wallet connection is paused; old business requests are never replayed");
392
- if (establishing && this.pending.size) throw new TypeError("Cannot establish a connection while requests are pending");
393
- if (establishing && this.explicitRecoveryActive) throw new TypeError("Connection recovery is already in progress");
394
- if (!establishing && !this.bindingId) throw new KeymasterProtocolError("invalid_request", "Login, resume or launch before making business requests");
395
- if ([...this.pending.values()].some((request) => ["connect.login", "connect.resume", "connect.launch"].includes(request.method))) throw new TypeError("Connection establishment is already pending");
396
- await this.connect();
397
- if (establishing && this.pending.size) throw new TypeError("Cannot establish a connection while requests are pending");
398
- if ([...this.pending.values()].some((request) => ["connect.login", "connect.resume", "connect.launch"].includes(request.method))) throw new TypeError("Connection establishment is already pending");
399
- if (establishing && this.explicitRecoveryActive) throw new TypeError("Connection recovery is already in progress");
400
- if (options.signal?.aborted) throw abortReason(options.signal);
401
- const target = this.sessionWindow;
402
- if (!target || isWindowClosed(target)) {
403
- throw new KeymasterTransportError("wallet_closed", "Keymaster parent wallet is closed");
404
- }
405
- const requestId = options.requestId ?? this.environment.randomUUID();
406
- if (!requestId || this.pending.has(requestId)) {
407
- throw new TypeError("requestId must be non-empty and unique among pending requests");
408
- }
409
- const timeoutMs = positiveNumber(options.timeoutMs ?? this.options.requestTimeoutMs, "timeoutMs");
410
- return new Promise((resolve, reject) => {
411
- const timer = this.environment.setTimeout(() => {
412
- this.postCancel(requestId);
413
- this.deletePending(requestId);
414
- reject(new KeymasterTransportError("request_timeout", `Keymaster request timed out: ${method}`));
415
- }, timeoutMs);
416
- const abortListener = options.signal ? () => {
417
- this.postCancel(requestId);
418
- this.deletePending(requestId);
419
- reject(abortReason(options.signal));
420
- } : void 0;
421
- if (abortListener) options.signal.addEventListener("abort", abortListener, { once: true });
422
- this.pending.set(requestId, {
423
- method,
424
- resolve: (value) => resolve(value),
425
- reject,
426
- timer,
427
- signal: options.signal,
428
- abortListener
429
- });
430
- try {
431
- target.postMessage({
432
- v: PROTOCOL_VERSION,
433
- type: "request",
434
- ...!establishing ? { bindingId: this.bindingId } : {},
435
- id: requestId,
436
- method,
437
- params: effectiveParams
438
- }, this.targetOrigin);
439
- } catch (cause) {
440
- this.deletePending(requestId);
441
- reject(new KeymasterTransportError("send_failed", errorMessage(cause, "Unable to send Keymaster request")));
244
+ const establishing = ["connect.login", "connect.launch"].includes(method);
245
+ if (this.establishmentActive) throw new TypeError("Connection establishment is already pending");
246
+ if (establishing) this.establishmentActive = true;
247
+ try {
248
+ let effectiveParams = params;
249
+ if ((method === "connect.login" || method === "connect.launch") && !("publicationProof" in params)) {
250
+ effectiveParams = withOwnPublicationProof(params);
442
251
  }
443
- });
252
+ if (establishing && this.pending.size) throw new TypeError("Cannot establish a connection while requests are pending");
253
+ if (!establishing && !this.bindingId) throw new KeymasterProtocolError("invalid_request", "Login or launch before making business requests");
254
+ if ([...this.pending.values()].some((request) => ["connect.login", "connect.launch"].includes(request.method))) throw new TypeError("Connection establishment is already pending");
255
+ if (establishing) {
256
+ const abortOpening = () => this.disconnect(abortReason(options.signal));
257
+ options.signal?.addEventListener("abort", abortOpening, { once: true });
258
+ try {
259
+ await this.connect();
260
+ } finally {
261
+ options.signal?.removeEventListener("abort", abortOpening);
262
+ }
263
+ }
264
+ if (establishing && this.pending.size) throw new TypeError("Cannot establish a connection while requests are pending");
265
+ if ([...this.pending.values()].some((request) => ["connect.login", "connect.launch"].includes(request.method))) throw new TypeError("Connection establishment is already pending");
266
+ if (options.signal?.aborted) throw abortReason(options.signal);
267
+ const target = this.sessionWindow;
268
+ if (!target || isWindowClosed(target) || !establishing && this.stateValue !== "connected") {
269
+ const error = new KeymasterTransportError("wallet_closed", "Wallet connection is unavailable; login again");
270
+ this.disconnect(error);
271
+ throw error;
272
+ }
273
+ const requestId = options.requestId ?? this.environment.randomUUID();
274
+ if (!requestId || this.pending.has(requestId)) {
275
+ throw new TypeError("requestId must be non-empty and unique among pending requests");
276
+ }
277
+ const timeoutMs = positiveNumber(options.timeoutMs ?? this.options.requestTimeoutMs, "timeoutMs");
278
+ return await new Promise((resolve, reject) => {
279
+ const timer = this.environment.setTimeout(() => {
280
+ this.postCancel(requestId);
281
+ this.deletePending(requestId);
282
+ const error = new KeymasterTransportError("request_timeout", `Keymaster request timed out: ${method}`);
283
+ if (establishing) this.disconnect(error);
284
+ reject(error);
285
+ }, timeoutMs);
286
+ const abortListener = options.signal ? () => {
287
+ this.postCancel(requestId);
288
+ this.deletePending(requestId);
289
+ if (establishing) this.disconnect(abortReason(options.signal));
290
+ reject(abortReason(options.signal));
291
+ } : void 0;
292
+ if (abortListener) options.signal.addEventListener("abort", abortListener, { once: true });
293
+ this.pending.set(requestId, {
294
+ method,
295
+ resolve: (value) => resolve(value),
296
+ reject,
297
+ timer,
298
+ signal: options.signal,
299
+ abortListener
300
+ });
301
+ try {
302
+ target.postMessage({
303
+ v: PROTOCOL_VERSION,
304
+ type: "request",
305
+ ...!establishing ? { bindingId: this.bindingId } : {},
306
+ id: requestId,
307
+ method,
308
+ params: effectiveParams
309
+ }, this.targetOrigin);
310
+ } catch (cause) {
311
+ this.deletePending(requestId);
312
+ const error = new KeymasterTransportError("send_failed", errorMessage(cause, "Unable to send Keymaster request"));
313
+ this.disconnect(error);
314
+ reject(error);
315
+ }
316
+ });
317
+ } finally {
318
+ if (establishing) this.establishmentActive = false;
319
+ }
444
320
  }
445
321
  /**
446
322
  * Calls `connect.login` to create a persistent Connect session.
@@ -450,37 +326,6 @@ var KeymasterConnectClient = class {
450
326
  login(params, options) {
451
327
  return this.request("connect.login", withOwnPublicationProof(params), options);
452
328
  }
453
- /**
454
- * Calls `connect.resume` to restore the unlock runtime for a persistent
455
- * session.
456
- *
457
- * 刷新恢复时只把保存的凭据和预期身份载入待恢复上下文,不直接置为已登录;
458
- * 钱包验证成功、结果身份一致并取得新 binding 后才开放业务调用。
459
- * 无可用凭据时直接拒绝并提示重新登录,不回退到无凭据的重建默认授权。
460
- *
461
- *
462
- * @group Connect
463
- */
464
- resume(params = {}, options) {
465
- if (options?.signal?.aborted) return Promise.reject(abortReason(options.signal));
466
- if (this.explicitRecoveryActive) return Promise.reject(new TypeError("Connection recovery is already in progress"));
467
- if (this.authorizationId && this.authorizationVerified) {
468
- return this.request("connect.resume", params, options);
469
- }
470
- const stored = loadConnectionRecoveryRecord({
471
- recoveryStorage: this.recoveryStorage ?? void 0,
472
- targetOrigin: this.targetOrigin,
473
- mode: this.mode
474
- });
475
- if (stored) {
476
- this.authorizationId = stored.authorizationId;
477
- this.authorizedIdentity = Object.freeze({ ...stored.networkIdentity });
478
- this.authorizationVerified = false;
479
- } else if (!this.authorizationId) {
480
- return Promise.reject(new KeymasterTransportError("client_closed", "No saved Keymaster recovery record for this origin and mode; login again"));
481
- }
482
- return this.continueConnection(options ?? {});
483
- }
484
329
  /**
485
330
  * Calls `connect.logout` to revoke a persistent Connect session.
486
331
  *
@@ -563,70 +408,6 @@ var KeymasterConnectClient = class {
563
408
  channelSubscriptionSet(params, options) {
564
409
  return this.request("channel.subscription_set", params, options);
565
410
  }
566
- /**
567
- * Calls `storage.list` to list paths in the verified application's namespace.
568
- *
569
- * @group Storage
570
- */
571
- storageList(params, options) {
572
- return this.request("storage.list", params, options);
573
- }
574
- /**
575
- * Calls `storage.directory.create` to create an app-scoped directory.
576
- *
577
- * @group Storage
578
- */
579
- storageDirectoryCreate(params, options) {
580
- return this.request("storage.directory.create", params, options);
581
- }
582
- /**
583
- * Calls `storage.directory.delete` to delete an app-scoped directory.
584
- *
585
- * @group Storage
586
- */
587
- storageDirectoryDelete(params, options) {
588
- return this.request("storage.directory.delete", params, options);
589
- }
590
- /**
591
- * Calls `storage.put` to write an app-scoped object.
592
- *
593
- * @group Storage
594
- */
595
- storagePut(params, options) {
596
- return this.request("storage.put", params, options);
597
- }
598
- /**
599
- * Calls `storage.get` to read an app-scoped object.
600
- *
601
- * @group Storage
602
- */
603
- storageGet(params, options) {
604
- return this.request("storage.get", params, options);
605
- }
606
- /**
607
- * 可选加密写入:向钱包提交明文,钱包以当前钱包密钥和 App 公钥隔离后加密保存。
608
- * 路径、条件创建语义与 storagePut 相同,size 返回明文字节数;不会返回加密密钥。
609
- * @group Storage
610
- */
611
- storagePutEncrypted(params, options) {
612
- return this.request("storage.encrypted.put", params, options);
613
- }
614
- /**
615
- * 可选加密读取:仅同一钱包能解密;offset/length 作用于明文,ifMatch 仍比较远端版本。
616
- * 明文对象、错误格式、篡改或密钥不匹配均失败,不自动回退为普通读取。
617
- * @group Storage
618
- */
619
- storageGetEncrypted(params, options) {
620
- return this.request("storage.encrypted.get", params, options);
621
- }
622
- /**
623
- * Calls `storage.delete` to delete an app-scoped object.
624
- *
625
- * @group Storage
626
- */
627
- storageDelete(params, options) {
628
- return this.request("storage.delete", params, options);
629
- }
630
411
  /**
631
412
  * Calls `msfile.stat` to query every enabled MSFile supplier for a seed
632
413
  * hash. The caller selects supplier/hash only; price policy stays inside
@@ -667,121 +448,37 @@ var KeymasterConnectClient = class {
667
448
  if (!pending) return false;
668
449
  this.postCancel(requestId);
669
450
  this.deletePending(requestId);
451
+ if (pending.method === "connect.login" || pending.method === "connect.launch") this.disconnect(reason);
670
452
  pending.reject(reason);
671
453
  return true;
672
454
  }
673
- /**
674
- * Tears down the local transport. This does not revoke persistent Connect
675
- * sessions; call {@link logout} before closing when revocation is required.
676
- *
677
- * 只结束运行连接,保留刷新恢复材料:`close()`、页面卸载和运行失效都不删除
678
- * 本地恢复记录;`logout` 成功、明确授权失效或用户主动清除才删除。
679
- *
680
- * @group Transport
681
- */
682
- close() {
683
- if (this.bindingId) {
684
- try {
685
- this.sessionWindow?.postMessage({ v: PROTOCOL_VERSION, type: "tools.register", bindingId: this.bindingId, id: this.environment.randomUUID(), tools: [] }, this.targetOrigin);
686
- } catch {
687
- }
688
- }
689
- this.aiTools.clear(new Error("Connect client closed"));
690
- for (const id of this.pending.keys()) this.postCancel(id);
691
- this.identityValue = null;
692
- this.bindingId = null;
693
- const error = new KeymasterTransportError("client_closed", "Keymaster client was closed");
694
- this.rejectAll(error);
695
- this.failReady(error);
696
- this.stopClosePolling();
697
- if (this.listenerInstalled) {
698
- this.environment.removeMessageListener(this.handleMessage);
699
- this.listenerInstalled = false;
700
- }
701
- if (!this.authorizationId) this.sessionWindow = null;
702
- this.recoveryId = null;
703
- this.explicitRecoveryActive = false;
704
- this.recoveryReadyContinue = null;
705
- this.finishRecovery(void 0, error);
706
- this.setState(this.authorizationId ? "paused" : "disconnected");
707
- }
708
- /** 主动恢复可由 popup 重新打开钱包;后台恢复从不打开窗口或重放业务。 */
709
- continueConnection(options) {
710
- if (options.signal?.aborted) return Promise.reject(abortReason(options.signal));
711
- if (this.explicitRecoveryActive) return Promise.reject(new TypeError("Connection recovery is already in progress"));
712
- if (this.pending.size) return Promise.reject(new TypeError("Cannot resume while business requests are pending"));
713
- this.installListener();
714
- let awaitReady = false;
715
- if (this.mode === "popup") {
716
- if (!this.sessionWindow || isWindowClosed(this.sessionWindow)) {
717
- const url = new URL(this.options.popupPath, `${this.targetOrigin}/`);
718
- if (url.origin !== this.targetOrigin) return Promise.reject(new TypeError("popupPath must resolve inside targetOrigin"));
719
- this.sessionWindow = this.environment.open(url.href, "_blank", "");
720
- if (!this.sessionWindow) return Promise.reject(new KeymasterTransportError("popup_blocked", "Keymaster wallet window was blocked"));
721
- this.sessionWindowReady = false;
722
- awaitReady = true;
723
- } else if (!this.sessionWindowReady) {
724
- awaitReady = true;
725
- }
726
- } else {
727
- const launcher = this.mode === "iframe" ? this.environment.parent() : this.environment.opener();
728
- if (!launcher || isWindowClosed(launcher)) return Promise.reject(new KeymasterTransportError("appview_session_lost", "Wallet launcher unavailable; relaunch from the wallet"));
729
- this.sessionWindow = launcher;
730
- }
731
- const wasVerified = this.authorizationVerified;
732
- this.explicitRecoveryActive = true;
733
- const endExplicitAttempt = (failed) => {
734
- this.explicitRecoveryActive = false;
735
- this.recoveryReadyContinue = null;
736
- if (failed && !wasVerified && this.authorizationId) {
737
- this.authorizationId = null;
738
- this.authorizedIdentity = null;
739
- this.recoveryId = null;
740
- }
741
- };
742
- this.pause(new KeymasterTransportError("wallet_paused", "Re-establishing the original wallet connection"));
743
- this.startClosePolling();
744
- return new Promise((resolve, reject) => {
745
- const finish = (error, result) => {
746
- this.environment.clearTimeout(timer);
747
- options.signal?.removeEventListener("abort", aborted);
748
- this.recoveryWaiters.delete(waiter);
749
- endExplicitAttempt(!!error);
750
- if (error) reject(error);
751
- else resolve(result);
752
- };
753
- const waiter = { resolve: (result) => finish(void 0, result), reject: (error) => finish(error) };
754
- const aborted = () => finish(abortReason(options.signal));
755
- const timer = this.environment.setTimeout(() => finish(new KeymasterTransportError("request_timeout", "Timed out restoring wallet connection")), positiveNumber(options.timeoutMs ?? this.options.readyTimeoutMs, "timeoutMs"));
756
- this.recoveryWaiters.add(waiter);
757
- options.signal?.addEventListener("abort", aborted, { once: true });
758
- if (awaitReady) {
759
- this.recoveryReadyContinue = () => this.sendRecovery();
760
- } else {
761
- this.sendRecovery();
762
- }
763
- });
764
- }
765
455
  connectPopup() {
766
456
  if (this.isConnected()) return Promise.resolve();
767
457
  if (this.readyPromise) return this.readyPromise;
768
458
  const url = new URL(this.options.popupPath, `${this.targetOrigin}/`);
769
459
  if (url.origin !== this.targetOrigin) return Promise.reject(new TypeError("popupPath must resolve inside targetOrigin"));
770
460
  this.installListener();
771
- this.setState("opening");
772
- this.sessionWindow = this.environment.open(url.href, "_blank", "");
773
- if (!this.sessionWindow) {
774
- this.setState("disconnected");
775
- return Promise.reject(new KeymasterTransportError("popup_blocked", "Keymaster wallet window was blocked"));
776
- }
777
- this.sessionWindowReady = false;
778
- this.startClosePolling();
779
- this.readyPromise = new Promise((resolve, reject) => {
461
+ const ready = new Promise((resolve, reject) => {
780
462
  this.readyResolve = resolve;
781
463
  this.readyReject = reject;
782
464
  this.readyTimer = this.environment.setTimeout(() => this.disconnect(new KeymasterTransportError("ready_timeout", "Timed out waiting for the wallet to initialize or unlock")), this.options.readyTimeoutMs);
783
465
  });
784
- return this.readyPromise;
466
+ this.readyPromise = ready;
467
+ this.setState("opening");
468
+ if (this.readyPromise !== ready) return ready;
469
+ try {
470
+ const target = this.environment.open(url.href, "_blank", "");
471
+ if (this.readyPromise !== ready) return ready;
472
+ if (!target) {
473
+ this.disconnect(new KeymasterTransportError("popup_blocked", "Keymaster wallet window was blocked"));
474
+ } else {
475
+ this.sessionWindow = target;
476
+ this.startClosePolling();
477
+ }
478
+ } catch (cause) {
479
+ this.disconnect(new KeymasterTransportError("send_failed", errorMessage(cause, "Unable to open Keymaster wallet")));
480
+ }
481
+ return ready;
785
482
  }
786
483
  connectAppView() {
787
484
  if (this.isConnected()) return Promise.resolve();
@@ -817,29 +514,16 @@ var KeymasterConnectClient = class {
817
514
  }
818
515
  if (this.aiTools.handle(value)) return;
819
516
  if (value.type === "ready") {
820
- this.sessionWindowReady = true;
821
517
  if (this.mode === "popup" && this.readyPromise) this.finishReady();
822
- if (this.explicitRecoveryActive && this.recoveryReadyContinue) {
823
- const send = this.recoveryReadyContinue;
824
- this.recoveryReadyContinue = null;
825
- send();
826
- }
518
+ else if (this.bindingId) this.disconnect(new KeymasterTransportError("wallet_closed", "Wallet runtime changed; login again"));
827
519
  return;
828
520
  }
829
521
  if (value.type === "closing") {
830
- if (this.authorizationId) this.pause(new KeymasterTransportError("wallet_paused", "Wallet runtime is unavailable"));
831
- else this.disconnect(new KeymasterTransportError("wallet_closed", "Keymaster wallet connection is closing"));
522
+ this.disconnect(new KeymasterTransportError("wallet_closed", "Keymaster wallet connection is closing"));
832
523
  return;
833
524
  }
834
525
  if (value.type === "revoked" && value.authorizationId === this.authorizationId) {
835
- const revokedId = this.authorizationId;
836
- this.authorizationId = null;
837
- this.authorizedIdentity = null;
838
- this.authorizationVerified = false;
839
- this.recoveryId = null;
840
- this.dropRecoveryRecord(revokedId);
841
526
  const revokedError = new KeymasterProtocolError("authorization_expired", "Application connection authorization was revoked");
842
- this.finishRecovery(void 0, revokedError);
843
527
  this.disconnect(revokedError);
844
528
  return;
845
529
  }
@@ -858,47 +542,6 @@ var KeymasterConnectClient = class {
858
542
  }
859
543
  if (value.type !== "result" || typeof value.id !== "string" || typeof value.ok !== "boolean") return;
860
544
  const result = event.data;
861
- if (this.authorizationId && result.id === this.recoveryId) {
862
- if (!result.ok) {
863
- const code = result.error?.code;
864
- const message = result.error?.message ?? "Failed to restore wallet connection";
865
- if (code === "authorization_expired") {
866
- const expiredId = this.authorizationId;
867
- this.authorizationId = null;
868
- this.authorizedIdentity = null;
869
- this.authorizationVerified = false;
870
- this.recoveryId = null;
871
- this.dropRecoveryRecord(expiredId);
872
- const expired = new KeymasterProtocolError(code, message);
873
- this.finishRecovery(void 0, expired);
874
- this.disconnect(expired);
875
- return;
876
- }
877
- const failure = new KeymasterProtocolError(code || "connection_expired", message);
878
- this.pause(failure);
879
- this.recoveryId = null;
880
- this.finishRecovery(void 0, failure);
881
- return;
882
- }
883
- try {
884
- const identity = validateNetworkIdentity(value.networkIdentity);
885
- const restored = result.result;
886
- 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");
887
- if (this.bindingId !== value.bindingId) this.pause(new KeymasterTransportError("wallet_paused", "Wallet runtime was replaced"));
888
- this.identityValue = Object.freeze({ ...identity });
889
- this.bindingId = value.bindingId;
890
- this.recoveryId = null;
891
- this.authorizationVerified = true;
892
- this.setState("connected");
893
- this.persistRecoveryRecord(restored.authorizationId, identity);
894
- this.finishRecovery(restored);
895
- } catch (error) {
896
- this.pause(error);
897
- this.recoveryId = null;
898
- this.finishRecovery(void 0, error);
899
- }
900
- return;
901
- }
902
545
  const pending = this.pending.get(result.id);
903
546
  if (!pending) return;
904
547
  this.deletePending(result.id);
@@ -907,42 +550,26 @@ var KeymasterConnectClient = class {
907
550
  pending.reject(new KeymasterProtocolError("invalid_request", "Malformed Keymaster error result"));
908
551
  return;
909
552
  }
910
- if (result.error.code === "connection_expired" || result.error.code === "authorization_expired") {
911
- if (this.authorizationId) this.pause(new KeymasterProtocolError(result.error.code, result.error.message));
912
- else {
913
- this.identityValue = null;
914
- this.bindingId = null;
915
- }
916
- }
553
+ if (result.error.code === "connection_expired" || result.error.code === "authorization_expired") this.disconnect(new KeymasterProtocolError(result.error.code, result.error.message));
554
+ if (pending.method === "connect.login" || pending.method === "connect.launch") this.disconnect(new KeymasterProtocolError(result.error.code, result.error.message));
917
555
  pending.reject(new KeymasterProtocolError(result.error.code, result.error.message));
918
556
  return;
919
557
  }
920
558
  try {
921
559
  const identity = validateNetworkIdentity(value.networkIdentity);
922
- if (["connect.login", "connect.resume", "connect.launch"].includes(pending.method)) {
560
+ if (["connect.login", "connect.launch"].includes(pending.method)) {
923
561
  const connected = result.result;
924
562
  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");
925
563
  this.aiTools.clear(new Error("Connection binding replaced; register tools again"));
926
564
  this.identityValue = Object.freeze({ ...identity });
927
- this.authorizedIdentity = this.identityValue;
928
565
  this.authorizationId = connected.authorizationId;
929
- this.authorizationVerified = true;
930
- this.recoveryId = null;
931
566
  this.bindingId = value.bindingId;
932
- this.persistRecoveryRecord(connected.authorizationId, identity);
567
+ this.setState("connected");
933
568
  } else if (!this.identityValue || value.bindingId !== this.bindingId || !sameNetworkIdentity(this.identityValue, identity)) {
934
569
  throw new Error("Keymaster connection identity mismatch");
935
570
  }
936
571
  if (pending.method === "connect.logout") {
937
- const logoutId = this.authorizationId;
938
- this.aiTools.clear(new Error("Logged out"));
939
- this.identityValue = null;
940
- this.bindingId = null;
941
- this.authorizationId = null;
942
- this.authorizedIdentity = null;
943
- this.authorizationVerified = false;
944
- this.recoveryId = null;
945
- this.dropRecoveryRecord(logoutId);
572
+ this.disconnect(new KeymasterTransportError("client_closed", "Logged out"));
946
573
  }
947
574
  pending.resolve(result.result);
948
575
  } catch (error) {
@@ -955,6 +582,7 @@ var KeymasterConnectClient = class {
955
582
  installListener() {
956
583
  if (this.listenerInstalled) return;
957
584
  this.environment.addMessageListener(this.handleMessage);
585
+ this.environment.addPageHideListener?.(this.handlePageHide);
958
586
  this.listenerInstalled = true;
959
587
  }
960
588
  finishReady() {
@@ -975,84 +603,38 @@ var KeymasterConnectClient = class {
975
603
  this.readyResolve = null;
976
604
  this.readyReject = null;
977
605
  }
606
+ /** 仅清理本地运行态,页签关闭不发送握手或等待回复。 */
607
+ handlePageHide = () => {
608
+ if (this.sessionWindow && this.bindingId) {
609
+ try {
610
+ this.sessionWindow.postMessage({ v: PROTOCOL_VERSION, type: "client_unloaded", bindingId: this.bindingId }, this.targetOrigin);
611
+ } catch {
612
+ }
613
+ }
614
+ this.disconnect(new KeymasterTransportError("client_closed", "Application page unloaded"));
615
+ };
978
616
  disconnect(reason) {
979
617
  this.aiTools.clear(reason);
980
- for (const id of this.pending.keys()) this.postCancel(id);
981
618
  this.identityValue = null;
982
619
  this.bindingId = null;
983
620
  this.rejectAll(reason);
984
621
  this.failReady(reason);
985
622
  this.stopClosePolling();
986
623
  this.sessionWindow = null;
987
- this.sessionWindowReady = false;
988
- this.explicitRecoveryActive = false;
989
- this.recoveryReadyContinue = null;
990
- this.setState("disconnected");
991
- }
992
- /** 暂停仅撤销瞬时绑定和旧请求,持久授权引用及原身份留作恢复校验。 */
993
- pause(reason) {
994
- this.aiTools.clear(reason);
995
- this.identityValue = null;
996
- this.bindingId = null;
997
- this.rejectAll(reason);
998
- this.failReady(reason);
999
- this.setState("paused");
1000
- }
1001
- /** 保存最近成功连接的恢复记录;写入失败只记录原因,不影响已成功的登录。 */
1002
- persistRecoveryRecord(authorizationId, identity) {
1003
- if (!this.recoveryStorage) {
1004
- this.recoverySaveErrorValue = "Recovery storage is unavailable; refresh will require re-login";
1005
- return;
1006
- }
1007
- try {
1008
- saveConnectionRecoveryRecord(this.recoveryStorage, {
1009
- version: 1,
1010
- targetOrigin: this.targetOrigin,
1011
- mode: this.mode,
1012
- authorizationId,
1013
- networkIdentity: { ...identity }
1014
- });
1015
- this.recoverySaveErrorValue = null;
1016
- } catch (error) {
1017
- this.recoverySaveErrorValue = errorMessage(error, "Failed to persist recovery record; refresh will require re-login");
1018
- }
1019
- }
1020
- /** 按目标与授权核对后清除本地恢复记录;旧实例迟到结果不得删除新记录。 */
1021
- dropRecoveryRecord(authorizationId) {
1022
- try {
1023
- clearConnectionRecovery({
1024
- recoveryStorage: this.recoveryStorage ?? void 0,
1025
- targetOrigin: this.targetOrigin,
1026
- ...authorizationId ? { authorizationId } : {}
1027
- });
1028
- } catch {
1029
- }
1030
- }
1031
- sendRecovery() {
1032
- if (!this.authorizationId || !this.sessionWindow || isWindowClosed(this.sessionWindow)) return;
1033
- if (this.stateValue === "opening") return;
1034
- if ([...this.pending.values()].some((request) => ["connect.login", "connect.resume", "connect.launch"].includes(request.method))) return;
1035
- this.recoveryId ??= this.environment.randomUUID();
1036
- try {
1037
- this.sessionWindow.postMessage({ v: PROTOCOL_VERSION, type: "reconnect", id: this.recoveryId, authorizationId: this.authorizationId, ...this.bindingId ? { bindingId: this.bindingId } : {} }, this.targetOrigin);
1038
- } catch (error) {
1039
- this.pause(error);
1040
- }
1041
- }
1042
- finishRecovery(result, error) {
1043
- for (const waiter of [...this.recoveryWaiters]) {
1044
- if (error) waiter.reject(error);
1045
- else if (result) waiter.resolve(result);
624
+ this.authorizationId = null;
625
+ if (this.listenerInstalled) {
626
+ this.environment.removeMessageListener(this.handleMessage);
627
+ this.environment.removePageHideListener?.(this.handlePageHide);
628
+ this.listenerInstalled = false;
1046
629
  }
630
+ this.setState("disconnected");
1047
631
  }
1048
632
  startClosePolling() {
1049
633
  this.stopClosePolling();
1050
634
  this.closePoller = this.environment.setInterval(() => {
1051
635
  if (this.sessionWindow && isWindowClosed(this.sessionWindow)) {
1052
- if (this.authorizationId) {
1053
- if (this.stateValue !== "paused") this.pause(new KeymasterTransportError("wallet_paused", "Wallet window is closed"));
1054
- } else this.disconnect(new KeymasterTransportError("wallet_closed", "Keymaster parent wallet was closed"));
1055
- } else if (!this.explicitRecoveryActive) this.sendRecovery();
636
+ this.disconnect(new KeymasterTransportError("wallet_closed", "Wallet window is closed"));
637
+ }
1056
638
  }, this.options.closePollMs);
1057
639
  }
1058
640
  stopClosePolling() {
@@ -1106,6 +688,8 @@ function createBrowserEnvironment() {
1106
688
  clearTimeout: (timer) => window.clearTimeout(timer),
1107
689
  setInterval: (handler, intervalMs) => window.setInterval(handler, intervalMs),
1108
690
  clearInterval: (timer) => window.clearInterval(timer),
691
+ addPageHideListener: (listener) => window.addEventListener("pagehide", listener),
692
+ removePageHideListener: (listener) => window.removeEventListener("pagehide", listener),
1109
693
  randomUUID: () => window.crypto.randomUUID()
1110
694
  };
1111
695
  }
@@ -1139,6 +723,6 @@ function withOwnPublicationProof(params) {
1139
723
  return proof ? { ...params, publicationProof: proof } : params;
1140
724
  }
1141
725
 
1142
- export { KeymasterConnectClient, KeymasterProtocolError, KeymasterTransportError, RECOVERY_STORAGE_KEY, binary, binaryBytes, binaryText, binaryToText, clearConnectionRecovery, createBrowserEnvironment, createKeymasterConnect, isRecoveryStorageAvailable, loadConnectionRecoveryRecord, readConnectionRecovery, resolveRecoveryStorage, saveConnectionRecoveryRecord };
726
+ export { KeymasterConnectClient, KeymasterProtocolError, KeymasterTransportError, binary, binaryBytes, binaryText, binaryToText, createBrowserEnvironment, createKeymasterConnect };
1143
727
  //# sourceMappingURL=index.js.map
1144
728
  //# sourceMappingURL=index.js.map