@bwalletx/connect 0.3.0 → 0.5.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 +34 -0
- package/README.md +145 -4
- package/assets/protocol/401.jpg +0 -0
- package/assets/protocol/401.mp4 +0 -0
- package/assets/protocol/402.jpg +0 -0
- package/assets/protocol/402.mp4 +0 -0
- package/assets/protocol/403.jpg +0 -0
- package/assets/protocol/403.mp4 +0 -0
- package/dist/access-Z6xQwKVF.d.cts +118 -0
- package/dist/access-Z6xQwKVF.d.ts +118 -0
- package/dist/bwalletx-connect.global.js +41 -3
- package/dist/bwalletx-connect.global.js.map +1 -1
- package/dist/{chunk-NNMUSWPG.js → chunk-CVLXFNAG.js} +123 -1
- package/dist/chunk-CVLXFNAG.js.map +1 -0
- package/dist/chunk-GF6GUDZL.js +404 -0
- package/dist/chunk-GF6GUDZL.js.map +1 -0
- package/dist/chunk-MWD4BCO5.js +182 -0
- package/dist/chunk-MWD4BCO5.js.map +1 -0
- package/dist/chunk-QRXFL66W.js +652 -0
- package/dist/chunk-QRXFL66W.js.map +1 -0
- package/dist/element.cjs +209 -0
- package/dist/element.cjs.map +1 -1
- package/dist/element.js +2 -1
- package/dist/element.js.map +1 -1
- package/dist/index.cjs +706 -5
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +66 -62
- package/dist/index.d.ts +66 -62
- package/dist/index.js +63 -3
- package/dist/index.js.map +1 -1
- package/dist/next.cjs +783 -0
- package/dist/next.cjs.map +1 -0
- package/dist/next.d.cts +98 -0
- package/dist/next.d.ts +98 -0
- package/dist/next.js +198 -0
- package/dist/next.js.map +1 -0
- package/dist/react.cjs +795 -36
- package/dist/react.cjs.map +1 -1
- package/dist/react.d.cts +74 -28
- package/dist/react.d.ts +74 -28
- package/dist/react.js +177 -4
- package/dist/react.js.map +1 -1
- package/dist/server.cjs +742 -10
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.cts +314 -2
- package/dist/server.d.ts +314 -2
- package/dist/server.js +82 -107
- package/dist/server.js.map +1 -1
- package/dist/wallets-VOKIKBbO.d.cts +250 -0
- package/dist/wallets-VOKIKBbO.d.ts +250 -0
- package/package.json +32 -6
- package/dist/chunk-NNMUSWPG.js.map +0 -1
|
@@ -1,3 +1,11 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ACCESS_PROTOCOL,
|
|
3
|
+
AccessError,
|
|
4
|
+
MAX_HOLDING_PROOFS,
|
|
5
|
+
challengeBytes,
|
|
6
|
+
parseAccessChallenge
|
|
7
|
+
} from "./chunk-MWD4BCO5.js";
|
|
8
|
+
|
|
1
9
|
// src/discover.ts
|
|
2
10
|
var RDNS_EXTENSION = "com.bwalletx.extension";
|
|
3
11
|
var RDNS_MOBILE = "space.bwallet.mobile";
|
|
@@ -424,6 +432,92 @@ async function signInWithBwalletX(opts) {
|
|
|
424
432
|
return { identityKey, signature: Array.from(signature), nonce: c.nonce, method, wallet };
|
|
425
433
|
}
|
|
426
434
|
|
|
435
|
+
// src/access-client.ts
|
|
436
|
+
import { Hash, PublicKey as PublicKey2, Utils } from "@bsv/sdk";
|
|
437
|
+
var ONESAT = [0, "onesat"];
|
|
438
|
+
var LEGACY_ONESAT = [0, "p 1sat"];
|
|
439
|
+
function toAccessError(e) {
|
|
440
|
+
if (e instanceof AccessError) return e;
|
|
441
|
+
const err = e;
|
|
442
|
+
const msg = String(err?.message ?? e ?? "");
|
|
443
|
+
if (err?.code === "NOT_FOUND") return new AccessError("not_installed", msg);
|
|
444
|
+
if (/reject|denied|declin|cancel|user/i.test(msg) || err?.code === "ERR_USER_REJECTED" || err?.status === 4001) {
|
|
445
|
+
return new AccessError("user_rejected", msg);
|
|
446
|
+
}
|
|
447
|
+
return new AccessError("bad_request", msg || "access failed");
|
|
448
|
+
}
|
|
449
|
+
function throwIfAccessError(body) {
|
|
450
|
+
const b = body;
|
|
451
|
+
if (b && typeof b.error === "string") throw new AccessError(b.error, b.message, { have: b.have, need: b.need });
|
|
452
|
+
}
|
|
453
|
+
function hash160FromP2pkh(script) {
|
|
454
|
+
const m = /^76a914([0-9a-f]{40})88ac$/i.exec(script.slice(-50));
|
|
455
|
+
return m ? m[1].toLowerCase() : null;
|
|
456
|
+
}
|
|
457
|
+
async function proveHoldings(wallet, challenge, tokenId, basket = "bsv21") {
|
|
458
|
+
const bare = tokenId.replace(/^bsv21:/, "");
|
|
459
|
+
const list = await wallet.listOutputs({ basket, include: "locking scripts", includeCustomInstructions: true, limit: 1e4 });
|
|
460
|
+
const byKey = /* @__PURE__ */ new Map();
|
|
461
|
+
const data = challengeBytes(challenge);
|
|
462
|
+
for (const out of list.outputs) {
|
|
463
|
+
if (byKey.size >= MAX_HOLDING_PROOFS) break;
|
|
464
|
+
let ci = {};
|
|
465
|
+
try {
|
|
466
|
+
ci = JSON.parse(out.customInstructions ?? "{}");
|
|
467
|
+
} catch {
|
|
468
|
+
continue;
|
|
469
|
+
}
|
|
470
|
+
if (ci.id !== bare || !ci.keyID) continue;
|
|
471
|
+
const want = out.lockingScript ? hash160FromP2pkh(out.lockingScript) : null;
|
|
472
|
+
const counterparty = ci.counterparty ?? "self";
|
|
473
|
+
for (const protocolID of ci.protocolID ? [ci.protocolID] : [ONESAT, LEGACY_ONESAT]) {
|
|
474
|
+
const { publicKey } = await wallet.getPublicKey({ protocolID, keyID: ci.keyID, counterparty });
|
|
475
|
+
const h = Utils.toHex(Hash.hash160(PublicKey2.fromString(publicKey).encode(true)));
|
|
476
|
+
if (want && h !== want) continue;
|
|
477
|
+
const existing = byKey.get(publicKey);
|
|
478
|
+
if (existing) {
|
|
479
|
+
existing.outpoints.push(out.outpoint.replace(".", "_"));
|
|
480
|
+
break;
|
|
481
|
+
}
|
|
482
|
+
const { signature } = await wallet.createSignature({ protocolID, keyID: ci.keyID, counterparty, data });
|
|
483
|
+
byKey.set(publicKey, { pubkey: publicKey, signature: Array.from(signature), outpoints: [out.outpoint.replace(".", "_")] });
|
|
484
|
+
break;
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
return [...byKey.values()];
|
|
488
|
+
}
|
|
489
|
+
async function requestAccess(o) {
|
|
490
|
+
let wallet;
|
|
491
|
+
try {
|
|
492
|
+
({ wallet } = await connectBwalletX({ wallet: o.wallet, pairing: o.pairing, discoverMs: o.discoverMs }));
|
|
493
|
+
} catch (e) {
|
|
494
|
+
throw e?.code === "NOT_FOUND" ? new AccessError("not_installed") : toAccessError(e);
|
|
495
|
+
}
|
|
496
|
+
try {
|
|
497
|
+
const { publicKey: identityKey } = await wallet.getPublicKey({ identityKey: true });
|
|
498
|
+
const { challenge } = await o.challenge(identityKey);
|
|
499
|
+
const c = parseAccessChallenge(challenge);
|
|
500
|
+
if (c.sub && c.sub !== identityKey.toLowerCase()) throw new AccessError("wrong_account");
|
|
501
|
+
if (Date.now() / 1e3 >= c.exp) throw new AccessError("expired");
|
|
502
|
+
const { signature } = await wallet.createSignature({
|
|
503
|
+
protocolID: ACCESS_PROTOCOL,
|
|
504
|
+
keyID: c.nonce,
|
|
505
|
+
counterparty: "anyone",
|
|
506
|
+
data: challengeBytes(challenge)
|
|
507
|
+
});
|
|
508
|
+
const response = { v: 1, challenge, identityKey, signature: Array.from(signature) };
|
|
509
|
+
if (c.require.token) response.holdings = await proveHoldings(wallet, challenge, c.require.token.id, o.tokenBasket);
|
|
510
|
+
let verified;
|
|
511
|
+
if (o.verify) {
|
|
512
|
+
verified = await o.verify(response);
|
|
513
|
+
throwIfAccessError(verified);
|
|
514
|
+
}
|
|
515
|
+
return { response, verified, wallet };
|
|
516
|
+
} catch (e) {
|
|
517
|
+
throw toAccessError(e);
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
|
|
427
521
|
// src/element.ts
|
|
428
522
|
var SIGNIN_TAG = "bwalletx-signin";
|
|
429
523
|
var GET_URL = "https://bwalletx.com/get";
|
|
@@ -519,6 +613,10 @@ async function postJson(url, body) {
|
|
|
519
613
|
if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`);
|
|
520
614
|
return data;
|
|
521
615
|
}
|
|
616
|
+
async function postAccess(url, body) {
|
|
617
|
+
const res = await fetch(url, { method: "POST", credentials: "include", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
|
|
618
|
+
return res.json().catch(() => ({ error: "bad_request", message: `HTTP ${res.status}` }));
|
|
619
|
+
}
|
|
522
620
|
var OBSERVED = ["size", "theme", "label", "brand", "subtitle", "loading", "disabled", "full-width", "aria-label", "get-url", "web-url"];
|
|
523
621
|
function createClass() {
|
|
524
622
|
return class BwalletxSigninElement extends HTMLElement {
|
|
@@ -601,6 +699,26 @@ function createClass() {
|
|
|
601
699
|
if (!found) {
|
|
602
700
|
this.#notFound = true;
|
|
603
701
|
this.#emit("bwalletx-not-found");
|
|
702
|
+
if (this.#attr("require-token")) this.#emit("bwalletx-access-denied", { code: "not_installed", message: "No wallet found" });
|
|
703
|
+
return;
|
|
704
|
+
}
|
|
705
|
+
const requireToken = this.#attr("require-token");
|
|
706
|
+
if (requireToken) {
|
|
707
|
+
const verifyUrl2 = this.#attr("verify-url");
|
|
708
|
+
const min = this.#attr("min");
|
|
709
|
+
const minBps = this.#attr("min-bps");
|
|
710
|
+
const hint = { token: { id: requireToken, ...minBps ? { minBps: Number(minBps) } : { min: min ?? "1" } } };
|
|
711
|
+
try {
|
|
712
|
+
const a = await requestAccess({
|
|
713
|
+
wallet: found.wallet,
|
|
714
|
+
challenge: (identityKey) => postJson(challengeUrl, { identityKey, require: hint }),
|
|
715
|
+
verify: verifyUrl2 ? (response2) => postAccess(verifyUrl2, response2) : void 0
|
|
716
|
+
});
|
|
717
|
+
this.#emit("bwalletx-access-granted", { identityKey: a.response.identityKey, response: a.verified });
|
|
718
|
+
} catch (e) {
|
|
719
|
+
const err = e instanceof AccessError ? e : new AccessError("bad_request", String(e));
|
|
720
|
+
this.#emit("bwalletx-access-denied", { code: err.code, message: err.message, have: err.have, need: err.need });
|
|
721
|
+
}
|
|
604
722
|
return;
|
|
605
723
|
}
|
|
606
724
|
const r = await signInWithBwalletX({ wallet: found.wallet, challenge: (identityKey) => postJson(challengeUrl, { identityKey }) });
|
|
@@ -637,6 +755,10 @@ export {
|
|
|
637
755
|
LOGIN_PROTOCOL,
|
|
638
756
|
connectBwalletX,
|
|
639
757
|
signInWithBwalletX,
|
|
758
|
+
toAccessError,
|
|
759
|
+
throwIfAccessError,
|
|
760
|
+
proveHoldings,
|
|
761
|
+
requestAccess,
|
|
640
762
|
SIGNIN_TAG,
|
|
641
763
|
GET_URL,
|
|
642
764
|
WEB_WALLET_URL,
|
|
@@ -646,4 +768,4 @@ export {
|
|
|
646
768
|
buildAuthorizeUrl,
|
|
647
769
|
defineBwalletxSignin
|
|
648
770
|
};
|
|
649
|
-
//# sourceMappingURL=chunk-
|
|
771
|
+
//# sourceMappingURL=chunk-CVLXFNAG.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/discover.ts","../src/in-order.ts","../src/pair.ts","../src/protocol.ts","../src/signin.ts","../src/access-client.ts","../src/element.ts"],"sourcesContent":["import type { WalletInterface } from '@bsv/sdk';\n\n/** Ids bWalletX announces in BRC-100 wallet discovery. */\nexport const RDNS_EXTENSION = 'com.bwalletx.extension';\nexport const RDNS_MOBILE = 'space.bwallet.mobile';\nexport const BWALLETX_RDNS = [RDNS_EXTENSION, RDNS_MOBILE] as const;\n\nexport type FoundBy = 'extension' | 'in-app';\n\nexport interface FoundWallet {\n wallet: WalletInterface;\n /** 'extension' for the Chrome extension; 'in-app' inside the bWalletX app's own browser. */\n method: FoundBy;\n rdns: string | null;\n}\n\n/**\n * Like findBwalletX, but also says which bWalletX answered.\n * Order: a BRC-100 announcement with a bWalletX rdns; then `window.CWI` (set by the in-app\n * browser, and by older builds that do not announce); otherwise null.\n */\nexport function discoverBwalletX(ms = 1200): Promise<FoundWallet | null> {\n if (typeof window === 'undefined') return Promise.resolve(null);\n return new Promise((resolve) => {\n let done = false;\n const finish = (r: FoundWallet | null) => {\n if (done) return;\n done = true;\n window.removeEventListener('brc100:announceWallet', onAnnounce);\n resolve(r);\n };\n const onAnnounce = (e: Event) => {\n const d = (e as CustomEvent).detail as { info?: { rdns?: string }; wallet?: WalletInterface } | undefined;\n const rdns = d?.info?.rdns ?? '';\n if (d?.wallet && (BWALLETX_RDNS as readonly string[]).includes(rdns)) {\n finish({ wallet: d.wallet, method: rdns === RDNS_EXTENSION ? 'extension' : 'in-app', rdns });\n }\n };\n window.addEventListener('brc100:announceWallet', onAnnounce);\n window.dispatchEvent(new Event('brc100:requestWallet'));\n setTimeout(() => {\n const cwi = (window as unknown as { CWI?: WalletInterface }).CWI;\n finish(cwi ? { wallet: cwi, method: 'in-app', rdns: null } : null);\n }, ms);\n });\n}\n\n/**\n * Find bWalletX in this page: the extension on a computer, or the wallet itself when the page is\n * open in bWalletX's in-app browser. Resolves null if nothing answered within `ms`.\n */\nexport async function findBwalletX(ms = 1200): Promise<WalletInterface | null> {\n return (await discoverBwalletX(ms))?.wallet ?? null;\n}\n","/**\n * Wrap an async frame handler so frames are handled one at a time, in arrival order.\n *\n * WebSocket `onmessage` does not wait for an async handler. The phone sends its plain `hello`\n * and then, as soon as the user taps Connect, a sealed `ready`. If the handler for `hello` is\n * still deriving the session key when `ready` arrives, a naive handler sees no key yet and drops\n * `ready`, so pairing never finishes. Chaining every frame onto one promise fixes that.\n */\nexport function inOrder<T>(handle: (frame: T) => Promise<void> | void, onError?: (e: unknown) => void) {\n let queue: Promise<void> = Promise.resolve();\n return (frame: T): Promise<void> => {\n queue = queue.then(() => handle(frame)).catch((e) => onError?.(e));\n return queue;\n };\n}\n","import { PrivateKey, type WalletInterface } from '@bsv/sdk';\nimport { inOrder } from './in-order.js';\nimport {\n DEFAULT_RELAY,\n PAIR_VERSION,\n QR_LIFETIME_S,\n Sealer,\n deriveSession,\n isSealed,\n newChannel,\n pairUrl,\n relaySocketUrl,\n type HelloFrame,\n type PairMessage,\n} from './protocol.js';\n\n/** localStorage-shaped storage. Methods may be sync or async. */\nexport interface PairStorage {\n getItem(key: string): string | null | Promise<string | null>;\n setItem(key: string, value: string): void | Promise<void>;\n removeItem(key: string): void | Promise<void>;\n}\n\n/** The minimum of the browser WebSocket API this package uses (the `ws` package also fits). */\nexport interface SocketLike {\n readonly readyState: number;\n onopen: ((ev: unknown) => void) | null;\n onmessage: ((ev: { data: unknown }) => void) | null;\n onerror: ((ev: unknown) => void) | null;\n onclose: ((ev: unknown) => void) | null;\n send(data: string): void;\n close(): void;\n}\nexport type SocketFactory = (url: string) => SocketLike;\n\nexport interface PairConnectionOptions {\n /** Where the pairing is kept so it survives a reload. Default: localStorage, else memory only. */\n storage?: PairStorage | null;\n /** Storage key. Default 'bwalletx.connect.pairing.v1'. */\n storageKey?: string;\n /** Opens a socket. Default: the global WebSocket. Pass one to run in Node or to test. */\n socket?: SocketFactory;\n /** Per-call timeout in ms. Default 120000. */\n callTimeoutMs?: number;\n}\n\nexport interface PairingOptions extends PairConnectionOptions {\n /** Show this link as a QR code, and as text to copy (web.bwalletx.com takes it pasted). */\n onLink: (link: string) => void;\n /** Show this 4-digit code. The wallet shows the same one; the user checks they match. */\n onCode: (code: string) => void;\n signal?: AbortSignal;\n /** Relay host. Default relay.bwallet.space. */\n relay?: string;\n /** This page's origin, as the relay will see it. Default location.origin. */\n origin?: string;\n}\n\n/** A BRC-100 wallet whose every call goes, end-to-end encrypted, to the paired phone or web wallet. */\nexport type PairedWallet = WalletInterface & {\n /** Close the relay connection. The pairing stays stored; the next call reconnects. */\n close(): void;\n /** Tell the wallet to unpair, close, and delete the stored pairing. */\n forget(): Promise<void>;\n};\n\ninterface StoredPairing {\n v: 1;\n c: string; // channel\n r: string; // relay host\n s: string; // our pairing private key (hex). Random; not a wallet key.\n k: string; // the wallet's pairing public key\n sent: number;\n lastSeen: number;\n pairedAt: number;\n}\n\nconst DEFAULT_KEY = 'bwalletx.connect.pairing.v1';\nconst OPEN = 1;\n\nfunction memoryStorage(): PairStorage {\n const m = new Map<string, string>();\n return { getItem: (k) => m.get(k) ?? null, setItem: (k, v) => void m.set(k, v), removeItem: (k) => void m.delete(k) };\n}\n\nfunction defaultStorage(): PairStorage {\n try {\n if (typeof localStorage !== 'undefined') return localStorage;\n } catch {\n /* blocked storage */\n }\n return memoryStorage();\n}\n\nfunction defaultSocket(): SocketFactory {\n return (url) => {\n if (typeof WebSocket === 'undefined') throw new Error('No WebSocket here. Pass options.socket.');\n return new WebSocket(url) as unknown as SocketLike;\n };\n}\n\nfunction parseStored(raw: string | null): StoredPairing | null {\n if (!raw) return null;\n try {\n const p = JSON.parse(raw) as Partial<StoredPairing>;\n const n = (x: unknown) => Number.isInteger(x) && (x as number) >= 0;\n if (p.v !== 1) return null;\n if (typeof p.c !== 'string' || !/^[A-Za-z0-9_-]{22}$/.test(p.c)) return null;\n if (typeof p.r !== 'string' || !/^[a-z0-9.-]+(:\\d+)?$/i.test(p.r)) return null;\n if (typeof p.s !== 'string' || !/^[0-9a-f]{64}$/i.test(p.s)) return null;\n if (typeof p.k !== 'string' || !/^0[23][0-9a-f]{64}$/i.test(p.k)) return null;\n if (!n(p.sent) || !n(p.lastSeen) || !n(p.pairedAt)) return null;\n return p as StoredPairing;\n } catch {\n return null;\n }\n}\n\nclass Link {\n private ws: SocketLike | null = null;\n private opening: Promise<void> | null = null;\n private waiting = new Map<string, { resolve: (v: unknown) => void; reject: (e: Error) => void; timer: ReturnType<typeof setTimeout> }>();\n private forgotten = false;\n\n constructor(\n private p: StoredPairing,\n private sealer: Sealer,\n private storage: PairStorage,\n private key: string,\n private socket: SocketFactory,\n private timeoutMs: number,\n ) {}\n\n /** Take over a socket that is already open (the one pairing used). */\n adopt(ws: SocketLike) {\n this.ws = ws;\n this.wire(ws);\n }\n\n private wire(ws: SocketLike) {\n ws.onmessage = inOrder((ev: { data: unknown }) => this.onFrame(String(ev.data)));\n ws.onerror = null;\n ws.onclose = () => {\n if (this.ws === ws) this.ws = null;\n this.failAll(new Error('The connection to bWalletX closed'));\n };\n }\n\n private persist() {\n if (this.forgotten) return;\n this.p = { ...this.p, ...this.sealer.counters };\n void Promise.resolve(this.storage.setItem(this.key, JSON.stringify(this.p))).catch(() => {});\n }\n\n private failAll(e: Error) {\n for (const w of this.waiting.values()) {\n clearTimeout(w.timer);\n w.reject(e);\n }\n this.waiting.clear();\n }\n\n private async ensure() {\n if (this.forgotten) throw new Error('This pairing was removed. Pair again.');\n if (this.ws && this.ws.readyState === OPEN) return;\n this.opening ??= this.reopen().finally(() => (this.opening = null));\n await this.opening;\n }\n\n private reopen() {\n // A fresh expiry lets the relay recreate the channel if it was dropped; the wallet rejoins on its own.\n const ws = this.socket(relaySocketUrl(this.p.r, this.p.c, 'site', Math.floor(Date.now() / 1000) + QR_LIFETIME_S - 10));\n return new Promise<void>((resolve, reject) => {\n ws.onopen = () => {\n this.ws = ws;\n this.wire(ws);\n resolve();\n };\n ws.onerror = () => reject(new Error('Could not reach the bWalletX pairing service'));\n ws.onclose = () => reject(new Error('Could not reach the bWalletX pairing service'));\n });\n }\n\n private async onFrame(raw: string) {\n let f: unknown;\n try {\n f = JSON.parse(raw);\n } catch {\n return;\n }\n const t = (f as { t?: string; error?: string }).t;\n if (t === 'relay' && (f as { error?: string }).error) {\n return this.failAll(new Error(`bWalletX pairing service: ${(f as { error: string }).error}`));\n }\n if (!isSealed(f)) return;\n const msg = await this.sealer.open(f);\n if (!msg) return;\n this.persist();\n if (msg.t === 'res') {\n const w = this.waiting.get(msg.id);\n if (!w) return;\n clearTimeout(w.timer);\n this.waiting.delete(msg.id);\n if (msg.error) w.reject(Object.assign(new Error(msg.error.message), { code: msg.error.code }));\n else w.resolve(msg.result);\n } else if (msg.t === 'close') {\n this.drop();\n this.failAll(new Error('bWalletX disconnected this site. Pair again.'));\n }\n }\n\n async call(action: string, params: unknown): Promise<unknown> {\n await this.ensure();\n const ws = this.ws!;\n const id = `${action}-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;\n const result = new Promise<unknown>((resolve, reject) => {\n const timer = setTimeout(() => {\n if (this.waiting.delete(id)) reject(new Error('No answer from bWalletX. Open it, unlocked, and approve.'));\n }, this.timeoutMs);\n this.waiting.set(id, { resolve, reject, timer });\n });\n ws.send(JSON.stringify(await this.sealer.seal({ t: 'req', id, action, params } satisfies PairMessage)));\n this.persist();\n return result;\n }\n\n close() {\n const ws = this.ws;\n this.ws = null;\n ws?.close();\n }\n\n private drop() {\n this.forgotten = true;\n void Promise.resolve(this.storage.removeItem(this.key)).catch(() => {});\n this.close();\n }\n\n async forget() {\n if (this.forgotten) return;\n try {\n if (this.ws && this.ws.readyState === OPEN) {\n this.ws.send(JSON.stringify(await this.sealer.seal({ t: 'close', reason: 'site unpaired' })));\n }\n } catch {\n /* best effort */\n }\n this.drop();\n }\n\n wallet(): PairedWallet {\n return new Proxy({} as PairedWallet, {\n get: (_t, method) => {\n if (method === 'close') return () => this.close();\n if (method === 'forget') return () => this.forget();\n if (typeof method !== 'string' || method === 'then' || method === 'toJSON') return undefined;\n return (params: unknown) => this.call(method, params ?? {});\n },\n });\n }\n}\n\n/**\n * Pair with bWalletX on a phone (scan the QR) or web.bwalletx.com (paste the link).\n * Resolves with a wallet once the user taps Connect. The pairing is stored (see `storage`) so\n * `restorePairing()` can reconnect after a reload without a new QR.\n */\nexport function pairBwalletX(opts: PairingOptions): Promise<PairedWallet> {\n const storage = opts.storage === undefined ? defaultStorage() : (opts.storage ?? memoryStorage());\n const key = opts.storageKey ?? DEFAULT_KEY;\n const socket = opts.socket ?? defaultSocket();\n const relay = opts.relay ?? DEFAULT_RELAY;\n const origin = opts.origin ?? (typeof location !== 'undefined' ? location.origin : '');\n if (!origin) return Promise.reject(new Error('pairBwalletX needs options.origin outside a browser'));\n\n const siteKey = PrivateKey.fromRandom(); // a throwaway pairing key, not a wallet key\n const channel = newChannel();\n const expiry = Math.floor(Date.now() / 1000) + QR_LIFETIME_S;\n\n return new Promise<PairedWallet>((resolve, reject) => {\n if (opts.signal?.aborted) return reject(new Error('cancelled'));\n let ws: SocketLike;\n try {\n ws = socket(relaySocketUrl(relay, channel, 'site', expiry));\n } catch (e) {\n return reject(e);\n }\n let sealer: Sealer | null = null;\n let walletKey = '';\n let settled = false;\n const fail = (e: Error) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n ws.close();\n reject(e);\n };\n const timer = setTimeout(() => fail(new Error('The pairing code expired. Show a new one.')), QR_LIFETIME_S * 1000);\n opts.signal?.addEventListener('abort', () => fail(new Error('cancelled')));\n ws.onerror = () => fail(new Error('Could not reach the bWalletX pairing service'));\n ws.onclose = () => fail(new Error('The connection to bWalletX closed before pairing finished'));\n ws.onmessage = inOrder(async (ev: { data: unknown }) => {\n if (settled) return;\n let f: unknown;\n try {\n f = JSON.parse(String(ev.data));\n } catch {\n return;\n }\n if ((f as HelloFrame).t === 'hello' && !sealer) {\n walletKey = (f as HelloFrame).k;\n const s = await deriveSession(siteKey, walletKey, channel);\n sealer = new Sealer(s.key, 'site');\n opts.onCode(s.code);\n return;\n }\n if (!sealer || !isSealed(f)) return;\n const msg = await sealer.open(f);\n if (!msg) return;\n if (msg.t === 'ready') {\n settled = true;\n clearTimeout(timer);\n const p: StoredPairing = { v: 1, c: channel, r: relay, s: siteKey.toHex(), k: walletKey, ...sealer.counters, pairedAt: Date.now() };\n await Promise.resolve(storage.setItem(key, JSON.stringify(p))).catch(() => {});\n const link = new Link(p, sealer, storage, key, socket, opts.callTimeoutMs ?? 120_000);\n link.adopt(ws);\n resolve(link.wallet());\n } else if (msg.t === 'close') {\n fail(new Error('Pairing was declined in bWalletX'));\n }\n });\n opts.onLink(pairUrl({ v: PAIR_VERSION, r: relay, c: channel, k: siteKey.toPublicKey().toString(), o: origin, e: expiry }));\n });\n}\n\n/**\n * The wallet from a pairing stored by an earlier `pairBwalletX`, or null if there is none.\n * It connects on the first call. The wallet must still have this site paired.\n */\nexport async function restorePairing(opts: PairConnectionOptions = {}): Promise<PairedWallet | null> {\n const storage = opts.storage === undefined ? defaultStorage() : (opts.storage ?? memoryStorage());\n const key = opts.storageKey ?? DEFAULT_KEY;\n const p = parseStored(await Promise.resolve(storage.getItem(key)).catch(() => null));\n if (!p) return null;\n const { key: aes } = await deriveSession(PrivateKey.fromHex(p.s), p.k, p.c);\n const sealer = new Sealer(aes, 'site');\n sealer.restore({ sent: p.sent, lastSeen: p.lastSeen });\n return new Link(p, sealer, storage, key, opts.socket ?? defaultSocket(), opts.callTimeoutMs ?? 120_000).wallet();\n}\n\n/** Delete the stored pairing without telling the wallet. */\nexport async function clearPairing(opts: Pick<PairConnectionOptions, 'storage' | 'storageKey'> = {}) {\n const storage = opts.storage === undefined ? defaultStorage() : (opts.storage ?? memoryStorage());\n await Promise.resolve(storage.removeItem(opts.storageKey ?? DEFAULT_KEY)).catch(() => {});\n}\n","/**\n * Phone pairing protocol (tokenblaster.lol docs/wallet-connect.md §4), shared by the site side and\n * bWallet. Kept dependency-light (@bsv/sdk + WebCrypto) so the same file can be copied into sites\n * until it ships as @b0ase/wallet.\n *\n * QR: https://www.bwallet.space/pair?v=1&r=<relay host>&c=<channel>&k=<site pubkey>&o=<origin>&e=<expiry>\n * key: ECDH(secp256k1) → HKDF-SHA256(salt = channel bytes, info = \"bwallet-pair-v1\") → AES-256-GCM\n * frame: { s: seq, n: nonce b64, d: ciphertext b64 }, AAD = \"<sender role>|<s>\", s strictly increasing\n * code: first 2 bytes of SHA-256(key bits) → 4 digits, shown on both screens\n */\nimport { PrivateKey, PublicKey } from '@bsv/sdk';\n\nexport const PAIR_VERSION = '1';\nexport const PAIR_INFO = 'bwallet-pair-v1';\n// www: the bare domain redirects there, and app-link checks (Apple's AASA) don't follow redirects.\nexport const PAIR_HOST = 'www.bwallet.space';\nconst PAIR_HOSTS = new Set([PAIR_HOST, 'bwallet.space']);\nexport const DEFAULT_RELAY = 'relay.bwallet.space';\nexport const QR_LIFETIME_S = 120;\n\nexport type Role = 'site' | 'wallet';\nexport type WalletInfo = { name: string; icon?: string; rdns: string };\n\nexport type PairLink = { v: string; r: string; c: string; k: string; o: string; e: number };\n\n/** Plaintext messages inside encrypted frames. */\nexport type PairMessage =\n | { t: 'req'; id: string; action: string; params: unknown }\n | { t: 'res'; id: string; result?: unknown; error?: { code: string; message: string } }\n | { t: 'ready' }\n | { t: 'ping' }\n | { t: 'close'; reason: string };\n\n/** Unencrypted frames: from the relay, and the phone's hello (its key isn't shared yet). */\nexport type RelayFrame = { t: 'relay'; verifiedOrigin?: string; peer?: 'joined' | 'left'; role?: Role; error?: string };\nexport type HelloFrame = { t: 'hello'; k: string; info: WalletInfo };\nexport type SealedFrame = { s: number; n: string; d: string };\n\nconst enc = new TextEncoder();\nconst dec = new TextDecoder();\n\n// Chunked: String.fromCharCode(...bytes) overflows the call stack on large frames (signed transactions).\nconst binary = (bytes: Uint8Array) => {\n let s = '';\n for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode(...bytes.subarray(i, i + 0x8000));\n return s;\n};\nexport const b64url = (bytes: Uint8Array) =>\n btoa(binary(bytes)).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\nexport const fromB64url = (s: string) => {\n const t = s.replace(/-/g, '+').replace(/_/g, '/');\n const bin = atob(t + '='.repeat((4 - (t.length % 4)) % 4));\n return Uint8Array.from(bin, (ch) => ch.charCodeAt(0));\n};\nconst b64 = (bytes: Uint8Array) => btoa(binary(bytes));\nconst fromB64 = (s: string) => Uint8Array.from(atob(s), (ch) => ch.charCodeAt(0));\n\nexport const newChannel = () => b64url(crypto.getRandomValues(new Uint8Array(16)));\n\nexport function pairUrl(link: PairLink): string {\n const q = new URLSearchParams({ v: link.v, r: link.r, c: link.c, k: link.k, o: link.o, e: String(link.e) });\n return `https://${PAIR_HOST}/pair?${q}`;\n}\n\n/** Parse a scanned QR (https link or bwallet:// fallback). Throws on anything else. */\nexport function parsePairUrl(text: string, nowS = Math.floor(Date.now() / 1000)): PairLink {\n const u = new URL(text.trim());\n const ok =\n (u.protocol === 'https:' && PAIR_HOSTS.has(u.host) && u.pathname === '/pair') ||\n (u.protocol === 'bwallet:' && /pair/.test(u.href));\n if (!ok) throw new Error('Not a bWallet pairing code');\n const g = (k: string) => u.searchParams.get(k) ?? '';\n const link: PairLink = { v: g('v'), r: g('r'), c: g('c'), k: g('k'), o: g('o'), e: Number(g('e')) };\n if (link.v !== PAIR_VERSION) throw new Error('This pairing code needs a newer bWallet');\n if (!/^[A-Za-z0-9_-]{22}$/.test(link.c)) throw new Error('Bad pairing code');\n if (!/^0[23][0-9a-f]{64}$/i.test(link.k)) throw new Error('Bad pairing code');\n if (!/^[a-z0-9.-]+(:\\d+)?$/i.test(link.r)) throw new Error('Bad pairing code');\n const o = new URL(link.o);\n if (o.origin !== link.o) throw new Error('Bad pairing code');\n if (!Number.isFinite(link.e) || link.e < nowS) throw new Error('This code has expired. Ask the site for a new one.');\n return link;\n}\n\nexport const relaySocketUrl = (relay: string, channel: string, role: Role, expiry?: number) => {\n const local = /^(localhost|127\\.0\\.0\\.1)(:\\d+)?$/.test(relay);\n const q = new URLSearchParams({ role });\n if (expiry) q.set('e', String(expiry));\n return `${local ? 'ws' : 'wss'}://${relay}/v1/c/${channel}?${q}`;\n};\n\n/** Shared AES key + 4-digit comparison code from my private key and their public key. */\nexport async function deriveSession(mine: PrivateKey, theirs: string, channel: string) {\n const point = mine.deriveSharedSecret(PublicKey.fromString(theirs));\n const ikm = new Uint8Array(point.encode(true) as number[]);\n const base = await crypto.subtle.importKey('raw', ikm, 'HKDF', false, ['deriveBits']);\n const bits = new Uint8Array(\n await crypto.subtle.deriveBits(\n { name: 'HKDF', hash: 'SHA-256', salt: fromB64url(channel), info: enc.encode(PAIR_INFO) },\n base,\n 256,\n ),\n );\n const key = await crypto.subtle.importKey('raw', bits, 'AES-GCM', false, ['encrypt', 'decrypt']);\n const h = new Uint8Array(await crypto.subtle.digest('SHA-256', bits));\n const code = String(((h[0] << 8) | h[1]) % 10000).padStart(4, '0');\n return { key, code };\n}\n\n/** One direction-aware encrypted pipe. `me` is the sender role used in the AAD. */\nexport class Sealer {\n private sent = 0;\n private lastSeen = 0;\n constructor(\n private key: CryptoKey,\n private me: Role,\n ) {}\n\n async seal(msg: PairMessage): Promise<SealedFrame> {\n const s = ++this.sent;\n const n = crypto.getRandomValues(new Uint8Array(12));\n const ct = new Uint8Array(\n await crypto.subtle.encrypt(\n { name: 'AES-GCM', iv: n, additionalData: enc.encode(`${this.me}|${s}`) },\n this.key,\n enc.encode(JSON.stringify(msg)),\n ),\n );\n return { s, n: b64(n), d: b64(ct) };\n }\n\n /** Decrypts a frame from the other side; null for replays, reflections or tampering. */\n async open(f: SealedFrame): Promise<PairMessage | null> {\n if (!Number.isInteger(f.s) || f.s <= this.lastSeen) return null;\n const from: Role = this.me === 'site' ? 'wallet' : 'site';\n try {\n const pt = await crypto.subtle.decrypt(\n { name: 'AES-GCM', iv: fromB64(f.n), additionalData: enc.encode(`${from}|${f.s}`) },\n this.key,\n fromB64(f.d),\n );\n this.lastSeen = f.s;\n return JSON.parse(dec.decode(pt)) as PairMessage;\n } catch {\n return null;\n }\n }\n\n /** For resuming a session after a reload: continue counters where they were. */\n get counters() {\n return { sent: this.sent, lastSeen: this.lastSeen };\n }\n restore(c: { sent: number; lastSeen: number }) {\n this.sent = c.sent;\n this.lastSeen = c.lastSeen;\n }\n}\n\nexport const isSealed = (x: unknown): x is SealedFrame =>\n !!x && typeof x === 'object' && 'd' in x && 'n' in x && 's' in x;\n","import type { WalletInterface, WalletProtocol } from '@bsv/sdk';\nimport { discoverBwalletX } from './discover.js';\nimport { pairBwalletX, restorePairing, type PairingOptions } from './pair.js';\n\n/** Security level 2, a protocol name used for nothing else. */\nexport const LOGIN_PROTOCOL: WalletProtocol = [2, 'bwallet sign in'];\n\n/** What your server's challenge route returns (createChallenge from '@bwalletx/connect/server'). */\nexport interface Challenge {\n nonce: string;\n message: string;\n keyID: string;\n protocolID?: WalletProtocol;\n}\n\nexport type SignInMethod = 'extension' | 'in-app' | 'pairing' | 'wallet';\n\nexport interface SignInOptions {\n /** Ask your server for a challenge for this identity key. */\n challenge: (identityKey: string) => Promise<Challenge>;\n /** Use this wallet instead of looking for one. `method` is then 'wallet'. */\n wallet?: WalletInterface;\n /** How to show the QR and code if pairing is needed. Without it, pairing is not tried. */\n pairing?: PairingOptions;\n /** Reuse a pairing stored by an earlier sign-in before showing a new QR. Default true. */\n reusePairing?: boolean;\n /** How long to wait for the extension or in-app browser to answer, in ms. Default 1200. */\n discoverMs?: number;\n}\n\nexport interface SignInResult {\n identityKey: string;\n /** DER signature as number[], ready to post to verifySignIn. */\n signature: number[];\n nonce: string;\n method: SignInMethod;\n /** The wallet that signed. Keep it to make more calls. */\n wallet: WalletInterface;\n}\n\n/** Find a wallet: extension or in-app browser first, then a stored pairing, then a new pairing. */\nexport async function connectBwalletX(\n opts: Pick<SignInOptions, 'wallet' | 'pairing' | 'reusePairing' | 'discoverMs'> = {},\n): Promise<{ wallet: WalletInterface; method: SignInMethod }> {\n if (opts.wallet) return { wallet: opts.wallet, method: 'wallet' };\n const found = await discoverBwalletX(opts.discoverMs);\n if (found) return { wallet: found.wallet, method: found.method };\n if (opts.reusePairing !== false) {\n const restored = await restorePairing(opts.pairing ?? {});\n if (restored) return { wallet: restored, method: 'pairing' };\n }\n if (!opts.pairing) {\n throw Object.assign(new Error('bWalletX was not found in this browser'), { code: 'NOT_FOUND' });\n }\n return { wallet: await pairBwalletX(opts.pairing), method: 'pairing' };\n}\n\n/**\n * Sign the server's challenge with the user's bWalletX identity key. Post the result's\n * identityKey, nonce and signature to your verify route.\n */\nexport async function signInWithBwalletX(opts: SignInOptions): Promise<SignInResult> {\n const { wallet, method } = await connectBwalletX(opts);\n if (method !== 'pairing') await wallet.waitForAuthentication({}).catch(() => {});\n const { publicKey: identityKey } = await wallet.getPublicKey({ identityKey: true });\n const c = await opts.challenge(identityKey);\n const { signature } = await wallet.createSignature({\n protocolID: c.protocolID ?? LOGIN_PROTOCOL,\n keyID: c.keyID,\n counterparty: 'anyone',\n data: Array.from(new TextEncoder().encode(c.message)),\n });\n return { identityKey, signature: Array.from(signature), nonce: c.nonce, method, wallet };\n}\n","/**\n * Browser side of the access protocol: ask the wallet to sign the site's challenge and prove the\n * keys holding the required token, using standard BRC-100 calls only (so any BRC-100 wallet works).\n */\nimport { Hash, PublicKey, Utils, type WalletInterface, type WalletProtocol } from '@bsv/sdk';\nimport {\n ACCESS_PROTOCOL,\n AccessError,\n MAX_HOLDING_PROOFS,\n challengeBytes,\n parseAccessChallenge,\n type AccessErrorBody,\n type AccessResponse,\n type HoldingProof,\n} from './access.js';\nimport { connectBwalletX, type SignInOptions } from './signin.js';\n\n/** The challenge route's answer (createAccessChallenge). */\nexport interface AccessChallengeLike {\n challenge: string;\n}\n\nexport interface RequestAccessOptions {\n /** Ask your server for a challenge. Gets the wallet's identity key. */\n challenge: (identityKey: string) => Promise<AccessChallengeLike>;\n /** Post the signed response to your server. Throw AccessError (or return an error body) to refuse. */\n verify?: (response: AccessResponse) => Promise<unknown>;\n wallet?: WalletInterface;\n pairing?: SignInOptions['pairing'];\n discoverMs?: number;\n /** Basket holding BSV-21 outputs. Default 'bsv21' (bWalletX, 1Sat wallets). */\n tokenBasket?: string;\n}\n\nexport interface RequestAccessResult {\n response: AccessResponse;\n /** Whatever `verify` returned. */\n verified?: unknown;\n wallet: WalletInterface;\n}\n\nconst ONESAT: WalletProtocol = [0, 'onesat'];\nconst LEGACY_ONESAT: WalletProtocol = [0, 'p 1sat'];\n\n/** Map a wallet / fetch failure to a protocol error. */\nexport function toAccessError(e: unknown): AccessError {\n if (e instanceof AccessError) return e;\n const err = e as { code?: string; message?: string; status?: number } | null;\n const msg = String(err?.message ?? e ?? '');\n if (err?.code === 'NOT_FOUND') return new AccessError('not_installed', msg);\n if (/reject|denied|declin|cancel|user/i.test(msg) || err?.code === 'ERR_USER_REJECTED' || err?.status === 4001) {\n return new AccessError('user_rejected', msg);\n }\n return new AccessError('bad_request', msg || 'access failed');\n}\n\n/** Read an AccessErrorBody from a server answer and throw it as AccessError. */\nexport function throwIfAccessError(body: unknown): void {\n const b = body as Partial<AccessErrorBody> | null;\n if (b && typeof b.error === 'string') throw new AccessError(b.error as AccessError['code'], b.message, { have: b.have, need: b.need });\n}\n\nfunction hash160FromP2pkh(script: string): string | null {\n const m = /^76a914([0-9a-f]{40})88ac$/i.exec(script.slice(-50));\n return m ? m[1].toLowerCase() : null;\n}\n\n/**\n * Sign the challenge with every key that locks an output of `tokenId` in the wallet's token basket.\n * Outputs whose derivation can't be reproduced are skipped (the server counts only what is proven).\n */\nexport async function proveHoldings(wallet: WalletInterface, challenge: string, tokenId: string, basket = 'bsv21'): Promise<HoldingProof[]> {\n const bare = tokenId.replace(/^bsv21:/, '');\n const list = await wallet.listOutputs({ basket, include: 'locking scripts', includeCustomInstructions: true, limit: 10000 });\n const byKey = new Map<string, HoldingProof>();\n const data = challengeBytes(challenge);\n for (const out of list.outputs) {\n if (byKey.size >= MAX_HOLDING_PROOFS) break;\n let ci: { id?: string; keyID?: string; protocolID?: WalletProtocol; counterparty?: string } = {};\n try {\n ci = JSON.parse(out.customInstructions ?? '{}');\n } catch {\n continue;\n }\n if (ci.id !== bare || !ci.keyID) continue;\n const want = out.lockingScript ? hash160FromP2pkh(out.lockingScript) : null;\n const counterparty = ci.counterparty ?? 'self';\n for (const protocolID of ci.protocolID ? [ci.protocolID] : [ONESAT, LEGACY_ONESAT]) {\n const { publicKey } = await wallet.getPublicKey({ protocolID, keyID: ci.keyID, counterparty });\n const h = Utils.toHex(Hash.hash160(PublicKey.fromString(publicKey).encode(true) as number[]));\n if (want && h !== want) continue;\n const existing = byKey.get(publicKey);\n if (existing) {\n existing.outpoints!.push(out.outpoint.replace('.', '_'));\n break;\n }\n const { signature } = await wallet.createSignature({ protocolID, keyID: ci.keyID, counterparty, data });\n byKey.set(publicKey, { pubkey: publicKey, signature: Array.from(signature), outpoints: [out.outpoint.replace('.', '_')] });\n break;\n }\n }\n return [...byKey.values()];\n}\n\n/**\n * Run the whole flow: find the wallet, get a challenge, sign it, prove holdings, post to verify.\n * Throws AccessError with a protocol code on every failure.\n */\nexport async function requestAccess(o: RequestAccessOptions): Promise<RequestAccessResult> {\n let wallet: WalletInterface;\n try {\n ({ wallet } = await connectBwalletX({ wallet: o.wallet, pairing: o.pairing, discoverMs: o.discoverMs }));\n } catch (e) {\n throw (e as { code?: string })?.code === 'NOT_FOUND' ? new AccessError('not_installed') : toAccessError(e);\n }\n try {\n const { publicKey: identityKey } = await wallet.getPublicKey({ identityKey: true });\n const { challenge } = await o.challenge(identityKey);\n const c = parseAccessChallenge(challenge);\n if (c.sub && c.sub !== identityKey.toLowerCase()) throw new AccessError('wrong_account');\n if (Date.now() / 1000 >= c.exp) throw new AccessError('expired');\n const { signature } = await wallet.createSignature({\n protocolID: ACCESS_PROTOCOL,\n keyID: c.nonce,\n counterparty: 'anyone',\n data: challengeBytes(challenge),\n });\n const response: AccessResponse = { v: 1, challenge, identityKey, signature: Array.from(signature) };\n if (c.require.token) response.holdings = await proveHoldings(wallet, challenge, c.require.token.id, o.tokenBasket);\n let verified: unknown;\n if (o.verify) {\n verified = await o.verify(response);\n throwIfAccessError(verified);\n }\n return { response, verified, wallet };\n } catch (e) {\n throw toAccessError(e);\n }\n}\n","/**\n * <bwalletx-signin>: the standard \"Sign in with bWalletX\" button as a framework-free web component.\n *\n * Design reference: the gold button in bit-sign's sign-in card (src/components/BwalletSignIn.tsx):\n * amber-300 → amber-500 vertical gradient, 12px radius, 16px/20px padding, 16px bold black label,\n * 11px subtitle at 60% black, a black 28px circle holding the gold \"b\", amber shadow.\n *\n * Attributes (all optional):\n * size lg (default) | md | sm | icon\n * theme gold (default) | dark | light\n * label signin (default) | continue | connect\n * brand bWalletX (default) | bWallet (store edition text)\n * subtitle on | off | <custom text>. Default on for lg/md, off for sm/icon and for brand=\"bWallet\"\n * full-width stretch to the container\n * loading show the spinner and set aria-busy\n * disabled disable the button\n * challenge-url / verify-url run the sign-in flow on click (POST JSON, as in the README)\n * require-token / min / min-bps with challenge-url: run the $403 access flow instead; emits\n * bwalletx-access-granted or bwalletx-access-denied { code, have, need }\n * get-url where \"Get bWalletX\" points. Default https://bwalletx.com/get\n * web-url the web wallet. Default https://web.bwalletx.com\n * discover-ms how long to wait for the wallet to answer. Default 1200\n * href plain link mode: navigate here on click\n * authorize-url (+ client-id, redirect-uri, scope) OAuth mode, for auth.bwalletx.com once it exists\n *\n * Events (bubble, composed):\n * bwalletx-signin on every click, before anything else. Cancelable: preventDefault() stops the\n * built-in behaviour so you can run your own flow.\n * bwalletx-signed-in detail { identityKey, method, nonce, signature, response }\n * bwalletx-not-found no bWalletX answered; the \"Get bWalletX\" row is shown\n * bwalletx-error detail { error }\n */\nimport { discoverBwalletX } from './discover.js';\nimport { signInWithBwalletX, type Challenge } from './signin.js';\nimport { requestAccess, type AccessChallengeLike } from './access-client.js';\nimport { AccessError } from './access.js';\n\nexport const SIGNIN_TAG = 'bwalletx-signin';\nexport const GET_URL = 'https://bwalletx.com/get';\nexport const WEB_WALLET_URL = 'https://web.bwalletx.com';\n\nexport type SigninSize = 'lg' | 'md' | 'sm' | 'icon';\nexport type SigninTheme = 'gold' | 'dark' | 'light';\nexport type SigninLabel = 'signin' | 'continue' | 'connect';\nexport type SigninBrand = 'bWalletX' | 'bWallet';\n\nconst VERBS: Record<SigninLabel, string> = { signin: 'Sign in with', continue: 'Continue with', connect: 'Connect' };\n\n/** The visible label for a label/brand pair, e.g. \"Sign in with bWalletX\". */\nexport function signinText(label: SigninLabel = 'signin', brand: SigninBrand = 'bWalletX'): string {\n return `${VERBS[label] ?? VERBS.signin} ${brand}`;\n}\n\nlet uid = 0;\n/** The gold \"b\" (bwalletx-site/logo.svg). Ids are unique per copy so several marks can share a page. */\nexport function markSvg(px = 20): string {\n const n = ++uid;\n 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>`;\n}\n\nexport const SIGNIN_CSS = `\n:host{display:inline-block;vertical-align:middle;font-family:Inter,ui-sans-serif,system-ui,-apple-system,\"Segoe UI\",Roboto,sans-serif}\n:host([full-width]){display:block;width:100%}\n:host([hidden]){display:none}\nbutton{all:unset;box-sizing:border-box;display:inline-flex;align-items:center;justify-content:center;gap:12px;width:100%;cursor:pointer;\n padding:16px 20px;border-radius:12px;font-size:16px;font-weight:700;line-height:1.2;text-align:left;\n background:linear-gradient(180deg,#fcd34d,#f59e0b);color:#000;\n box-shadow:0 10px 15px -3px rgba(245,158,11,.2),0 4px 6px -4px rgba(245,158,11,.2);\n transition:background .15s,transform .1s,box-shadow .15s,border-color .15s;-webkit-tap-highlight-color:transparent}\nbutton:hover{background:linear-gradient(180deg,#fde68a,#fbbf24)}\nbutton:active{transform:translateY(1px);background:linear-gradient(180deg,#fbbf24,#d97706)}\nbutton:focus-visible{outline:2px solid #b45309;outline-offset:3px}\nbutton:disabled{opacity:.6;cursor:not-allowed;transform:none}\nbutton[aria-busy=true]{cursor:wait}\n.mark{display:inline-flex;align-items:center;justify-content:center;flex:none;width:28px;height:28px;border-radius:50%;background:#000}\n.txt{display:flex;flex-direction:column;align-items:flex-start;min-width:0}\n.txt b{font-weight:700;white-space:nowrap}\n.txt small{font-size:11px;font-weight:500;color:rgba(0,0,0,.65);white-space:nowrap}\n.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}\n@keyframes r{to{transform:rotate(360deg)}}\n@media (prefers-reduced-motion:reduce){button{transition:none}button:active{transform:none}.spin{animation:none;border-color:#ffd24d;border-right-color:transparent}}\n/* sizes */\n:host([size=md]) button{padding:10px 16px;border-radius:10px;font-size:15px;gap:10px}\n:host([size=md]) .mark{width:24px;height:24px}\n:host([size=md]) .txt small{font-size:10.5px}\n:host([size=sm]) button{padding:6px 12px 6px 6px;border-radius:8px;font-size:13px;gap:8px;min-height:36px}\n:host([size=sm]) .mark{width:22px;height:22px}\n:host([size=icon]) button{width:48px;height:48px;padding:0;border-radius:50%;gap:0}\n:host([size=icon]) .mark{width:34px;height:34px}\n/* themes */\n:host([theme=dark]) button{background:#0a0a0a;color:#fafafa;border:1px solid #3f3f46;box-shadow:none}\n:host([theme=dark]) button:hover{background:#18181b;border-color:rgba(251,191,36,.6)}\n:host([theme=dark]) button:active{background:#000}\n:host([theme=dark]) button:focus-visible{outline-color:#fcd34d}\n:host([theme=dark]) .mark{box-shadow:inset 0 0 0 1px #3f3f46}\n:host([theme=dark]) .txt small{color:rgba(255,255,255,.65)}\n:host([theme=light]) button{background:#fff;color:#09090b;border:1px solid #d4d4d8;box-shadow:0 1px 2px rgba(0,0,0,.06)}\n:host([theme=light]) button:hover{background:#fafafa;border-color:#f59e0b}\n:host([theme=light]) button:active{background:#f4f4f5}\n:host([theme=light]) .txt small{color:#52525b}\n/* not found */\n.nf{margin-top:8px;font-size:12px;line-height:1.4;color:#71717a;text-align:center}\n.nf a{color:inherit;font-weight:600;text-decoration:underline;text-underline-offset:2px}\n.nf a:focus-visible{outline:2px solid #b45309;outline-offset:2px;border-radius:2px}\n:host([theme=dark]) .nf,:host-context(.dark) .nf{color:#a1a1aa}\n.sr{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}\n`;\n\n/** Optional OAuth parameters for authorize-url mode. auth.bwalletx.com is planned, not live. */\nexport interface AuthorizeParams { authorizeUrl: string; clientId?: string | null; redirectUri?: string | null; scope?: string | null }\n\nfunction b64url(bytes: Uint8Array): string {\n let s = '';\n for (const b of bytes) s += String.fromCharCode(b);\n return btoa(s).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\n/**\n * Build an OAuth 2.1 authorization-code + S256 PKCE redirect URL, and keep the verifier, state and\n * nonce in sessionStorage under \"bwalletx:oauth\" for your callback page. Matches the plan in\n * bit-sign docs/SIGN-IN-WITH-BWALLETX.md. The provider is not live yet.\n */\nexport async function buildAuthorizeUrl(p: AuthorizeParams): Promise<string> {\n const rnd = (n: number) => b64url(crypto.getRandomValues(new Uint8Array(n)));\n const verifier = rnd(32);\n const state = rnd(16);\n const nonce = rnd(16);\n const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier)));\n const u = new URL(p.authorizeUrl, typeof location !== 'undefined' ? location.href : undefined);\n const set = (k: string, v: string | null | undefined) => { if (v) u.searchParams.set(k, v); };\n set('response_type', 'code');\n set('client_id', p.clientId);\n set('redirect_uri', p.redirectUri);\n set('scope', p.scope || 'openid profile');\n set('state', state);\n set('nonce', nonce);\n set('code_challenge', b64url(digest));\n set('code_challenge_method', 'S256');\n try { sessionStorage.setItem('bwalletx:oauth', JSON.stringify({ verifier, state, nonce })); } catch { /* storage blocked */ }\n return u.toString();\n}\n\nasync function postJson<T>(url: string, body: unknown): Promise<T> {\n const res = await fetch(url, { method: 'POST', credentials: 'include', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });\n const data = await res.json().catch(() => ({}));\n if (!res.ok) throw new Error((data as { error?: string }).error ?? `HTTP ${res.status}`);\n return data as T;\n}\n\n/** POST that returns the body even on 4xx, so access error codes reach requestAccess. */\nasync function postAccess(url: string, body: unknown): Promise<unknown> {\n const res = await fetch(url, { method: 'POST', credentials: 'include', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });\n return res.json().catch(() => ({ error: 'bad_request', message: `HTTP ${res.status}` }));\n}\n\nconst OBSERVED = ['size', 'theme', 'label', 'brand', 'subtitle', 'loading', 'disabled', 'full-width', 'aria-label', 'get-url', 'web-url'];\n\n/** The element class. Created lazily so importing this module on a server is harmless. */\nfunction createClass(): CustomElementConstructor {\n return class BwalletxSigninElement extends HTMLElement {\n static get observedAttributes() { return OBSERVED; }\n #root: ShadowRoot;\n #notFound = false;\n #busy = false;\n\n constructor() {\n super();\n this.#root = this.attachShadow({ mode: 'open' });\n }\n\n connectedCallback() { this.#render(); }\n attributeChangedCallback() { if (this.isConnected) this.#render(); }\n\n /** The inner <button>, for focus() and tests. */\n get button(): HTMLButtonElement | null { return this.#root.querySelector('button'); }\n get notFound() { return this.#notFound; }\n\n focus(opts?: FocusOptions) { this.button?.focus(opts); }\n\n #attr(name: string) { return this.getAttribute(name); }\n\n #render() {\n const size = (this.#attr('size') ?? 'lg') as SigninSize;\n const brand: SigninBrand = this.#attr('brand') === 'bWallet' ? 'bWallet' : 'bWalletX';\n const text = signinText((this.#attr('label') ?? 'signin') as SigninLabel, brand);\n const subAttr = this.#attr('subtitle');\n const subDefault = brand === 'bWalletX' && (size === 'lg' || size === 'md') ? 'also works with bWallet' : null;\n const subtitle = subAttr === null || subAttr === '' || subAttr === 'on' ? (subAttr === 'on' ? 'also works with bWallet' : subDefault)\n : subAttr === 'off' ? null : subAttr;\n const loading = this.hasAttribute('loading') || this.#busy;\n const disabled = this.hasAttribute('disabled');\n const markPx = size === 'icon' ? 24 : size === 'sm' ? 15 : size === 'md' ? 17 : 20;\n const aria = this.#attr('aria-label') ?? (subtitle && size !== 'icon' ? `${text}, ${subtitle}` : text);\n const getUrl = this.#attr('get-url') ?? GET_URL;\n const webUrl = this.#attr('web-url') ?? WEB_WALLET_URL;\n\n const esc = (s: string) => s.replace(/[&<>\"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '\"': '"' })[c]!);\n const label = size === 'icon' ? '' : `<span class=\"txt\" part=\"text\"><b part=\"label\">${esc(text)}</b>${subtitle ? `<small part=\"subtitle\">${esc(subtitle)}</small>` : ''}</span>`;\n const mark = loading ? '<span class=\"spin\" aria-hidden=\"true\"></span>' : markSvg(markPx);\n const nf = this.#notFound\n ? `<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>`\n : '';\n 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…</span>' : ''}${nf}`;\n this.button!.addEventListener('click', () => void this.#click());\n }\n\n #emit(type: string, detail?: unknown, cancelable = false) {\n return this.dispatchEvent(new CustomEvent(type, { detail, bubbles: true, composed: true, cancelable }));\n }\n\n #setBusy(on: boolean) { this.#busy = on; this.#render(); }\n\n async #click() {\n if (this.hasAttribute('disabled') || this.hasAttribute('loading') || this.#busy) return;\n if (!this.#emit('bwalletx-signin', { element: this }, true)) return;\n\n const href = this.#attr('href');\n const authorizeUrl = this.#attr('authorize-url');\n if (authorizeUrl) {\n location.assign(await buildAuthorizeUrl({ authorizeUrl, clientId: this.#attr('client-id'), redirectUri: this.#attr('redirect-uri'), scope: this.#attr('scope') }));\n return;\n }\n if (href) { location.assign(href); return; }\n\n const challengeUrl = this.#attr('challenge-url');\n if (!challengeUrl) return; // event-only mode: the page runs its own flow\n\n this.#notFound = false;\n this.#setBusy(true);\n try {\n const ms = Number(this.#attr('discover-ms')) || 1200;\n const found = await discoverBwalletX(ms);\n if (!found) {\n this.#notFound = true;\n this.#emit('bwalletx-not-found');\n if (this.#attr('require-token')) this.#emit('bwalletx-access-denied', { code: 'not_installed', message: 'No wallet found' });\n return;\n }\n const requireToken = this.#attr('require-token');\n if (requireToken) {\n // $403 gate. The server's own config is authoritative; these attributes are passed along as a hint.\n const verifyUrl = this.#attr('verify-url');\n const min = this.#attr('min');\n const minBps = this.#attr('min-bps');\n const hint = { token: { id: requireToken, ...(minBps ? { minBps: Number(minBps) } : { min: min ?? '1' }) } };\n try {\n const a = await requestAccess({\n wallet: found.wallet,\n challenge: (identityKey) => postJson<AccessChallengeLike>(challengeUrl, { identityKey, require: hint }),\n verify: verifyUrl ? (response) => postAccess(verifyUrl, response) : undefined,\n });\n this.#emit('bwalletx-access-granted', { identityKey: a.response.identityKey, response: a.verified });\n } catch (e) {\n const err = e instanceof AccessError ? e : new AccessError('bad_request', String(e));\n this.#emit('bwalletx-access-denied', { code: err.code, message: err.message, have: err.have, need: err.need });\n }\n return;\n }\n const r = await signInWithBwalletX({ wallet: found.wallet, challenge: (identityKey) => postJson<Challenge>(challengeUrl, { identityKey }) });\n const verifyUrl = this.#attr('verify-url');\n const response = verifyUrl ? await postJson(verifyUrl, { identityKey: r.identityKey, nonce: r.nonce, signature: r.signature }) : null;\n this.#emit('bwalletx-signed-in', { identityKey: r.identityKey, method: found.method, nonce: r.nonce, signature: r.signature, response });\n } catch (error) {\n this.#emit('bwalletx-error', { error });\n } finally {\n this.#setBusy(false);\n }\n }\n };\n}\n\n/** Register <bwalletx-signin> (once). Safe to call on a server: it does nothing there. */\nexport function defineBwalletxSignin(tag = SIGNIN_TAG): CustomElementConstructor | undefined {\n if (typeof window === 'undefined' || typeof customElements === 'undefined') return undefined;\n const existing = customElements.get(tag);\n if (existing) return existing;\n const C = createClass();\n customElements.define(tag, C);\n return C;\n}\n"],"mappings":";;;;;;;;;AAGO,IAAM,iBAAiB;AACvB,IAAM,cAAc;AACpB,IAAM,gBAAgB,CAAC,gBAAgB,WAAW;AAgBlD,SAAS,iBAAiB,KAAK,MAAmC;AACvE,MAAI,O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