keymaster-connect 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +661 -0
- package/README.md +37 -2
- package/dist/chunk-AAVOIS5Q.js +72 -0
- package/dist/chunk-AAVOIS5Q.js.map +1 -0
- package/dist/index.d.ts +370 -0
- package/dist/index.js +680 -0
- package/dist/index.js.map +1 -0
- package/dist/protocol.d.ts +719 -0
- package/dist/protocol.js +3 -0
- package/dist/protocol.js.map +1 -0
- package/dist/server.d.ts +162 -0
- package/dist/server.js +995 -0
- package/dist/server.js.map +1 -0
- package/package.json +32 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,680 @@
|
|
|
1
|
+
import { PROTOCOL_VERSION, sameNetworkIdentity, validateNetworkIdentity } from './chunk-AAVOIS5Q.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-AAVOIS5Q.js';
|
|
3
|
+
|
|
4
|
+
// src/binary.ts
|
|
5
|
+
function binary(bytes, mime) {
|
|
6
|
+
const view = bytes instanceof ArrayBuffer ? new Uint8Array(bytes) : new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
7
|
+
const copy = new Uint8Array(view.byteLength);
|
|
8
|
+
copy.set(view);
|
|
9
|
+
return {
|
|
10
|
+
$type: "binary",
|
|
11
|
+
bytes: copy.buffer,
|
|
12
|
+
...mime ? { mime } : {}
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
function binaryBytes(field) {
|
|
16
|
+
if (field.$type !== "binary" || !(field.bytes instanceof ArrayBuffer)) {
|
|
17
|
+
throw new TypeError("Expected a Keymaster BinaryField");
|
|
18
|
+
}
|
|
19
|
+
return new Uint8Array(field.bytes.slice(0));
|
|
20
|
+
}
|
|
21
|
+
function binaryText(value, mime = "text/plain;charset=utf-8") {
|
|
22
|
+
return binary(new TextEncoder().encode(value), mime);
|
|
23
|
+
}
|
|
24
|
+
function binaryToText(field) {
|
|
25
|
+
return new TextDecoder().decode(binaryBytes(field));
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// src/client.ts
|
|
29
|
+
var KeymasterTransportError = class extends Error {
|
|
30
|
+
constructor(code, message) {
|
|
31
|
+
super(message);
|
|
32
|
+
this.code = code;
|
|
33
|
+
this.name = "KeymasterTransportError";
|
|
34
|
+
}
|
|
35
|
+
code;
|
|
36
|
+
};
|
|
37
|
+
var KeymasterProtocolError = class extends Error {
|
|
38
|
+
constructor(code, message) {
|
|
39
|
+
super(message);
|
|
40
|
+
this.code = code;
|
|
41
|
+
this.name = "KeymasterProtocolError";
|
|
42
|
+
}
|
|
43
|
+
code;
|
|
44
|
+
};
|
|
45
|
+
var DEFAULT_POPUP_PATH = "/protocol/v1/popup";
|
|
46
|
+
var DEFAULT_POPUP_NAME = "keymaster-connect-v1";
|
|
47
|
+
var DEFAULT_READY_TIMEOUT_MS = 3e4;
|
|
48
|
+
var DEFAULT_REQUEST_TIMEOUT_MS = 12e4;
|
|
49
|
+
var DEFAULT_CLOSE_POLL_MS = 500;
|
|
50
|
+
var KeymasterConnectClient = class {
|
|
51
|
+
identityValue = null;
|
|
52
|
+
bindingId = null;
|
|
53
|
+
/** Identity returned by the authenticated wallet, or null before establishment. */
|
|
54
|
+
get networkIdentity() {
|
|
55
|
+
return this.identityValue;
|
|
56
|
+
}
|
|
57
|
+
targetOrigin;
|
|
58
|
+
mode;
|
|
59
|
+
environment;
|
|
60
|
+
options;
|
|
61
|
+
pending = /* @__PURE__ */ new Map();
|
|
62
|
+
stateValue = "idle";
|
|
63
|
+
sessionWindow = null;
|
|
64
|
+
ownsSessionWindow = false;
|
|
65
|
+
listenerInstalled = false;
|
|
66
|
+
readyPromise = null;
|
|
67
|
+
readyResolve = null;
|
|
68
|
+
readyReject = null;
|
|
69
|
+
readyTimer = null;
|
|
70
|
+
closePoller = null;
|
|
71
|
+
constructor(options) {
|
|
72
|
+
if ("networkIdentity" in options) throw new TypeError("networkIdentity option has been removed; read identity from the connection result");
|
|
73
|
+
this.targetOrigin = normalizeHttpOrigin(options.targetOrigin);
|
|
74
|
+
this.mode = options.mode ?? "popup";
|
|
75
|
+
this.options = {
|
|
76
|
+
...options,
|
|
77
|
+
popupPath: options.popupPath ?? DEFAULT_POPUP_PATH,
|
|
78
|
+
popupName: options.popupName ?? DEFAULT_POPUP_NAME,
|
|
79
|
+
popupWidth: positiveNumber(options.popupWidth ?? 520, "popupWidth"),
|
|
80
|
+
popupHeight: positiveNumber(options.popupHeight ?? 760, "popupHeight"),
|
|
81
|
+
readyTimeoutMs: positiveNumber(options.readyTimeoutMs ?? DEFAULT_READY_TIMEOUT_MS, "readyTimeoutMs"),
|
|
82
|
+
requestTimeoutMs: positiveNumber(options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS, "requestTimeoutMs"),
|
|
83
|
+
closePollMs: positiveNumber(options.closePollMs ?? DEFAULT_CLOSE_POLL_MS, "closePollMs")
|
|
84
|
+
};
|
|
85
|
+
this.environment = options.environment ?? createBrowserEnvironment();
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Current browser transport state.
|
|
89
|
+
*
|
|
90
|
+
* @group Transport
|
|
91
|
+
*/
|
|
92
|
+
get state() {
|
|
93
|
+
return this.stateValue;
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Establishes the browser transport.
|
|
97
|
+
*
|
|
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.
|
|
101
|
+
*
|
|
102
|
+
* @group Transport
|
|
103
|
+
*/
|
|
104
|
+
connect() {
|
|
105
|
+
return this.mode === "appView" ? this.connectAppView() : this.connectPopup();
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Sends any public Connect method with compile-time parameter and result
|
|
109
|
+
* inference.
|
|
110
|
+
*
|
|
111
|
+
* @group Transport
|
|
112
|
+
*/
|
|
113
|
+
async request(method, params, options = {}) {
|
|
114
|
+
if (options.signal?.aborted) throw abortReason(options.signal);
|
|
115
|
+
if (!params || typeof params !== "object" || Array.isArray(params)) throw new TypeError("params must be an object");
|
|
116
|
+
for (const field of ["walletPublicKeyHex", "networkIdentity", "bsvNetwork", "assetId"]) {
|
|
117
|
+
if (field in params) throw new TypeError(`Removed wallet selector: ${field}`);
|
|
118
|
+
}
|
|
119
|
+
const establishing = ["connect.login", "connect.resume", "connect.launch"].includes(method);
|
|
120
|
+
if (establishing && this.pending.size) throw new TypeError("Cannot establish a connection while requests are pending");
|
|
121
|
+
if (!establishing && !this.bindingId) throw new KeymasterProtocolError("invalid_request", "Login, resume or launch before making business requests");
|
|
122
|
+
if ([...this.pending.values()].some((request) => ["connect.login", "connect.resume", "connect.launch"].includes(request.method))) throw new TypeError("Connection establishment is already pending");
|
|
123
|
+
await this.connect();
|
|
124
|
+
if (establishing && this.pending.size) throw new TypeError("Cannot establish a connection while requests are pending");
|
|
125
|
+
if ([...this.pending.values()].some((request) => ["connect.login", "connect.resume", "connect.launch"].includes(request.method))) throw new TypeError("Connection establishment is already pending");
|
|
126
|
+
if (options.signal?.aborted) throw abortReason(options.signal);
|
|
127
|
+
const target = this.sessionWindow;
|
|
128
|
+
if (!target || isWindowClosed(target)) {
|
|
129
|
+
throw new KeymasterTransportError("popup_closed", "Keymaster Session Window is closed");
|
|
130
|
+
}
|
|
131
|
+
const requestId = options.requestId ?? this.environment.randomUUID();
|
|
132
|
+
if (!requestId || this.pending.has(requestId)) {
|
|
133
|
+
throw new TypeError("requestId must be non-empty and unique among pending requests");
|
|
134
|
+
}
|
|
135
|
+
const timeoutMs = positiveNumber(options.timeoutMs ?? this.options.requestTimeoutMs, "timeoutMs");
|
|
136
|
+
return new Promise((resolve, reject) => {
|
|
137
|
+
const timer = this.environment.setTimeout(() => {
|
|
138
|
+
this.postCancel(requestId);
|
|
139
|
+
this.deletePending(requestId);
|
|
140
|
+
reject(new KeymasterTransportError("request_timeout", `Keymaster request timed out: ${method}`));
|
|
141
|
+
}, timeoutMs);
|
|
142
|
+
const abortListener = options.signal ? () => {
|
|
143
|
+
this.postCancel(requestId);
|
|
144
|
+
this.deletePending(requestId);
|
|
145
|
+
reject(abortReason(options.signal));
|
|
146
|
+
} : void 0;
|
|
147
|
+
if (abortListener) options.signal.addEventListener("abort", abortListener, { once: true });
|
|
148
|
+
this.pending.set(requestId, {
|
|
149
|
+
method,
|
|
150
|
+
resolve: (value) => resolve(value),
|
|
151
|
+
reject,
|
|
152
|
+
timer,
|
|
153
|
+
signal: options.signal,
|
|
154
|
+
abortListener
|
|
155
|
+
});
|
|
156
|
+
try {
|
|
157
|
+
target.postMessage({
|
|
158
|
+
v: PROTOCOL_VERSION,
|
|
159
|
+
type: "request",
|
|
160
|
+
...!establishing ? { bindingId: this.bindingId } : {},
|
|
161
|
+
id: requestId,
|
|
162
|
+
method,
|
|
163
|
+
params
|
|
164
|
+
}, this.targetOrigin);
|
|
165
|
+
} catch (cause) {
|
|
166
|
+
this.deletePending(requestId);
|
|
167
|
+
reject(new KeymasterTransportError("send_failed", errorMessage(cause, "Unable to send Keymaster request")));
|
|
168
|
+
}
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* Calls `connect.login` to create a persistent Connect session.
|
|
173
|
+
*
|
|
174
|
+
* @group Connect
|
|
175
|
+
*/
|
|
176
|
+
login(params, options) {
|
|
177
|
+
return this.request("connect.login", params, options);
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Calls `connect.resume` to restore the unlock runtime for a persistent
|
|
181
|
+
* session.
|
|
182
|
+
*
|
|
183
|
+
* @group Connect
|
|
184
|
+
*/
|
|
185
|
+
resume(params = {}, options) {
|
|
186
|
+
return this.request("connect.resume", params, options);
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Calls `connect.logout` to revoke a persistent Connect session.
|
|
190
|
+
*
|
|
191
|
+
* @group Connect
|
|
192
|
+
*/
|
|
193
|
+
logout(options) {
|
|
194
|
+
if (options !== void 0 && (typeof options !== "object" || options === null)) return Promise.reject(new TypeError("logout no longer accepts a wallet public key"));
|
|
195
|
+
return this.request("connect.logout", {}, options);
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Calls `connect.launch` to consume the one-time launch token of an appView
|
|
199
|
+
* session.
|
|
200
|
+
*
|
|
201
|
+
* @group Connect
|
|
202
|
+
*/
|
|
203
|
+
launch(params, options) {
|
|
204
|
+
if (this.mode !== "appView") {
|
|
205
|
+
return Promise.reject(new TypeError('connect.launch requires mode: "appView"'));
|
|
206
|
+
}
|
|
207
|
+
return this.request("connect.launch", params, options);
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* Calls `identity.get` to return signed identity claims for the session
|
|
211
|
+
* owner.
|
|
212
|
+
*
|
|
213
|
+
* @group Identity
|
|
214
|
+
*/
|
|
215
|
+
identityGet(params, options) {
|
|
216
|
+
return this.request("identity.get", params, options);
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* Calls `intent.sign` to sign caller-provided bytes with a human-readable
|
|
220
|
+
* intent.
|
|
221
|
+
*
|
|
222
|
+
* @group Identity
|
|
223
|
+
*/
|
|
224
|
+
intentSign(params, options) {
|
|
225
|
+
return this.request("intent.sign", params, options);
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Calls `cipher.encrypt` to encrypt origin-bound application data.
|
|
229
|
+
*
|
|
230
|
+
* @group Cipher
|
|
231
|
+
*/
|
|
232
|
+
cipherEncrypt(params, options) {
|
|
233
|
+
return this.request("cipher.encrypt", params, options);
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* Calls `cipher.decrypt` to decrypt data previously returned by
|
|
237
|
+
* `cipher.encrypt`.
|
|
238
|
+
*
|
|
239
|
+
* @group Cipher
|
|
240
|
+
*/
|
|
241
|
+
cipherDecrypt(params, options) {
|
|
242
|
+
return this.request("cipher.decrypt", params, options);
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* 请求 `payment.pay`;资金审批、选币与持久幂等由钱包负责。
|
|
246
|
+
* Promise resolve 不等于已广播,应检查返回状态。
|
|
247
|
+
*
|
|
248
|
+
* @group Payment
|
|
249
|
+
*/
|
|
250
|
+
paymentPay(params, options) {
|
|
251
|
+
return this.request("payment.pay", params, options);
|
|
252
|
+
}
|
|
253
|
+
/** 按原业务 ID 只读查询付款状态,不自动重付或更换 ID。 */
|
|
254
|
+
paymentStatus(params, options) {
|
|
255
|
+
return this.request("payment.status", params, options);
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* @deprecated Connect v1 接收端拒绝旧转账方法,使用 paymentPay。
|
|
259
|
+
* @group Transfer
|
|
260
|
+
*/
|
|
261
|
+
p2pkhTransfer(params, options) {
|
|
262
|
+
return this.request("p2pkh.transfer", params, options);
|
|
263
|
+
}
|
|
264
|
+
/** 注册零额度渠道;用户在钱包设置额度后,付款携带返回的 channelId。 */
|
|
265
|
+
registerPaymentChannel(params, options) {
|
|
266
|
+
return this.request("payment.channel.register", params, options);
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* 发布到任意精确频道;owner、公钥签名和消息编号由 Keymaster 生成。
|
|
270
|
+
*
|
|
271
|
+
* @group Channel
|
|
272
|
+
*/
|
|
273
|
+
channelPublish(params, options) {
|
|
274
|
+
return this.request("channel.publish", params, options);
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* 替换当前 Connect caller 的精确频道订阅集合;传空数组表示释放。
|
|
278
|
+
*
|
|
279
|
+
* @group Channel
|
|
280
|
+
*/
|
|
281
|
+
channelSubscriptionSet(params, options) {
|
|
282
|
+
return this.request("channel.subscription_set", params, options);
|
|
283
|
+
}
|
|
284
|
+
/**
|
|
285
|
+
* 一次读取 Keymaster 当前的 BSV 展示价格(金额 + 单位)。
|
|
286
|
+
*
|
|
287
|
+
* 未就绪(未配置 / 未收到快照 / 订阅出错)时返回 `amount: "0.00"`;
|
|
288
|
+
* 价格只作显示参考,不用于业务判断。
|
|
289
|
+
*
|
|
290
|
+
* @group Price
|
|
291
|
+
*/
|
|
292
|
+
priceGet(params, options) {
|
|
293
|
+
return this.request("price.get", params, options);
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* 订阅 `price.changed` 推送;订阅前不会收到价格事件。
|
|
297
|
+
*
|
|
298
|
+
* @group Price
|
|
299
|
+
*/
|
|
300
|
+
priceSubscribe(params, options) {
|
|
301
|
+
return this.request("price.subscribe", params, options);
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* 取消当前会话的 `price.changed` 推送。
|
|
305
|
+
*
|
|
306
|
+
* @group Price
|
|
307
|
+
*/
|
|
308
|
+
priceUnsubscribe(params, options) {
|
|
309
|
+
return this.request("price.unsubscribe", params, options);
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* Calls `storage.list` to list paths in the verified application's namespace.
|
|
313
|
+
*
|
|
314
|
+
* @group Storage
|
|
315
|
+
*/
|
|
316
|
+
storageList(params, options) {
|
|
317
|
+
return this.request("storage.list", params, options);
|
|
318
|
+
}
|
|
319
|
+
/**
|
|
320
|
+
* Calls `storage.directory.create` to create an app-scoped directory.
|
|
321
|
+
*
|
|
322
|
+
* @group Storage
|
|
323
|
+
*/
|
|
324
|
+
storageDirectoryCreate(params, options) {
|
|
325
|
+
return this.request("storage.directory.create", params, options);
|
|
326
|
+
}
|
|
327
|
+
/**
|
|
328
|
+
* Calls `storage.directory.delete` to delete an app-scoped directory.
|
|
329
|
+
*
|
|
330
|
+
* @group Storage
|
|
331
|
+
*/
|
|
332
|
+
storageDirectoryDelete(params, options) {
|
|
333
|
+
return this.request("storage.directory.delete", params, options);
|
|
334
|
+
}
|
|
335
|
+
/**
|
|
336
|
+
* Calls `storage.put` to write an app-scoped object.
|
|
337
|
+
*
|
|
338
|
+
* @group Storage
|
|
339
|
+
*/
|
|
340
|
+
storagePut(params, options) {
|
|
341
|
+
return this.request("storage.put", params, options);
|
|
342
|
+
}
|
|
343
|
+
/**
|
|
344
|
+
* Calls `storage.get` to read an app-scoped object.
|
|
345
|
+
*
|
|
346
|
+
* @group Storage
|
|
347
|
+
*/
|
|
348
|
+
storageGet(params, options) {
|
|
349
|
+
return this.request("storage.get", params, options);
|
|
350
|
+
}
|
|
351
|
+
/**
|
|
352
|
+
* Calls `storage.delete` to delete an app-scoped object.
|
|
353
|
+
*
|
|
354
|
+
* @group Storage
|
|
355
|
+
*/
|
|
356
|
+
storageDelete(params, options) {
|
|
357
|
+
return this.request("storage.delete", params, options);
|
|
358
|
+
}
|
|
359
|
+
/**
|
|
360
|
+
* Calls `msfile.stat` to query every enabled MSFile supplier for a seed
|
|
361
|
+
* hash. The caller selects supplier/hash only; price policy stays inside
|
|
362
|
+
* Keymaster.
|
|
363
|
+
*
|
|
364
|
+
* @group MSFile
|
|
365
|
+
*/
|
|
366
|
+
msfileStat(params, options) {
|
|
367
|
+
return this.request("msfile.stat", params, options);
|
|
368
|
+
}
|
|
369
|
+
/**
|
|
370
|
+
* Calls `msfile.seed.read` to buy and read a MasterSeed by hash. There is no
|
|
371
|
+
* price parameter: Keymaster resolves the amount from its settings or asks
|
|
372
|
+
* the user for approval when needed.
|
|
373
|
+
*
|
|
374
|
+
* @group MSFile
|
|
375
|
+
*/
|
|
376
|
+
msfileReadSeed(params, options) {
|
|
377
|
+
return this.request("msfile.seed.read", params, options);
|
|
378
|
+
}
|
|
379
|
+
/**
|
|
380
|
+
* Calls `msfile.block.read` to buy and read a single file block by hash.
|
|
381
|
+
* Like {@link msfileReadSeed}, no caller-supplied price is accepted.
|
|
382
|
+
*
|
|
383
|
+
* @group MSFile
|
|
384
|
+
*/
|
|
385
|
+
msfileReadBlock(params, options) {
|
|
386
|
+
return this.request("msfile.block.read", params, options);
|
|
387
|
+
}
|
|
388
|
+
/**
|
|
389
|
+
* Cancels a locally pending request. Keymaster only cancels work that has not
|
|
390
|
+
* entered execution; cancellation is therefore best-effort remotely.
|
|
391
|
+
*
|
|
392
|
+
* @group Transport
|
|
393
|
+
*/
|
|
394
|
+
cancel(requestId, reason = new DOMException("The operation was aborted", "AbortError")) {
|
|
395
|
+
const pending = this.pending.get(requestId);
|
|
396
|
+
if (!pending) return false;
|
|
397
|
+
this.postCancel(requestId);
|
|
398
|
+
this.deletePending(requestId);
|
|
399
|
+
pending.reject(reason);
|
|
400
|
+
return true;
|
|
401
|
+
}
|
|
402
|
+
/**
|
|
403
|
+
* Tears down the local transport. This does not revoke persistent Connect
|
|
404
|
+
* sessions; call {@link logout} before closing when revocation is required.
|
|
405
|
+
*
|
|
406
|
+
* @group Transport
|
|
407
|
+
*/
|
|
408
|
+
close() {
|
|
409
|
+
this.identityValue = null;
|
|
410
|
+
this.bindingId = null;
|
|
411
|
+
const error = new KeymasterTransportError("client_closed", "Keymaster client was closed");
|
|
412
|
+
this.rejectAll(error);
|
|
413
|
+
this.failReady(error);
|
|
414
|
+
this.stopClosePolling();
|
|
415
|
+
if (this.listenerInstalled) {
|
|
416
|
+
this.environment.removeMessageListener(this.handleMessage);
|
|
417
|
+
this.listenerInstalled = false;
|
|
418
|
+
}
|
|
419
|
+
try {
|
|
420
|
+
if (this.ownsSessionWindow && this.sessionWindow && !isWindowClosed(this.sessionWindow)) {
|
|
421
|
+
this.sessionWindow.close();
|
|
422
|
+
}
|
|
423
|
+
} catch {
|
|
424
|
+
}
|
|
425
|
+
this.sessionWindow = null;
|
|
426
|
+
this.ownsSessionWindow = false;
|
|
427
|
+
this.setState("disconnected");
|
|
428
|
+
}
|
|
429
|
+
connectPopup() {
|
|
430
|
+
if (this.isConnected()) return Promise.resolve();
|
|
431
|
+
if (this.readyPromise) return this.readyPromise;
|
|
432
|
+
const url = new URL(this.options.popupPath, `${this.targetOrigin}/`);
|
|
433
|
+
if (url.origin !== this.targetOrigin) {
|
|
434
|
+
return Promise.reject(new TypeError("popupPath must resolve inside targetOrigin"));
|
|
435
|
+
}
|
|
436
|
+
this.installListener();
|
|
437
|
+
this.setState("opening");
|
|
438
|
+
this.sessionWindow = this.environment.open(
|
|
439
|
+
url.toString(),
|
|
440
|
+
this.options.popupName,
|
|
441
|
+
popupFeatures(this.options.popupWidth, this.options.popupHeight)
|
|
442
|
+
);
|
|
443
|
+
if (!this.sessionWindow) {
|
|
444
|
+
this.setState("disconnected");
|
|
445
|
+
return Promise.reject(new KeymasterTransportError("popup_blocked", "Keymaster Session Window was blocked"));
|
|
446
|
+
}
|
|
447
|
+
this.ownsSessionWindow = true;
|
|
448
|
+
this.startClosePolling();
|
|
449
|
+
this.readyPromise = new Promise((resolve, reject) => {
|
|
450
|
+
this.readyResolve = resolve;
|
|
451
|
+
this.readyReject = reject;
|
|
452
|
+
this.readyTimer = this.environment.setTimeout(() => {
|
|
453
|
+
this.disconnect(new KeymasterTransportError("ready_timeout", "Timed out waiting for Keymaster ready"));
|
|
454
|
+
}, this.options.readyTimeoutMs);
|
|
455
|
+
});
|
|
456
|
+
return this.readyPromise;
|
|
457
|
+
}
|
|
458
|
+
connectAppView() {
|
|
459
|
+
if (this.isConnected()) return Promise.resolve();
|
|
460
|
+
const opener = this.environment.opener();
|
|
461
|
+
if (!opener || isWindowClosed(opener)) {
|
|
462
|
+
const code = this.stateValue === "idle" ? "no_opener" : "appview_session_lost";
|
|
463
|
+
this.setState("disconnected");
|
|
464
|
+
return Promise.reject(new KeymasterTransportError(
|
|
465
|
+
code,
|
|
466
|
+
"No live Keymaster appView Session Window is available"
|
|
467
|
+
));
|
|
468
|
+
}
|
|
469
|
+
this.installListener();
|
|
470
|
+
this.sessionWindow = opener;
|
|
471
|
+
this.ownsSessionWindow = false;
|
|
472
|
+
try {
|
|
473
|
+
opener.postMessage({ v: PROTOCOL_VERSION, type: "ready" }, this.targetOrigin);
|
|
474
|
+
} catch (cause) {
|
|
475
|
+
this.sessionWindow = null;
|
|
476
|
+
this.setState("disconnected");
|
|
477
|
+
return Promise.reject(new KeymasterTransportError("send_failed", errorMessage(cause, "Unable to send appView ready")));
|
|
478
|
+
}
|
|
479
|
+
this.startClosePolling();
|
|
480
|
+
this.setState("connected");
|
|
481
|
+
return Promise.resolve();
|
|
482
|
+
}
|
|
483
|
+
handleMessage = (event) => {
|
|
484
|
+
if (!this.sessionWindow || event.origin !== this.targetOrigin || event.source !== this.sessionWindow) return;
|
|
485
|
+
const value = event.data;
|
|
486
|
+
if (!value || typeof value.type !== "string") return;
|
|
487
|
+
if (value.v !== PROTOCOL_VERSION) {
|
|
488
|
+
if (value.type === "ready" || value.type === "result") this.disconnect(new KeymasterTransportError("unsupported_protocol", "Incompatible Keymaster protocol version"));
|
|
489
|
+
return;
|
|
490
|
+
}
|
|
491
|
+
if (value.type === "ready" && this.mode === "popup") {
|
|
492
|
+
this.finishReady();
|
|
493
|
+
return;
|
|
494
|
+
}
|
|
495
|
+
if (value.type === "closing") {
|
|
496
|
+
this.disconnect(new KeymasterTransportError("popup_closed", "Keymaster Session Window is closing"));
|
|
497
|
+
return;
|
|
498
|
+
}
|
|
499
|
+
if (value.type === "event") {
|
|
500
|
+
try {
|
|
501
|
+
if (!this.identityValue || value.bindingId !== this.bindingId || !sameNetworkIdentity(this.identityValue, validateNetworkIdentity(value.networkIdentity))) return;
|
|
502
|
+
} catch {
|
|
503
|
+
return;
|
|
504
|
+
}
|
|
505
|
+
try {
|
|
506
|
+
this.options.onEvent?.(event.data);
|
|
507
|
+
} catch {
|
|
508
|
+
}
|
|
509
|
+
return;
|
|
510
|
+
}
|
|
511
|
+
if (value.type !== "result" || typeof value.id !== "string" || typeof value.ok !== "boolean") return;
|
|
512
|
+
const result = event.data;
|
|
513
|
+
const pending = this.pending.get(result.id);
|
|
514
|
+
if (!pending) return;
|
|
515
|
+
this.deletePending(result.id);
|
|
516
|
+
if (!result.ok) {
|
|
517
|
+
if (!result.error || typeof result.error.code !== "string" || !result.error.code || typeof result.error.message !== "string") {
|
|
518
|
+
pending.reject(new KeymasterProtocolError("invalid_request", "Malformed Keymaster error result"));
|
|
519
|
+
return;
|
|
520
|
+
}
|
|
521
|
+
if (result.error.code === "connection_expired") {
|
|
522
|
+
this.identityValue = null;
|
|
523
|
+
this.bindingId = null;
|
|
524
|
+
}
|
|
525
|
+
pending.reject(new KeymasterProtocolError(result.error.code, result.error.message));
|
|
526
|
+
return;
|
|
527
|
+
}
|
|
528
|
+
try {
|
|
529
|
+
const identity = validateNetworkIdentity(value.networkIdentity);
|
|
530
|
+
if (["connect.login", "connect.resume", "connect.launch"].includes(pending.method)) {
|
|
531
|
+
const connected = result.result;
|
|
532
|
+
if (!sameNetworkIdentity(identity, validateNetworkIdentity(connected.networkIdentity)) || typeof value.bindingId !== "string" || !value.bindingId) throw new Error("Invalid connection identity or binding");
|
|
533
|
+
this.identityValue = Object.freeze({ ...identity });
|
|
534
|
+
this.bindingId = value.bindingId;
|
|
535
|
+
} else if (!this.identityValue || value.bindingId !== this.bindingId || !sameNetworkIdentity(this.identityValue, identity)) {
|
|
536
|
+
throw new Error("Keymaster connection identity mismatch");
|
|
537
|
+
}
|
|
538
|
+
if (pending.method === "connect.logout") {
|
|
539
|
+
this.identityValue = null;
|
|
540
|
+
this.bindingId = null;
|
|
541
|
+
}
|
|
542
|
+
pending.resolve(result.result);
|
|
543
|
+
} catch (error) {
|
|
544
|
+
pending.reject(new KeymasterProtocolError("invalid_request", errorMessage(error, "Invalid connection result")));
|
|
545
|
+
}
|
|
546
|
+
};
|
|
547
|
+
isConnected() {
|
|
548
|
+
return this.stateValue === "connected" && !!this.sessionWindow && !isWindowClosed(this.sessionWindow);
|
|
549
|
+
}
|
|
550
|
+
installListener() {
|
|
551
|
+
if (this.listenerInstalled) return;
|
|
552
|
+
this.environment.addMessageListener(this.handleMessage);
|
|
553
|
+
this.listenerInstalled = true;
|
|
554
|
+
}
|
|
555
|
+
finishReady() {
|
|
556
|
+
if (!this.readyPromise) return;
|
|
557
|
+
if (this.readyTimer !== null) this.environment.clearTimeout(this.readyTimer);
|
|
558
|
+
this.readyTimer = null;
|
|
559
|
+
this.readyResolve?.();
|
|
560
|
+
this.readyPromise = null;
|
|
561
|
+
this.readyResolve = null;
|
|
562
|
+
this.readyReject = null;
|
|
563
|
+
this.setState("connected");
|
|
564
|
+
}
|
|
565
|
+
failReady(reason) {
|
|
566
|
+
if (this.readyTimer !== null) this.environment.clearTimeout(this.readyTimer);
|
|
567
|
+
this.readyTimer = null;
|
|
568
|
+
this.readyReject?.(reason);
|
|
569
|
+
this.readyPromise = null;
|
|
570
|
+
this.readyResolve = null;
|
|
571
|
+
this.readyReject = null;
|
|
572
|
+
}
|
|
573
|
+
disconnect(reason) {
|
|
574
|
+
this.identityValue = null;
|
|
575
|
+
this.bindingId = null;
|
|
576
|
+
this.rejectAll(reason);
|
|
577
|
+
this.failReady(reason);
|
|
578
|
+
this.stopClosePolling();
|
|
579
|
+
try {
|
|
580
|
+
if (this.ownsSessionWindow && this.sessionWindow && !isWindowClosed(this.sessionWindow)) {
|
|
581
|
+
this.sessionWindow.close();
|
|
582
|
+
}
|
|
583
|
+
} catch {
|
|
584
|
+
}
|
|
585
|
+
this.sessionWindow = null;
|
|
586
|
+
this.ownsSessionWindow = false;
|
|
587
|
+
this.setState("disconnected");
|
|
588
|
+
}
|
|
589
|
+
startClosePolling() {
|
|
590
|
+
this.stopClosePolling();
|
|
591
|
+
this.closePoller = this.environment.setInterval(() => {
|
|
592
|
+
if (this.sessionWindow && isWindowClosed(this.sessionWindow)) {
|
|
593
|
+
this.disconnect(new KeymasterTransportError("popup_closed", "Keymaster Session Window was closed"));
|
|
594
|
+
}
|
|
595
|
+
}, this.options.closePollMs);
|
|
596
|
+
}
|
|
597
|
+
stopClosePolling() {
|
|
598
|
+
if (this.closePoller !== null) this.environment.clearInterval(this.closePoller);
|
|
599
|
+
this.closePoller = null;
|
|
600
|
+
}
|
|
601
|
+
rejectAll(reason) {
|
|
602
|
+
for (const [id, pending] of this.pending) {
|
|
603
|
+
this.deletePending(id);
|
|
604
|
+
pending.reject(reason);
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
deletePending(id) {
|
|
608
|
+
const pending = this.pending.get(id);
|
|
609
|
+
if (!pending) return;
|
|
610
|
+
this.environment.clearTimeout(pending.timer);
|
|
611
|
+
if (pending.signal && pending.abortListener) {
|
|
612
|
+
pending.signal.removeEventListener("abort", pending.abortListener);
|
|
613
|
+
}
|
|
614
|
+
this.pending.delete(id);
|
|
615
|
+
}
|
|
616
|
+
postCancel(id) {
|
|
617
|
+
try {
|
|
618
|
+
this.sessionWindow?.postMessage({ v: PROTOCOL_VERSION, type: "cancel", id, ...this.bindingId ? { bindingId: this.bindingId } : {} }, this.targetOrigin);
|
|
619
|
+
} catch {
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
setState(state) {
|
|
623
|
+
if (state === this.stateValue) return;
|
|
624
|
+
this.stateValue = state;
|
|
625
|
+
try {
|
|
626
|
+
this.options.onStateChange?.(state);
|
|
627
|
+
} catch {
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
};
|
|
631
|
+
function createKeymasterConnect(options) {
|
|
632
|
+
return new KeymasterConnectClient(options);
|
|
633
|
+
}
|
|
634
|
+
function createBrowserEnvironment() {
|
|
635
|
+
if (typeof window === "undefined") {
|
|
636
|
+
throw new TypeError("keymaster-connect requires a browser Window or an explicit environment");
|
|
637
|
+
}
|
|
638
|
+
return {
|
|
639
|
+
open: (url, target, features) => window.open(url, target, features),
|
|
640
|
+
opener: () => window.opener,
|
|
641
|
+
addMessageListener: (listener) => window.addEventListener("message", listener),
|
|
642
|
+
removeMessageListener: (listener) => window.removeEventListener("message", listener),
|
|
643
|
+
setTimeout: (handler, timeoutMs) => window.setTimeout(handler, timeoutMs),
|
|
644
|
+
clearTimeout: (timer) => window.clearTimeout(timer),
|
|
645
|
+
setInterval: (handler, intervalMs) => window.setInterval(handler, intervalMs),
|
|
646
|
+
clearInterval: (timer) => window.clearInterval(timer),
|
|
647
|
+
randomUUID: () => window.crypto.randomUUID()
|
|
648
|
+
};
|
|
649
|
+
}
|
|
650
|
+
function normalizeHttpOrigin(input) {
|
|
651
|
+
const url = new URL(input);
|
|
652
|
+
if (url.protocol !== "https:" && url.protocol !== "http:") {
|
|
653
|
+
throw new TypeError("targetOrigin must use http or https");
|
|
654
|
+
}
|
|
655
|
+
return url.origin;
|
|
656
|
+
}
|
|
657
|
+
function popupFeatures(width, height) {
|
|
658
|
+
return `popup=yes,width=${Math.max(320, Math.trunc(width))},height=${Math.max(320, Math.trunc(height))}`;
|
|
659
|
+
}
|
|
660
|
+
function positiveNumber(value, name) {
|
|
661
|
+
if (!Number.isFinite(value) || value <= 0) throw new TypeError(`${name} must be a positive number`);
|
|
662
|
+
return value;
|
|
663
|
+
}
|
|
664
|
+
function isWindowClosed(value) {
|
|
665
|
+
try {
|
|
666
|
+
return value.closed === true;
|
|
667
|
+
} catch {
|
|
668
|
+
return true;
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
function abortReason(signal) {
|
|
672
|
+
return signal.reason ?? new DOMException("The operation was aborted", "AbortError");
|
|
673
|
+
}
|
|
674
|
+
function errorMessage(value, fallback) {
|
|
675
|
+
return value instanceof Error && value.message ? value.message : fallback;
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
export { KeymasterConnectClient, KeymasterProtocolError, KeymasterTransportError, binary, binaryBytes, binaryText, binaryToText, createBrowserEnvironment, createKeymasterConnect };
|
|
679
|
+
//# sourceMappingURL=index.js.map
|
|
680
|
+
//# sourceMappingURL=index.js.map
|