@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
|
@@ -0,0 +1,652 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ACCESS_CHALLENGE_LIFETIME_S,
|
|
3
|
+
ACCESS_PROTOCOL,
|
|
4
|
+
AccessError,
|
|
5
|
+
MAX_HOLDING_PROOFS,
|
|
6
|
+
atLeastRaw,
|
|
7
|
+
canonicalJson,
|
|
8
|
+
challengeBytes,
|
|
9
|
+
kindFor,
|
|
10
|
+
normaliseRequirement,
|
|
11
|
+
parseAccessChallenge,
|
|
12
|
+
tokenNeedRaw
|
|
13
|
+
} from "./chunk-MWD4BCO5.js";
|
|
14
|
+
|
|
15
|
+
// src/server.ts
|
|
16
|
+
import { ProtoWallet as ProtoWallet2, PublicKey as PublicKey2 } from "@bsv/sdk";
|
|
17
|
+
|
|
18
|
+
// src/nonce-stores.ts
|
|
19
|
+
var ttlSeconds = (c) => Math.max(1, Math.ceil((c.expiresAt - Date.now()) / 1e3));
|
|
20
|
+
function parse(v) {
|
|
21
|
+
if (v == null) return null;
|
|
22
|
+
try {
|
|
23
|
+
const c = typeof v === "string" ? JSON.parse(v) : v;
|
|
24
|
+
if (!c || typeof c.identityKey !== "string" || typeof c.message !== "string" || typeof c.expiresAt !== "number") return null;
|
|
25
|
+
return c.expiresAt < Date.now() ? null : c;
|
|
26
|
+
} catch {
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
function redisStore(opts) {
|
|
31
|
+
const { client } = opts;
|
|
32
|
+
const prefix = opts.prefix ?? "bwalletx:nonce:";
|
|
33
|
+
const getdel = client.getdel?.bind(client) ?? client.getDel?.bind(client);
|
|
34
|
+
if (!getdel) throw new Error("redisStore: the client needs getdel (or getDel). Redis 6.2+.");
|
|
35
|
+
return {
|
|
36
|
+
async put(nonce, c) {
|
|
37
|
+
const s = ttlSeconds(c);
|
|
38
|
+
if (opts.flavor === "ioredis") await client.set(prefix + nonce, JSON.stringify(c), "EX", s);
|
|
39
|
+
else await client.set(prefix + nonce, JSON.stringify(c), { ex: s, EX: s });
|
|
40
|
+
},
|
|
41
|
+
async take(nonce) {
|
|
42
|
+
return parse(await getdel(prefix + nonce));
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
function pgNonceTableSql(table = "bwalletx_nonces") {
|
|
47
|
+
const t = safeTable(table);
|
|
48
|
+
return `create table if not exists ${t} (
|
|
49
|
+
nonce text primary key,
|
|
50
|
+
challenge jsonb not null,
|
|
51
|
+
expires_at timestamptz not null
|
|
52
|
+
);
|
|
53
|
+
create index if not exists ${t.replace(".", "_")}_expires_idx on ${t} (expires_at);`;
|
|
54
|
+
}
|
|
55
|
+
function safeTable(t) {
|
|
56
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)?$/.test(t)) throw new Error(`pgStore: bad table name ${t}`);
|
|
57
|
+
return t;
|
|
58
|
+
}
|
|
59
|
+
function pgStore(opts) {
|
|
60
|
+
const t = safeTable(opts.table ?? "bwalletx_nonces");
|
|
61
|
+
const rows = (r) => Array.isArray(r) ? r : r.rows;
|
|
62
|
+
return {
|
|
63
|
+
async put(nonce, c) {
|
|
64
|
+
await opts.query(`delete from ${t} where expires_at < now()`, []);
|
|
65
|
+
await opts.query(`insert into ${t} (nonce, challenge, expires_at) values ($1, $2, to_timestamp($3 / 1000.0))`, [
|
|
66
|
+
nonce,
|
|
67
|
+
JSON.stringify(c),
|
|
68
|
+
c.expiresAt
|
|
69
|
+
]);
|
|
70
|
+
},
|
|
71
|
+
async take(nonce) {
|
|
72
|
+
const r = rows(await opts.query(`delete from ${t} where nonce = $1 returning challenge`, [nonce]));
|
|
73
|
+
const row = r[0];
|
|
74
|
+
return parse(row?.challenge);
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// src/session.ts
|
|
80
|
+
var MIN_SECRET_LENGTH = 32;
|
|
81
|
+
var enc = new TextEncoder();
|
|
82
|
+
var dec = new TextDecoder();
|
|
83
|
+
function b64u(bytes) {
|
|
84
|
+
let s = "";
|
|
85
|
+
for (const b of bytes) s += String.fromCharCode(b);
|
|
86
|
+
return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
87
|
+
}
|
|
88
|
+
function unb64u(s) {
|
|
89
|
+
if (!/^[A-Za-z0-9_-]*$/.test(s)) throw new Error("bad base64url");
|
|
90
|
+
const b = atob(s.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - s.length % 4) % 4));
|
|
91
|
+
return Uint8Array.from(b, (c) => c.charCodeAt(0));
|
|
92
|
+
}
|
|
93
|
+
function assertSecret(secret) {
|
|
94
|
+
if (typeof secret !== "string" || secret.length < MIN_SECRET_LENGTH) {
|
|
95
|
+
throw new Error(
|
|
96
|
+
`[@bwalletx/connect] A session secret of at least ${MIN_SECRET_LENGTH} characters is required. Set it in an environment variable (e.g. BWALLETX_SESSION_SECRET). There is no default.`
|
|
97
|
+
);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
var keys = /* @__PURE__ */ new Map();
|
|
101
|
+
function hmacKey(secret) {
|
|
102
|
+
let k = keys.get(secret);
|
|
103
|
+
if (!k) {
|
|
104
|
+
k = globalThis.crypto.subtle.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"]);
|
|
105
|
+
keys.set(secret, k);
|
|
106
|
+
}
|
|
107
|
+
return k;
|
|
108
|
+
}
|
|
109
|
+
async function signSession(claims, opts) {
|
|
110
|
+
assertSecret(opts.secret);
|
|
111
|
+
if (typeof claims.sub !== "string" || !claims.sub) throw new Error("session needs a sub (identity key)");
|
|
112
|
+
const iat = Math.floor((opts.now ?? Date.now()) / 1e3);
|
|
113
|
+
const payload = { ...claims, sub: claims.sub, iat, exp: iat + (opts.maxAge ?? 7 * 24 * 3600) };
|
|
114
|
+
const body = b64u(enc.encode(JSON.stringify(payload)));
|
|
115
|
+
const sig = new Uint8Array(await globalThis.crypto.subtle.sign("HMAC", await hmacKey(opts.secret), enc.encode(body)));
|
|
116
|
+
return `${body}.${b64u(sig)}`;
|
|
117
|
+
}
|
|
118
|
+
async function verifySession(token, opts) {
|
|
119
|
+
assertSecret(opts.secret);
|
|
120
|
+
if (typeof token !== "string" || token.length > 8192) return null;
|
|
121
|
+
const dot = token.indexOf(".");
|
|
122
|
+
if (dot < 1 || dot !== token.lastIndexOf(".")) return null;
|
|
123
|
+
const body = token.slice(0, dot);
|
|
124
|
+
try {
|
|
125
|
+
const sig = unb64u(token.slice(dot + 1));
|
|
126
|
+
const ok = await globalThis.crypto.subtle.verify("HMAC", await hmacKey(opts.secret), sig, enc.encode(body));
|
|
127
|
+
if (!ok) return null;
|
|
128
|
+
const p = JSON.parse(dec.decode(unb64u(body)));
|
|
129
|
+
if (!p || typeof p.sub !== "string" || typeof p.exp !== "number") return null;
|
|
130
|
+
if (Math.floor((opts.now ?? Date.now()) / 1e3) >= p.exp) return null;
|
|
131
|
+
return p;
|
|
132
|
+
} catch {
|
|
133
|
+
return null;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
function serializeCookie(value, o) {
|
|
137
|
+
const parts = [`${o.name}=${value}`, `Path=${o.path ?? "/"}`, `Max-Age=${o.maxAge}`, "HttpOnly", `SameSite=${o.sameSite ?? "Lax"}`];
|
|
138
|
+
if (o.secure !== false) parts.push("Secure");
|
|
139
|
+
if (o.domain) parts.push(`Domain=${o.domain}`);
|
|
140
|
+
return parts.join("; ");
|
|
141
|
+
}
|
|
142
|
+
function readCookie(header, name) {
|
|
143
|
+
if (!header) return null;
|
|
144
|
+
for (const part of header.split(";")) {
|
|
145
|
+
const i = part.indexOf("=");
|
|
146
|
+
if (i > 0 && part.slice(0, i).trim() === name) return part.slice(i + 1).trim();
|
|
147
|
+
}
|
|
148
|
+
return null;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// src/verify-payment.ts
|
|
152
|
+
import { P2PKH, Transaction, Utils } from "@bsv/sdk";
|
|
153
|
+
var PaymentVerificationError = class extends Error {
|
|
154
|
+
constructor(code, message, txid) {
|
|
155
|
+
super(message);
|
|
156
|
+
this.code = code;
|
|
157
|
+
this.txid = txid;
|
|
158
|
+
this.name = "PaymentVerificationError";
|
|
159
|
+
}
|
|
160
|
+
code;
|
|
161
|
+
txid;
|
|
162
|
+
};
|
|
163
|
+
var isHex = (s) => /^([0-9a-fA-F]{2})+$/.test(s);
|
|
164
|
+
var woc = (n) => `https://api.whatsonchain.com/v1/bsv/${n}`;
|
|
165
|
+
function parseTx(input) {
|
|
166
|
+
const bytes = typeof input === "string" ? Utils.toArray(input, "hex") : Array.from(input);
|
|
167
|
+
const tries = [
|
|
168
|
+
() => Transaction.fromAtomicBEEF(bytes),
|
|
169
|
+
() => Transaction.fromBEEF(bytes),
|
|
170
|
+
() => Transaction.fromBinary(bytes)
|
|
171
|
+
];
|
|
172
|
+
for (const t of tries) {
|
|
173
|
+
try {
|
|
174
|
+
return t();
|
|
175
|
+
} catch {
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
throw new PaymentVerificationError("BAD_TX", "Could not parse the transaction (expected a txid, raw tx, BEEF or Atomic BEEF).");
|
|
179
|
+
}
|
|
180
|
+
function expectedScript(e) {
|
|
181
|
+
if (!Number.isSafeInteger(e.satoshis) || e.satoshis < 0) throw new PaymentVerificationError("BAD_EXPECTED", "expected.satoshis must be a non-negative integer");
|
|
182
|
+
if (e.script) {
|
|
183
|
+
if (!isHex(e.script)) throw new PaymentVerificationError("BAD_EXPECTED", "expected.script must be hex");
|
|
184
|
+
return e.script.toLowerCase();
|
|
185
|
+
}
|
|
186
|
+
if (e.address) {
|
|
187
|
+
try {
|
|
188
|
+
return new P2PKH().lock(e.address).toHex();
|
|
189
|
+
} catch {
|
|
190
|
+
throw new PaymentVerificationError("BAD_EXPECTED", `Not a valid address: ${e.address}`);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
throw new PaymentVerificationError("BAD_EXPECTED", "Each expected output needs a script or an address");
|
|
194
|
+
}
|
|
195
|
+
async function getJson(f, url, headers = {}) {
|
|
196
|
+
let r;
|
|
197
|
+
try {
|
|
198
|
+
r = await f(url, { headers });
|
|
199
|
+
} catch (e) {
|
|
200
|
+
throw new PaymentVerificationError("NETWORK", `Could not reach ${new URL(url).host}: ${e.message}`);
|
|
201
|
+
}
|
|
202
|
+
const text = await r.text();
|
|
203
|
+
let body = text;
|
|
204
|
+
try {
|
|
205
|
+
body = JSON.parse(text);
|
|
206
|
+
} catch {
|
|
207
|
+
}
|
|
208
|
+
return { status: r.status, body };
|
|
209
|
+
}
|
|
210
|
+
async function checkStatus(o, f, txid) {
|
|
211
|
+
const mode = o.status ?? "woc";
|
|
212
|
+
if (mode === "none") return { state: "unchecked" };
|
|
213
|
+
if (mode === "arc") {
|
|
214
|
+
if (!o.arcUrl) throw new PaymentVerificationError("NETWORK", "status 'arc' needs arcUrl");
|
|
215
|
+
const { status: status2, body: body2 } = await getJson(f, `${o.arcUrl.replace(/\/$/, "")}/v1/tx/${txid}`, o.arcApiKey ? { Authorization: `Bearer ${o.arcApiKey}` } : {});
|
|
216
|
+
if (status2 === 404) return { state: "not-found", source: "arc" };
|
|
217
|
+
if (status2 >= 400) throw new PaymentVerificationError("NETWORK", `ARC answered ${status2}`, txid);
|
|
218
|
+
const b = body2;
|
|
219
|
+
const s = String(b.txStatus ?? "").toUpperCase();
|
|
220
|
+
if (s === "MINED" || s === "IMMUTABLE") return { state: "confirmed", confirmations: 1, source: "arc" };
|
|
221
|
+
if (s === "REJECTED" || s === "DOUBLE_SPEND_ATTEMPTED") return { state: "rejected", source: "arc", detail: b.extraInfo ?? s };
|
|
222
|
+
if (s === "UNKNOWN" || s === "") return { state: "not-found", source: "arc", detail: s };
|
|
223
|
+
return { state: "mempool", source: "arc", detail: s };
|
|
224
|
+
}
|
|
225
|
+
const { status, body } = await getJson(f, `${woc(o.network ?? "main")}/tx/hash/${txid}`);
|
|
226
|
+
if (status === 404) return { state: "not-found", source: "woc" };
|
|
227
|
+
if (status >= 400) throw new PaymentVerificationError("NETWORK", `WhatsOnChain answered ${status}`, txid);
|
|
228
|
+
const c = Number(body.confirmations ?? 0);
|
|
229
|
+
return c > 0 ? { state: "confirmed", confirmations: c, source: "woc" } : { state: "mempool", source: "woc" };
|
|
230
|
+
}
|
|
231
|
+
async function verifyPayment(o) {
|
|
232
|
+
const f = o.fetch ?? globalThis.fetch;
|
|
233
|
+
if (!o.expected?.length) throw new PaymentVerificationError("BAD_EXPECTED", "Pass at least one expected output");
|
|
234
|
+
const want = o.expected.map((e) => ({ script: expectedScript(e), satoshis: e.satoshis }));
|
|
235
|
+
let tx;
|
|
236
|
+
if (typeof o.tx === "string" && /^[0-9a-fA-F]{64}$/.test(o.tx)) {
|
|
237
|
+
const txid2 = o.tx.toLowerCase();
|
|
238
|
+
let r;
|
|
239
|
+
try {
|
|
240
|
+
r = await f(`${woc(o.network ?? "main")}/tx/${txid2}/hex`);
|
|
241
|
+
} catch (e) {
|
|
242
|
+
throw new PaymentVerificationError("NETWORK", `Could not reach WhatsOnChain: ${e.message}`, txid2);
|
|
243
|
+
}
|
|
244
|
+
if (r.status === 404) throw new PaymentVerificationError("TX_NOT_FOUND", `Transaction ${txid2} was not found`, txid2);
|
|
245
|
+
if (!r.ok) throw new PaymentVerificationError("NETWORK", `WhatsOnChain answered ${r.status}`, txid2);
|
|
246
|
+
tx = parseTx((await r.text()).trim());
|
|
247
|
+
if (tx.id("hex") !== txid2) throw new PaymentVerificationError("BAD_TX", "The fetched transaction does not match the txid", txid2);
|
|
248
|
+
} else {
|
|
249
|
+
if (typeof o.tx === "string" && !isHex(o.tx)) throw new PaymentVerificationError("BAD_TX", "tx must be a txid or hex");
|
|
250
|
+
tx = parseTx(o.tx);
|
|
251
|
+
}
|
|
252
|
+
const txid = tx.id("hex");
|
|
253
|
+
if (o.spv) {
|
|
254
|
+
let ok = false;
|
|
255
|
+
try {
|
|
256
|
+
ok = await tx.verify(o.spv);
|
|
257
|
+
} catch (e) {
|
|
258
|
+
throw new PaymentVerificationError("SPV_FAILED", `SPV check failed: ${e.message}`, txid);
|
|
259
|
+
}
|
|
260
|
+
if (!ok) throw new PaymentVerificationError("SPV_FAILED", "SPV check failed", txid);
|
|
261
|
+
}
|
|
262
|
+
const used = /* @__PURE__ */ new Set();
|
|
263
|
+
const matched = [];
|
|
264
|
+
for (const w of want) {
|
|
265
|
+
const vout = tx.outputs.findIndex(
|
|
266
|
+
(out, i) => !used.has(i) && out.lockingScript.toHex() === w.script && (out.satoshis ?? 0) >= w.satoshis
|
|
267
|
+
);
|
|
268
|
+
if (vout < 0) {
|
|
269
|
+
throw new PaymentVerificationError("OUTPUT_MISSING", `No output pays ${w.satoshis} sats to script ${w.script.slice(0, 16)}\u2026`, txid);
|
|
270
|
+
}
|
|
271
|
+
used.add(vout);
|
|
272
|
+
matched.push({ vout, satoshis: tx.outputs[vout].satoshis ?? 0, script: w.script });
|
|
273
|
+
}
|
|
274
|
+
const status = await checkStatus(o, f, txid);
|
|
275
|
+
if (status.state === "rejected") throw new PaymentVerificationError("REJECTED", `The network rejected ${txid}: ${status.detail ?? ""}`.trim(), txid);
|
|
276
|
+
if ((o.requireSeen || (o.minConfirmations ?? 0) > 0) && status.state !== "mempool" && status.state !== "confirmed") {
|
|
277
|
+
throw new PaymentVerificationError("NOT_SEEN", `The network has not seen ${txid} yet`, txid);
|
|
278
|
+
}
|
|
279
|
+
const conf = status.state === "confirmed" ? status.confirmations : 0;
|
|
280
|
+
if ((o.minConfirmations ?? 0) > conf) {
|
|
281
|
+
throw new PaymentVerificationError("NOT_SEEN", `${txid} has ${conf} confirmations, needs ${o.minConfirmations}`, txid);
|
|
282
|
+
}
|
|
283
|
+
return { ok: true, txid, matched, status };
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
// src/link.ts
|
|
287
|
+
var IdentityLinkConflictError = class extends Error {
|
|
288
|
+
constructor(identityKey, otherUserId) {
|
|
289
|
+
super("This bWalletX identity is already linked to a different account. Sign in with that account, or unlink it there first.");
|
|
290
|
+
this.identityKey = identityKey;
|
|
291
|
+
this.otherUserId = otherUserId;
|
|
292
|
+
this.name = "IdentityLinkConflictError";
|
|
293
|
+
}
|
|
294
|
+
identityKey;
|
|
295
|
+
otherUserId;
|
|
296
|
+
code = "IDENTITY_LINKED_TO_OTHER_USER";
|
|
297
|
+
};
|
|
298
|
+
var norm = (k) => {
|
|
299
|
+
if (typeof k !== "string" || !/^0[23][0-9a-fA-F]{64}$/.test(k)) throw new Error("identityKey must be a compressed public key (66 hex chars)");
|
|
300
|
+
return k.toLowerCase();
|
|
301
|
+
};
|
|
302
|
+
async function linkIdentity(userId, identityKey, cb) {
|
|
303
|
+
if (!userId) throw new Error("linkIdentity needs the current user id");
|
|
304
|
+
const key = norm(identityKey);
|
|
305
|
+
const owner = await cb.findUserByIdentityKey(key);
|
|
306
|
+
if (owner && owner !== userId) throw new IdentityLinkConflictError(key, owner);
|
|
307
|
+
if (owner === userId) return { status: "already-linked", userId, identityKey: key };
|
|
308
|
+
await cb.attach(userId, key);
|
|
309
|
+
return { status: "linked", userId, identityKey: key };
|
|
310
|
+
}
|
|
311
|
+
async function signInOrLink(identityKey, o) {
|
|
312
|
+
const key = norm(identityKey);
|
|
313
|
+
if (o.currentUserId) return linkIdentity(o.currentUserId, key, o);
|
|
314
|
+
const owner = await o.findUserByIdentityKey(key);
|
|
315
|
+
if (owner) return { status: "signed-in", userId: owner, identityKey: key };
|
|
316
|
+
if (!o.createUser) return { status: "unknown", userId: null, identityKey: key };
|
|
317
|
+
const userId = await o.createUser(key);
|
|
318
|
+
await o.attach(userId, key);
|
|
319
|
+
return { status: "created", userId, identityKey: key };
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
// src/access-server.ts
|
|
323
|
+
import { ProtoWallet, PublicKey, Signature } from "@bsv/sdk";
|
|
324
|
+
var bare = (tokenId) => tokenId.replace(/^bsv21:/, "");
|
|
325
|
+
function oneSatResolver(o = {}) {
|
|
326
|
+
const base = (o.base ?? "https://api.1sat.app/1sat").replace(/\/$/, "");
|
|
327
|
+
const f = o.fetch ?? globalThis.fetch;
|
|
328
|
+
const t = o.timeoutMs ?? 12e3;
|
|
329
|
+
const call = async (path, init) => {
|
|
330
|
+
const res = await f(`${base}${path}`, { ...init, signal: AbortSignal.timeout(t), cache: "no-store" });
|
|
331
|
+
if (!res.ok) throw new Error(`1sat ${res.status} for ${path}`);
|
|
332
|
+
return res.json();
|
|
333
|
+
};
|
|
334
|
+
return {
|
|
335
|
+
async tokenBalance(tokenId, addresses) {
|
|
336
|
+
const sorted = [...new Set(addresses)].sort();
|
|
337
|
+
let total = 0n;
|
|
338
|
+
for (let i = 0; i < sorted.length; i += 100) {
|
|
339
|
+
const j = await call(`/bsv21/${bare(tokenId)}/p2pkh/balance`, {
|
|
340
|
+
method: "POST",
|
|
341
|
+
headers: { "content-type": "application/json" },
|
|
342
|
+
body: JSON.stringify(sorted.slice(i, i + 100))
|
|
343
|
+
});
|
|
344
|
+
const b = j?.balance ?? 0;
|
|
345
|
+
const s = typeof b === "number" ? String(Math.trunc(b)) : String(b).split(".")[0] || "0";
|
|
346
|
+
if (!/^\d+$/.test(s)) throw new Error("1sat returned a bad balance");
|
|
347
|
+
total += BigInt(s);
|
|
348
|
+
}
|
|
349
|
+
return total.toString();
|
|
350
|
+
},
|
|
351
|
+
async tokenSupply(tokenId) {
|
|
352
|
+
const j = await call(`/bsv21/${bare(tokenId)}`);
|
|
353
|
+
const tok = (j?.token ?? j) || {};
|
|
354
|
+
const v = tok.amt ?? tok.max ?? tok.supply;
|
|
355
|
+
const s = v === void 0 || v === null ? "" : String(v).split(".")[0];
|
|
356
|
+
if (!/^\d+$/.test(s) || s === "0") throw new Error("1sat did not report a supply");
|
|
357
|
+
return s;
|
|
358
|
+
}
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
function bitSignResolver(o = {}) {
|
|
362
|
+
const base = (o.base ?? "https://bit-sign.online").replace(/\/$/, "");
|
|
363
|
+
const f = o.fetch ?? globalThis.fetch;
|
|
364
|
+
const tokens = o.tokens ?? oneSatResolver({ fetch: f });
|
|
365
|
+
return {
|
|
366
|
+
tokenBalance: (id, a) => tokens.tokenBalance(id, a),
|
|
367
|
+
tokenSupply: tokens.tokenSupply ? (id) => tokens.tokenSupply(id) : void 0,
|
|
368
|
+
async identity(identityKey, response) {
|
|
369
|
+
const res = await f(`${base}/api/access/verify`, {
|
|
370
|
+
method: "POST",
|
|
371
|
+
headers: { "content-type": "application/json" },
|
|
372
|
+
body: JSON.stringify({ response, only: "identity" }),
|
|
373
|
+
signal: AbortSignal.timeout(o.timeoutMs ?? 12e3),
|
|
374
|
+
cache: "no-store"
|
|
375
|
+
});
|
|
376
|
+
const j = await res.json().catch(() => null);
|
|
377
|
+
if (!j?.identity || j.identityKey !== identityKey) throw new Error(`bit-sign ${res.status}`);
|
|
378
|
+
return { level: Number(j.identity.level) || 0, kyc: j.identity.kyc === true };
|
|
379
|
+
}
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
function normalOrigin(origin) {
|
|
383
|
+
const u = new URL(origin);
|
|
384
|
+
if (u.origin === "null" || u.origin !== origin.replace(/\/$/, "")) throw new Error(`origin must be scheme://host[:port], got ${origin}`);
|
|
385
|
+
return u.origin;
|
|
386
|
+
}
|
|
387
|
+
function randomNonce() {
|
|
388
|
+
const b = new Uint8Array(18);
|
|
389
|
+
globalThis.crypto.getRandomValues(b);
|
|
390
|
+
let s = "";
|
|
391
|
+
for (const x of b) s += String.fromCharCode(x);
|
|
392
|
+
return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
393
|
+
}
|
|
394
|
+
async function createAccessChallenge(o) {
|
|
395
|
+
const origin = normalOrigin(o.origin);
|
|
396
|
+
const require2 = normaliseRequirement(o.require);
|
|
397
|
+
let sub;
|
|
398
|
+
if (o.identityKey !== void 0 && o.identityKey !== null && o.identityKey !== "") {
|
|
399
|
+
if (!isIdentityKey(o.identityKey)) throw new AccessError("bad_request", "identityKey must be a compressed public key");
|
|
400
|
+
sub = o.identityKey.toLowerCase();
|
|
401
|
+
}
|
|
402
|
+
const iat = Math.floor((o.now ?? Date.now()) / 1e3);
|
|
403
|
+
const exp = iat + (o.lifetimeS ?? ACCESS_CHALLENGE_LIFETIME_S);
|
|
404
|
+
const nonce = randomNonce();
|
|
405
|
+
const c = { v: 1, kind: o.kind ?? kindFor(require2), origin, nonce, iat, exp, sub, require: require2 };
|
|
406
|
+
const challenge = canonicalJson(c);
|
|
407
|
+
await o.store.put(nonce, { identityKey: sub ?? "", origin, message: challenge, expiresAt: exp * 1e3 });
|
|
408
|
+
return { challenge, nonce, kind: c.kind, protocolID: ACCESS_PROTOCOL, keyID: nonce, exp };
|
|
409
|
+
}
|
|
410
|
+
var isByteArray = (s) => Array.isArray(s) && s.length >= 8 && s.length <= 80 && s.every((b) => Number.isInteger(b) && b >= 0 && b <= 255);
|
|
411
|
+
function verifyHoldingProof(challenge, p) {
|
|
412
|
+
const proof = p;
|
|
413
|
+
if (!proof || typeof proof.pubkey !== "string" || !/^0[23][0-9a-fA-F]{64}$/.test(proof.pubkey) || !isByteArray(proof.signature)) return null;
|
|
414
|
+
try {
|
|
415
|
+
const pub = PublicKey.fromString(proof.pubkey);
|
|
416
|
+
const sig = Signature.fromDER(proof.signature);
|
|
417
|
+
return pub.verify(challengeBytes(challenge), sig) ? pub.toAddress() : null;
|
|
418
|
+
} catch {
|
|
419
|
+
return null;
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
async function verifyAccess(o) {
|
|
423
|
+
const r = o.response;
|
|
424
|
+
if (!r || typeof r !== "object" || r.v !== 1) throw new AccessError("bad_request", "response must be { v: 1, challenge, identityKey, signature }");
|
|
425
|
+
const c = parseAccessChallenge(r.challenge);
|
|
426
|
+
const nowS = Math.floor((o.now ?? Date.now()) / 1e3);
|
|
427
|
+
const pending = await o.store.take(c.nonce);
|
|
428
|
+
if (!pending) throw new AccessError(nowS >= c.exp ? "expired" : "replay");
|
|
429
|
+
if (nowS >= c.exp || (o.now ?? Date.now()) > pending.expiresAt) throw new AccessError("expired");
|
|
430
|
+
if (pending.message !== r.challenge) throw new AccessError("replay", "challenge does not match the one issued");
|
|
431
|
+
let origin;
|
|
432
|
+
try {
|
|
433
|
+
origin = normalOrigin(o.origin);
|
|
434
|
+
} catch {
|
|
435
|
+
throw new AccessError("bad_request", "server origin is misconfigured");
|
|
436
|
+
}
|
|
437
|
+
if (c.origin !== origin || pending.origin !== origin) throw new AccessError("bad_request", "origin mismatch");
|
|
438
|
+
if (o.require && canonicalJson(normaliseRequirement(o.require)) !== canonicalJson(c.require)) {
|
|
439
|
+
throw new AccessError("bad_request", "challenge requirement does not match this gate");
|
|
440
|
+
}
|
|
441
|
+
if (!isIdentityKey(r.identityKey)) throw new AccessError("bad_request", "identityKey must be a compressed public key");
|
|
442
|
+
const identityKey = r.identityKey.toLowerCase();
|
|
443
|
+
if (c.sub && c.sub !== identityKey) throw new AccessError("wrong_account");
|
|
444
|
+
if (!isByteArray(r.signature)) throw new AccessError("invalid_signature");
|
|
445
|
+
let valid = false;
|
|
446
|
+
try {
|
|
447
|
+
({ valid } = await new ProtoWallet("anyone").verifySignature({
|
|
448
|
+
protocolID: ACCESS_PROTOCOL,
|
|
449
|
+
keyID: c.nonce,
|
|
450
|
+
counterparty: identityKey,
|
|
451
|
+
data: challengeBytes(r.challenge),
|
|
452
|
+
signature: r.signature
|
|
453
|
+
}));
|
|
454
|
+
} catch {
|
|
455
|
+
valid = false;
|
|
456
|
+
}
|
|
457
|
+
if (!valid) throw new AccessError("invalid_signature");
|
|
458
|
+
const grant = { ok: true, identityKey, kind: c.kind, require: c.require, addresses: [], have: {} };
|
|
459
|
+
if (c.require.identityLevel || c.require.kyc) {
|
|
460
|
+
if (!o.resolver.identity) throw new AccessError("indexer_unavailable", "no identity resolver configured");
|
|
461
|
+
let id;
|
|
462
|
+
try {
|
|
463
|
+
id = await o.resolver.identity(identityKey, r);
|
|
464
|
+
} catch (e) {
|
|
465
|
+
throw new AccessError("indexer_unavailable", `identity lookup failed: ${e.message}`);
|
|
466
|
+
}
|
|
467
|
+
grant.have.identityLevel = id.level;
|
|
468
|
+
grant.have.kyc = id.kyc;
|
|
469
|
+
if (c.require.kyc && !id.kyc) throw new AccessError("kyc_required");
|
|
470
|
+
if (c.require.identityLevel && id.level < c.require.identityLevel) {
|
|
471
|
+
throw new AccessError("identity_level_too_low", void 0, { have: id.level, need: c.require.identityLevel });
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
if (c.require.token) {
|
|
475
|
+
const proofs = Array.isArray(r.holdings) ? r.holdings.slice(0, MAX_HOLDING_PROOFS) : [];
|
|
476
|
+
const addresses = /* @__PURE__ */ new Set();
|
|
477
|
+
for (const p of proofs) {
|
|
478
|
+
const a = verifyHoldingProof(r.challenge, p);
|
|
479
|
+
if (a) addresses.add(a);
|
|
480
|
+
}
|
|
481
|
+
grant.addresses = [...addresses].sort();
|
|
482
|
+
const check = await checkTokenHolding(c.require, grant.addresses, o.resolver);
|
|
483
|
+
grant.have.tokenRaw = check.have;
|
|
484
|
+
grant.have.needRaw = check.need;
|
|
485
|
+
}
|
|
486
|
+
return grant;
|
|
487
|
+
}
|
|
488
|
+
async function checkTokenHolding(require2, addresses, resolver) {
|
|
489
|
+
const t = require2.token;
|
|
490
|
+
if (!t) return { have: "0", need: "0" };
|
|
491
|
+
let supply;
|
|
492
|
+
if (t.minBps) {
|
|
493
|
+
if (!resolver.tokenSupply) throw new AccessError("indexer_unavailable", "no supply resolver configured");
|
|
494
|
+
try {
|
|
495
|
+
supply = await resolver.tokenSupply(t.id);
|
|
496
|
+
} catch (e) {
|
|
497
|
+
throw new AccessError("indexer_unavailable", `supply lookup failed: ${e.message}`);
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
const need = tokenNeedRaw(t, supply);
|
|
501
|
+
if (!addresses.length) throw new AccessError("insufficient_tokens", void 0, { have: "0", need });
|
|
502
|
+
let have;
|
|
503
|
+
try {
|
|
504
|
+
have = await resolver.tokenBalance(t.id, addresses);
|
|
505
|
+
} catch (e) {
|
|
506
|
+
throw new AccessError("indexer_unavailable", `balance lookup failed: ${e.message}`);
|
|
507
|
+
}
|
|
508
|
+
if (!atLeastRaw(have, need)) throw new AccessError("insufficient_tokens", void 0, { have, need });
|
|
509
|
+
return { have, need };
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
// src/server.ts
|
|
513
|
+
var LOGIN_PROTOCOL = [2, "bwallet sign in"];
|
|
514
|
+
var CHALLENGE_LIFETIME_MS = 2 * 60 * 1e3;
|
|
515
|
+
var warned = false;
|
|
516
|
+
function memoryStore(opts = {}) {
|
|
517
|
+
const prod = typeof process !== "undefined" && process.env?.NODE_ENV === "production";
|
|
518
|
+
if ((prod || !opts.quiet) && !warned) {
|
|
519
|
+
warned = true;
|
|
520
|
+
console.warn(
|
|
521
|
+
prod ? "[@bwalletx/connect] WARNING: the in-memory nonce store is running in production. It is not shared between instances and breaks on serverless. Use redisStore or pgStore." : "[@bwalletx/connect] Using the in-memory nonce store. It is for development only; pass a shared store (redisStore, pgStore) in production."
|
|
522
|
+
);
|
|
523
|
+
}
|
|
524
|
+
const m = /* @__PURE__ */ new Map();
|
|
525
|
+
return {
|
|
526
|
+
put(nonce, c) {
|
|
527
|
+
const now = Date.now();
|
|
528
|
+
for (const [k, v] of m) if (v.expiresAt < now) m.delete(k);
|
|
529
|
+
m.set(nonce, c);
|
|
530
|
+
},
|
|
531
|
+
take(nonce) {
|
|
532
|
+
const c = m.get(nonce) ?? null;
|
|
533
|
+
m.delete(nonce);
|
|
534
|
+
return c;
|
|
535
|
+
}
|
|
536
|
+
};
|
|
537
|
+
}
|
|
538
|
+
var defaultStore = null;
|
|
539
|
+
var storeOrDefault = (s) => s ?? (defaultStore ??= memoryStore());
|
|
540
|
+
function isIdentityKey(x) {
|
|
541
|
+
if (typeof x !== "string" || !/^0[23][0-9a-fA-F]{64}$/.test(x)) return false;
|
|
542
|
+
try {
|
|
543
|
+
PublicKey2.fromString(x);
|
|
544
|
+
return true;
|
|
545
|
+
} catch {
|
|
546
|
+
return false;
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
function normalOrigin2(origin) {
|
|
550
|
+
const u = new URL(origin);
|
|
551
|
+
if (u.origin === "null" || u.origin !== origin.replace(/\/$/, "")) {
|
|
552
|
+
throw new Error(`origin must be scheme://host[:port], got ${origin}`);
|
|
553
|
+
}
|
|
554
|
+
return u.origin;
|
|
555
|
+
}
|
|
556
|
+
function loginMessage(origin, nonce, expiresAt) {
|
|
557
|
+
return [
|
|
558
|
+
`Sign in to ${new URL(origin).host} with bWallet`,
|
|
559
|
+
"",
|
|
560
|
+
"This proves you hold this wallet. It does not spend anything.",
|
|
561
|
+
"",
|
|
562
|
+
`Origin: ${origin}`,
|
|
563
|
+
`Nonce: ${nonce}`,
|
|
564
|
+
`Expires: ${new Date(expiresAt).toISOString()}`
|
|
565
|
+
].join("\n");
|
|
566
|
+
}
|
|
567
|
+
function randomNonce2() {
|
|
568
|
+
const b = new Uint8Array(16);
|
|
569
|
+
globalThis.crypto.getRandomValues(b);
|
|
570
|
+
let s = "";
|
|
571
|
+
for (const x of b) s += String.fromCharCode(x);
|
|
572
|
+
return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
573
|
+
}
|
|
574
|
+
async function createChallenge(opts) {
|
|
575
|
+
if (!isIdentityKey(opts.identityKey)) throw new Error("identityKey must be a compressed public key (66 hex chars)");
|
|
576
|
+
const origin = normalOrigin2(opts.origin);
|
|
577
|
+
const nonce = randomNonce2();
|
|
578
|
+
const expiresAt = Date.now() + CHALLENGE_LIFETIME_MS;
|
|
579
|
+
const message = loginMessage(origin, nonce, expiresAt);
|
|
580
|
+
await storeOrDefault(opts.store).put(nonce, { identityKey: opts.identityKey.toLowerCase(), origin, message, expiresAt });
|
|
581
|
+
return { nonce, message, protocolID: LOGIN_PROTOCOL, keyID: nonce, expiresAt };
|
|
582
|
+
}
|
|
583
|
+
async function verifySignIn(opts) {
|
|
584
|
+
if (typeof opts.nonce !== "string" || opts.nonce.length > 64) return null;
|
|
585
|
+
const c = await storeOrDefault(opts.store).take(opts.nonce);
|
|
586
|
+
if (!c || Date.now() > c.expiresAt) return null;
|
|
587
|
+
let origin;
|
|
588
|
+
try {
|
|
589
|
+
origin = normalOrigin2(opts.origin);
|
|
590
|
+
} catch {
|
|
591
|
+
return null;
|
|
592
|
+
}
|
|
593
|
+
if (c.origin !== origin) return null;
|
|
594
|
+
if (!isIdentityKey(opts.identityKey)) return null;
|
|
595
|
+
const identityKey = opts.identityKey.toLowerCase();
|
|
596
|
+
if (c.identityKey !== identityKey) return null;
|
|
597
|
+
const sig = opts.signature;
|
|
598
|
+
if (!Array.isArray(sig) || sig.length < 8 || sig.length > 80 || !sig.every((b) => Number.isInteger(b) && b >= 0 && b <= 255)) {
|
|
599
|
+
return null;
|
|
600
|
+
}
|
|
601
|
+
try {
|
|
602
|
+
const { valid } = await new ProtoWallet2("anyone").verifySignature({
|
|
603
|
+
protocolID: LOGIN_PROTOCOL,
|
|
604
|
+
keyID: opts.nonce,
|
|
605
|
+
counterparty: identityKey,
|
|
606
|
+
data: Array.from(new TextEncoder().encode(c.message)),
|
|
607
|
+
signature: sig
|
|
608
|
+
});
|
|
609
|
+
return valid ? identityKey : null;
|
|
610
|
+
} catch {
|
|
611
|
+
return null;
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
function originAllowed(requestOrigin, origin) {
|
|
615
|
+
try {
|
|
616
|
+
return !!requestOrigin && requestOrigin === normalOrigin2(origin);
|
|
617
|
+
} catch {
|
|
618
|
+
return false;
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
export {
|
|
623
|
+
redisStore,
|
|
624
|
+
pgNonceTableSql,
|
|
625
|
+
pgStore,
|
|
626
|
+
MIN_SECRET_LENGTH,
|
|
627
|
+
assertSecret,
|
|
628
|
+
signSession,
|
|
629
|
+
verifySession,
|
|
630
|
+
serializeCookie,
|
|
631
|
+
readCookie,
|
|
632
|
+
PaymentVerificationError,
|
|
633
|
+
verifyPayment,
|
|
634
|
+
IdentityLinkConflictError,
|
|
635
|
+
linkIdentity,
|
|
636
|
+
signInOrLink,
|
|
637
|
+
oneSatResolver,
|
|
638
|
+
bitSignResolver,
|
|
639
|
+
createAccessChallenge,
|
|
640
|
+
verifyHoldingProof,
|
|
641
|
+
verifyAccess,
|
|
642
|
+
checkTokenHolding,
|
|
643
|
+
LOGIN_PROTOCOL,
|
|
644
|
+
CHALLENGE_LIFETIME_MS,
|
|
645
|
+
memoryStore,
|
|
646
|
+
isIdentityKey,
|
|
647
|
+
loginMessage,
|
|
648
|
+
createChallenge,
|
|
649
|
+
verifySignIn,
|
|
650
|
+
originAllowed
|
|
651
|
+
};
|
|
652
|
+
//# sourceMappingURL=chunk-QRXFL66W.js.map
|