@bwalletx/connect 0.5.4 → 0.7.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/CHANGELOG.md +56 -0
- package/README.md +97 -9
- package/dist/bwalletx-connect.global.js +97 -25
- package/dist/bwalletx-connect.global.js.map +1 -1
- package/dist/choice-B97AjqF4.d.cts +442 -0
- package/dist/choice-B97AjqF4.d.ts +442 -0
- package/dist/chunk-6EFFOIHK.js +2441 -0
- package/dist/chunk-6EFFOIHK.js.map +1 -0
- package/dist/{chunk-QRXFL66W.js → chunk-A2WLGS25.js} +6 -4
- package/dist/chunk-A2WLGS25.js.map +1 -0
- package/dist/chunk-DIKJFKND.js +239 -0
- package/dist/chunk-DIKJFKND.js.map +1 -0
- package/dist/chunk-TNRI7ARM.js +206 -0
- package/dist/chunk-TNRI7ARM.js.map +1 -0
- package/dist/element-BXEoOdXY.d.cts +53 -0
- package/dist/element-BXEoOdXY.d.ts +53 -0
- package/dist/element.cjs +1576 -60
- package/dist/element.cjs.map +1 -1
- package/dist/element.d.cts +26 -26
- package/dist/element.d.ts +26 -26
- package/dist/element.js +35 -2
- package/dist/element.js.map +1 -1
- package/dist/index.cjs +2046 -454
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +323 -16
- package/dist/index.d.ts +323 -16
- package/dist/index.js +186 -12
- package/dist/index.js.map +1 -1
- package/dist/next.cjs +5 -3
- package/dist/next.cjs.map +1 -1
- package/dist/next.js +1 -1
- package/dist/react.cjs +1601 -210
- package/dist/react.cjs.map +1 -1
- package/dist/react.d.cts +115 -9
- package/dist/react.d.ts +115 -9
- package/dist/react.js +262 -46
- package/dist/react.js.map +1 -1
- package/dist/server.cjs +5 -3
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.cts +8 -3
- package/dist/server.d.ts +8 -3
- package/dist/server.js +1 -1
- package/package.json +10 -9
- package/dist/chunk-EXRQJTXF.js +0 -910
- package/dist/chunk-EXRQJTXF.js.map +0 -1
- package/dist/chunk-QRXFL66W.js.map +0 -1
- package/dist/chunk-RIOHG5JH.js +0 -459
- package/dist/chunk-RIOHG5JH.js.map +0 -1
- package/dist/wallets-CbzMtxrf.d.cts +0 -250
- package/dist/wallets-CbzMtxrf.d.ts +0 -250
package/dist/chunk-EXRQJTXF.js
DELETED
|
@@ -1,910 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
ACCESS_PROTOCOL,
|
|
3
|
-
AccessError,
|
|
4
|
-
MAX_HOLDING_PROOFS,
|
|
5
|
-
challengeBytes,
|
|
6
|
-
parseAccessChallenge
|
|
7
|
-
} from "./chunk-MWD4BCO5.js";
|
|
8
|
-
|
|
9
|
-
// src/discover.ts
|
|
10
|
-
import { WalletClient, XDM } from "@bsv/sdk";
|
|
11
|
-
var RDNS_EXTENSION = "com.bwalletx.extension";
|
|
12
|
-
var RDNS_MOBILE = "space.bwallet.mobile";
|
|
13
|
-
var BWALLETX_RDNS = [RDNS_EXTENSION, RDNS_MOBILE];
|
|
14
|
-
var DEFAULT_DISCOVER_MS = 300;
|
|
15
|
-
function discoverBwalletX(ms = DEFAULT_DISCOVER_MS) {
|
|
16
|
-
if (typeof window === "undefined") return Promise.resolve(null);
|
|
17
|
-
return new Promise((resolve) => {
|
|
18
|
-
let done = false;
|
|
19
|
-
let timer;
|
|
20
|
-
const finish = (r) => {
|
|
21
|
-
if (done) return;
|
|
22
|
-
done = true;
|
|
23
|
-
if (timer !== void 0) clearTimeout(timer);
|
|
24
|
-
window.removeEventListener("brc100:announceWallet", onAnnounce);
|
|
25
|
-
resolve(r);
|
|
26
|
-
};
|
|
27
|
-
const onAnnounce = (e) => {
|
|
28
|
-
const d = e.detail;
|
|
29
|
-
const rdns = d?.info?.rdns ?? "";
|
|
30
|
-
if (d?.wallet && BWALLETX_RDNS.includes(rdns)) {
|
|
31
|
-
finish({ wallet: d.wallet, method: rdns === RDNS_EXTENSION ? "extension" : "in-app", rdns });
|
|
32
|
-
}
|
|
33
|
-
};
|
|
34
|
-
const cwiNow = () => {
|
|
35
|
-
const cwi = window.CWI;
|
|
36
|
-
if (cwi) finish({ wallet: cwi, method: "in-app", rdns: null });
|
|
37
|
-
return !!cwi;
|
|
38
|
-
};
|
|
39
|
-
window.addEventListener("brc100:announceWallet", onAnnounce);
|
|
40
|
-
window.dispatchEvent(new Event("brc100:requestWallet"));
|
|
41
|
-
if (done || cwiNow()) return;
|
|
42
|
-
if (isFramed()) {
|
|
43
|
-
void probeXdm(Math.max(ms, 1200)).then((w) => finish(w ? { wallet: w, method: "in-app", rdns: null } : null));
|
|
44
|
-
return;
|
|
45
|
-
}
|
|
46
|
-
timer = setTimeout(() => {
|
|
47
|
-
timer = void 0;
|
|
48
|
-
if (!cwiNow()) finish(null);
|
|
49
|
-
}, ms);
|
|
50
|
-
});
|
|
51
|
-
}
|
|
52
|
-
async function findBwalletX(ms = DEFAULT_DISCOVER_MS) {
|
|
53
|
-
return (await discoverBwalletX(ms))?.wallet ?? null;
|
|
54
|
-
}
|
|
55
|
-
var isFramed = () => {
|
|
56
|
-
try {
|
|
57
|
-
return window.parent !== window;
|
|
58
|
-
} catch {
|
|
59
|
-
return true;
|
|
60
|
-
}
|
|
61
|
-
};
|
|
62
|
-
var BWALLETX_PARENT_ORIGINS = [
|
|
63
|
-
"https://web.bwalletx.com",
|
|
64
|
-
"https://desktop.bwalletx.com",
|
|
65
|
-
"https://bwalletx.com",
|
|
66
|
-
"https://www.bwallet.space",
|
|
67
|
-
"https://bwallet.space",
|
|
68
|
-
"capacitor://localhost",
|
|
69
|
-
// iOS app shell
|
|
70
|
-
"https://localhost",
|
|
71
|
-
// Android app shell
|
|
72
|
-
"tauri://localhost",
|
|
73
|
-
// bWalletX Desktop (macOS)
|
|
74
|
-
"https://tauri.localhost",
|
|
75
|
-
// bWalletX Desktop (Windows)
|
|
76
|
-
"chrome-extension://bombmmcjghjdlbmcclnhjodgcelnehgl"
|
|
77
|
-
// bWalletX for Chrome (fixed id)
|
|
78
|
-
];
|
|
79
|
-
var parentOrigin = () => {
|
|
80
|
-
try {
|
|
81
|
-
const anc = window.location.ancestorOrigins;
|
|
82
|
-
if (anc && anc.length > 0) return anc[0] ?? null;
|
|
83
|
-
if (!document.referrer) return null;
|
|
84
|
-
const u = new URL(document.referrer);
|
|
85
|
-
return `${u.protocol}//${u.host}`;
|
|
86
|
-
} catch {
|
|
87
|
-
return null;
|
|
88
|
-
}
|
|
89
|
-
};
|
|
90
|
-
async function probeXdm(ms = 1200, allowed = BWALLETX_PARENT_ORIGINS) {
|
|
91
|
-
const origin = parentOrigin();
|
|
92
|
-
if (!origin || !allowed.includes(origin)) return null;
|
|
93
|
-
try {
|
|
94
|
-
const w = new WalletClient(new XDM(origin));
|
|
95
|
-
const ok = await Promise.race([
|
|
96
|
-
w.isAuthenticated({}).then(
|
|
97
|
-
() => true,
|
|
98
|
-
() => false
|
|
99
|
-
),
|
|
100
|
-
new Promise((r) => setTimeout(() => r(false), ms))
|
|
101
|
-
]);
|
|
102
|
-
return ok ? w : null;
|
|
103
|
-
} catch {
|
|
104
|
-
return null;
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
var warmedAt = 0;
|
|
108
|
-
function prewarmBwalletX() {
|
|
109
|
-
if (typeof window === "undefined" || Date.now() - warmedAt < 2e4) return;
|
|
110
|
-
warmedAt = Date.now();
|
|
111
|
-
void discoverBwalletX(0).then((f) => {
|
|
112
|
-
if (f && f.method === "extension") void f.wallet.isAuthenticated({}).catch(() => {
|
|
113
|
-
});
|
|
114
|
-
});
|
|
115
|
-
}
|
|
116
|
-
function bindPrewarm(el) {
|
|
117
|
-
const on = () => prewarmBwalletX();
|
|
118
|
-
const evs = ["pointerenter", "focus", "touchstart"];
|
|
119
|
-
for (const e of evs) el.addEventListener(e, on, { passive: true });
|
|
120
|
-
return () => evs.forEach((e) => el.removeEventListener(e, on));
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
// src/in-order.ts
|
|
124
|
-
function inOrder(handle, onError) {
|
|
125
|
-
let queue = Promise.resolve();
|
|
126
|
-
return (frame) => {
|
|
127
|
-
queue = queue.then(() => handle(frame)).catch((e) => onError?.(e));
|
|
128
|
-
return queue;
|
|
129
|
-
};
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
// src/pair.ts
|
|
133
|
-
import { PrivateKey as PrivateKey2 } from "@bsv/sdk";
|
|
134
|
-
|
|
135
|
-
// src/protocol.ts
|
|
136
|
-
import { PublicKey } from "@bsv/sdk";
|
|
137
|
-
var PAIR_VERSION = "1";
|
|
138
|
-
var PAIR_INFO = "bwallet-pair-v1";
|
|
139
|
-
var PAIR_HOST = "www.bwallet.space";
|
|
140
|
-
var DEFAULT_RELAY = "relay.bwallet.space";
|
|
141
|
-
var QR_LIFETIME_S = 120;
|
|
142
|
-
var enc = new TextEncoder();
|
|
143
|
-
var dec = new TextDecoder();
|
|
144
|
-
var binary = (bytes) => {
|
|
145
|
-
let s = "";
|
|
146
|
-
for (let i = 0; i < bytes.length; i += 32768) s += String.fromCharCode(...bytes.subarray(i, i + 32768));
|
|
147
|
-
return s;
|
|
148
|
-
};
|
|
149
|
-
var b64url = (bytes) => btoa(binary(bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
150
|
-
var fromB64url = (s) => {
|
|
151
|
-
const t = s.replace(/-/g, "+").replace(/_/g, "/");
|
|
152
|
-
const bin = atob(t + "=".repeat((4 - t.length % 4) % 4));
|
|
153
|
-
return Uint8Array.from(bin, (ch) => ch.charCodeAt(0));
|
|
154
|
-
};
|
|
155
|
-
var b64 = (bytes) => btoa(binary(bytes));
|
|
156
|
-
var fromB64 = (s) => Uint8Array.from(atob(s), (ch) => ch.charCodeAt(0));
|
|
157
|
-
var newChannel = () => b64url(crypto.getRandomValues(new Uint8Array(16)));
|
|
158
|
-
function pairUrl(link) {
|
|
159
|
-
const q = new URLSearchParams({ v: link.v, r: link.r, c: link.c, k: link.k, o: link.o, e: String(link.e) });
|
|
160
|
-
return `https://${PAIR_HOST}/pair?${q}`;
|
|
161
|
-
}
|
|
162
|
-
var newClaim = () => b64url(crypto.getRandomValues(new Uint8Array(16)));
|
|
163
|
-
var WALLET_CLAIM_INFO = "bwallet-pair-wallet-claim-v1";
|
|
164
|
-
var hex = (b) => Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
|
|
165
|
-
async function walletClaimFor(channel, sitePub) {
|
|
166
|
-
const d = await crypto.subtle.digest("SHA-256", enc.encode(`${WALLET_CLAIM_INFO}|${channel}|${sitePub}`));
|
|
167
|
-
return b64url(new Uint8Array(d));
|
|
168
|
-
}
|
|
169
|
-
async function claimDigest(claim) {
|
|
170
|
-
return hex(new Uint8Array(await crypto.subtle.digest("SHA-256", enc.encode(claim))));
|
|
171
|
-
}
|
|
172
|
-
var relaySocketUrl = (relay, channel, role, expiry, claim, walletClaimHash) => {
|
|
173
|
-
const local = /^(localhost|127\.0\.0\.1)(:\d+)?$/.test(relay);
|
|
174
|
-
const q = new URLSearchParams({ role });
|
|
175
|
-
if (expiry) q.set("e", String(expiry));
|
|
176
|
-
if (claim) q.set("claim", claim);
|
|
177
|
-
if (walletClaimHash && role === "site") q.set("wc", walletClaimHash);
|
|
178
|
-
return `${local ? "ws" : "wss"}://${relay}/v1/c/${channel}?${q}`;
|
|
179
|
-
};
|
|
180
|
-
async function deriveSession(mine, theirs, channel) {
|
|
181
|
-
const point = mine.deriveSharedSecret(PublicKey.fromString(theirs));
|
|
182
|
-
const ikm = new Uint8Array(point.encode(true));
|
|
183
|
-
const base = await crypto.subtle.importKey("raw", ikm, "HKDF", false, ["deriveBits"]);
|
|
184
|
-
const bits = new Uint8Array(
|
|
185
|
-
await crypto.subtle.deriveBits(
|
|
186
|
-
{ name: "HKDF", hash: "SHA-256", salt: fromB64url(channel), info: enc.encode(PAIR_INFO) },
|
|
187
|
-
base,
|
|
188
|
-
256
|
|
189
|
-
)
|
|
190
|
-
);
|
|
191
|
-
const key = await crypto.subtle.importKey("raw", bits, "AES-GCM", false, ["encrypt", "decrypt"]);
|
|
192
|
-
const h = new Uint8Array(await crypto.subtle.digest("SHA-256", bits));
|
|
193
|
-
const code = String((h[0] << 8 | h[1]) % 1e4).padStart(4, "0");
|
|
194
|
-
return { key, code };
|
|
195
|
-
}
|
|
196
|
-
var Sealer = class {
|
|
197
|
-
constructor(key, me) {
|
|
198
|
-
this.key = key;
|
|
199
|
-
this.me = me;
|
|
200
|
-
}
|
|
201
|
-
key;
|
|
202
|
-
me;
|
|
203
|
-
sent = 0;
|
|
204
|
-
lastSeen = 0;
|
|
205
|
-
async seal(msg) {
|
|
206
|
-
const s = ++this.sent;
|
|
207
|
-
const n = crypto.getRandomValues(new Uint8Array(12));
|
|
208
|
-
const ct = new Uint8Array(
|
|
209
|
-
await crypto.subtle.encrypt(
|
|
210
|
-
{ name: "AES-GCM", iv: n, additionalData: enc.encode(`${this.me}|${s}`) },
|
|
211
|
-
this.key,
|
|
212
|
-
enc.encode(JSON.stringify(msg))
|
|
213
|
-
)
|
|
214
|
-
);
|
|
215
|
-
return { s, n: b64(n), d: b64(ct) };
|
|
216
|
-
}
|
|
217
|
-
/** Decrypts a frame from the other side; null for replays, reflections or tampering. */
|
|
218
|
-
async open(f) {
|
|
219
|
-
if (!Number.isInteger(f.s) || f.s <= this.lastSeen) return null;
|
|
220
|
-
const from = this.me === "site" ? "wallet" : "site";
|
|
221
|
-
try {
|
|
222
|
-
const pt = await crypto.subtle.decrypt(
|
|
223
|
-
{ name: "AES-GCM", iv: fromB64(f.n), additionalData: enc.encode(`${from}|${f.s}`) },
|
|
224
|
-
this.key,
|
|
225
|
-
fromB64(f.d)
|
|
226
|
-
);
|
|
227
|
-
this.lastSeen = f.s;
|
|
228
|
-
return JSON.parse(dec.decode(pt));
|
|
229
|
-
} catch {
|
|
230
|
-
return null;
|
|
231
|
-
}
|
|
232
|
-
}
|
|
233
|
-
/** For resuming a session after a reload: continue counters where they were. */
|
|
234
|
-
get counters() {
|
|
235
|
-
return { sent: this.sent, lastSeen: this.lastSeen };
|
|
236
|
-
}
|
|
237
|
-
restore(c) {
|
|
238
|
-
this.sent = c.sent;
|
|
239
|
-
this.lastSeen = c.lastSeen;
|
|
240
|
-
}
|
|
241
|
-
};
|
|
242
|
-
var isSealed = (x) => !!x && typeof x === "object" && "d" in x && "n" in x && "s" in x;
|
|
243
|
-
|
|
244
|
-
// src/pair.ts
|
|
245
|
-
var DEFAULT_KEY = "bwalletx.connect.pairing.v1";
|
|
246
|
-
var OPEN = 1;
|
|
247
|
-
function memoryStorage() {
|
|
248
|
-
const m = /* @__PURE__ */ new Map();
|
|
249
|
-
return { getItem: (k) => m.get(k) ?? null, setItem: (k, v) => void m.set(k, v), removeItem: (k) => void m.delete(k) };
|
|
250
|
-
}
|
|
251
|
-
function defaultStorage() {
|
|
252
|
-
try {
|
|
253
|
-
if (typeof localStorage !== "undefined") return localStorage;
|
|
254
|
-
} catch {
|
|
255
|
-
}
|
|
256
|
-
return memoryStorage();
|
|
257
|
-
}
|
|
258
|
-
function defaultSocket() {
|
|
259
|
-
return (url) => {
|
|
260
|
-
if (typeof WebSocket === "undefined") throw new Error("No WebSocket here. Pass options.socket.");
|
|
261
|
-
return new WebSocket(url);
|
|
262
|
-
};
|
|
263
|
-
}
|
|
264
|
-
function parseStored(raw) {
|
|
265
|
-
if (!raw) return null;
|
|
266
|
-
try {
|
|
267
|
-
const p = JSON.parse(raw);
|
|
268
|
-
const n = (x) => Number.isInteger(x) && x >= 0;
|
|
269
|
-
if (p.v !== 1) return null;
|
|
270
|
-
if (typeof p.c !== "string" || !/^[A-Za-z0-9_-]{22}$/.test(p.c)) return null;
|
|
271
|
-
if (typeof p.r !== "string" || !/^[a-z0-9.-]+(:\d+)?$/i.test(p.r)) return null;
|
|
272
|
-
if (typeof p.s !== "string" || !/^[0-9a-f]{64}$/i.test(p.s)) return null;
|
|
273
|
-
if (typeof p.k !== "string" || !/^0[23][0-9a-f]{64}$/i.test(p.k)) return null;
|
|
274
|
-
if (!n(p.sent) || !n(p.lastSeen) || !n(p.pairedAt)) return null;
|
|
275
|
-
if (p.sc !== void 0 && (typeof p.sc !== "string" || !/^[A-Za-z0-9_-]{22,64}$/.test(p.sc))) return null;
|
|
276
|
-
return p;
|
|
277
|
-
} catch {
|
|
278
|
-
return null;
|
|
279
|
-
}
|
|
280
|
-
}
|
|
281
|
-
var Link = class {
|
|
282
|
-
constructor(p, sealer, storage, key, socket, timeoutMs) {
|
|
283
|
-
this.p = p;
|
|
284
|
-
this.sealer = sealer;
|
|
285
|
-
this.storage = storage;
|
|
286
|
-
this.key = key;
|
|
287
|
-
this.socket = socket;
|
|
288
|
-
this.timeoutMs = timeoutMs;
|
|
289
|
-
}
|
|
290
|
-
p;
|
|
291
|
-
sealer;
|
|
292
|
-
storage;
|
|
293
|
-
key;
|
|
294
|
-
socket;
|
|
295
|
-
timeoutMs;
|
|
296
|
-
ws = null;
|
|
297
|
-
opening = null;
|
|
298
|
-
waiting = /* @__PURE__ */ new Map();
|
|
299
|
-
forgotten = false;
|
|
300
|
-
/** Take over a socket that is already open (the one pairing used). */
|
|
301
|
-
adopt(ws) {
|
|
302
|
-
this.ws = ws;
|
|
303
|
-
this.wire(ws);
|
|
304
|
-
}
|
|
305
|
-
wire(ws) {
|
|
306
|
-
ws.onmessage = inOrder((ev) => this.onFrame(String(ev.data)));
|
|
307
|
-
ws.onerror = null;
|
|
308
|
-
ws.onclose = () => {
|
|
309
|
-
if (this.ws === ws) this.ws = null;
|
|
310
|
-
this.failAll(new Error("The connection to bWalletX closed"));
|
|
311
|
-
};
|
|
312
|
-
}
|
|
313
|
-
persist() {
|
|
314
|
-
if (this.forgotten) return;
|
|
315
|
-
this.p = { ...this.p, ...this.sealer.counters };
|
|
316
|
-
void Promise.resolve(this.storage.setItem(this.key, JSON.stringify(this.p))).catch(() => {
|
|
317
|
-
});
|
|
318
|
-
}
|
|
319
|
-
failAll(e) {
|
|
320
|
-
for (const w of this.waiting.values()) {
|
|
321
|
-
clearTimeout(w.timer);
|
|
322
|
-
w.reject(e);
|
|
323
|
-
}
|
|
324
|
-
this.waiting.clear();
|
|
325
|
-
}
|
|
326
|
-
async ensure() {
|
|
327
|
-
if (this.forgotten) throw new Error("This pairing was removed. Pair again.");
|
|
328
|
-
if (this.ws && this.ws.readyState === OPEN) return;
|
|
329
|
-
this.opening ??= this.reopen().finally(() => this.opening = null);
|
|
330
|
-
await this.opening;
|
|
331
|
-
}
|
|
332
|
-
reopen() {
|
|
333
|
-
if (!this.p.sc) {
|
|
334
|
-
this.p = { ...this.p, sc: newClaim() };
|
|
335
|
-
this.persist();
|
|
336
|
-
}
|
|
337
|
-
const e = Math.floor(Date.now() / 1e3) + QR_LIFETIME_S - 10;
|
|
338
|
-
const ws = this.socket(relaySocketUrl(this.p.r, this.p.c, "site", e, this.p.sc));
|
|
339
|
-
return new Promise((resolve, reject) => {
|
|
340
|
-
ws.onopen = () => {
|
|
341
|
-
this.ws = ws;
|
|
342
|
-
this.wire(ws);
|
|
343
|
-
resolve();
|
|
344
|
-
};
|
|
345
|
-
ws.onerror = () => reject(new Error("Could not reach the bWalletX pairing service"));
|
|
346
|
-
ws.onclose = () => reject(new Error("Could not reach the bWalletX pairing service"));
|
|
347
|
-
});
|
|
348
|
-
}
|
|
349
|
-
async onFrame(raw) {
|
|
350
|
-
let f;
|
|
351
|
-
try {
|
|
352
|
-
f = JSON.parse(raw);
|
|
353
|
-
} catch {
|
|
354
|
-
return;
|
|
355
|
-
}
|
|
356
|
-
const t = f.t;
|
|
357
|
-
if (t === "relay" && f.error) {
|
|
358
|
-
return this.failAll(new Error(`bWalletX pairing service: ${f.error}`));
|
|
359
|
-
}
|
|
360
|
-
if (!isSealed(f)) return;
|
|
361
|
-
const msg = await this.sealer.open(f);
|
|
362
|
-
if (!msg) return;
|
|
363
|
-
this.persist();
|
|
364
|
-
if (msg.t === "res") {
|
|
365
|
-
const w = this.waiting.get(msg.id);
|
|
366
|
-
if (!w) return;
|
|
367
|
-
clearTimeout(w.timer);
|
|
368
|
-
this.waiting.delete(msg.id);
|
|
369
|
-
if (msg.error) w.reject(Object.assign(new Error(msg.error.message), { code: msg.error.code }));
|
|
370
|
-
else w.resolve(msg.result);
|
|
371
|
-
} else if (msg.t === "close") {
|
|
372
|
-
this.drop();
|
|
373
|
-
this.failAll(new Error("bWalletX disconnected this site. Pair again."));
|
|
374
|
-
}
|
|
375
|
-
}
|
|
376
|
-
async call(action, params) {
|
|
377
|
-
await this.ensure();
|
|
378
|
-
const ws = this.ws;
|
|
379
|
-
const id = `${action}-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
|
380
|
-
const result = new Promise((resolve, reject) => {
|
|
381
|
-
const timer = setTimeout(() => {
|
|
382
|
-
if (this.waiting.delete(id)) reject(new Error("No answer from bWalletX. Open it, unlocked, and approve."));
|
|
383
|
-
}, this.timeoutMs);
|
|
384
|
-
this.waiting.set(id, { resolve, reject, timer });
|
|
385
|
-
});
|
|
386
|
-
ws.send(JSON.stringify(await this.sealer.seal({ t: "req", id, action, params })));
|
|
387
|
-
this.persist();
|
|
388
|
-
return result;
|
|
389
|
-
}
|
|
390
|
-
close() {
|
|
391
|
-
const ws = this.ws;
|
|
392
|
-
this.ws = null;
|
|
393
|
-
ws?.close();
|
|
394
|
-
}
|
|
395
|
-
drop() {
|
|
396
|
-
this.forgotten = true;
|
|
397
|
-
void Promise.resolve(this.storage.removeItem(this.key)).catch(() => {
|
|
398
|
-
});
|
|
399
|
-
this.close();
|
|
400
|
-
}
|
|
401
|
-
async forget() {
|
|
402
|
-
if (this.forgotten) return;
|
|
403
|
-
try {
|
|
404
|
-
if (this.ws && this.ws.readyState === OPEN) {
|
|
405
|
-
this.ws.send(JSON.stringify(await this.sealer.seal({ t: "close", reason: "site unpaired" })));
|
|
406
|
-
}
|
|
407
|
-
} catch {
|
|
408
|
-
}
|
|
409
|
-
this.drop();
|
|
410
|
-
}
|
|
411
|
-
wallet() {
|
|
412
|
-
return new Proxy({}, {
|
|
413
|
-
get: (_t, method) => {
|
|
414
|
-
if (method === "close") return () => this.close();
|
|
415
|
-
if (method === "forget") return () => this.forget();
|
|
416
|
-
if (typeof method !== "string" || method === "then" || method === "toJSON") return void 0;
|
|
417
|
-
return (params) => this.call(method, params ?? {});
|
|
418
|
-
}
|
|
419
|
-
});
|
|
420
|
-
}
|
|
421
|
-
};
|
|
422
|
-
function pairBwalletX(opts) {
|
|
423
|
-
const storage = opts.storage === void 0 ? defaultStorage() : opts.storage ?? memoryStorage();
|
|
424
|
-
const key = opts.storageKey ?? DEFAULT_KEY;
|
|
425
|
-
const socket = opts.socket ?? defaultSocket();
|
|
426
|
-
const relay = opts.relay ?? DEFAULT_RELAY;
|
|
427
|
-
const origin = opts.origin ?? (typeof location !== "undefined" ? location.origin : "");
|
|
428
|
-
if (!origin) return Promise.reject(new Error("pairBwalletX needs options.origin outside a browser"));
|
|
429
|
-
const siteKey = PrivateKey2.fromRandom();
|
|
430
|
-
const channel = newChannel();
|
|
431
|
-
const expiry = Math.floor(Date.now() / 1e3) + QR_LIFETIME_S;
|
|
432
|
-
const siteClaim = newClaim();
|
|
433
|
-
const sitePub = siteKey.toPublicKey().toString();
|
|
434
|
-
return walletClaimFor(channel, sitePub).then(claimDigest).then((wc) => new Promise((resolve, reject) => {
|
|
435
|
-
if (opts.signal?.aborted) return reject(new Error("cancelled"));
|
|
436
|
-
let ws;
|
|
437
|
-
try {
|
|
438
|
-
ws = socket(relaySocketUrl(relay, channel, "site", expiry, siteClaim, wc));
|
|
439
|
-
} catch (e) {
|
|
440
|
-
return reject(e);
|
|
441
|
-
}
|
|
442
|
-
let sealer = null;
|
|
443
|
-
let walletKey = "";
|
|
444
|
-
let settled = false;
|
|
445
|
-
const fail = (e) => {
|
|
446
|
-
if (settled) return;
|
|
447
|
-
settled = true;
|
|
448
|
-
clearTimeout(timer);
|
|
449
|
-
ws.close();
|
|
450
|
-
reject(e);
|
|
451
|
-
};
|
|
452
|
-
const timer = setTimeout(() => fail(new Error("The pairing code expired. Show a new one.")), QR_LIFETIME_S * 1e3);
|
|
453
|
-
opts.signal?.addEventListener("abort", () => fail(new Error("cancelled")));
|
|
454
|
-
ws.onerror = () => fail(new Error("Could not reach the bWalletX pairing service"));
|
|
455
|
-
ws.onclose = () => fail(new Error("The connection to bWalletX closed before pairing finished"));
|
|
456
|
-
ws.onmessage = inOrder(async (ev) => {
|
|
457
|
-
if (settled) return;
|
|
458
|
-
let f;
|
|
459
|
-
try {
|
|
460
|
-
f = JSON.parse(String(ev.data));
|
|
461
|
-
} catch {
|
|
462
|
-
return;
|
|
463
|
-
}
|
|
464
|
-
if (f.t === "hello" && !sealer) {
|
|
465
|
-
walletKey = f.k;
|
|
466
|
-
const s = await deriveSession(siteKey, walletKey, channel);
|
|
467
|
-
sealer = new Sealer(s.key, "site");
|
|
468
|
-
opts.onCode(s.code);
|
|
469
|
-
return;
|
|
470
|
-
}
|
|
471
|
-
if (!sealer || !isSealed(f)) return;
|
|
472
|
-
const msg = await sealer.open(f);
|
|
473
|
-
if (!msg) return;
|
|
474
|
-
if (msg.t === "ready") {
|
|
475
|
-
settled = true;
|
|
476
|
-
clearTimeout(timer);
|
|
477
|
-
const p = { v: 1, c: channel, r: relay, s: siteKey.toHex(), k: walletKey, ...sealer.counters, pairedAt: Date.now(), sc: siteClaim };
|
|
478
|
-
await Promise.resolve(storage.setItem(key, JSON.stringify(p))).catch(() => {
|
|
479
|
-
});
|
|
480
|
-
const link = new Link(p, sealer, storage, key, socket, opts.callTimeoutMs ?? 12e4);
|
|
481
|
-
link.adopt(ws);
|
|
482
|
-
resolve(link.wallet());
|
|
483
|
-
} else if (msg.t === "close") {
|
|
484
|
-
fail(new Error("Pairing was declined in bWalletX"));
|
|
485
|
-
}
|
|
486
|
-
});
|
|
487
|
-
opts.onLink(pairUrl({ v: PAIR_VERSION, r: relay, c: channel, k: sitePub, o: origin, e: expiry }));
|
|
488
|
-
}));
|
|
489
|
-
}
|
|
490
|
-
async function restorePairing(opts = {}) {
|
|
491
|
-
const storage = opts.storage === void 0 ? defaultStorage() : opts.storage ?? memoryStorage();
|
|
492
|
-
const key = opts.storageKey ?? DEFAULT_KEY;
|
|
493
|
-
const p = parseStored(await Promise.resolve(storage.getItem(key)).catch(() => null));
|
|
494
|
-
if (!p) return null;
|
|
495
|
-
const { key: aes } = await deriveSession(PrivateKey2.fromHex(p.s), p.k, p.c);
|
|
496
|
-
const sealer = new Sealer(aes, "site");
|
|
497
|
-
sealer.restore({ sent: p.sent, lastSeen: p.lastSeen });
|
|
498
|
-
return new Link(p, sealer, storage, key, opts.socket ?? defaultSocket(), opts.callTimeoutMs ?? 12e4).wallet();
|
|
499
|
-
}
|
|
500
|
-
async function clearPairing(opts = {}) {
|
|
501
|
-
const storage = opts.storage === void 0 ? defaultStorage() : opts.storage ?? memoryStorage();
|
|
502
|
-
await Promise.resolve(storage.removeItem(opts.storageKey ?? DEFAULT_KEY)).catch(() => {
|
|
503
|
-
});
|
|
504
|
-
}
|
|
505
|
-
|
|
506
|
-
// src/signin.ts
|
|
507
|
-
var LOGIN_PROTOCOL = [2, "bwallet sign in"];
|
|
508
|
-
async function connectBwalletX(opts = {}) {
|
|
509
|
-
const status = (s) => {
|
|
510
|
-
try {
|
|
511
|
-
opts.onStatus?.(s);
|
|
512
|
-
} catch {
|
|
513
|
-
}
|
|
514
|
-
};
|
|
515
|
-
if (opts.wallet) {
|
|
516
|
-
status("opening");
|
|
517
|
-
return { wallet: opts.wallet, method: "wallet" };
|
|
518
|
-
}
|
|
519
|
-
status("finding");
|
|
520
|
-
const found = await discoverBwalletX(opts.discoverMs ?? DEFAULT_DISCOVER_MS);
|
|
521
|
-
if (found) {
|
|
522
|
-
status("opening");
|
|
523
|
-
return { wallet: found.wallet, method: found.method };
|
|
524
|
-
}
|
|
525
|
-
if (opts.reusePairing !== false) {
|
|
526
|
-
const restored = await restorePairing(opts.pairing ?? {});
|
|
527
|
-
if (restored) {
|
|
528
|
-
status("opening");
|
|
529
|
-
return { wallet: restored, method: "pairing" };
|
|
530
|
-
}
|
|
531
|
-
}
|
|
532
|
-
if (!opts.pairing) {
|
|
533
|
-
throw Object.assign(new Error("bWalletX was not found in this browser"), { code: "NOT_FOUND" });
|
|
534
|
-
}
|
|
535
|
-
status("pairing");
|
|
536
|
-
return { wallet: await pairBwalletX(opts.pairing), method: "pairing" };
|
|
537
|
-
}
|
|
538
|
-
async function signInWithBwalletX(opts) {
|
|
539
|
-
const { wallet, method } = await connectBwalletX(opts);
|
|
540
|
-
if (method !== "pairing") await wallet.waitForAuthentication({}).catch(() => {
|
|
541
|
-
});
|
|
542
|
-
const { publicKey: identityKey } = await atStage("identity", () => wallet.getPublicKey({ identityKey: true }));
|
|
543
|
-
try {
|
|
544
|
-
opts.onStatus?.("signing");
|
|
545
|
-
} catch {
|
|
546
|
-
}
|
|
547
|
-
const c = await atStage("challenge", () => opts.challenge(identityKey));
|
|
548
|
-
const { signature } = await atStage(
|
|
549
|
-
"signature",
|
|
550
|
-
() => wallet.createSignature({
|
|
551
|
-
protocolID: c.protocolID ?? LOGIN_PROTOCOL,
|
|
552
|
-
keyID: c.keyID,
|
|
553
|
-
counterparty: "anyone",
|
|
554
|
-
data: Array.from(new TextEncoder().encode(c.message))
|
|
555
|
-
})
|
|
556
|
-
);
|
|
557
|
-
return { identityKey, signature: Array.from(signature), nonce: c.nonce, method, wallet };
|
|
558
|
-
}
|
|
559
|
-
async function atStage(stage, run) {
|
|
560
|
-
try {
|
|
561
|
-
return await run();
|
|
562
|
-
} catch (e) {
|
|
563
|
-
const err = e instanceof Error ? e : new Error(String(e));
|
|
564
|
-
if (!err.stage) Object.assign(err, { stage });
|
|
565
|
-
throw err;
|
|
566
|
-
}
|
|
567
|
-
}
|
|
568
|
-
|
|
569
|
-
// src/access-client.ts
|
|
570
|
-
import { Hash, PublicKey as PublicKey2, Utils } from "@bsv/sdk";
|
|
571
|
-
var ONESAT = [0, "onesat"];
|
|
572
|
-
var LEGACY_ONESAT = [0, "p 1sat"];
|
|
573
|
-
function toAccessError(e) {
|
|
574
|
-
if (e instanceof AccessError) return e;
|
|
575
|
-
const err = e;
|
|
576
|
-
const msg = String(err?.message ?? e ?? "");
|
|
577
|
-
if (err?.code === "NOT_FOUND") return new AccessError("not_installed", msg);
|
|
578
|
-
if (/reject|denied|declin|cancel|user/i.test(msg) || err?.code === "ERR_USER_REJECTED" || err?.status === 4001) {
|
|
579
|
-
return new AccessError("user_rejected", msg);
|
|
580
|
-
}
|
|
581
|
-
return new AccessError("bad_request", msg || "access failed");
|
|
582
|
-
}
|
|
583
|
-
function throwIfAccessError(body) {
|
|
584
|
-
const b = body;
|
|
585
|
-
if (b && typeof b.error === "string") throw new AccessError(b.error, b.message, { have: b.have, need: b.need });
|
|
586
|
-
}
|
|
587
|
-
function hash160FromP2pkh(script) {
|
|
588
|
-
const m = /^76a914([0-9a-f]{40})88ac$/i.exec(script.slice(-50));
|
|
589
|
-
return m ? m[1].toLowerCase() : null;
|
|
590
|
-
}
|
|
591
|
-
async function proveHoldings(wallet, challenge, tokenId, basket = "bsv21") {
|
|
592
|
-
const bare = tokenId.replace(/^bsv21:/, "");
|
|
593
|
-
const list = await wallet.listOutputs({ basket, include: "locking scripts", includeCustomInstructions: true, limit: 1e4 });
|
|
594
|
-
const byKey = /* @__PURE__ */ new Map();
|
|
595
|
-
const data = challengeBytes(challenge);
|
|
596
|
-
for (const out of list.outputs) {
|
|
597
|
-
if (byKey.size >= MAX_HOLDING_PROOFS) break;
|
|
598
|
-
let ci = {};
|
|
599
|
-
try {
|
|
600
|
-
ci = JSON.parse(out.customInstructions ?? "{}");
|
|
601
|
-
} catch {
|
|
602
|
-
continue;
|
|
603
|
-
}
|
|
604
|
-
if (ci.id !== bare || !ci.keyID) continue;
|
|
605
|
-
const want = out.lockingScript ? hash160FromP2pkh(out.lockingScript) : null;
|
|
606
|
-
const counterparty = ci.counterparty ?? "self";
|
|
607
|
-
for (const protocolID of ci.protocolID ? [ci.protocolID] : [ONESAT, LEGACY_ONESAT]) {
|
|
608
|
-
const { publicKey } = await wallet.getPublicKey({ protocolID, keyID: ci.keyID, counterparty });
|
|
609
|
-
const h = Utils.toHex(Hash.hash160(PublicKey2.fromString(publicKey).encode(true)));
|
|
610
|
-
if (want && h !== want) continue;
|
|
611
|
-
const existing = byKey.get(publicKey);
|
|
612
|
-
if (existing) {
|
|
613
|
-
existing.outpoints.push(out.outpoint.replace(".", "_"));
|
|
614
|
-
break;
|
|
615
|
-
}
|
|
616
|
-
const { signature } = await wallet.createSignature({ protocolID, keyID: ci.keyID, counterparty, data });
|
|
617
|
-
byKey.set(publicKey, { pubkey: publicKey, signature: Array.from(signature), outpoints: [out.outpoint.replace(".", "_")] });
|
|
618
|
-
break;
|
|
619
|
-
}
|
|
620
|
-
}
|
|
621
|
-
return [...byKey.values()];
|
|
622
|
-
}
|
|
623
|
-
async function requestAccess(o) {
|
|
624
|
-
let wallet;
|
|
625
|
-
try {
|
|
626
|
-
({ wallet } = await connectBwalletX({ wallet: o.wallet, pairing: o.pairing, discoverMs: o.discoverMs }));
|
|
627
|
-
} catch (e) {
|
|
628
|
-
throw e?.code === "NOT_FOUND" ? new AccessError("not_installed") : toAccessError(e);
|
|
629
|
-
}
|
|
630
|
-
try {
|
|
631
|
-
const { publicKey: identityKey } = await wallet.getPublicKey({ identityKey: true });
|
|
632
|
-
const { challenge } = await o.challenge(identityKey);
|
|
633
|
-
const c = parseAccessChallenge(challenge);
|
|
634
|
-
if (c.sub && c.sub !== identityKey.toLowerCase()) throw new AccessError("wrong_account");
|
|
635
|
-
if (Date.now() / 1e3 >= c.exp) throw new AccessError("expired");
|
|
636
|
-
const { signature } = await wallet.createSignature({
|
|
637
|
-
protocolID: ACCESS_PROTOCOL,
|
|
638
|
-
keyID: c.nonce,
|
|
639
|
-
counterparty: "anyone",
|
|
640
|
-
data: challengeBytes(challenge)
|
|
641
|
-
});
|
|
642
|
-
const response = { v: 1, challenge, identityKey, signature: Array.from(signature) };
|
|
643
|
-
if (c.require.token) response.holdings = await proveHoldings(wallet, challenge, c.require.token.id, o.tokenBasket);
|
|
644
|
-
let verified;
|
|
645
|
-
if (o.verify) {
|
|
646
|
-
verified = await o.verify(response);
|
|
647
|
-
throwIfAccessError(verified);
|
|
648
|
-
}
|
|
649
|
-
return { response, verified, wallet };
|
|
650
|
-
} catch (e) {
|
|
651
|
-
throw toAccessError(e);
|
|
652
|
-
}
|
|
653
|
-
}
|
|
654
|
-
|
|
655
|
-
// src/element.ts
|
|
656
|
-
var SIGNIN_TAG = "bwalletx-signin";
|
|
657
|
-
var GET_URL = "https://bwalletx.com/get";
|
|
658
|
-
var WEB_WALLET_URL = "https://web.bwalletx.com";
|
|
659
|
-
var VERBS = { signin: "Sign in with", continue: "Continue with", connect: "Connect" };
|
|
660
|
-
function signinText(label = "signin", brand = "bWalletX") {
|
|
661
|
-
return `${VERBS[label] ?? VERBS.signin} ${brand}`;
|
|
662
|
-
}
|
|
663
|
-
var uid = 0;
|
|
664
|
-
function markSvg(px = 20) {
|
|
665
|
-
const n = ++uid;
|
|
666
|
-
return `<svg viewBox="23 8 74 100" width="${Math.round(px * 0.74)}" height="${px}" aria-hidden="true" focusable="false"><defs><linearGradient id="bwxg${n}" gradientUnits="userSpaceOnUse" x1="0" y1="12" x2="0" y2="105"><stop offset="0" stop-color="#FFE58A"/><stop offset=".55" stop-color="#FFD24D"/><stop offset="1" stop-color="#C98F00"/></linearGradient><mask id="bwxh${n}"><rect width="140" height="140" fill="#fff"/><circle cx="60" cy="72" r="15" fill="#000"/></mask></defs><g fill="url(#bwxg${n})" mask="url(#bwxh${n})"><polygon points="45,12 45,76 27,76 27,30"/><circle cx="60" cy="72" r="33"/></g></svg>`;
|
|
667
|
-
}
|
|
668
|
-
var SIGNIN_CSS = `
|
|
669
|
-
:host{display:inline-block;vertical-align:middle;font-family:Inter,ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
|
|
670
|
-
:host([full-width]){display:block;width:100%}
|
|
671
|
-
:host([hidden]){display:none}
|
|
672
|
-
button{all:unset;box-sizing:border-box;display:inline-flex;align-items:center;justify-content:center;gap:12px;width:100%;cursor:pointer;
|
|
673
|
-
padding:16px 20px;border-radius:12px;font-size:16px;font-weight:700;line-height:1.2;text-align:left;
|
|
674
|
-
background:linear-gradient(180deg,#fcd34d,#f59e0b);color:#000;
|
|
675
|
-
box-shadow:0 10px 15px -3px rgba(245,158,11,.2),0 4px 6px -4px rgba(245,158,11,.2);
|
|
676
|
-
transition:background .15s,transform .1s,box-shadow .15s,border-color .15s;-webkit-tap-highlight-color:transparent}
|
|
677
|
-
button:hover{background:linear-gradient(180deg,#fde68a,#fbbf24)}
|
|
678
|
-
button:active{transform:translateY(1px);background:linear-gradient(180deg,#fbbf24,#d97706)}
|
|
679
|
-
button:focus-visible{outline:2px solid #b45309;outline-offset:3px}
|
|
680
|
-
button:disabled{opacity:.6;cursor:not-allowed;transform:none}
|
|
681
|
-
button[aria-busy=true]{cursor:wait}
|
|
682
|
-
.mark{display:inline-flex;align-items:center;justify-content:center;flex:none;width:28px;height:28px;border-radius:50%;background:#000}
|
|
683
|
-
.txt{display:flex;flex-direction:column;align-items:flex-start;min-width:0}
|
|
684
|
-
.txt b{font-weight:700;white-space:nowrap}
|
|
685
|
-
.txt small{font-size:11px;font-weight:500;color:rgba(0,0,0,.65);white-space:nowrap}
|
|
686
|
-
.spin{width:16px;height:16px;border-radius:50%;border:2px solid rgba(255,210,77,.35);border-top-color:#ffd24d;animation:r .8s linear infinite}
|
|
687
|
-
@keyframes r{to{transform:rotate(360deg)}}
|
|
688
|
-
@media (prefers-reduced-motion:reduce){button{transition:none}button:active{transform:none}.spin{animation:none;border-color:#ffd24d;border-right-color:transparent}}
|
|
689
|
-
/* sizes */
|
|
690
|
-
:host([size=md]) button{padding:10px 16px;border-radius:10px;font-size:15px;gap:10px}
|
|
691
|
-
:host([size=md]) .mark{width:24px;height:24px}
|
|
692
|
-
:host([size=md]) .txt small{font-size:10.5px}
|
|
693
|
-
:host([size=sm]) button{padding:6px 12px 6px 6px;border-radius:8px;font-size:13px;gap:8px;min-height:36px}
|
|
694
|
-
:host([size=sm]) .mark{width:22px;height:22px}
|
|
695
|
-
:host([size=icon]) button{width:48px;height:48px;padding:0;border-radius:50%;gap:0}
|
|
696
|
-
:host([size=icon]) .mark{width:34px;height:34px}
|
|
697
|
-
/* themes */
|
|
698
|
-
:host([theme=dark]) button{background:#0a0a0a;color:#fafafa;border:1px solid #3f3f46;box-shadow:none}
|
|
699
|
-
:host([theme=dark]) button:hover{background:#18181b;border-color:rgba(251,191,36,.6)}
|
|
700
|
-
:host([theme=dark]) button:active{background:#000}
|
|
701
|
-
:host([theme=dark]) button:focus-visible{outline-color:#fcd34d}
|
|
702
|
-
:host([theme=dark]) .mark{box-shadow:inset 0 0 0 1px #3f3f46}
|
|
703
|
-
:host([theme=dark]) .txt small{color:rgba(255,255,255,.65)}
|
|
704
|
-
:host([theme=light]) button{background:#fff;color:#09090b;border:1px solid #d4d4d8;box-shadow:0 1px 2px rgba(0,0,0,.06)}
|
|
705
|
-
:host([theme=light]) button:hover{background:#fafafa;border-color:#f59e0b}
|
|
706
|
-
:host([theme=light]) button:active{background:#f4f4f5}
|
|
707
|
-
:host([theme=light]) .txt small{color:#52525b}
|
|
708
|
-
/* not found */
|
|
709
|
-
.nf{margin-top:8px;font-size:12px;line-height:1.4;color:#71717a;text-align:center}
|
|
710
|
-
.nf a{color:inherit;font-weight:600;text-decoration:underline;text-underline-offset:2px}
|
|
711
|
-
.nf a:focus-visible{outline:2px solid #b45309;outline-offset:2px;border-radius:2px}
|
|
712
|
-
:host([theme=dark]) .nf,:host-context(.dark) .nf{color:#a1a1aa}
|
|
713
|
-
.sr{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}
|
|
714
|
-
`;
|
|
715
|
-
function b64url2(bytes) {
|
|
716
|
-
let s = "";
|
|
717
|
-
for (const b of bytes) s += String.fromCharCode(b);
|
|
718
|
-
return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
719
|
-
}
|
|
720
|
-
async function buildAuthorizeUrl(p) {
|
|
721
|
-
const rnd = (n) => b64url2(crypto.getRandomValues(new Uint8Array(n)));
|
|
722
|
-
const verifier = rnd(32);
|
|
723
|
-
const state = rnd(16);
|
|
724
|
-
const nonce = rnd(16);
|
|
725
|
-
const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier)));
|
|
726
|
-
const u = new URL(p.authorizeUrl, typeof location !== "undefined" ? location.href : void 0);
|
|
727
|
-
const set = (k, v) => {
|
|
728
|
-
if (v) u.searchParams.set(k, v);
|
|
729
|
-
};
|
|
730
|
-
set("response_type", "code");
|
|
731
|
-
set("client_id", p.clientId);
|
|
732
|
-
set("redirect_uri", p.redirectUri);
|
|
733
|
-
set("scope", p.scope || "openid profile");
|
|
734
|
-
set("state", state);
|
|
735
|
-
set("nonce", nonce);
|
|
736
|
-
set("code_challenge", b64url2(digest));
|
|
737
|
-
set("code_challenge_method", "S256");
|
|
738
|
-
try {
|
|
739
|
-
sessionStorage.setItem("bwalletx:oauth", JSON.stringify({ verifier, state, nonce }));
|
|
740
|
-
} catch {
|
|
741
|
-
}
|
|
742
|
-
return u.toString();
|
|
743
|
-
}
|
|
744
|
-
async function postJson(url, body) {
|
|
745
|
-
const res = await fetch(url, { method: "POST", credentials: "include", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
|
|
746
|
-
const data = await res.json().catch(() => ({}));
|
|
747
|
-
if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`);
|
|
748
|
-
return data;
|
|
749
|
-
}
|
|
750
|
-
async function postAccess(url, body) {
|
|
751
|
-
const res = await fetch(url, { method: "POST", credentials: "include", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
|
|
752
|
-
return res.json().catch(() => ({ error: "bad_request", message: `HTTP ${res.status}` }));
|
|
753
|
-
}
|
|
754
|
-
var OBSERVED = ["size", "theme", "label", "brand", "subtitle", "loading", "disabled", "full-width", "aria-label", "get-url", "web-url"];
|
|
755
|
-
function createClass() {
|
|
756
|
-
return class BwalletxSigninElement extends HTMLElement {
|
|
757
|
-
static get observedAttributes() {
|
|
758
|
-
return OBSERVED;
|
|
759
|
-
}
|
|
760
|
-
#root;
|
|
761
|
-
#notFound = false;
|
|
762
|
-
#busy = false;
|
|
763
|
-
constructor() {
|
|
764
|
-
super();
|
|
765
|
-
this.#root = this.attachShadow({ mode: "open" });
|
|
766
|
-
}
|
|
767
|
-
connectedCallback() {
|
|
768
|
-
this.#render();
|
|
769
|
-
}
|
|
770
|
-
attributeChangedCallback() {
|
|
771
|
-
if (this.isConnected) this.#render();
|
|
772
|
-
}
|
|
773
|
-
/** The inner <button>, for focus() and tests. */
|
|
774
|
-
get button() {
|
|
775
|
-
return this.#root.querySelector("button");
|
|
776
|
-
}
|
|
777
|
-
get notFound() {
|
|
778
|
-
return this.#notFound;
|
|
779
|
-
}
|
|
780
|
-
focus(opts) {
|
|
781
|
-
this.button?.focus(opts);
|
|
782
|
-
}
|
|
783
|
-
#attr(name) {
|
|
784
|
-
return this.getAttribute(name);
|
|
785
|
-
}
|
|
786
|
-
#render() {
|
|
787
|
-
const size = this.#attr("size") ?? "lg";
|
|
788
|
-
const brand = this.#attr("brand") === "bWallet" ? "bWallet" : "bWalletX";
|
|
789
|
-
const text = signinText(this.#attr("label") ?? "signin", brand);
|
|
790
|
-
const subAttr = this.#attr("subtitle");
|
|
791
|
-
const subDefault = brand === "bWalletX" && (size === "lg" || size === "md") ? "also works with bWallet" : null;
|
|
792
|
-
const subtitle = subAttr === null || subAttr === "" || subAttr === "on" ? subAttr === "on" ? "also works with bWallet" : subDefault : subAttr === "off" ? null : subAttr;
|
|
793
|
-
const loading = this.hasAttribute("loading") || this.#busy;
|
|
794
|
-
const disabled = this.hasAttribute("disabled");
|
|
795
|
-
const markPx = size === "icon" ? 24 : size === "sm" ? 15 : size === "md" ? 17 : 20;
|
|
796
|
-
const aria = this.#attr("aria-label") ?? (subtitle && size !== "icon" ? `${text}, ${subtitle}` : text);
|
|
797
|
-
const getUrl = this.#attr("get-url") ?? GET_URL;
|
|
798
|
-
const webUrl = this.#attr("web-url") ?? WEB_WALLET_URL;
|
|
799
|
-
const esc = (s) => s.replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]);
|
|
800
|
-
const label = size === "icon" ? "" : `<span class="txt" part="text"><b part="label">${esc(text)}</b>${subtitle ? `<small part="subtitle">${esc(subtitle)}</small>` : ""}</span>`;
|
|
801
|
-
const mark = loading ? '<span class="spin" aria-hidden="true"></span>' : markSvg(markPx);
|
|
802
|
-
const nf = this.#notFound ? `<p class="nf" part="not-found" role="status">bWalletX wasn't found in this browser. <a href="${esc(getUrl)}" target="_blank" rel="noopener">Get ${brand}</a> or <a href="${esc(webUrl)}" target="_blank" rel="noopener">use the web wallet</a>.</p>` : "";
|
|
803
|
-
this.#root.innerHTML = `<style>${SIGNIN_CSS}</style><button type="button" part="button" aria-label="${esc(aria)}" title="${esc(subtitle ? `${text} (${subtitle})` : text)}"${disabled ? " disabled" : ""}${loading ? ' aria-busy="true"' : ""}><span class="mark" part="mark">${mark}</span>${label}</button>${loading ? '<span class="sr" role="status">Connecting to bWalletX\u2026</span>' : ""}${nf}`;
|
|
804
|
-
this.button.addEventListener("click", () => void this.#click());
|
|
805
|
-
bindPrewarm(this.button);
|
|
806
|
-
}
|
|
807
|
-
#emit(type, detail, cancelable = false) {
|
|
808
|
-
return this.dispatchEvent(new CustomEvent(type, { detail, bubbles: true, composed: true, cancelable }));
|
|
809
|
-
}
|
|
810
|
-
#setBusy(on) {
|
|
811
|
-
this.#busy = on;
|
|
812
|
-
this.#render();
|
|
813
|
-
}
|
|
814
|
-
async #click() {
|
|
815
|
-
if (this.hasAttribute("disabled") || this.hasAttribute("loading") || this.#busy) return;
|
|
816
|
-
if (!this.#emit("bwalletx-signin", { element: this }, true)) return;
|
|
817
|
-
const href = this.#attr("href");
|
|
818
|
-
const authorizeUrl = this.#attr("authorize-url");
|
|
819
|
-
if (authorizeUrl) {
|
|
820
|
-
location.assign(await buildAuthorizeUrl({ authorizeUrl, clientId: this.#attr("client-id"), redirectUri: this.#attr("redirect-uri"), scope: this.#attr("scope") }));
|
|
821
|
-
return;
|
|
822
|
-
}
|
|
823
|
-
if (href) {
|
|
824
|
-
location.assign(href);
|
|
825
|
-
return;
|
|
826
|
-
}
|
|
827
|
-
const challengeUrl = this.#attr("challenge-url");
|
|
828
|
-
if (!challengeUrl) return;
|
|
829
|
-
this.#notFound = false;
|
|
830
|
-
this.#setBusy(true);
|
|
831
|
-
try {
|
|
832
|
-
const ms = Number(this.#attr("discover-ms")) || DEFAULT_DISCOVER_MS;
|
|
833
|
-
const found = await discoverBwalletX(ms);
|
|
834
|
-
if (!found) {
|
|
835
|
-
this.#notFound = true;
|
|
836
|
-
this.#emit("bwalletx-not-found");
|
|
837
|
-
if (this.#attr("require-token")) this.#emit("bwalletx-access-denied", { code: "not_installed", message: "No wallet found" });
|
|
838
|
-
return;
|
|
839
|
-
}
|
|
840
|
-
const requireToken = this.#attr("require-token");
|
|
841
|
-
if (requireToken) {
|
|
842
|
-
const verifyUrl2 = this.#attr("verify-url");
|
|
843
|
-
const min = this.#attr("min");
|
|
844
|
-
const minBps = this.#attr("min-bps");
|
|
845
|
-
const hint = { token: { id: requireToken, ...minBps ? { minBps: Number(minBps) } : { min: min ?? "1" } } };
|
|
846
|
-
try {
|
|
847
|
-
const a = await requestAccess({
|
|
848
|
-
wallet: found.wallet,
|
|
849
|
-
challenge: (identityKey) => postJson(challengeUrl, { identityKey, require: hint }),
|
|
850
|
-
verify: verifyUrl2 ? (response2) => postAccess(verifyUrl2, response2) : void 0
|
|
851
|
-
});
|
|
852
|
-
this.#emit("bwalletx-access-granted", { identityKey: a.response.identityKey, response: a.verified });
|
|
853
|
-
} catch (e) {
|
|
854
|
-
const err = e instanceof AccessError ? e : new AccessError("bad_request", String(e));
|
|
855
|
-
this.#emit("bwalletx-access-denied", { code: err.code, message: err.message, have: err.have, need: err.need });
|
|
856
|
-
}
|
|
857
|
-
return;
|
|
858
|
-
}
|
|
859
|
-
const r = await signInWithBwalletX({ wallet: found.wallet, challenge: (identityKey) => postJson(challengeUrl, { identityKey }) });
|
|
860
|
-
const verifyUrl = this.#attr("verify-url");
|
|
861
|
-
const response = verifyUrl ? await postJson(verifyUrl, { identityKey: r.identityKey, nonce: r.nonce, signature: r.signature }) : null;
|
|
862
|
-
this.#emit("bwalletx-signed-in", { identityKey: r.identityKey, method: found.method, nonce: r.nonce, signature: r.signature, response });
|
|
863
|
-
} catch (error) {
|
|
864
|
-
this.#emit("bwalletx-error", { error });
|
|
865
|
-
} finally {
|
|
866
|
-
this.#setBusy(false);
|
|
867
|
-
}
|
|
868
|
-
}
|
|
869
|
-
};
|
|
870
|
-
}
|
|
871
|
-
function defineBwalletxSignin(tag = SIGNIN_TAG) {
|
|
872
|
-
if (typeof window === "undefined" || typeof customElements === "undefined") return void 0;
|
|
873
|
-
const existing = customElements.get(tag);
|
|
874
|
-
if (existing) return existing;
|
|
875
|
-
const C = createClass();
|
|
876
|
-
customElements.define(tag, C);
|
|
877
|
-
return C;
|
|
878
|
-
}
|
|
879
|
-
|
|
880
|
-
export {
|
|
881
|
-
RDNS_EXTENSION,
|
|
882
|
-
RDNS_MOBILE,
|
|
883
|
-
BWALLETX_RDNS,
|
|
884
|
-
DEFAULT_DISCOVER_MS,
|
|
885
|
-
discoverBwalletX,
|
|
886
|
-
findBwalletX,
|
|
887
|
-
prewarmBwalletX,
|
|
888
|
-
bindPrewarm,
|
|
889
|
-
inOrder,
|
|
890
|
-
pairBwalletX,
|
|
891
|
-
restorePairing,
|
|
892
|
-
clearPairing,
|
|
893
|
-
LOGIN_PROTOCOL,
|
|
894
|
-
connectBwalletX,
|
|
895
|
-
signInWithBwalletX,
|
|
896
|
-
atStage,
|
|
897
|
-
toAccessError,
|
|
898
|
-
throwIfAccessError,
|
|
899
|
-
proveHoldings,
|
|
900
|
-
requestAccess,
|
|
901
|
-
SIGNIN_TAG,
|
|
902
|
-
GET_URL,
|
|
903
|
-
WEB_WALLET_URL,
|
|
904
|
-
signinText,
|
|
905
|
-
markSvg,
|
|
906
|
-
SIGNIN_CSS,
|
|
907
|
-
buildAuthorizeUrl,
|
|
908
|
-
defineBwalletxSignin
|
|
909
|
-
};
|
|
910
|
-
//# sourceMappingURL=chunk-EXRQJTXF.js.map
|