keymaster-connect 0.1.3 → 0.1.5

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,7 @@
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';
1
+ import { parseToolDefinitions, assertToolPayload, isAiToolMessage, validateToolArguments } from './chunk-VVOTW5ZT.js';
2
+ export { AI_TOOLS_MAX_JSON_CHARS, assertToolJson, assertToolPayload, isAiToolMessage, parseToolDefinitions, validateToolArguments } from './chunk-VVOTW5ZT.js';
3
+ import { PROTOCOL_METHODS, PROTOCOL_VERSION, sameNetworkIdentity, validateNetworkIdentity } from './chunk-ZDIFZJYD.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-ZDIFZJYD.js';
3
5
 
4
6
  // src/binary.ts
5
7
  function binary(bytes, mime) {
@@ -25,6 +27,235 @@ function binaryToText(field) {
25
27
  return new TextDecoder().decode(binaryBytes(field));
26
28
  }
27
29
 
30
+ // src/toolClient.ts
31
+ var AiToolClient = class {
32
+ constructor(current, send, uuid) {
33
+ this.current = current;
34
+ this.send = send;
35
+ this.uuid = uuid;
36
+ }
37
+ current;
38
+ send;
39
+ uuid;
40
+ callbacks = /* @__PURE__ */ new Map();
41
+ pending;
42
+ running = /* @__PURE__ */ new Map();
43
+ seen = /* @__PURE__ */ new Set();
44
+ register(tools, options = {}) {
45
+ const bindingId = this.current();
46
+ if (!bindingId) return Promise.reject(new Error("Connect before registering AI tools"));
47
+ if (this.pending) return Promise.reject(new Error("Tool registration is already pending"));
48
+ if (tools.length && this.running.size) return Promise.reject(new Error("Cannot replace tools while callbacks are running"));
49
+ const definitions = parseToolDefinitions(tools.map(({ name, description, parameters }) => ({ name, description, parameters })));
50
+ if (tools.some((tool) => typeof tool.execute !== "function")) throw new TypeError("Tool execute must be a function");
51
+ if (options.signal?.aborted) return Promise.reject(options.signal.reason ?? new Error("Registration aborted"));
52
+ const timeout = options.timeoutMs ?? 3e4;
53
+ if (!Number.isFinite(timeout) || timeout <= 0) throw new TypeError("Invalid registration timeout");
54
+ const id = this.uuid();
55
+ const callbacks = new Map(definitions.map((definition, index) => [definition.name, { ...definition, execute: tools[index].execute }]));
56
+ return new Promise((resolve, reject) => {
57
+ const fail = (reason) => {
58
+ if (this.pending?.id !== id) return;
59
+ clearTimeout(this.pending.timer);
60
+ this.pending.off();
61
+ this.pending = void 0;
62
+ this.callbacks.clear();
63
+ reject(reason);
64
+ };
65
+ const abort = () => fail(options.signal?.reason ?? new Error("Registration aborted; registration outcome is unknown"));
66
+ options.signal?.addEventListener("abort", abort, { once: true });
67
+ this.pending = { id, tools: callbacks, resolve, reject, timer: setTimeout(() => fail(new Error("AI tool registration timed out; outcome is unknown")), timeout), off: () => options.signal?.removeEventListener("abort", abort) };
68
+ try {
69
+ const message = { v: 1, type: "tools.register", id, bindingId, tools: definitions };
70
+ assertToolPayload(message);
71
+ this.send(message);
72
+ } catch (error) {
73
+ fail(error);
74
+ }
75
+ });
76
+ }
77
+ handle(value) {
78
+ if (!isAiToolMessage(value)) return false;
79
+ if (value.bindingId !== this.current()) return true;
80
+ if (value.type === "tools.registered") {
81
+ const pending = this.pending;
82
+ if (!pending || pending.id !== value.id) return true;
83
+ clearTimeout(pending.timer);
84
+ pending.off();
85
+ this.pending = void 0;
86
+ if (value.ok) {
87
+ if (!pending.tools.size) {
88
+ for (const controller of this.running.values()) controller.abort(new Error("Tools unregistered"));
89
+ }
90
+ this.callbacks = pending.tools;
91
+ pending.resolve({ names: value.names });
92
+ } else pending.reject(new Error(value.error));
93
+ } else if (value.type === "tools.cancel") {
94
+ this.running.get(value.id)?.abort(new Error("Wallet cancelled tool invocation"));
95
+ } else if (value.type === "tools.invoke") {
96
+ if (this.seen.has(value.id)) return true;
97
+ if (this.seen.size >= 1e4 || this.running.size >= 16) {
98
+ this.reply(value.bindingId, value.id, { ok: false, error: "Too many tool invocations; reconnect explicitly" });
99
+ return true;
100
+ }
101
+ this.seen.add(value.id);
102
+ const tool = this.callbacks.get(value.name);
103
+ if (!tool) {
104
+ this.reply(value.bindingId, value.id, { ok: false, error: "Tool is not registered on this connection" });
105
+ return true;
106
+ }
107
+ const controller = new AbortController();
108
+ this.running.set(value.id, controller);
109
+ void (async () => {
110
+ try {
111
+ validateToolArguments(value.arguments, tool.parameters);
112
+ const result = await tool.execute(structuredClone(value.arguments), { signal: controller.signal });
113
+ controller.signal.throwIfAborted();
114
+ assertToolPayload({ v: 1, type: "tools.result", bindingId: value.bindingId, id: value.id, ok: true, result });
115
+ this.reply(value.bindingId, value.id, { ok: true, result });
116
+ } catch {
117
+ this.reply(value.bindingId, value.id, { ok: false, error: controller.signal.aborted ? "Tool invocation cancelled; side effects may already have occurred" : "App tool execution failed" });
118
+ } finally {
119
+ this.running.delete(value.id);
120
+ }
121
+ })();
122
+ }
123
+ return true;
124
+ }
125
+ reply(bindingId, id, payload) {
126
+ if (this.current() !== bindingId) return;
127
+ try {
128
+ this.send({ v: 1, type: "tools.result", bindingId, id, ...payload });
129
+ } catch {
130
+ }
131
+ }
132
+ clear(reason) {
133
+ if (this.pending) {
134
+ clearTimeout(this.pending.timer);
135
+ this.pending.off();
136
+ this.pending.reject(reason);
137
+ this.pending = void 0;
138
+ }
139
+ for (const controller of this.running.values()) controller.abort(reason);
140
+ this.running.clear();
141
+ this.callbacks.clear();
142
+ this.seen.clear();
143
+ }
144
+ };
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
+
28
259
  // src/client.ts
29
260
  var KeymasterTransportError = class extends Error {
30
261
  constructor(code, message) {
@@ -48,10 +279,30 @@ var DEFAULT_CLOSE_POLL_MS = 500;
48
279
  var KeymasterConnectClient = class {
49
280
  identityValue = null;
50
281
  bindingId = null;
282
+ aiTools = new AiToolClient(
283
+ () => this.stateValue === "connected" ? this.bindingId : null,
284
+ (message) => {
285
+ if (!this.sessionWindow || isWindowClosed(this.sessionWindow)) throw new Error("Wallet unavailable");
286
+ this.sessionWindow.postMessage(message, this.targetOrigin);
287
+ },
288
+ () => this.environment.randomUUID()
289
+ );
290
+ /** Replace this connection's tool set. Empty array unregisters all tools. Re-register explicitly after reconnect. */
291
+ registerTools(tools, options = {}) {
292
+ return this.aiTools.register(tools, options);
293
+ }
51
294
  /** Identity returned by the authenticated wallet, or null before establishment. */
52
295
  get networkIdentity() {
53
296
  return this.identityValue;
54
297
  }
298
+ /** 最近一次持久化失败的原因;成功后清零。登录成功不受写入失败影响。 */
299
+ get recoverySaveError() {
300
+ return this.recoverySaveErrorValue;
301
+ }
302
+ /** 刷新恢复存储是否可用;不可用时仍可登录,但刷新后需重新登录。 */
303
+ get recoveryStorageAvailable() {
304
+ return this.recoveryStorage !== null;
305
+ }
55
306
  targetOrigin;
56
307
  mode;
57
308
  environment;
@@ -68,6 +319,17 @@ var KeymasterConnectClient = class {
68
319
  authorizationId = null;
69
320
  authorizedIdentity = null;
70
321
  recoveryId = null;
322
+ recoveryStorage;
323
+ recoverySaveErrorValue = null;
324
+ /** 显式恢复期间暂停后台心跳,保证本次尝试使用同一份 proof;结束(成功/失败/取消/超时)后恢复。 */
325
+ explicitRecoveryActive = false;
326
+ explicitRecoveryProof = void 0;
327
+ /** 内存授权是否已验证:login/launch/恢复成功置 true;仅从存储装载的待验证凭据为 false。 */
328
+ authorizationVerified = false;
329
+ /** 当前传输窗口是否已可信就绪(收到过匹配来源与窗口的 ready);新开窗口后重置,存在≠就绪。 */
330
+ sessionWindowReady = false;
331
+ /** 新 popup 首发前等待可信窗口 ready 的一次性继续函数;超时/结束时清空。 */
332
+ recoveryReadyContinue = null;
71
333
  recoveryWaiters = /* @__PURE__ */ new Set();
72
334
  constructor(options) {
73
335
  if ("networkIdentity" in options) throw new TypeError("networkIdentity option has been removed; read identity from the connection result");
@@ -82,6 +344,7 @@ var KeymasterConnectClient = class {
82
344
  closePollMs: positiveNumber(options.closePollMs ?? DEFAULT_CLOSE_POLL_MS, "closePollMs")
83
345
  };
84
346
  this.environment = options.environment ?? createBrowserEnvironment();
347
+ this.recoveryStorage = resolveRecoveryStorage(options.recoveryStorage);
85
348
  }
86
349
  /**
87
350
  * Current browser transport state.
@@ -94,11 +357,15 @@ var KeymasterConnectClient = class {
94
357
  /**
95
358
  * Establishes the browser transport.
96
359
  *
97
- * iframe / appView 绑定真实 parent / opener;popup 打开完整钱包等待 ready。
360
+ * 只建立传输,不恢复授权:iframe / appView 绑定真实 parent / opener;
361
+ * popup 打开完整钱包等待 ready。刷新后的授权恢复请使用 `resume()`,
362
+ * 它会先装载本地恢复记录再复用 `continueConnection()`;`connect()` 本身
363
+ * 不读取恢复记录、不自动恢复。
98
364
  *
99
365
  * @group Transport
100
366
  */
101
367
  connect() {
368
+ if (this.explicitRecoveryActive) return Promise.reject(new TypeError("Connection recovery is already in progress"));
102
369
  return this.mode === "popup" ? this.connectPopup() : this.connectAppView();
103
370
  }
104
371
  /**
@@ -114,15 +381,20 @@ var KeymasterConnectClient = class {
114
381
  for (const field of ["walletPublicKeyHex", "networkIdentity", "bsvNetwork", "assetId"]) {
115
382
  if (field in params) throw new TypeError(`Removed wallet selector: ${field}`);
116
383
  }
117
- if (method === "connect.resume" && this.authorizationId) return this.continueConnection(options);
384
+ if (method === "connect.resume" && this.authorizationId) {
385
+ const resumeProof = params.appIdentity;
386
+ return this.continueConnection(options, resumeProof);
387
+ }
118
388
  const establishing = ["connect.login", "connect.resume", "connect.launch"].includes(method);
119
389
  if (!establishing && this.stateValue === "paused") throw new KeymasterTransportError("wallet_paused", "Wallet connection is paused; old business requests are never replayed");
120
390
  if (establishing && this.pending.size) throw new TypeError("Cannot establish a connection while requests are pending");
391
+ if (establishing && this.explicitRecoveryActive) throw new TypeError("Connection recovery is already in progress");
121
392
  if (!establishing && !this.bindingId) throw new KeymasterProtocolError("invalid_request", "Login, resume or launch before making business requests");
122
393
  if ([...this.pending.values()].some((request) => ["connect.login", "connect.resume", "connect.launch"].includes(request.method))) throw new TypeError("Connection establishment is already pending");
123
394
  await this.connect();
124
395
  if (establishing && this.pending.size) throw new TypeError("Cannot establish a connection while requests are pending");
125
396
  if ([...this.pending.values()].some((request) => ["connect.login", "connect.resume", "connect.launch"].includes(request.method))) throw new TypeError("Connection establishment is already pending");
397
+ if (establishing && this.explicitRecoveryActive) throw new TypeError("Connection recovery is already in progress");
126
398
  if (options.signal?.aborted) throw abortReason(options.signal);
127
399
  const target = this.sessionWindow;
128
400
  if (!target || isWindowClosed(target)) {
@@ -180,10 +452,32 @@ var KeymasterConnectClient = class {
180
452
  * Calls `connect.resume` to restore the unlock runtime for a persistent
181
453
  * session.
182
454
  *
455
+ * 刷新恢复时只把保存的凭据和预期身份载入待恢复上下文,不直接置为已登录;
456
+ * 钱包验证成功、结果身份一致并取得新 binding 后才开放业务调用。
457
+ * 无可用凭据时直接拒绝并提示重新登录,不回退到无凭据的重建默认授权。
458
+ * 恢复请求携带调用方当前入口的 `appIdentity`(如有),不静默丢弃。
459
+ *
183
460
  * @group Connect
184
461
  */
185
462
  resume(params = {}, options) {
186
- return this.request("connect.resume", params, options);
463
+ if (options?.signal?.aborted) return Promise.reject(abortReason(options.signal));
464
+ if (this.explicitRecoveryActive) return Promise.reject(new TypeError("Connection recovery is already in progress"));
465
+ if (this.authorizationId && this.authorizationVerified) {
466
+ return this.request("connect.resume", params, options);
467
+ }
468
+ const stored = loadConnectionRecoveryRecord({
469
+ recoveryStorage: this.recoveryStorage ?? void 0,
470
+ targetOrigin: this.targetOrigin,
471
+ mode: this.mode
472
+ });
473
+ if (stored) {
474
+ this.authorizationId = stored.authorizationId;
475
+ this.authorizedIdentity = Object.freeze({ ...stored.networkIdentity });
476
+ this.authorizationVerified = false;
477
+ } else if (!this.authorizationId) {
478
+ return Promise.reject(new KeymasterTransportError("client_closed", "No saved Keymaster recovery record for this origin and mode; login again"));
479
+ }
480
+ return this.continueConnection(options ?? {}, params.appIdentity);
187
481
  }
188
482
  /**
189
483
  * Calls `connect.logout` to revoke a persistent Connect session.
@@ -251,17 +545,6 @@ var KeymasterConnectClient = class {
251
545
  paymentStatus(params, options) {
252
546
  return this.request("payment.status", params, options);
253
547
  }
254
- /**
255
- * @deprecated Connect v1 接收端拒绝旧转账方法,使用 paymentPay。
256
- * @group Transfer
257
- */
258
- p2pkhTransfer(params, options) {
259
- return this.request("p2pkh.transfer", params, options);
260
- }
261
- /** 注册零额度渠道;用户在钱包设置额度后,付款携带返回的 channelId。 */
262
- registerPaymentChannel(params, options) {
263
- return this.request("payment.channel.register", params, options);
264
- }
265
548
  /**
266
549
  * 发布到任意精确频道;owner、公钥签名和消息编号由 Keymaster 生成。
267
550
  *
@@ -318,6 +601,22 @@ var KeymasterConnectClient = class {
318
601
  storageGet(params, options) {
319
602
  return this.request("storage.get", params, options);
320
603
  }
604
+ /**
605
+ * 可选加密写入:向钱包提交明文,钱包以当前钱包密钥和 App 公钥隔离后加密保存。
606
+ * 路径、条件创建语义与 storagePut 相同,size 返回明文字节数;不会返回加密密钥。
607
+ * @group Storage
608
+ */
609
+ storagePutEncrypted(params, options) {
610
+ return this.request("storage.encrypted.put", params, options);
611
+ }
612
+ /**
613
+ * 可选加密读取:仅同一钱包能解密;offset/length 作用于明文,ifMatch 仍比较远端版本。
614
+ * 明文对象、错误格式、篡改或密钥不匹配均失败,不自动回退为普通读取。
615
+ * @group Storage
616
+ */
617
+ storageGetEncrypted(params, options) {
618
+ return this.request("storage.encrypted.get", params, options);
619
+ }
321
620
  /**
322
621
  * Calls `storage.delete` to delete an app-scoped object.
323
622
  *
@@ -373,9 +672,19 @@ var KeymasterConnectClient = class {
373
672
  * Tears down the local transport. This does not revoke persistent Connect
374
673
  * sessions; call {@link logout} before closing when revocation is required.
375
674
  *
675
+ * 只结束运行连接,保留刷新恢复材料:`close()`、页面卸载和运行失效都不删除
676
+ * 本地恢复记录;`logout` 成功、明确授权失效或用户主动清除才删除。
677
+ *
376
678
  * @group Transport
377
679
  */
378
680
  close() {
681
+ if (this.bindingId) {
682
+ try {
683
+ this.sessionWindow?.postMessage({ v: PROTOCOL_VERSION, type: "tools.register", bindingId: this.bindingId, id: this.environment.randomUUID(), tools: [] }, this.targetOrigin);
684
+ } catch {
685
+ }
686
+ }
687
+ this.aiTools.clear(new Error("Connect client closed"));
379
688
  for (const id of this.pending.keys()) this.postCancel(id);
380
689
  this.identityValue = null;
381
690
  this.bindingId = null;
@@ -389,25 +698,48 @@ var KeymasterConnectClient = class {
389
698
  }
390
699
  if (!this.authorizationId) this.sessionWindow = null;
391
700
  this.recoveryId = null;
701
+ this.explicitRecoveryActive = false;
702
+ this.explicitRecoveryProof = void 0;
703
+ this.recoveryReadyContinue = null;
392
704
  this.finishRecovery(void 0, error);
393
705
  this.setState(this.authorizationId ? "paused" : "disconnected");
394
706
  }
395
707
  /** 主动恢复可由 popup 重新打开钱包;后台恢复从不打开窗口或重放业务。 */
396
- continueConnection(options) {
708
+ continueConnection(options, appIdentity) {
709
+ if (options.signal?.aborted) return Promise.reject(abortReason(options.signal));
710
+ if (this.explicitRecoveryActive) return Promise.reject(new TypeError("Connection recovery is already in progress"));
397
711
  if (this.pending.size) return Promise.reject(new TypeError("Cannot resume while business requests are pending"));
398
712
  this.installListener();
713
+ let awaitReady = false;
399
714
  if (this.mode === "popup") {
400
715
  if (!this.sessionWindow || isWindowClosed(this.sessionWindow)) {
401
716
  const url = new URL(this.options.popupPath, `${this.targetOrigin}/`);
402
717
  if (url.origin !== this.targetOrigin) return Promise.reject(new TypeError("popupPath must resolve inside targetOrigin"));
403
718
  this.sessionWindow = this.environment.open(url.href, "_blank", "");
404
719
  if (!this.sessionWindow) return Promise.reject(new KeymasterTransportError("popup_blocked", "Keymaster wallet window was blocked"));
720
+ this.sessionWindowReady = false;
721
+ awaitReady = true;
722
+ } else if (!this.sessionWindowReady) {
723
+ awaitReady = true;
405
724
  }
406
725
  } else {
407
726
  const launcher = this.mode === "iframe" ? this.environment.parent() : this.environment.opener();
408
727
  if (!launcher || isWindowClosed(launcher)) return Promise.reject(new KeymasterTransportError("appview_session_lost", "Wallet launcher unavailable; relaunch from the wallet"));
409
728
  this.sessionWindow = launcher;
410
729
  }
730
+ const wasVerified = this.authorizationVerified;
731
+ this.explicitRecoveryActive = true;
732
+ this.explicitRecoveryProof = appIdentity;
733
+ const endExplicitAttempt = (failed) => {
734
+ this.explicitRecoveryActive = false;
735
+ this.explicitRecoveryProof = void 0;
736
+ this.recoveryReadyContinue = null;
737
+ if (failed && !wasVerified && this.authorizationId) {
738
+ this.authorizationId = null;
739
+ this.authorizedIdentity = null;
740
+ this.recoveryId = null;
741
+ }
742
+ };
411
743
  this.pause(new KeymasterTransportError("wallet_paused", "Re-establishing the original wallet connection"));
412
744
  this.startClosePolling();
413
745
  return new Promise((resolve, reject) => {
@@ -415,6 +747,7 @@ var KeymasterConnectClient = class {
415
747
  this.environment.clearTimeout(timer);
416
748
  options.signal?.removeEventListener("abort", aborted);
417
749
  this.recoveryWaiters.delete(waiter);
750
+ endExplicitAttempt(!!error);
418
751
  if (error) reject(error);
419
752
  else resolve(result);
420
753
  };
@@ -423,7 +756,11 @@ var KeymasterConnectClient = class {
423
756
  const timer = this.environment.setTimeout(() => finish(new KeymasterTransportError("request_timeout", "Timed out restoring wallet connection")), positiveNumber(options.timeoutMs ?? this.options.readyTimeoutMs, "timeoutMs"));
424
757
  this.recoveryWaiters.add(waiter);
425
758
  options.signal?.addEventListener("abort", aborted, { once: true });
426
- this.sendRecovery();
759
+ if (awaitReady) {
760
+ this.recoveryReadyContinue = () => this.sendRecovery(this.explicitRecoveryProof);
761
+ } else {
762
+ this.sendRecovery(this.explicitRecoveryProof);
763
+ }
427
764
  });
428
765
  }
429
766
  connectPopup() {
@@ -438,6 +775,7 @@ var KeymasterConnectClient = class {
438
775
  this.setState("disconnected");
439
776
  return Promise.reject(new KeymasterTransportError("popup_blocked", "Keymaster wallet window was blocked"));
440
777
  }
778
+ this.sessionWindowReady = false;
441
779
  this.startClosePolling();
442
780
  this.readyPromise = new Promise((resolve, reject) => {
443
781
  this.readyResolve = resolve;
@@ -450,7 +788,7 @@ var KeymasterConnectClient = class {
450
788
  if (this.isConnected()) return Promise.resolve();
451
789
  const parent = this.mode === "iframe" ? this.environment.parent() : this.environment.opener();
452
790
  if (!parent || isWindowClosed(parent)) {
453
- const code = this.stateValue === "idle" ? "not_embedded" : "appview_session_lost";
791
+ const code = this.stateValue === "idle" ? this.mode === "iframe" ? "not_embedded" : "no_opener" : "appview_session_lost";
454
792
  this.setState("disconnected");
455
793
  return Promise.reject(new KeymasterTransportError(
456
794
  code,
@@ -478,8 +816,15 @@ var KeymasterConnectClient = class {
478
816
  if (value.type === "ready" || value.type === "result") this.disconnect(new KeymasterTransportError("unsupported_protocol", "Incompatible Keymaster protocol version"));
479
817
  return;
480
818
  }
819
+ if (this.aiTools.handle(value)) return;
481
820
  if (value.type === "ready") {
821
+ this.sessionWindowReady = true;
482
822
  if (this.mode === "popup" && this.readyPromise) this.finishReady();
823
+ if (this.explicitRecoveryActive && this.recoveryReadyContinue) {
824
+ const send = this.recoveryReadyContinue;
825
+ this.recoveryReadyContinue = null;
826
+ send();
827
+ }
483
828
  return;
484
829
  }
485
830
  if (value.type === "closing") {
@@ -488,11 +833,15 @@ var KeymasterConnectClient = class {
488
833
  return;
489
834
  }
490
835
  if (value.type === "revoked" && value.authorizationId === this.authorizationId) {
836
+ const revokedId = this.authorizationId;
491
837
  this.authorizationId = null;
492
838
  this.authorizedIdentity = null;
839
+ this.authorizationVerified = false;
493
840
  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"));
841
+ this.dropRecoveryRecord(revokedId);
842
+ const revokedError = new KeymasterProtocolError("authorization_expired", "Application connection authorization was revoked");
843
+ this.finishRecovery(void 0, revokedError);
844
+ this.disconnect(revokedError);
496
845
  return;
497
846
  }
498
847
  if (value.type === "event") {
@@ -512,7 +861,24 @@ var KeymasterConnectClient = class {
512
861
  const result = event.data;
513
862
  if (this.authorizationId && result.id === this.recoveryId) {
514
863
  if (!result.ok) {
515
- this.pause(new KeymasterProtocolError(result.error.code, result.error.message));
864
+ const code = result.error?.code;
865
+ const message = result.error?.message ?? "Failed to restore wallet connection";
866
+ if (code === "authorization_expired") {
867
+ const expiredId = this.authorizationId;
868
+ this.authorizationId = null;
869
+ this.authorizedIdentity = null;
870
+ this.authorizationVerified = false;
871
+ this.recoveryId = null;
872
+ this.dropRecoveryRecord(expiredId);
873
+ const expired = new KeymasterProtocolError(code, message);
874
+ this.finishRecovery(void 0, expired);
875
+ this.disconnect(expired);
876
+ return;
877
+ }
878
+ const failure = new KeymasterProtocolError(code || "connection_expired", message);
879
+ this.pause(failure);
880
+ this.recoveryId = null;
881
+ this.finishRecovery(void 0, failure);
516
882
  return;
517
883
  }
518
884
  try {
@@ -523,10 +889,13 @@ var KeymasterConnectClient = class {
523
889
  this.identityValue = Object.freeze({ ...identity });
524
890
  this.bindingId = value.bindingId;
525
891
  this.recoveryId = null;
892
+ this.authorizationVerified = true;
526
893
  this.setState("connected");
894
+ this.persistRecoveryRecord(restored.authorizationId, identity);
527
895
  this.finishRecovery(restored);
528
896
  } catch (error) {
529
897
  this.pause(error);
898
+ this.recoveryId = null;
530
899
  this.finishRecovery(void 0, error);
531
900
  }
532
901
  return;
@@ -539,7 +908,7 @@ var KeymasterConnectClient = class {
539
908
  pending.reject(new KeymasterProtocolError("invalid_request", "Malformed Keymaster error result"));
540
909
  return;
541
910
  }
542
- if (result.error.code === "connection_expired") {
911
+ if (result.error.code === "connection_expired" || result.error.code === "authorization_expired") {
543
912
  if (this.authorizationId) this.pause(new KeymasterProtocolError(result.error.code, result.error.message));
544
913
  else {
545
914
  this.identityValue = null;
@@ -554,20 +923,27 @@ var KeymasterConnectClient = class {
554
923
  if (["connect.login", "connect.resume", "connect.launch"].includes(pending.method)) {
555
924
  const connected = result.result;
556
925
  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");
926
+ this.aiTools.clear(new Error("Connection binding replaced; register tools again"));
557
927
  this.identityValue = Object.freeze({ ...identity });
558
928
  this.authorizedIdentity = this.identityValue;
559
929
  this.authorizationId = connected.authorizationId;
930
+ this.authorizationVerified = true;
560
931
  this.recoveryId = null;
561
932
  this.bindingId = value.bindingId;
933
+ this.persistRecoveryRecord(connected.authorizationId, identity);
562
934
  } else if (!this.identityValue || value.bindingId !== this.bindingId || !sameNetworkIdentity(this.identityValue, identity)) {
563
935
  throw new Error("Keymaster connection identity mismatch");
564
936
  }
565
937
  if (pending.method === "connect.logout") {
938
+ const logoutId = this.authorizationId;
939
+ this.aiTools.clear(new Error("Logged out"));
566
940
  this.identityValue = null;
567
941
  this.bindingId = null;
568
942
  this.authorizationId = null;
569
943
  this.authorizedIdentity = null;
944
+ this.authorizationVerified = false;
570
945
  this.recoveryId = null;
946
+ this.dropRecoveryRecord(logoutId);
571
947
  }
572
948
  pending.resolve(result.result);
573
949
  } catch (error) {
@@ -601,6 +977,7 @@ var KeymasterConnectClient = class {
601
977
  this.readyReject = null;
602
978
  }
603
979
  disconnect(reason) {
980
+ this.aiTools.clear(reason);
604
981
  for (const id of this.pending.keys()) this.postCancel(id);
605
982
  this.identityValue = null;
606
983
  this.bindingId = null;
@@ -608,21 +985,58 @@ var KeymasterConnectClient = class {
608
985
  this.failReady(reason);
609
986
  this.stopClosePolling();
610
987
  this.sessionWindow = null;
988
+ this.sessionWindowReady = false;
989
+ this.explicitRecoveryActive = false;
990
+ this.explicitRecoveryProof = void 0;
991
+ this.recoveryReadyContinue = null;
611
992
  this.setState("disconnected");
612
993
  }
613
994
  /** 暂停仅撤销瞬时绑定和旧请求,持久授权引用及原身份留作恢复校验。 */
614
995
  pause(reason) {
996
+ this.aiTools.clear(reason);
615
997
  this.identityValue = null;
616
998
  this.bindingId = null;
617
999
  this.rejectAll(reason);
618
1000
  this.failReady(reason);
619
1001
  this.setState("paused");
620
1002
  }
621
- sendRecovery() {
1003
+ /** 保存最近成功连接的恢复记录;写入失败只记录原因,不影响已成功的登录。 */
1004
+ persistRecoveryRecord(authorizationId, identity) {
1005
+ if (!this.recoveryStorage) {
1006
+ this.recoverySaveErrorValue = "Recovery storage is unavailable; refresh will require re-login";
1007
+ return;
1008
+ }
1009
+ try {
1010
+ saveConnectionRecoveryRecord(this.recoveryStorage, {
1011
+ version: 1,
1012
+ targetOrigin: this.targetOrigin,
1013
+ mode: this.mode,
1014
+ authorizationId,
1015
+ networkIdentity: { ...identity }
1016
+ });
1017
+ this.recoverySaveErrorValue = null;
1018
+ } catch (error) {
1019
+ this.recoverySaveErrorValue = errorMessage(error, "Failed to persist recovery record; refresh will require re-login");
1020
+ }
1021
+ }
1022
+ /** 按目标与授权核对后清除本地恢复记录;旧实例迟到结果不得删除新记录。 */
1023
+ dropRecoveryRecord(authorizationId) {
1024
+ try {
1025
+ clearConnectionRecovery({
1026
+ recoveryStorage: this.recoveryStorage ?? void 0,
1027
+ targetOrigin: this.targetOrigin,
1028
+ ...authorizationId ? { authorizationId } : {}
1029
+ });
1030
+ } catch {
1031
+ }
1032
+ }
1033
+ sendRecovery(appIdentity) {
622
1034
  if (!this.authorizationId || !this.sessionWindow || isWindowClosed(this.sessionWindow)) return;
1035
+ if (this.stateValue === "opening") return;
1036
+ if ([...this.pending.values()].some((request) => ["connect.login", "connect.resume", "connect.launch"].includes(request.method))) return;
623
1037
  this.recoveryId ??= this.environment.randomUUID();
624
1038
  try {
625
- this.sessionWindow.postMessage({ v: PROTOCOL_VERSION, type: "reconnect", id: this.recoveryId, authorizationId: this.authorizationId, ...this.bindingId ? { bindingId: this.bindingId } : {} }, this.targetOrigin);
1039
+ this.sessionWindow.postMessage({ v: PROTOCOL_VERSION, type: "reconnect", id: this.recoveryId, authorizationId: this.authorizationId, ...this.bindingId ? { bindingId: this.bindingId } : {}, ...appIdentity ? { appIdentity } : {} }, this.targetOrigin);
626
1040
  } catch (error) {
627
1041
  this.pause(error);
628
1042
  }
@@ -640,7 +1054,7 @@ var KeymasterConnectClient = class {
640
1054
  if (this.authorizationId) {
641
1055
  if (this.stateValue !== "paused") this.pause(new KeymasterTransportError("wallet_paused", "Wallet window is closed"));
642
1056
  } else this.disconnect(new KeymasterTransportError("wallet_closed", "Keymaster parent wallet was closed"));
643
- } else this.sendRecovery();
1057
+ } else if (!this.explicitRecoveryActive) this.sendRecovery();
644
1058
  }, this.options.closePollMs);
645
1059
  }
646
1060
  stopClosePolling() {
@@ -722,6 +1136,6 @@ function errorMessage(value, fallback) {
722
1136
  return value instanceof Error && value.message ? value.message : fallback;
723
1137
  }
724
1138
 
725
- export { KeymasterConnectClient, KeymasterProtocolError, KeymasterTransportError, binary, binaryBytes, binaryText, binaryToText, createBrowserEnvironment, createKeymasterConnect };
1139
+ export { KeymasterConnectClient, KeymasterProtocolError, KeymasterTransportError, RECOVERY_STORAGE_KEY, binary, binaryBytes, binaryText, binaryToText, clearConnectionRecovery, createBrowserEnvironment, createKeymasterConnect, isRecoveryStorageAvailable, loadConnectionRecoveryRecord, readConnectionRecovery, resolveRecoveryStorage, saveConnectionRecoveryRecord };
726
1140
  //# sourceMappingURL=index.js.map
727
1141
  //# sourceMappingURL=index.js.map