@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
package/dist/next.cjs
ADDED
|
@@ -0,0 +1,783 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/next.ts
|
|
31
|
+
var next_exports = {};
|
|
32
|
+
__export(next_exports, {
|
|
33
|
+
IdentityLinkConflictError: () => IdentityLinkConflictError,
|
|
34
|
+
createBwalletXAccess: () => createBwalletXAccess,
|
|
35
|
+
createBwalletXAuth: () => createBwalletXAuth,
|
|
36
|
+
linkIdentity: () => linkIdentity,
|
|
37
|
+
memoryStore: () => memoryStore,
|
|
38
|
+
pgNonceTableSql: () => pgNonceTableSql,
|
|
39
|
+
pgStore: () => pgStore,
|
|
40
|
+
redisStore: () => redisStore,
|
|
41
|
+
signInOrLink: () => signInOrLink
|
|
42
|
+
});
|
|
43
|
+
module.exports = __toCommonJS(next_exports);
|
|
44
|
+
|
|
45
|
+
// src/link.ts
|
|
46
|
+
var IdentityLinkConflictError = class extends Error {
|
|
47
|
+
constructor(identityKey, otherUserId) {
|
|
48
|
+
super("This bWalletX identity is already linked to a different account. Sign in with that account, or unlink it there first.");
|
|
49
|
+
this.identityKey = identityKey;
|
|
50
|
+
this.otherUserId = otherUserId;
|
|
51
|
+
this.name = "IdentityLinkConflictError";
|
|
52
|
+
}
|
|
53
|
+
identityKey;
|
|
54
|
+
otherUserId;
|
|
55
|
+
code = "IDENTITY_LINKED_TO_OTHER_USER";
|
|
56
|
+
};
|
|
57
|
+
var norm = (k) => {
|
|
58
|
+
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)");
|
|
59
|
+
return k.toLowerCase();
|
|
60
|
+
};
|
|
61
|
+
async function linkIdentity(userId, identityKey, cb) {
|
|
62
|
+
if (!userId) throw new Error("linkIdentity needs the current user id");
|
|
63
|
+
const key = norm(identityKey);
|
|
64
|
+
const owner = await cb.findUserByIdentityKey(key);
|
|
65
|
+
if (owner && owner !== userId) throw new IdentityLinkConflictError(key, owner);
|
|
66
|
+
if (owner === userId) return { status: "already-linked", userId, identityKey: key };
|
|
67
|
+
await cb.attach(userId, key);
|
|
68
|
+
return { status: "linked", userId, identityKey: key };
|
|
69
|
+
}
|
|
70
|
+
async function signInOrLink(identityKey, o) {
|
|
71
|
+
const key = norm(identityKey);
|
|
72
|
+
if (o.currentUserId) return linkIdentity(o.currentUserId, key, o);
|
|
73
|
+
const owner = await o.findUserByIdentityKey(key);
|
|
74
|
+
if (owner) return { status: "signed-in", userId: owner, identityKey: key };
|
|
75
|
+
if (!o.createUser) return { status: "unknown", userId: null, identityKey: key };
|
|
76
|
+
const userId = await o.createUser(key);
|
|
77
|
+
await o.attach(userId, key);
|
|
78
|
+
return { status: "created", userId, identityKey: key };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// src/server.ts
|
|
82
|
+
var import_sdk2 = require("@bsv/sdk");
|
|
83
|
+
|
|
84
|
+
// src/nonce-stores.ts
|
|
85
|
+
var ttlSeconds = (c) => Math.max(1, Math.ceil((c.expiresAt - Date.now()) / 1e3));
|
|
86
|
+
function parse(v) {
|
|
87
|
+
if (v == null) return null;
|
|
88
|
+
try {
|
|
89
|
+
const c = typeof v === "string" ? JSON.parse(v) : v;
|
|
90
|
+
if (!c || typeof c.identityKey !== "string" || typeof c.message !== "string" || typeof c.expiresAt !== "number") return null;
|
|
91
|
+
return c.expiresAt < Date.now() ? null : c;
|
|
92
|
+
} catch {
|
|
93
|
+
return null;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
function redisStore(opts) {
|
|
97
|
+
const { client } = opts;
|
|
98
|
+
const prefix = opts.prefix ?? "bwalletx:nonce:";
|
|
99
|
+
const getdel = client.getdel?.bind(client) ?? client.getDel?.bind(client);
|
|
100
|
+
if (!getdel) throw new Error("redisStore: the client needs getdel (or getDel). Redis 6.2+.");
|
|
101
|
+
return {
|
|
102
|
+
async put(nonce, c) {
|
|
103
|
+
const s = ttlSeconds(c);
|
|
104
|
+
if (opts.flavor === "ioredis") await client.set(prefix + nonce, JSON.stringify(c), "EX", s);
|
|
105
|
+
else await client.set(prefix + nonce, JSON.stringify(c), { ex: s, EX: s });
|
|
106
|
+
},
|
|
107
|
+
async take(nonce) {
|
|
108
|
+
return parse(await getdel(prefix + nonce));
|
|
109
|
+
}
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
function pgNonceTableSql(table = "bwalletx_nonces") {
|
|
113
|
+
const t = safeTable(table);
|
|
114
|
+
return `create table if not exists ${t} (
|
|
115
|
+
nonce text primary key,
|
|
116
|
+
challenge jsonb not null,
|
|
117
|
+
expires_at timestamptz not null
|
|
118
|
+
);
|
|
119
|
+
create index if not exists ${t.replace(".", "_")}_expires_idx on ${t} (expires_at);`;
|
|
120
|
+
}
|
|
121
|
+
function safeTable(t) {
|
|
122
|
+
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}`);
|
|
123
|
+
return t;
|
|
124
|
+
}
|
|
125
|
+
function pgStore(opts) {
|
|
126
|
+
const t = safeTable(opts.table ?? "bwalletx_nonces");
|
|
127
|
+
const rows = (r) => Array.isArray(r) ? r : r.rows;
|
|
128
|
+
return {
|
|
129
|
+
async put(nonce, c) {
|
|
130
|
+
await opts.query(`delete from ${t} where expires_at < now()`, []);
|
|
131
|
+
await opts.query(`insert into ${t} (nonce, challenge, expires_at) values ($1, $2, to_timestamp($3 / 1000.0))`, [
|
|
132
|
+
nonce,
|
|
133
|
+
JSON.stringify(c),
|
|
134
|
+
c.expiresAt
|
|
135
|
+
]);
|
|
136
|
+
},
|
|
137
|
+
async take(nonce) {
|
|
138
|
+
const r = rows(await opts.query(`delete from ${t} where nonce = $1 returning challenge`, [nonce]));
|
|
139
|
+
const row = r[0];
|
|
140
|
+
return parse(row?.challenge);
|
|
141
|
+
}
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// src/session.ts
|
|
146
|
+
var MIN_SECRET_LENGTH = 32;
|
|
147
|
+
var enc = new TextEncoder();
|
|
148
|
+
var dec = new TextDecoder();
|
|
149
|
+
function b64u(bytes) {
|
|
150
|
+
let s = "";
|
|
151
|
+
for (const b of bytes) s += String.fromCharCode(b);
|
|
152
|
+
return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
153
|
+
}
|
|
154
|
+
function unb64u(s) {
|
|
155
|
+
if (!/^[A-Za-z0-9_-]*$/.test(s)) throw new Error("bad base64url");
|
|
156
|
+
const b = atob(s.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - s.length % 4) % 4));
|
|
157
|
+
return Uint8Array.from(b, (c) => c.charCodeAt(0));
|
|
158
|
+
}
|
|
159
|
+
function assertSecret(secret) {
|
|
160
|
+
if (typeof secret !== "string" || secret.length < MIN_SECRET_LENGTH) {
|
|
161
|
+
throw new Error(
|
|
162
|
+
`[@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.`
|
|
163
|
+
);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
var keys = /* @__PURE__ */ new Map();
|
|
167
|
+
function hmacKey(secret) {
|
|
168
|
+
let k = keys.get(secret);
|
|
169
|
+
if (!k) {
|
|
170
|
+
k = globalThis.crypto.subtle.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"]);
|
|
171
|
+
keys.set(secret, k);
|
|
172
|
+
}
|
|
173
|
+
return k;
|
|
174
|
+
}
|
|
175
|
+
async function signSession(claims, opts) {
|
|
176
|
+
assertSecret(opts.secret);
|
|
177
|
+
if (typeof claims.sub !== "string" || !claims.sub) throw new Error("session needs a sub (identity key)");
|
|
178
|
+
const iat = Math.floor((opts.now ?? Date.now()) / 1e3);
|
|
179
|
+
const payload = { ...claims, sub: claims.sub, iat, exp: iat + (opts.maxAge ?? 7 * 24 * 3600) };
|
|
180
|
+
const body2 = b64u(enc.encode(JSON.stringify(payload)));
|
|
181
|
+
const sig = new Uint8Array(await globalThis.crypto.subtle.sign("HMAC", await hmacKey(opts.secret), enc.encode(body2)));
|
|
182
|
+
return `${body2}.${b64u(sig)}`;
|
|
183
|
+
}
|
|
184
|
+
async function verifySession(token, opts) {
|
|
185
|
+
assertSecret(opts.secret);
|
|
186
|
+
if (typeof token !== "string" || token.length > 8192) return null;
|
|
187
|
+
const dot = token.indexOf(".");
|
|
188
|
+
if (dot < 1 || dot !== token.lastIndexOf(".")) return null;
|
|
189
|
+
const body2 = token.slice(0, dot);
|
|
190
|
+
try {
|
|
191
|
+
const sig = unb64u(token.slice(dot + 1));
|
|
192
|
+
const ok = await globalThis.crypto.subtle.verify("HMAC", await hmacKey(opts.secret), sig, enc.encode(body2));
|
|
193
|
+
if (!ok) return null;
|
|
194
|
+
const p = JSON.parse(dec.decode(unb64u(body2)));
|
|
195
|
+
if (!p || typeof p.sub !== "string" || typeof p.exp !== "number") return null;
|
|
196
|
+
if (Math.floor((opts.now ?? Date.now()) / 1e3) >= p.exp) return null;
|
|
197
|
+
return p;
|
|
198
|
+
} catch {
|
|
199
|
+
return null;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
function serializeCookie(value, o) {
|
|
203
|
+
const parts = [`${o.name}=${value}`, `Path=${o.path ?? "/"}`, `Max-Age=${o.maxAge}`, "HttpOnly", `SameSite=${o.sameSite ?? "Lax"}`];
|
|
204
|
+
if (o.secure !== false) parts.push("Secure");
|
|
205
|
+
if (o.domain) parts.push(`Domain=${o.domain}`);
|
|
206
|
+
return parts.join("; ");
|
|
207
|
+
}
|
|
208
|
+
function readCookie(header, name) {
|
|
209
|
+
if (!header) return null;
|
|
210
|
+
for (const part of header.split(";")) {
|
|
211
|
+
const i = part.indexOf("=");
|
|
212
|
+
if (i > 0 && part.slice(0, i).trim() === name) return part.slice(i + 1).trim();
|
|
213
|
+
}
|
|
214
|
+
return null;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// src/access.ts
|
|
218
|
+
var ACCESS_PROTOCOL = [2, "bwalletx access"];
|
|
219
|
+
var ACCESS_CHALLENGE_LIFETIME_S = 120;
|
|
220
|
+
var MAX_HOLDING_PROOFS = 50;
|
|
221
|
+
var ACCESS_ERROR_STATUS = {
|
|
222
|
+
not_installed: 424,
|
|
223
|
+
user_rejected: 403,
|
|
224
|
+
wrong_account: 409,
|
|
225
|
+
insufficient_tokens: 403,
|
|
226
|
+
identity_level_too_low: 403,
|
|
227
|
+
kyc_required: 403,
|
|
228
|
+
indexer_unavailable: 503,
|
|
229
|
+
expired: 401,
|
|
230
|
+
replay: 401,
|
|
231
|
+
invalid_signature: 401,
|
|
232
|
+
bad_request: 400
|
|
233
|
+
};
|
|
234
|
+
var AccessError = class extends Error {
|
|
235
|
+
code;
|
|
236
|
+
have;
|
|
237
|
+
need;
|
|
238
|
+
constructor(code, message, extra = {}) {
|
|
239
|
+
super(message ?? code);
|
|
240
|
+
this.name = "AccessError";
|
|
241
|
+
this.code = code;
|
|
242
|
+
this.have = extra.have;
|
|
243
|
+
this.need = extra.need;
|
|
244
|
+
}
|
|
245
|
+
toJSON() {
|
|
246
|
+
const b = { error: this.code, message: this.message };
|
|
247
|
+
if (this.have !== void 0) b.have = this.have;
|
|
248
|
+
if (this.need !== void 0) b.need = this.need;
|
|
249
|
+
return b;
|
|
250
|
+
}
|
|
251
|
+
};
|
|
252
|
+
function canonicalJson(v) {
|
|
253
|
+
if (v === null) return "null";
|
|
254
|
+
if (typeof v === "string" || typeof v === "boolean") return JSON.stringify(v);
|
|
255
|
+
if (typeof v === "number") {
|
|
256
|
+
if (!Number.isFinite(v)) throw new Error("canonicalJson: non-finite number");
|
|
257
|
+
return JSON.stringify(v);
|
|
258
|
+
}
|
|
259
|
+
if (Array.isArray(v)) return `[${v.map((x) => canonicalJson(x)).join(",")}]`;
|
|
260
|
+
if (typeof v === "object") {
|
|
261
|
+
const o = v;
|
|
262
|
+
const keys2 = Object.keys(o).filter((k) => o[k] !== void 0).sort();
|
|
263
|
+
return `{${keys2.map((k) => `${JSON.stringify(k)}:${canonicalJson(o[k])}`).join(",")}}`;
|
|
264
|
+
}
|
|
265
|
+
throw new Error(`canonicalJson: unsupported ${typeof v}`);
|
|
266
|
+
}
|
|
267
|
+
function challengeBytes(challenge) {
|
|
268
|
+
return Array.from(new TextEncoder().encode(challenge));
|
|
269
|
+
}
|
|
270
|
+
var TOKEN_ID = /^bsv21:[0-9a-f]{64}_\d{1,6}$/;
|
|
271
|
+
var RAW = /^[1-9]\d{0,38}$/;
|
|
272
|
+
function normaliseRequirement(r) {
|
|
273
|
+
if (!r || typeof r !== "object") throw new AccessError("bad_request", "require must be an object");
|
|
274
|
+
const req = r;
|
|
275
|
+
const out = {};
|
|
276
|
+
if (req.token !== void 0) {
|
|
277
|
+
const t = req.token;
|
|
278
|
+
if (!t || typeof t !== "object" || typeof t.id !== "string") throw new AccessError("bad_request", "require.token.id is required");
|
|
279
|
+
const id = t.id.trim().toLowerCase();
|
|
280
|
+
if (!TOKEN_ID.test(id)) throw new AccessError("bad_request", "require.token.id must be 'bsv21:<txid>_<vout>'");
|
|
281
|
+
const hasMin = t.min !== void 0;
|
|
282
|
+
const hasBps = t.minBps !== void 0;
|
|
283
|
+
if (hasMin === hasBps) throw new AccessError("bad_request", "require.token needs exactly one of min or minBps");
|
|
284
|
+
out.token = { id };
|
|
285
|
+
if (hasMin) {
|
|
286
|
+
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)");
|
|
287
|
+
out.token.min = t.min;
|
|
288
|
+
} else {
|
|
289
|
+
if (!Number.isInteger(t.minBps) || t.minBps < 1 || t.minBps > 1e4) {
|
|
290
|
+
throw new AccessError("bad_request", "require.token.minBps must be an integer 1..10000");
|
|
291
|
+
}
|
|
292
|
+
out.token.minBps = t.minBps;
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
if (req.identityLevel !== void 0) {
|
|
296
|
+
if (!Number.isInteger(req.identityLevel) || req.identityLevel < 1 || req.identityLevel > 10) {
|
|
297
|
+
throw new AccessError("bad_request", "require.identityLevel must be an integer 1..10");
|
|
298
|
+
}
|
|
299
|
+
out.identityLevel = req.identityLevel;
|
|
300
|
+
}
|
|
301
|
+
if (req.kyc !== void 0) {
|
|
302
|
+
if (typeof req.kyc !== "boolean") throw new AccessError("bad_request", "require.kyc must be a boolean");
|
|
303
|
+
if (req.kyc) out.kyc = true;
|
|
304
|
+
}
|
|
305
|
+
if (!out.token && !out.identityLevel && !out.kyc) throw new AccessError("bad_request", "require is empty");
|
|
306
|
+
return out;
|
|
307
|
+
}
|
|
308
|
+
function kindFor(r) {
|
|
309
|
+
return r.token ? "403" : "401";
|
|
310
|
+
}
|
|
311
|
+
function parseAccessChallenge(s) {
|
|
312
|
+
if (typeof s !== "string" || s.length > 4096) throw new AccessError("bad_request", "challenge must be a string");
|
|
313
|
+
let c;
|
|
314
|
+
try {
|
|
315
|
+
c = JSON.parse(s);
|
|
316
|
+
} catch {
|
|
317
|
+
throw new AccessError("bad_request", "challenge is not JSON");
|
|
318
|
+
}
|
|
319
|
+
if (!c || typeof c !== "object" || c.v !== 1) throw new AccessError("bad_request", "unsupported challenge version");
|
|
320
|
+
if (c.kind !== "401" && c.kind !== "402" && c.kind !== "403") throw new AccessError("bad_request", "bad kind");
|
|
321
|
+
if (typeof c.origin !== "string" || typeof c.nonce !== "string" || !/^[A-Za-z0-9_-]{16,64}$/.test(c.nonce)) {
|
|
322
|
+
throw new AccessError("bad_request", "bad origin or nonce");
|
|
323
|
+
}
|
|
324
|
+
if (!Number.isInteger(c.iat) || !Number.isInteger(c.exp) || c.exp <= c.iat) throw new AccessError("bad_request", "bad iat/exp");
|
|
325
|
+
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");
|
|
326
|
+
c.require = normaliseRequirement(c.require);
|
|
327
|
+
if (canonicalJson(c) !== s) throw new AccessError("bad_request", "challenge is not canonical");
|
|
328
|
+
return c;
|
|
329
|
+
}
|
|
330
|
+
function tokenNeedRaw(t, supplyRaw) {
|
|
331
|
+
if (t.min) return t.min;
|
|
332
|
+
if (supplyRaw === void 0 || !/^\d+$/.test(supplyRaw)) throw new AccessError("indexer_unavailable", "token supply unknown");
|
|
333
|
+
const n = BigInt(supplyRaw) * BigInt(t.minBps);
|
|
334
|
+
const need = (n + 9999n) / 10000n;
|
|
335
|
+
return (need < 1n ? 1n : need).toString();
|
|
336
|
+
}
|
|
337
|
+
function atLeastRaw(have, need) {
|
|
338
|
+
try {
|
|
339
|
+
return BigInt(have) >= BigInt(need);
|
|
340
|
+
} catch {
|
|
341
|
+
return false;
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
function accessErrorMessage(code, e = {}) {
|
|
345
|
+
switch (code) {
|
|
346
|
+
case "not_installed":
|
|
347
|
+
return "No bWalletX (or other BRC-100 wallet) was found.";
|
|
348
|
+
case "user_rejected":
|
|
349
|
+
return "The request was declined in the wallet.";
|
|
350
|
+
case "wrong_account":
|
|
351
|
+
return "The wallet is signed in to a different account than this site expects.";
|
|
352
|
+
case "insufficient_tokens":
|
|
353
|
+
return `Not enough tokens: holding ${e.have ?? 0}, need ${e.need ?? "?"}.`;
|
|
354
|
+
case "identity_level_too_low":
|
|
355
|
+
return `Identity level ${e.have ?? 0} is below the required level ${e.need ?? "?"}.`;
|
|
356
|
+
case "kyc_required":
|
|
357
|
+
return "A verified identity (KYC) is required.";
|
|
358
|
+
case "indexer_unavailable":
|
|
359
|
+
return "Holdings could not be checked right now. Try again shortly.";
|
|
360
|
+
case "expired":
|
|
361
|
+
return "The request expired. Try again.";
|
|
362
|
+
case "replay":
|
|
363
|
+
return "That request was already used. Try again.";
|
|
364
|
+
case "invalid_signature":
|
|
365
|
+
return "The wallet signature did not verify.";
|
|
366
|
+
case "bad_request":
|
|
367
|
+
return "The request was malformed.";
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
// src/access-server.ts
|
|
372
|
+
var import_sdk = require("@bsv/sdk");
|
|
373
|
+
function normalOrigin(origin) {
|
|
374
|
+
const u = new URL(origin);
|
|
375
|
+
if (u.origin === "null" || u.origin !== origin.replace(/\/$/, "")) throw new Error(`origin must be scheme://host[:port], got ${origin}`);
|
|
376
|
+
return u.origin;
|
|
377
|
+
}
|
|
378
|
+
function randomNonce() {
|
|
379
|
+
const b = new Uint8Array(18);
|
|
380
|
+
globalThis.crypto.getRandomValues(b);
|
|
381
|
+
let s = "";
|
|
382
|
+
for (const x of b) s += String.fromCharCode(x);
|
|
383
|
+
return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
384
|
+
}
|
|
385
|
+
async function createAccessChallenge(o) {
|
|
386
|
+
const origin = normalOrigin(o.origin);
|
|
387
|
+
const require2 = normaliseRequirement(o.require);
|
|
388
|
+
let sub;
|
|
389
|
+
if (o.identityKey !== void 0 && o.identityKey !== null && o.identityKey !== "") {
|
|
390
|
+
if (!isIdentityKey(o.identityKey)) throw new AccessError("bad_request", "identityKey must be a compressed public key");
|
|
391
|
+
sub = o.identityKey.toLowerCase();
|
|
392
|
+
}
|
|
393
|
+
const iat = Math.floor((o.now ?? Date.now()) / 1e3);
|
|
394
|
+
const exp = iat + (o.lifetimeS ?? ACCESS_CHALLENGE_LIFETIME_S);
|
|
395
|
+
const nonce = randomNonce();
|
|
396
|
+
const c = { v: 1, kind: o.kind ?? kindFor(require2), origin, nonce, iat, exp, sub, require: require2 };
|
|
397
|
+
const challenge = canonicalJson(c);
|
|
398
|
+
await o.store.put(nonce, { identityKey: sub ?? "", origin, message: challenge, expiresAt: exp * 1e3 });
|
|
399
|
+
return { challenge, nonce, kind: c.kind, protocolID: ACCESS_PROTOCOL, keyID: nonce, exp };
|
|
400
|
+
}
|
|
401
|
+
var isByteArray = (s) => Array.isArray(s) && s.length >= 8 && s.length <= 80 && s.every((b) => Number.isInteger(b) && b >= 0 && b <= 255);
|
|
402
|
+
function verifyHoldingProof(challenge, p) {
|
|
403
|
+
const proof = p;
|
|
404
|
+
if (!proof || typeof proof.pubkey !== "string" || !/^0[23][0-9a-fA-F]{64}$/.test(proof.pubkey) || !isByteArray(proof.signature)) return null;
|
|
405
|
+
try {
|
|
406
|
+
const pub = import_sdk.PublicKey.fromString(proof.pubkey);
|
|
407
|
+
const sig = import_sdk.Signature.fromDER(proof.signature);
|
|
408
|
+
return pub.verify(challengeBytes(challenge), sig) ? pub.toAddress() : null;
|
|
409
|
+
} catch {
|
|
410
|
+
return null;
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
async function verifyAccess(o) {
|
|
414
|
+
const r = o.response;
|
|
415
|
+
if (!r || typeof r !== "object" || r.v !== 1) throw new AccessError("bad_request", "response must be { v: 1, challenge, identityKey, signature }");
|
|
416
|
+
const c = parseAccessChallenge(r.challenge);
|
|
417
|
+
const nowS = Math.floor((o.now ?? Date.now()) / 1e3);
|
|
418
|
+
const pending = await o.store.take(c.nonce);
|
|
419
|
+
if (!pending) throw new AccessError(nowS >= c.exp ? "expired" : "replay");
|
|
420
|
+
if (nowS >= c.exp || (o.now ?? Date.now()) > pending.expiresAt) throw new AccessError("expired");
|
|
421
|
+
if (pending.message !== r.challenge) throw new AccessError("replay", "challenge does not match the one issued");
|
|
422
|
+
let origin;
|
|
423
|
+
try {
|
|
424
|
+
origin = normalOrigin(o.origin);
|
|
425
|
+
} catch {
|
|
426
|
+
throw new AccessError("bad_request", "server origin is misconfigured");
|
|
427
|
+
}
|
|
428
|
+
if (c.origin !== origin || pending.origin !== origin) throw new AccessError("bad_request", "origin mismatch");
|
|
429
|
+
if (o.require && canonicalJson(normaliseRequirement(o.require)) !== canonicalJson(c.require)) {
|
|
430
|
+
throw new AccessError("bad_request", "challenge requirement does not match this gate");
|
|
431
|
+
}
|
|
432
|
+
if (!isIdentityKey(r.identityKey)) throw new AccessError("bad_request", "identityKey must be a compressed public key");
|
|
433
|
+
const identityKey = r.identityKey.toLowerCase();
|
|
434
|
+
if (c.sub && c.sub !== identityKey) throw new AccessError("wrong_account");
|
|
435
|
+
if (!isByteArray(r.signature)) throw new AccessError("invalid_signature");
|
|
436
|
+
let valid = false;
|
|
437
|
+
try {
|
|
438
|
+
({ valid } = await new import_sdk.ProtoWallet("anyone").verifySignature({
|
|
439
|
+
protocolID: ACCESS_PROTOCOL,
|
|
440
|
+
keyID: c.nonce,
|
|
441
|
+
counterparty: identityKey,
|
|
442
|
+
data: challengeBytes(r.challenge),
|
|
443
|
+
signature: r.signature
|
|
444
|
+
}));
|
|
445
|
+
} catch {
|
|
446
|
+
valid = false;
|
|
447
|
+
}
|
|
448
|
+
if (!valid) throw new AccessError("invalid_signature");
|
|
449
|
+
const grant = { ok: true, identityKey, kind: c.kind, require: c.require, addresses: [], have: {} };
|
|
450
|
+
if (c.require.identityLevel || c.require.kyc) {
|
|
451
|
+
if (!o.resolver.identity) throw new AccessError("indexer_unavailable", "no identity resolver configured");
|
|
452
|
+
let id;
|
|
453
|
+
try {
|
|
454
|
+
id = await o.resolver.identity(identityKey, r);
|
|
455
|
+
} catch (e) {
|
|
456
|
+
throw new AccessError("indexer_unavailable", `identity lookup failed: ${e.message}`);
|
|
457
|
+
}
|
|
458
|
+
grant.have.identityLevel = id.level;
|
|
459
|
+
grant.have.kyc = id.kyc;
|
|
460
|
+
if (c.require.kyc && !id.kyc) throw new AccessError("kyc_required");
|
|
461
|
+
if (c.require.identityLevel && id.level < c.require.identityLevel) {
|
|
462
|
+
throw new AccessError("identity_level_too_low", void 0, { have: id.level, need: c.require.identityLevel });
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
if (c.require.token) {
|
|
466
|
+
const proofs = Array.isArray(r.holdings) ? r.holdings.slice(0, MAX_HOLDING_PROOFS) : [];
|
|
467
|
+
const addresses = /* @__PURE__ */ new Set();
|
|
468
|
+
for (const p of proofs) {
|
|
469
|
+
const a = verifyHoldingProof(r.challenge, p);
|
|
470
|
+
if (a) addresses.add(a);
|
|
471
|
+
}
|
|
472
|
+
grant.addresses = [...addresses].sort();
|
|
473
|
+
const check = await checkTokenHolding(c.require, grant.addresses, o.resolver);
|
|
474
|
+
grant.have.tokenRaw = check.have;
|
|
475
|
+
grant.have.needRaw = check.need;
|
|
476
|
+
}
|
|
477
|
+
return grant;
|
|
478
|
+
}
|
|
479
|
+
async function checkTokenHolding(require2, addresses, resolver) {
|
|
480
|
+
const t = require2.token;
|
|
481
|
+
if (!t) return { have: "0", need: "0" };
|
|
482
|
+
let supply;
|
|
483
|
+
if (t.minBps) {
|
|
484
|
+
if (!resolver.tokenSupply) throw new AccessError("indexer_unavailable", "no supply resolver configured");
|
|
485
|
+
try {
|
|
486
|
+
supply = await resolver.tokenSupply(t.id);
|
|
487
|
+
} catch (e) {
|
|
488
|
+
throw new AccessError("indexer_unavailable", `supply lookup failed: ${e.message}`);
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
const need = tokenNeedRaw(t, supply);
|
|
492
|
+
if (!addresses.length) throw new AccessError("insufficient_tokens", void 0, { have: "0", need });
|
|
493
|
+
let have;
|
|
494
|
+
try {
|
|
495
|
+
have = await resolver.tokenBalance(t.id, addresses);
|
|
496
|
+
} catch (e) {
|
|
497
|
+
throw new AccessError("indexer_unavailable", `balance lookup failed: ${e.message}`);
|
|
498
|
+
}
|
|
499
|
+
if (!atLeastRaw(have, need)) throw new AccessError("insufficient_tokens", void 0, { have, need });
|
|
500
|
+
return { have, need };
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
// src/server.ts
|
|
504
|
+
var LOGIN_PROTOCOL = [2, "bwallet sign in"];
|
|
505
|
+
var CHALLENGE_LIFETIME_MS = 2 * 60 * 1e3;
|
|
506
|
+
var warned = false;
|
|
507
|
+
function memoryStore(opts = {}) {
|
|
508
|
+
const prod = typeof process !== "undefined" && process.env?.NODE_ENV === "production";
|
|
509
|
+
if ((prod || !opts.quiet) && !warned) {
|
|
510
|
+
warned = true;
|
|
511
|
+
console.warn(
|
|
512
|
+
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."
|
|
513
|
+
);
|
|
514
|
+
}
|
|
515
|
+
const m = /* @__PURE__ */ new Map();
|
|
516
|
+
return {
|
|
517
|
+
put(nonce, c) {
|
|
518
|
+
const now = Date.now();
|
|
519
|
+
for (const [k, v] of m) if (v.expiresAt < now) m.delete(k);
|
|
520
|
+
m.set(nonce, c);
|
|
521
|
+
},
|
|
522
|
+
take(nonce) {
|
|
523
|
+
const c = m.get(nonce) ?? null;
|
|
524
|
+
m.delete(nonce);
|
|
525
|
+
return c;
|
|
526
|
+
}
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
var defaultStore = null;
|
|
530
|
+
var storeOrDefault = (s) => s ?? (defaultStore ??= memoryStore());
|
|
531
|
+
function isIdentityKey(x) {
|
|
532
|
+
if (typeof x !== "string" || !/^0[23][0-9a-fA-F]{64}$/.test(x)) return false;
|
|
533
|
+
try {
|
|
534
|
+
import_sdk2.PublicKey.fromString(x);
|
|
535
|
+
return true;
|
|
536
|
+
} catch {
|
|
537
|
+
return false;
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
function normalOrigin2(origin) {
|
|
541
|
+
const u = new URL(origin);
|
|
542
|
+
if (u.origin === "null" || u.origin !== origin.replace(/\/$/, "")) {
|
|
543
|
+
throw new Error(`origin must be scheme://host[:port], got ${origin}`);
|
|
544
|
+
}
|
|
545
|
+
return u.origin;
|
|
546
|
+
}
|
|
547
|
+
function loginMessage(origin, nonce, expiresAt) {
|
|
548
|
+
return [
|
|
549
|
+
`Sign in to ${new URL(origin).host} with bWallet`,
|
|
550
|
+
"",
|
|
551
|
+
"This proves you hold this wallet. It does not spend anything.",
|
|
552
|
+
"",
|
|
553
|
+
`Origin: ${origin}`,
|
|
554
|
+
`Nonce: ${nonce}`,
|
|
555
|
+
`Expires: ${new Date(expiresAt).toISOString()}`
|
|
556
|
+
].join("\n");
|
|
557
|
+
}
|
|
558
|
+
function randomNonce2() {
|
|
559
|
+
const b = new Uint8Array(16);
|
|
560
|
+
globalThis.crypto.getRandomValues(b);
|
|
561
|
+
let s = "";
|
|
562
|
+
for (const x of b) s += String.fromCharCode(x);
|
|
563
|
+
return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
564
|
+
}
|
|
565
|
+
async function createChallenge(opts) {
|
|
566
|
+
if (!isIdentityKey(opts.identityKey)) throw new Error("identityKey must be a compressed public key (66 hex chars)");
|
|
567
|
+
const origin = normalOrigin2(opts.origin);
|
|
568
|
+
const nonce = randomNonce2();
|
|
569
|
+
const expiresAt = Date.now() + CHALLENGE_LIFETIME_MS;
|
|
570
|
+
const message = loginMessage(origin, nonce, expiresAt);
|
|
571
|
+
await storeOrDefault(opts.store).put(nonce, { identityKey: opts.identityKey.toLowerCase(), origin, message, expiresAt });
|
|
572
|
+
return { nonce, message, protocolID: LOGIN_PROTOCOL, keyID: nonce, expiresAt };
|
|
573
|
+
}
|
|
574
|
+
async function verifySignIn(opts) {
|
|
575
|
+
if (typeof opts.nonce !== "string" || opts.nonce.length > 64) return null;
|
|
576
|
+
const c = await storeOrDefault(opts.store).take(opts.nonce);
|
|
577
|
+
if (!c || Date.now() > c.expiresAt) return null;
|
|
578
|
+
let origin;
|
|
579
|
+
try {
|
|
580
|
+
origin = normalOrigin2(opts.origin);
|
|
581
|
+
} catch {
|
|
582
|
+
return null;
|
|
583
|
+
}
|
|
584
|
+
if (c.origin !== origin) return null;
|
|
585
|
+
if (!isIdentityKey(opts.identityKey)) return null;
|
|
586
|
+
const identityKey = opts.identityKey.toLowerCase();
|
|
587
|
+
if (c.identityKey !== identityKey) return null;
|
|
588
|
+
const sig = opts.signature;
|
|
589
|
+
if (!Array.isArray(sig) || sig.length < 8 || sig.length > 80 || !sig.every((b) => Number.isInteger(b) && b >= 0 && b <= 255)) {
|
|
590
|
+
return null;
|
|
591
|
+
}
|
|
592
|
+
try {
|
|
593
|
+
const { valid } = await new import_sdk2.ProtoWallet("anyone").verifySignature({
|
|
594
|
+
protocolID: LOGIN_PROTOCOL,
|
|
595
|
+
keyID: opts.nonce,
|
|
596
|
+
counterparty: identityKey,
|
|
597
|
+
data: Array.from(new TextEncoder().encode(c.message)),
|
|
598
|
+
signature: sig
|
|
599
|
+
});
|
|
600
|
+
return valid ? identityKey : null;
|
|
601
|
+
} catch {
|
|
602
|
+
return null;
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
function originAllowed(requestOrigin, origin) {
|
|
606
|
+
try {
|
|
607
|
+
return !!requestOrigin && requestOrigin === normalOrigin2(origin);
|
|
608
|
+
} catch {
|
|
609
|
+
return false;
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
// src/next.ts
|
|
614
|
+
var json = (body2, status = 200, headers = {}) => new Response(JSON.stringify(body2), { status, headers: { "content-type": "application/json", "cache-control": "no-store", ...headers } });
|
|
615
|
+
async function body(req) {
|
|
616
|
+
try {
|
|
617
|
+
const b = await req.json();
|
|
618
|
+
return b && typeof b === "object" ? b : null;
|
|
619
|
+
} catch {
|
|
620
|
+
return null;
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
function createBwalletXAuth(o) {
|
|
624
|
+
if (!o.store) throw new Error("createBwalletXAuth needs a nonce store (redisStore, pgStore; memoryStore for dev)");
|
|
625
|
+
const cookieName = o.cookieName ?? "bwx_session";
|
|
626
|
+
const maxAge = o.maxAge ?? 7 * 24 * 3600;
|
|
627
|
+
const secure = o.secureCookie ?? o.origin.startsWith("https:");
|
|
628
|
+
const secret = () => {
|
|
629
|
+
const s = o.secret ?? (typeof process !== "undefined" ? process.env?.[o.secretEnv ?? "BWALLETX_SESSION_SECRET"] : void 0);
|
|
630
|
+
assertSecret(s);
|
|
631
|
+
return s;
|
|
632
|
+
};
|
|
633
|
+
const cookie = (v, age) => serializeCookie(v, { name: cookieName, maxAge: age, secure, sameSite: o.sameSite, domain: o.cookieDomain });
|
|
634
|
+
const badOrigin = (req) => !originAllowed(req.headers.get("origin"), o.origin);
|
|
635
|
+
const fromSource = async (source) => {
|
|
636
|
+
if (typeof source === "string") return readCookie(source, cookieName);
|
|
637
|
+
if (source instanceof Headers) return readCookie(source.get("cookie"), cookieName);
|
|
638
|
+
if (source && typeof source.headers?.get === "function") return readCookie(source.headers.get("cookie"), cookieName);
|
|
639
|
+
const { cookies } = await import("next/headers");
|
|
640
|
+
const jar = await cookies();
|
|
641
|
+
return jar.get(cookieName)?.value ?? null;
|
|
642
|
+
};
|
|
643
|
+
const auth = {
|
|
644
|
+
async challenge(req) {
|
|
645
|
+
secret();
|
|
646
|
+
if (badOrigin(req)) return json({ error: "origin not allowed" }, 403);
|
|
647
|
+
const b = await body(req);
|
|
648
|
+
try {
|
|
649
|
+
return json(await createChallenge({ origin: o.origin, identityKey: b?.identityKey, store: o.store }));
|
|
650
|
+
} catch (e) {
|
|
651
|
+
return json({ error: e.message }, 400);
|
|
652
|
+
}
|
|
653
|
+
},
|
|
654
|
+
async verify(req) {
|
|
655
|
+
const key = secret();
|
|
656
|
+
if (badOrigin(req)) return json({ error: "origin not allowed" }, 403);
|
|
657
|
+
const b = await body(req);
|
|
658
|
+
const identityKey = await verifySignIn({ origin: o.origin, identityKey: b?.identityKey, nonce: b?.nonce, signature: b?.signature, store: o.store });
|
|
659
|
+
if (!identityKey) return json({ error: "sign-in failed" }, 401);
|
|
660
|
+
let extra = {};
|
|
661
|
+
try {
|
|
662
|
+
const r = await o.onVerified?.(identityKey, req);
|
|
663
|
+
if (r === false) return json({ error: "not allowed" }, 403);
|
|
664
|
+
if (r) extra = r;
|
|
665
|
+
} catch (e) {
|
|
666
|
+
if (e instanceof IdentityLinkConflictError) return json({ error: e.message, code: e.code }, 409);
|
|
667
|
+
throw e;
|
|
668
|
+
}
|
|
669
|
+
const token = await signSession({ ...extra, sub: identityKey }, { secret: key, maxAge });
|
|
670
|
+
return json({ identityKey, uid: extra.uid, handle: extra.handle, paymail: extra.paymail }, 200, { "set-cookie": cookie(token, maxAge) });
|
|
671
|
+
},
|
|
672
|
+
async logout(req) {
|
|
673
|
+
if (badOrigin(req)) return json({ error: "origin not allowed" }, 403);
|
|
674
|
+
return json({ ok: true }, 200, { "set-cookie": cookie("", 0) });
|
|
675
|
+
},
|
|
676
|
+
async session(req) {
|
|
677
|
+
const s = await auth.getSession(req);
|
|
678
|
+
return s ? json({ identityKey: s.sub, uid: s.uid, handle: s.handle, paymail: s.paymail, exp: s.exp }) : json({ identityKey: null }, 200);
|
|
679
|
+
},
|
|
680
|
+
async getSession(source) {
|
|
681
|
+
const key = secret();
|
|
682
|
+
return verifySession(await fromSource(source), { secret: key });
|
|
683
|
+
},
|
|
684
|
+
async sessionCookie(claims) {
|
|
685
|
+
return cookie(await signSession(claims, { secret: secret(), maxAge }), maxAge);
|
|
686
|
+
},
|
|
687
|
+
clearCookie: () => cookie("", 0)
|
|
688
|
+
};
|
|
689
|
+
return auth;
|
|
690
|
+
}
|
|
691
|
+
var errJson = (e) => json(e.toJSON(), ACCESS_ERROR_STATUS[e.code]);
|
|
692
|
+
function createBwalletXAccess(o) {
|
|
693
|
+
if (!o.store) throw new Error("createBwalletXAccess needs a nonce store");
|
|
694
|
+
const require2 = normaliseRequirement(o.require);
|
|
695
|
+
const reqHash = canonicalJson(require2);
|
|
696
|
+
const cookieName = o.cookieName ?? "bwx_access";
|
|
697
|
+
const maxAge = o.maxAge ?? 24 * 3600;
|
|
698
|
+
const recheckMs = (o.recheckEvery ?? 300) * 1e3;
|
|
699
|
+
const secure = o.secureCookie ?? o.origin.startsWith("https:");
|
|
700
|
+
const secret = () => {
|
|
701
|
+
const s = o.secret ?? (typeof process !== "undefined" ? process.env?.[o.secretEnv ?? "BWALLETX_SESSION_SECRET"] : void 0);
|
|
702
|
+
assertSecret(s);
|
|
703
|
+
return s;
|
|
704
|
+
};
|
|
705
|
+
const cookie = (v, age) => serializeCookie(v, { name: cookieName, maxAge: age, secure, sameSite: o.sameSite, domain: o.cookieDomain });
|
|
706
|
+
const badOrigin = (req) => !originAllowed(req.headers.get("origin"), o.origin);
|
|
707
|
+
const checked = /* @__PURE__ */ new Map();
|
|
708
|
+
const readToken = async (source) => {
|
|
709
|
+
if (typeof source === "string") return readCookie(source, cookieName);
|
|
710
|
+
if (source instanceof Headers) return readCookie(source.get("cookie"), cookieName);
|
|
711
|
+
if (source && typeof source.headers?.get === "function") return readCookie(source.headers.get("cookie"), cookieName);
|
|
712
|
+
const { cookies } = await import("next/headers");
|
|
713
|
+
const jar = await cookies();
|
|
714
|
+
return jar.get(cookieName)?.value ?? null;
|
|
715
|
+
};
|
|
716
|
+
const gate = {
|
|
717
|
+
require: require2,
|
|
718
|
+
async challenge(req) {
|
|
719
|
+
secret();
|
|
720
|
+
if (badOrigin(req)) return json({ error: "bad_request", message: "origin not allowed" }, 403);
|
|
721
|
+
const b = await body(req);
|
|
722
|
+
try {
|
|
723
|
+
return json(await createAccessChallenge({ origin: o.origin, require: require2, store: o.store, identityKey: b?.identityKey }));
|
|
724
|
+
} catch (e) {
|
|
725
|
+
return errJson(e instanceof AccessError ? e : new AccessError("bad_request", e.message));
|
|
726
|
+
}
|
|
727
|
+
},
|
|
728
|
+
async verify(req) {
|
|
729
|
+
const key = secret();
|
|
730
|
+
if (badOrigin(req)) return json({ error: "bad_request", message: "origin not allowed" }, 403);
|
|
731
|
+
const b = await body(req);
|
|
732
|
+
try {
|
|
733
|
+
const g = await verifyAccess({ origin: o.origin, response: b, store: o.store, resolver: o.resolver, require: require2 });
|
|
734
|
+
const token = await signSession({ sub: g.identityKey, acc: reqHash, ad: g.addresses }, { secret: key, maxAge });
|
|
735
|
+
checked.set(`${g.identityKey}|${g.addresses.join(",")}`, Date.now());
|
|
736
|
+
return json({ ok: true, identityKey: g.identityKey, have: g.have }, 200, { "set-cookie": cookie(token, maxAge) });
|
|
737
|
+
} catch (e) {
|
|
738
|
+
if (e instanceof AccessError) return errJson(e);
|
|
739
|
+
throw e;
|
|
740
|
+
}
|
|
741
|
+
},
|
|
742
|
+
async logout(req) {
|
|
743
|
+
if (badOrigin(req)) return json({ error: "bad_request", message: "origin not allowed" }, 403);
|
|
744
|
+
return json({ ok: true }, 200, { "set-cookie": cookie("", 0) });
|
|
745
|
+
},
|
|
746
|
+
async status(req) {
|
|
747
|
+
const a = await gate.getAccess(req);
|
|
748
|
+
return json(a, 200);
|
|
749
|
+
},
|
|
750
|
+
async getAccess(source) {
|
|
751
|
+
const s = await verifySession(await readToken(source), { secret: secret() });
|
|
752
|
+
if (!s || s.acc !== reqHash) return { ok: false, error: "no_session", message: "Not signed in to this gate." };
|
|
753
|
+
const addresses = Array.isArray(s.ad) ? s.ad.filter((x) => typeof x === "string") : [];
|
|
754
|
+
const k = `${s.sub}|${addresses.join(",")}`;
|
|
755
|
+
const last = checked.get(k) ?? 0;
|
|
756
|
+
if (require2.token && Date.now() - last >= recheckMs) {
|
|
757
|
+
try {
|
|
758
|
+
await checkTokenHolding(require2, addresses, o.resolver);
|
|
759
|
+
checked.set(k, Date.now());
|
|
760
|
+
} catch (e) {
|
|
761
|
+
checked.delete(k);
|
|
762
|
+
const ae = e instanceof AccessError ? e : new AccessError("indexer_unavailable", e.message);
|
|
763
|
+
return { ok: false, error: ae.code, message: ae.message === ae.code ? accessErrorMessage(ae.code, ae) : ae.message, have: ae.have, need: ae.need };
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
return { ok: true, identityKey: s.sub, addresses, checkedAt: checked.get(k) ?? last };
|
|
767
|
+
}
|
|
768
|
+
};
|
|
769
|
+
return gate;
|
|
770
|
+
}
|
|
771
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
772
|
+
0 && (module.exports = {
|
|
773
|
+
IdentityLinkConflictError,
|
|
774
|
+
createBwalletXAccess,
|
|
775
|
+
createBwalletXAuth,
|
|
776
|
+
linkIdentity,
|
|
777
|
+
memoryStore,
|
|
778
|
+
pgNonceTableSql,
|
|
779
|
+
pgStore,
|
|
780
|
+
redisStore,
|
|
781
|
+
signInOrLink
|
|
782
|
+
});
|
|
783
|
+
//# sourceMappingURL=next.cjs.map
|