@bwalletx/connect 0.4.1 → 0.5.3
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 +20 -0
- package/README.md +6 -2
- 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-Dp0eKIOc.d.cts +118 -0
- package/dist/access-Dp0eKIOc.d.ts +118 -0
- package/dist/bwalletx-connect.global.js +20 -17
- package/dist/bwalletx-connect.global.js.map +1 -1
- package/dist/{chunk-NNMUSWPG.js → chunk-IUDD7YTQ.js} +200 -10
- package/dist/chunk-IUDD7YTQ.js.map +1 -0
- package/dist/chunk-MWD4BCO5.js +182 -0
- package/dist/chunk-MWD4BCO5.js.map +1 -0
- package/dist/{chunk-FUQ46RJV.js → chunk-PI42H3XY.js} +65 -10
- package/dist/chunk-PI42H3XY.js.map +1 -0
- package/dist/{chunk-7NAKOJGZ.js → chunk-QRXFL66W.js} +220 -10
- package/dist/chunk-QRXFL66W.js.map +1 -0
- package/dist/element.cjs +290 -14
- package/dist/element.cjs.map +1 -1
- package/dist/element.js +2 -1
- package/dist/element.js.map +1 -1
- package/dist/index.cjs +437 -32
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +71 -1
- package/dist/index.d.ts +71 -1
- package/dist/index.js +36 -4
- package/dist/index.js.map +1 -1
- package/dist/next.cjs +377 -9
- package/dist/next.cjs.map +1 -1
- package/dist/next.d.cts +52 -2
- package/dist/next.d.ts +52 -2
- package/dist/next.js +92 -1
- package/dist/next.js.map +1 -1
- package/dist/react.cjs +561 -226
- package/dist/react.cjs.map +1 -1
- package/dist/react.d.cts +5 -0
- package/dist/react.d.ts +5 -0
- package/dist/react.js +12 -3
- package/dist/react.js.map +1 -1
- package/dist/server.cjs +406 -9
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.cts +111 -1
- package/dist/server.d.ts +111 -1
- package/dist/server.js +47 -1
- package/package.json +12 -11
- package/dist/chunk-7NAKOJGZ.js.map +0 -1
- package/dist/chunk-FUQ46RJV.js.map +0 -1
- package/dist/chunk-NNMUSWPG.js.map +0 -1
package/dist/server.cjs
CHANGED
|
@@ -20,30 +20,52 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
20
20
|
// src/server.ts
|
|
21
21
|
var server_exports = {};
|
|
22
22
|
__export(server_exports, {
|
|
23
|
+
ACCESS_CHALLENGE_LIFETIME_S: () => ACCESS_CHALLENGE_LIFETIME_S,
|
|
24
|
+
ACCESS_ERROR_STATUS: () => ACCESS_ERROR_STATUS,
|
|
25
|
+
ACCESS_PROTOCOL: () => ACCESS_PROTOCOL,
|
|
26
|
+
ACCESS_VERSION: () => ACCESS_VERSION,
|
|
27
|
+
AccessError: () => AccessError,
|
|
23
28
|
CHALLENGE_LIFETIME_MS: () => CHALLENGE_LIFETIME_MS,
|
|
24
29
|
IdentityLinkConflictError: () => IdentityLinkConflictError,
|
|
25
30
|
LOGIN_PROTOCOL: () => LOGIN_PROTOCOL,
|
|
31
|
+
MAX_HOLDING_PROOFS: () => MAX_HOLDING_PROOFS,
|
|
26
32
|
MIN_SECRET_LENGTH: () => MIN_SECRET_LENGTH,
|
|
33
|
+
PROTOCOL_MEDIA: () => PROTOCOL_MEDIA,
|
|
27
34
|
PaymentVerificationError: () => PaymentVerificationError,
|
|
35
|
+
accessErrorMessage: () => accessErrorMessage,
|
|
36
|
+
atLeastRaw: () => atLeastRaw,
|
|
37
|
+
bitSignResolver: () => bitSignResolver,
|
|
38
|
+
canonicalJson: () => canonicalJson,
|
|
39
|
+
challengeBytes: () => challengeBytes,
|
|
40
|
+
checkTokenHolding: () => checkTokenHolding,
|
|
41
|
+
createAccessChallenge: () => createAccessChallenge,
|
|
28
42
|
createChallenge: () => createChallenge,
|
|
29
43
|
isIdentityKey: () => isIdentityKey,
|
|
44
|
+
kindFor: () => kindFor,
|
|
30
45
|
linkIdentity: () => linkIdentity,
|
|
31
46
|
loginMessage: () => loginMessage,
|
|
32
47
|
memoryStore: () => memoryStore,
|
|
48
|
+
normaliseRequirement: () => normaliseRequirement,
|
|
49
|
+
oneSatResolver: () => oneSatResolver,
|
|
33
50
|
originAllowed: () => originAllowed,
|
|
51
|
+
parseAccessChallenge: () => parseAccessChallenge,
|
|
34
52
|
pgNonceTableSql: () => pgNonceTableSql,
|
|
35
53
|
pgStore: () => pgStore,
|
|
54
|
+
protocolMediaUrl: () => protocolMediaUrl,
|
|
36
55
|
readCookie: () => readCookie,
|
|
37
56
|
redisStore: () => redisStore,
|
|
38
57
|
serializeCookie: () => serializeCookie,
|
|
39
58
|
signInOrLink: () => signInOrLink,
|
|
40
59
|
signSession: () => signSession,
|
|
60
|
+
tokenNeedRaw: () => tokenNeedRaw,
|
|
61
|
+
verifyAccess: () => verifyAccess,
|
|
62
|
+
verifyHoldingProof: () => verifyHoldingProof,
|
|
41
63
|
verifyPayment: () => verifyPayment,
|
|
42
64
|
verifySession: () => verifySession,
|
|
43
65
|
verifySignIn: () => verifySignIn
|
|
44
66
|
});
|
|
45
67
|
module.exports = __toCommonJS(server_exports);
|
|
46
|
-
var
|
|
68
|
+
var import_sdk3 = require("@bsv/sdk");
|
|
47
69
|
|
|
48
70
|
// src/nonce-stores.ts
|
|
49
71
|
var ttlSeconds = (c) => Math.max(1, Math.ceil((c.expiresAt - Date.now()) / 1e3));
|
|
@@ -349,6 +371,359 @@ async function signInOrLink(identityKey, o) {
|
|
|
349
371
|
return { status: "created", userId, identityKey: key };
|
|
350
372
|
}
|
|
351
373
|
|
|
374
|
+
// src/access.ts
|
|
375
|
+
var ACCESS_VERSION = 1;
|
|
376
|
+
var ACCESS_PROTOCOL = [2, "bwalletx access"];
|
|
377
|
+
var ACCESS_CHALLENGE_LIFETIME_S = 120;
|
|
378
|
+
var MAX_HOLDING_PROOFS = 50;
|
|
379
|
+
var ACCESS_ERROR_STATUS = {
|
|
380
|
+
not_installed: 424,
|
|
381
|
+
user_rejected: 403,
|
|
382
|
+
wrong_account: 409,
|
|
383
|
+
insufficient_tokens: 403,
|
|
384
|
+
identity_level_too_low: 403,
|
|
385
|
+
kyc_required: 403,
|
|
386
|
+
indexer_unavailable: 503,
|
|
387
|
+
expired: 401,
|
|
388
|
+
replay: 401,
|
|
389
|
+
invalid_signature: 401,
|
|
390
|
+
bad_request: 400
|
|
391
|
+
};
|
|
392
|
+
var AccessError = class extends Error {
|
|
393
|
+
code;
|
|
394
|
+
have;
|
|
395
|
+
need;
|
|
396
|
+
constructor(code, message, extra = {}) {
|
|
397
|
+
super(message ?? code);
|
|
398
|
+
this.name = "AccessError";
|
|
399
|
+
this.code = code;
|
|
400
|
+
this.have = extra.have;
|
|
401
|
+
this.need = extra.need;
|
|
402
|
+
}
|
|
403
|
+
toJSON() {
|
|
404
|
+
const b = { error: this.code, message: this.message };
|
|
405
|
+
if (this.have !== void 0) b.have = this.have;
|
|
406
|
+
if (this.need !== void 0) b.need = this.need;
|
|
407
|
+
return b;
|
|
408
|
+
}
|
|
409
|
+
};
|
|
410
|
+
var PROTOCOL_MEDIA = {
|
|
411
|
+
"401": { name: "Identity", color: "#22c55e", video: "assets/protocol/401.mp4", poster: "assets/protocol/401.jpg" },
|
|
412
|
+
"402": { name: "Payment", color: "#3b82f6", video: "assets/protocol/402.mp4", poster: "assets/protocol/402.jpg" },
|
|
413
|
+
"403": { name: "Access", color: "#ef4444", video: "assets/protocol/403.mp4", poster: "assets/protocol/403.jpg" }
|
|
414
|
+
};
|
|
415
|
+
function protocolMediaUrl(kind, which, version = "latest") {
|
|
416
|
+
return `https://unpkg.com/@bwalletx/connect@${version}/${PROTOCOL_MEDIA[kind][which]}`;
|
|
417
|
+
}
|
|
418
|
+
function canonicalJson(v) {
|
|
419
|
+
if (v === null) return "null";
|
|
420
|
+
if (typeof v === "string" || typeof v === "boolean") return JSON.stringify(v);
|
|
421
|
+
if (typeof v === "number") {
|
|
422
|
+
if (!Number.isFinite(v)) throw new Error("canonicalJson: non-finite number");
|
|
423
|
+
return JSON.stringify(v);
|
|
424
|
+
}
|
|
425
|
+
if (Array.isArray(v)) return `[${v.map((x) => canonicalJson(x)).join(",")}]`;
|
|
426
|
+
if (typeof v === "object") {
|
|
427
|
+
const o = v;
|
|
428
|
+
const keys2 = Object.keys(o).filter((k) => o[k] !== void 0).sort();
|
|
429
|
+
return `{${keys2.map((k) => `${JSON.stringify(k)}:${canonicalJson(o[k])}`).join(",")}}`;
|
|
430
|
+
}
|
|
431
|
+
throw new Error(`canonicalJson: unsupported ${typeof v}`);
|
|
432
|
+
}
|
|
433
|
+
function challengeBytes(challenge) {
|
|
434
|
+
return Array.from(new TextEncoder().encode(challenge));
|
|
435
|
+
}
|
|
436
|
+
var TOKEN_ID = /^bsv21:[0-9a-f]{64}_\d{1,6}$/;
|
|
437
|
+
var RAW = /^[1-9]\d{0,38}$/;
|
|
438
|
+
function normaliseRequirement(r) {
|
|
439
|
+
if (!r || typeof r !== "object") throw new AccessError("bad_request", "require must be an object");
|
|
440
|
+
const req = r;
|
|
441
|
+
const out = {};
|
|
442
|
+
if (req.token !== void 0) {
|
|
443
|
+
const t = req.token;
|
|
444
|
+
if (!t || typeof t !== "object" || typeof t.id !== "string") throw new AccessError("bad_request", "require.token.id is required");
|
|
445
|
+
const id = t.id.trim().toLowerCase();
|
|
446
|
+
if (!TOKEN_ID.test(id)) throw new AccessError("bad_request", "require.token.id must be 'bsv21:<txid>_<vout>'");
|
|
447
|
+
const hasMin = t.min !== void 0;
|
|
448
|
+
const hasBps = t.minBps !== void 0;
|
|
449
|
+
if (hasMin === hasBps) throw new AccessError("bad_request", "require.token needs exactly one of min or minBps");
|
|
450
|
+
out.token = { id };
|
|
451
|
+
if (hasMin) {
|
|
452
|
+
if (typeof t.min !== "string" || !RAW.test(t.min)) throw new AccessError("bad_request", "require.token.min must be a positive integer string (raw units)");
|
|
453
|
+
out.token.min = t.min;
|
|
454
|
+
} else {
|
|
455
|
+
if (!Number.isInteger(t.minBps) || t.minBps < 1 || t.minBps > 1e4) {
|
|
456
|
+
throw new AccessError("bad_request", "require.token.minBps must be an integer 1..10000");
|
|
457
|
+
}
|
|
458
|
+
out.token.minBps = t.minBps;
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
if (req.identityLevel !== void 0) {
|
|
462
|
+
if (!Number.isInteger(req.identityLevel) || req.identityLevel < 1 || req.identityLevel > 10) {
|
|
463
|
+
throw new AccessError("bad_request", "require.identityLevel must be an integer 1..10");
|
|
464
|
+
}
|
|
465
|
+
out.identityLevel = req.identityLevel;
|
|
466
|
+
}
|
|
467
|
+
if (req.kyc !== void 0) {
|
|
468
|
+
if (typeof req.kyc !== "boolean") throw new AccessError("bad_request", "require.kyc must be a boolean");
|
|
469
|
+
if (req.kyc) out.kyc = true;
|
|
470
|
+
}
|
|
471
|
+
if (!out.token && !out.identityLevel && !out.kyc) throw new AccessError("bad_request", "require is empty");
|
|
472
|
+
return out;
|
|
473
|
+
}
|
|
474
|
+
function kindFor(r) {
|
|
475
|
+
return r.token ? "403" : "401";
|
|
476
|
+
}
|
|
477
|
+
function parseAccessChallenge(s) {
|
|
478
|
+
if (typeof s !== "string" || s.length > 4096) throw new AccessError("bad_request", "challenge must be a string");
|
|
479
|
+
let c;
|
|
480
|
+
try {
|
|
481
|
+
c = JSON.parse(s);
|
|
482
|
+
} catch {
|
|
483
|
+
throw new AccessError("bad_request", "challenge is not JSON");
|
|
484
|
+
}
|
|
485
|
+
if (!c || typeof c !== "object" || c.v !== 1) throw new AccessError("bad_request", "unsupported challenge version");
|
|
486
|
+
if (c.kind !== "401" && c.kind !== "402" && c.kind !== "403") throw new AccessError("bad_request", "bad kind");
|
|
487
|
+
if (typeof c.origin !== "string" || typeof c.nonce !== "string" || !/^[A-Za-z0-9_-]{16,64}$/.test(c.nonce)) {
|
|
488
|
+
throw new AccessError("bad_request", "bad origin or nonce");
|
|
489
|
+
}
|
|
490
|
+
if (!Number.isInteger(c.iat) || !Number.isInteger(c.exp) || c.exp <= c.iat) throw new AccessError("bad_request", "bad iat/exp");
|
|
491
|
+
if (c.sub !== void 0 && (typeof c.sub !== "string" || !/^0[23][0-9a-f]{64}$/.test(c.sub))) throw new AccessError("bad_request", "bad sub");
|
|
492
|
+
c.require = normaliseRequirement(c.require);
|
|
493
|
+
if (canonicalJson(c) !== s) throw new AccessError("bad_request", "challenge is not canonical");
|
|
494
|
+
return c;
|
|
495
|
+
}
|
|
496
|
+
function tokenNeedRaw(t, supplyRaw) {
|
|
497
|
+
if (t.min) return t.min;
|
|
498
|
+
if (supplyRaw === void 0 || !/^\d+$/.test(supplyRaw)) throw new AccessError("indexer_unavailable", "token supply unknown");
|
|
499
|
+
const n = BigInt(supplyRaw) * BigInt(t.minBps);
|
|
500
|
+
const need = (n + 9999n) / 10000n;
|
|
501
|
+
return (need < 1n ? 1n : need).toString();
|
|
502
|
+
}
|
|
503
|
+
function atLeastRaw(have, need) {
|
|
504
|
+
try {
|
|
505
|
+
return BigInt(have) >= BigInt(need);
|
|
506
|
+
} catch {
|
|
507
|
+
return false;
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
function accessErrorMessage(code, e = {}) {
|
|
511
|
+
switch (code) {
|
|
512
|
+
case "not_installed":
|
|
513
|
+
return "No bWalletX (or other BRC-100 wallet) was found.";
|
|
514
|
+
case "user_rejected":
|
|
515
|
+
return "The request was declined in the wallet.";
|
|
516
|
+
case "wrong_account":
|
|
517
|
+
return "The wallet is signed in to a different account than this site expects.";
|
|
518
|
+
case "insufficient_tokens":
|
|
519
|
+
return `Not enough tokens: holding ${e.have ?? 0}, need ${e.need ?? "?"}.`;
|
|
520
|
+
case "identity_level_too_low":
|
|
521
|
+
return `Identity level ${e.have ?? 0} is below the required level ${e.need ?? "?"}.`;
|
|
522
|
+
case "kyc_required":
|
|
523
|
+
return "A verified identity (KYC) is required.";
|
|
524
|
+
case "indexer_unavailable":
|
|
525
|
+
return "Holdings could not be checked right now. Try again shortly.";
|
|
526
|
+
case "expired":
|
|
527
|
+
return "The request expired. Try again.";
|
|
528
|
+
case "replay":
|
|
529
|
+
return "That request was already used. Try again.";
|
|
530
|
+
case "invalid_signature":
|
|
531
|
+
return "The wallet signature did not verify.";
|
|
532
|
+
case "bad_request":
|
|
533
|
+
return "The request was malformed.";
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
// src/access-server.ts
|
|
538
|
+
var import_sdk2 = require("@bsv/sdk");
|
|
539
|
+
var bare = (tokenId) => tokenId.replace(/^bsv21:/, "");
|
|
540
|
+
function oneSatResolver(o = {}) {
|
|
541
|
+
const base = (o.base ?? "https://api.1sat.app/1sat").replace(/\/$/, "");
|
|
542
|
+
const f = o.fetch ?? globalThis.fetch;
|
|
543
|
+
const t = o.timeoutMs ?? 12e3;
|
|
544
|
+
const call = async (path, init) => {
|
|
545
|
+
const res = await f(`${base}${path}`, { ...init, signal: AbortSignal.timeout(t), cache: "no-store" });
|
|
546
|
+
if (!res.ok) throw new Error(`1sat ${res.status} for ${path}`);
|
|
547
|
+
return res.json();
|
|
548
|
+
};
|
|
549
|
+
return {
|
|
550
|
+
async tokenBalance(tokenId, addresses) {
|
|
551
|
+
const sorted = [...new Set(addresses)].sort();
|
|
552
|
+
let total = 0n;
|
|
553
|
+
for (let i = 0; i < sorted.length; i += 100) {
|
|
554
|
+
const j = await call(`/bsv21/${bare(tokenId)}/p2pkh/balance`, {
|
|
555
|
+
method: "POST",
|
|
556
|
+
headers: { "content-type": "application/json" },
|
|
557
|
+
body: JSON.stringify(sorted.slice(i, i + 100))
|
|
558
|
+
});
|
|
559
|
+
const b = j?.balance ?? 0;
|
|
560
|
+
const s = typeof b === "number" ? String(Math.trunc(b)) : String(b).split(".")[0] || "0";
|
|
561
|
+
if (!/^\d+$/.test(s)) throw new Error("1sat returned a bad balance");
|
|
562
|
+
total += BigInt(s);
|
|
563
|
+
}
|
|
564
|
+
return total.toString();
|
|
565
|
+
},
|
|
566
|
+
async tokenSupply(tokenId) {
|
|
567
|
+
const j = await call(`/bsv21/${bare(tokenId)}`);
|
|
568
|
+
const tok = (j?.token ?? j) || {};
|
|
569
|
+
const v = tok.amt ?? tok.max ?? tok.supply;
|
|
570
|
+
const s = v === void 0 || v === null ? "" : String(v).split(".")[0];
|
|
571
|
+
if (!/^\d+$/.test(s) || s === "0") throw new Error("1sat did not report a supply");
|
|
572
|
+
return s;
|
|
573
|
+
}
|
|
574
|
+
};
|
|
575
|
+
}
|
|
576
|
+
function bitSignResolver(o = {}) {
|
|
577
|
+
const base = (o.base ?? "https://bit-sign.online").replace(/\/$/, "");
|
|
578
|
+
const f = o.fetch ?? globalThis.fetch;
|
|
579
|
+
const tokens = o.tokens ?? oneSatResolver({ fetch: f });
|
|
580
|
+
return {
|
|
581
|
+
tokenBalance: (id, a) => tokens.tokenBalance(id, a),
|
|
582
|
+
tokenSupply: tokens.tokenSupply ? (id) => tokens.tokenSupply(id) : void 0,
|
|
583
|
+
async identity(identityKey, response) {
|
|
584
|
+
const res = await f(`${base}/api/access/verify`, {
|
|
585
|
+
method: "POST",
|
|
586
|
+
headers: { "content-type": "application/json" },
|
|
587
|
+
body: JSON.stringify({ response, only: "identity" }),
|
|
588
|
+
signal: AbortSignal.timeout(o.timeoutMs ?? 12e3),
|
|
589
|
+
cache: "no-store"
|
|
590
|
+
});
|
|
591
|
+
const j = await res.json().catch(() => null);
|
|
592
|
+
if (!j?.identity || j.identityKey !== identityKey) throw new Error(`bit-sign ${res.status}`);
|
|
593
|
+
return { level: Number(j.identity.level) || 0, kyc: j.identity.kyc === true };
|
|
594
|
+
}
|
|
595
|
+
};
|
|
596
|
+
}
|
|
597
|
+
function normalOrigin(origin) {
|
|
598
|
+
const u = new URL(origin);
|
|
599
|
+
if (u.origin === "null" || u.origin !== origin.replace(/\/$/, "")) throw new Error(`origin must be scheme://host[:port], got ${origin}`);
|
|
600
|
+
return u.origin;
|
|
601
|
+
}
|
|
602
|
+
function randomNonce() {
|
|
603
|
+
const b = new Uint8Array(18);
|
|
604
|
+
globalThis.crypto.getRandomValues(b);
|
|
605
|
+
let s = "";
|
|
606
|
+
for (const x of b) s += String.fromCharCode(x);
|
|
607
|
+
return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
608
|
+
}
|
|
609
|
+
async function createAccessChallenge(o) {
|
|
610
|
+
const origin = normalOrigin(o.origin);
|
|
611
|
+
const require2 = normaliseRequirement(o.require);
|
|
612
|
+
let sub;
|
|
613
|
+
if (o.identityKey !== void 0 && o.identityKey !== null && o.identityKey !== "") {
|
|
614
|
+
if (!isIdentityKey(o.identityKey)) throw new AccessError("bad_request", "identityKey must be a compressed public key");
|
|
615
|
+
sub = o.identityKey.toLowerCase();
|
|
616
|
+
}
|
|
617
|
+
const iat = Math.floor((o.now ?? Date.now()) / 1e3);
|
|
618
|
+
const exp = iat + (o.lifetimeS ?? ACCESS_CHALLENGE_LIFETIME_S);
|
|
619
|
+
const nonce = randomNonce();
|
|
620
|
+
const c = { v: 1, kind: o.kind ?? kindFor(require2), origin, nonce, iat, exp, sub, require: require2 };
|
|
621
|
+
const challenge = canonicalJson(c);
|
|
622
|
+
await o.store.put(nonce, { identityKey: sub ?? "", origin, message: challenge, expiresAt: exp * 1e3 });
|
|
623
|
+
return { challenge, nonce, kind: c.kind, protocolID: ACCESS_PROTOCOL, keyID: nonce, exp };
|
|
624
|
+
}
|
|
625
|
+
var isByteArray = (s) => Array.isArray(s) && s.length >= 8 && s.length <= 80 && s.every((b) => Number.isInteger(b) && b >= 0 && b <= 255);
|
|
626
|
+
function verifyHoldingProof(challenge, p) {
|
|
627
|
+
const proof = p;
|
|
628
|
+
if (!proof || typeof proof.pubkey !== "string" || !/^0[23][0-9a-fA-F]{64}$/.test(proof.pubkey) || !isByteArray(proof.signature)) return null;
|
|
629
|
+
try {
|
|
630
|
+
const pub = import_sdk2.PublicKey.fromString(proof.pubkey);
|
|
631
|
+
const sig = import_sdk2.Signature.fromDER(proof.signature);
|
|
632
|
+
return pub.verify(challengeBytes(challenge), sig) ? pub.toAddress() : null;
|
|
633
|
+
} catch {
|
|
634
|
+
return null;
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
async function verifyAccess(o) {
|
|
638
|
+
const r = o.response;
|
|
639
|
+
if (!r || typeof r !== "object" || r.v !== 1) throw new AccessError("bad_request", "response must be { v: 1, challenge, identityKey, signature }");
|
|
640
|
+
const c = parseAccessChallenge(r.challenge);
|
|
641
|
+
const nowS = Math.floor((o.now ?? Date.now()) / 1e3);
|
|
642
|
+
const pending = await o.store.take(c.nonce);
|
|
643
|
+
if (!pending) throw new AccessError(nowS >= c.exp ? "expired" : "replay");
|
|
644
|
+
if (nowS >= c.exp || (o.now ?? Date.now()) > pending.expiresAt) throw new AccessError("expired");
|
|
645
|
+
if (pending.message !== r.challenge) throw new AccessError("replay", "challenge does not match the one issued");
|
|
646
|
+
let origin;
|
|
647
|
+
try {
|
|
648
|
+
origin = normalOrigin(o.origin);
|
|
649
|
+
} catch {
|
|
650
|
+
throw new AccessError("bad_request", "server origin is misconfigured");
|
|
651
|
+
}
|
|
652
|
+
if (c.origin !== origin || pending.origin !== origin) throw new AccessError("bad_request", "origin mismatch");
|
|
653
|
+
if (o.require && canonicalJson(normaliseRequirement(o.require)) !== canonicalJson(c.require)) {
|
|
654
|
+
throw new AccessError("bad_request", "challenge requirement does not match this gate");
|
|
655
|
+
}
|
|
656
|
+
if (!isIdentityKey(r.identityKey)) throw new AccessError("bad_request", "identityKey must be a compressed public key");
|
|
657
|
+
const identityKey = r.identityKey.toLowerCase();
|
|
658
|
+
if (c.sub && c.sub !== identityKey) throw new AccessError("wrong_account");
|
|
659
|
+
if (!isByteArray(r.signature)) throw new AccessError("invalid_signature");
|
|
660
|
+
let valid = false;
|
|
661
|
+
try {
|
|
662
|
+
({ valid } = await new import_sdk2.ProtoWallet("anyone").verifySignature({
|
|
663
|
+
protocolID: ACCESS_PROTOCOL,
|
|
664
|
+
keyID: c.nonce,
|
|
665
|
+
counterparty: identityKey,
|
|
666
|
+
data: challengeBytes(r.challenge),
|
|
667
|
+
signature: r.signature
|
|
668
|
+
}));
|
|
669
|
+
} catch {
|
|
670
|
+
valid = false;
|
|
671
|
+
}
|
|
672
|
+
if (!valid) throw new AccessError("invalid_signature");
|
|
673
|
+
const grant = { ok: true, identityKey, kind: c.kind, require: c.require, addresses: [], have: {} };
|
|
674
|
+
if (c.require.identityLevel || c.require.kyc) {
|
|
675
|
+
if (!o.resolver.identity) throw new AccessError("indexer_unavailable", "no identity resolver configured");
|
|
676
|
+
let id;
|
|
677
|
+
try {
|
|
678
|
+
id = await o.resolver.identity(identityKey, r);
|
|
679
|
+
} catch (e) {
|
|
680
|
+
throw new AccessError("indexer_unavailable", `identity lookup failed: ${e.message}`);
|
|
681
|
+
}
|
|
682
|
+
grant.have.identityLevel = id.level;
|
|
683
|
+
grant.have.kyc = id.kyc;
|
|
684
|
+
if (c.require.kyc && !id.kyc) throw new AccessError("kyc_required");
|
|
685
|
+
if (c.require.identityLevel && id.level < c.require.identityLevel) {
|
|
686
|
+
throw new AccessError("identity_level_too_low", void 0, { have: id.level, need: c.require.identityLevel });
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
if (c.require.token) {
|
|
690
|
+
const proofs = Array.isArray(r.holdings) ? r.holdings.slice(0, MAX_HOLDING_PROOFS) : [];
|
|
691
|
+
const addresses = /* @__PURE__ */ new Set();
|
|
692
|
+
for (const p of proofs) {
|
|
693
|
+
const a = verifyHoldingProof(r.challenge, p);
|
|
694
|
+
if (a) addresses.add(a);
|
|
695
|
+
}
|
|
696
|
+
grant.addresses = [...addresses].sort();
|
|
697
|
+
const check = await checkTokenHolding(c.require, grant.addresses, o.resolver);
|
|
698
|
+
grant.have.tokenRaw = check.have;
|
|
699
|
+
grant.have.needRaw = check.need;
|
|
700
|
+
}
|
|
701
|
+
return grant;
|
|
702
|
+
}
|
|
703
|
+
async function checkTokenHolding(require2, addresses, resolver) {
|
|
704
|
+
const t = require2.token;
|
|
705
|
+
if (!t) return { have: "0", need: "0" };
|
|
706
|
+
let supply;
|
|
707
|
+
if (t.minBps) {
|
|
708
|
+
if (!resolver.tokenSupply) throw new AccessError("indexer_unavailable", "no supply resolver configured");
|
|
709
|
+
try {
|
|
710
|
+
supply = await resolver.tokenSupply(t.id);
|
|
711
|
+
} catch (e) {
|
|
712
|
+
throw new AccessError("indexer_unavailable", `supply lookup failed: ${e.message}`);
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
const need = tokenNeedRaw(t, supply);
|
|
716
|
+
if (!addresses.length) throw new AccessError("insufficient_tokens", void 0, { have: "0", need });
|
|
717
|
+
let have;
|
|
718
|
+
try {
|
|
719
|
+
have = await resolver.tokenBalance(t.id, addresses);
|
|
720
|
+
} catch (e) {
|
|
721
|
+
throw new AccessError("indexer_unavailable", `balance lookup failed: ${e.message}`);
|
|
722
|
+
}
|
|
723
|
+
if (!atLeastRaw(have, need)) throw new AccessError("insufficient_tokens", void 0, { have, need });
|
|
724
|
+
return { have, need };
|
|
725
|
+
}
|
|
726
|
+
|
|
352
727
|
// src/server.ts
|
|
353
728
|
var LOGIN_PROTOCOL = [2, "bwallet sign in"];
|
|
354
729
|
var CHALLENGE_LIFETIME_MS = 2 * 60 * 1e3;
|
|
@@ -380,13 +755,13 @@ var storeOrDefault = (s) => s ?? (defaultStore ??= memoryStore());
|
|
|
380
755
|
function isIdentityKey(x) {
|
|
381
756
|
if (typeof x !== "string" || !/^0[23][0-9a-fA-F]{64}$/.test(x)) return false;
|
|
382
757
|
try {
|
|
383
|
-
|
|
758
|
+
import_sdk3.PublicKey.fromString(x);
|
|
384
759
|
return true;
|
|
385
760
|
} catch {
|
|
386
761
|
return false;
|
|
387
762
|
}
|
|
388
763
|
}
|
|
389
|
-
function
|
|
764
|
+
function normalOrigin2(origin) {
|
|
390
765
|
const u = new URL(origin);
|
|
391
766
|
if (u.origin === "null" || u.origin !== origin.replace(/\/$/, "")) {
|
|
392
767
|
throw new Error(`origin must be scheme://host[:port], got ${origin}`);
|
|
@@ -404,7 +779,7 @@ function loginMessage(origin, nonce, expiresAt) {
|
|
|
404
779
|
`Expires: ${new Date(expiresAt).toISOString()}`
|
|
405
780
|
].join("\n");
|
|
406
781
|
}
|
|
407
|
-
function
|
|
782
|
+
function randomNonce2() {
|
|
408
783
|
const b = new Uint8Array(16);
|
|
409
784
|
globalThis.crypto.getRandomValues(b);
|
|
410
785
|
let s = "";
|
|
@@ -413,8 +788,8 @@ function randomNonce() {
|
|
|
413
788
|
}
|
|
414
789
|
async function createChallenge(opts) {
|
|
415
790
|
if (!isIdentityKey(opts.identityKey)) throw new Error("identityKey must be a compressed public key (66 hex chars)");
|
|
416
|
-
const origin =
|
|
417
|
-
const nonce =
|
|
791
|
+
const origin = normalOrigin2(opts.origin);
|
|
792
|
+
const nonce = randomNonce2();
|
|
418
793
|
const expiresAt = Date.now() + CHALLENGE_LIFETIME_MS;
|
|
419
794
|
const message = loginMessage(origin, nonce, expiresAt);
|
|
420
795
|
await storeOrDefault(opts.store).put(nonce, { identityKey: opts.identityKey.toLowerCase(), origin, message, expiresAt });
|
|
@@ -426,7 +801,7 @@ async function verifySignIn(opts) {
|
|
|
426
801
|
if (!c || Date.now() > c.expiresAt) return null;
|
|
427
802
|
let origin;
|
|
428
803
|
try {
|
|
429
|
-
origin =
|
|
804
|
+
origin = normalOrigin2(opts.origin);
|
|
430
805
|
} catch {
|
|
431
806
|
return null;
|
|
432
807
|
}
|
|
@@ -439,7 +814,7 @@ async function verifySignIn(opts) {
|
|
|
439
814
|
return null;
|
|
440
815
|
}
|
|
441
816
|
try {
|
|
442
|
-
const { valid } = await new
|
|
817
|
+
const { valid } = await new import_sdk3.ProtoWallet("anyone").verifySignature({
|
|
443
818
|
protocolID: LOGIN_PROTOCOL,
|
|
444
819
|
keyID: opts.nonce,
|
|
445
820
|
counterparty: identityKey,
|
|
@@ -453,31 +828,53 @@ async function verifySignIn(opts) {
|
|
|
453
828
|
}
|
|
454
829
|
function originAllowed(requestOrigin, origin) {
|
|
455
830
|
try {
|
|
456
|
-
return !!requestOrigin && requestOrigin ===
|
|
831
|
+
return !!requestOrigin && requestOrigin === normalOrigin2(origin);
|
|
457
832
|
} catch {
|
|
458
833
|
return false;
|
|
459
834
|
}
|
|
460
835
|
}
|
|
461
836
|
// Annotate the CommonJS export names for ESM import in node:
|
|
462
837
|
0 && (module.exports = {
|
|
838
|
+
ACCESS_CHALLENGE_LIFETIME_S,
|
|
839
|
+
ACCESS_ERROR_STATUS,
|
|
840
|
+
ACCESS_PROTOCOL,
|
|
841
|
+
ACCESS_VERSION,
|
|
842
|
+
AccessError,
|
|
463
843
|
CHALLENGE_LIFETIME_MS,
|
|
464
844
|
IdentityLinkConflictError,
|
|
465
845
|
LOGIN_PROTOCOL,
|
|
846
|
+
MAX_HOLDING_PROOFS,
|
|
466
847
|
MIN_SECRET_LENGTH,
|
|
848
|
+
PROTOCOL_MEDIA,
|
|
467
849
|
PaymentVerificationError,
|
|
850
|
+
accessErrorMessage,
|
|
851
|
+
atLeastRaw,
|
|
852
|
+
bitSignResolver,
|
|
853
|
+
canonicalJson,
|
|
854
|
+
challengeBytes,
|
|
855
|
+
checkTokenHolding,
|
|
856
|
+
createAccessChallenge,
|
|
468
857
|
createChallenge,
|
|
469
858
|
isIdentityKey,
|
|
859
|
+
kindFor,
|
|
470
860
|
linkIdentity,
|
|
471
861
|
loginMessage,
|
|
472
862
|
memoryStore,
|
|
863
|
+
normaliseRequirement,
|
|
864
|
+
oneSatResolver,
|
|
473
865
|
originAllowed,
|
|
866
|
+
parseAccessChallenge,
|
|
474
867
|
pgNonceTableSql,
|
|
475
868
|
pgStore,
|
|
869
|
+
protocolMediaUrl,
|
|
476
870
|
readCookie,
|
|
477
871
|
redisStore,
|
|
478
872
|
serializeCookie,
|
|
479
873
|
signInOrLink,
|
|
480
874
|
signSession,
|
|
875
|
+
tokenNeedRaw,
|
|
876
|
+
verifyAccess,
|
|
877
|
+
verifyHoldingProof,
|
|
481
878
|
verifyPayment,
|
|
482
879
|
verifySession,
|
|
483
880
|
verifySignIn
|