@bwalletx/connect 0.3.0 → 0.4.1
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 +25 -0
- package/README.md +145 -4
- package/dist/bwalletx-connect.global.js +41 -3
- package/dist/bwalletx-connect.global.js.map +1 -1
- package/dist/chunk-7NAKOJGZ.js +442 -0
- package/dist/chunk-7NAKOJGZ.js.map +1 -0
- package/dist/chunk-FUQ46RJV.js +404 -0
- package/dist/chunk-FUQ46RJV.js.map +1 -0
- package/dist/index.cjs +425 -5
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +23 -62
- package/dist/index.d.ts +23 -62
- package/dist/index.js +35 -1
- package/dist/index.js.map +1 -1
- package/dist/next.cjs +415 -0
- package/dist/next.cjs.map +1 -0
- package/dist/next.d.cts +48 -0
- package/dist/next.d.ts +48 -0
- package/dist/next.js +107 -0
- package/dist/next.js.map +1 -0
- package/dist/react.cjs +586 -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 +175 -3
- package/dist/react.js.map +1 -1
- package/dist/server.cjs +339 -4
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.cts +204 -2
- package/dist/server.d.ts +204 -2
- package/dist/server.js +36 -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 +38 -13
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/next.ts","../src/link.ts","../src/server.ts","../src/nonce-stores.ts","../src/session.ts"],"sourcesContent":["/**\n * Next.js App Router adapter. Route handlers use standard Request/Response, so they also work in\n * any Fetch-API server (Hono, Remix, Bun, Workers).\n *\n * // lib/bwalletx.ts\n * export const auth = createBwalletXAuth({ origin: process.env.APP_ORIGIN!, store: pgStore({ query }) });\n * // app/api/bwalletx/challenge/route.ts → export const POST = auth.challenge;\n * // app/api/bwalletx/verify/route.ts → export const POST = auth.verify;\n * // app/api/bwalletx/logout/route.ts → export const POST = auth.logout;\n * // app/api/bwalletx/session/route.ts → export const GET = auth.session;\n * // server component: const s = await auth.getSession();\n */\nimport { IdentityLinkConflictError } from './link.js';\nimport { createChallenge, originAllowed, verifySignIn, type NonceStore } from './server.js';\nimport { assertSecret, readCookie, serializeCookie, signSession, verifySession, type SessionPayload } from './session.js';\n\nexport type { SessionPayload } from './session.js';\n\nexport interface VerifiedExtra {\n /** Your user id (e.g. from signInOrLink). Stored in the session as `uid`. */\n uid?: string;\n handle?: string;\n paymail?: string;\n [claim: string]: unknown;\n}\n\nexport interface BwalletXAuthOptions {\n /** YOUR origin from config, e.g. \"https://example.com\". Never from the request. */\n origin: string;\n /** A shared nonce store: redisStore or pgStore. memoryStore only in development. */\n store: NonceStore;\n /** HMAC secret, 32+ chars. Default: process.env[secretEnv]. There is no fallback; requests throw without it. */\n secret?: string;\n /** Env var holding the secret. Default 'BWALLETX_SESSION_SECRET'. */\n secretEnv?: string;\n /** Cookie name. Default 'bwx_session'. */\n cookieName?: string;\n /** Session lifetime in seconds. Default 7 days. */\n maxAge?: number;\n /** Default: true when origin is https. */\n secureCookie?: boolean;\n sameSite?: 'Lax' | 'Strict' | 'None';\n cookieDomain?: string;\n /**\n * Runs after the signature is verified, before the cookie is set: link to your user, look up a\n * handle. Throw IdentityLinkConflictError to answer 409; return false to refuse (403).\n */\n onVerified?: (identityKey: string, req: Request) => Promise<VerifiedExtra | void | false> | VerifiedExtra | void | false;\n}\n\nexport interface BwalletXAuth {\n challenge(req: Request): Promise<Response>;\n verify(req: Request): Promise<Response>;\n logout(req: Request): Promise<Response>;\n session(req: Request): Promise<Response>;\n /** The session, or null. With no argument it reads cookies() from next/headers. */\n getSession(source?: Request | Headers | string | null): Promise<SessionPayload | null>;\n /** Make a cookie for an identity you verified yourself (e.g. after account linking elsewhere). */\n sessionCookie(claims: Omit<SessionPayload, 'iat' | 'exp'>): Promise<string>;\n clearCookie(): string;\n}\n\nconst json = (body: unknown, status = 200, headers: Record<string, string> = {}) =>\n new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json', 'cache-control': 'no-store', ...headers } });\n\nasync function body(req: Request): Promise<Record<string, unknown> | null> {\n try {\n const b = await req.json();\n return b && typeof b === 'object' ? (b as Record<string, unknown>) : null;\n } catch {\n return null;\n }\n}\n\nexport function createBwalletXAuth(o: BwalletXAuthOptions): BwalletXAuth {\n if (!o.store) throw new Error('createBwalletXAuth needs a nonce store (redisStore, pgStore; memoryStore for dev)');\n const cookieName = o.cookieName ?? 'bwx_session';\n const maxAge = o.maxAge ?? 7 * 24 * 3600;\n const secure = o.secureCookie ?? o.origin.startsWith('https:');\n const secret = () => {\n const s = o.secret ?? (typeof process !== 'undefined' ? process.env?.[o.secretEnv ?? 'BWALLETX_SESSION_SECRET'] : undefined);\n assertSecret(s);\n return s;\n };\n const cookie = (v: string, age: number) => serializeCookie(v, { name: cookieName, maxAge: age, secure, sameSite: o.sameSite, domain: o.cookieDomain });\n const badOrigin = (req: Request) => !originAllowed(req.headers.get('origin'), o.origin);\n\n const fromSource = async (source?: Request | Headers | string | null): Promise<string | null> => {\n if (typeof source === 'string') return readCookie(source, cookieName);\n if (source instanceof Headers) return readCookie(source.get('cookie'), cookieName);\n if (source && typeof (source as Request).headers?.get === 'function') return readCookie((source as Request).headers.get('cookie'), cookieName);\n // Server components / route handlers: Next's cookies(). Imported lazily so the package does not require Next.\n const { cookies } = (await import('next/headers')) as { cookies: () => unknown };\n const jar = (await cookies()) as { get(n: string): { value: string } | undefined };\n return jar.get(cookieName)?.value ?? null;\n };\n\n const auth: BwalletXAuth = {\n async challenge(req) {\n secret();\n if (badOrigin(req)) return json({ error: 'origin not allowed' }, 403);\n const b = await body(req);\n try {\n return json(await createChallenge({ origin: o.origin, identityKey: b?.identityKey, store: o.store }));\n } catch (e) {\n return json({ error: (e as Error).message }, 400);\n }\n },\n async verify(req) {\n const key = secret();\n if (badOrigin(req)) return json({ error: 'origin not allowed' }, 403);\n const b = await body(req);\n const identityKey = await verifySignIn({ origin: o.origin, identityKey: b?.identityKey, nonce: b?.nonce, signature: b?.signature, store: o.store });\n if (!identityKey) return json({ error: 'sign-in failed' }, 401);\n let extra: VerifiedExtra = {};\n try {\n const r = await o.onVerified?.(identityKey, req);\n if (r === false) return json({ error: 'not allowed' }, 403);\n if (r) extra = r;\n } catch (e) {\n if (e instanceof IdentityLinkConflictError) return json({ error: e.message, code: e.code }, 409);\n throw e;\n }\n const token = await signSession({ ...extra, sub: identityKey }, { secret: key, maxAge });\n return json({ identityKey, uid: extra.uid, handle: extra.handle, paymail: extra.paymail }, 200, { 'set-cookie': cookie(token, maxAge) });\n },\n async logout(req) {\n if (badOrigin(req)) return json({ error: 'origin not allowed' }, 403);\n return json({ ok: true }, 200, { 'set-cookie': cookie('', 0) });\n },\n async session(req) {\n const s = await auth.getSession(req);\n return s ? json({ identityKey: s.sub, uid: s.uid, handle: s.handle, paymail: s.paymail, exp: s.exp }) : json({ identityKey: null }, 200);\n },\n async getSession(source) {\n const key = secret();\n return verifySession(await fromSource(source), { secret: key });\n },\n async sessionCookie(claims) {\n return cookie(await signSession(claims, { secret: secret(), maxAge }), maxAge);\n },\n clearCookie: () => cookie('', 0),\n };\n return auth;\n}\n\nexport { IdentityLinkConflictError, linkIdentity, signInOrLink } from './link.js';\nexport { memoryStore, redisStore, pgStore, pgNonceTableSql } from './server.js';\n","/**\n * Link a proven identity key to a user in YOUR auth system (Supabase, next-auth, your own table).\n * You supply the storage callbacks; this module only holds the rules.\n */\n\nexport interface LinkCallbacks {\n /** The user id this identity key is linked to, or null. */\n findUserByIdentityKey(identityKey: string): Promise<string | null> | string | null;\n /** Save the link. Make (identity_key) unique in your table so a race cannot double-link. */\n attach(userId: string, identityKey: string): Promise<void> | void;\n}\n\nexport type LinkResult = { status: 'linked' | 'already-linked'; userId: string; identityKey: string };\n\nexport class IdentityLinkConflictError extends Error {\n readonly code = 'IDENTITY_LINKED_TO_OTHER_USER';\n constructor(\n readonly identityKey: string,\n readonly otherUserId: string,\n ) {\n super('This bWalletX identity is already linked to a different account. Sign in with that account, or unlink it there first.');\n this.name = 'IdentityLinkConflictError';\n }\n}\n\nconst norm = (k: string) => {\n 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)');\n return k.toLowerCase();\n};\n\n/**\n * Link `identityKey` (already verified with verifySignIn) to the signed-in `userId`.\n * Throws IdentityLinkConflictError if it belongs to someone else. Idempotent for the same user.\n */\nexport async function linkIdentity(userId: string, identityKey: string, cb: LinkCallbacks): Promise<LinkResult> {\n if (!userId) throw new Error('linkIdentity needs the current user id');\n const key = norm(identityKey);\n const owner = await cb.findUserByIdentityKey(key);\n if (owner && owner !== userId) throw new IdentityLinkConflictError(key, owner);\n if (owner === userId) return { status: 'already-linked', userId, identityKey: key };\n await cb.attach(userId, key);\n return { status: 'linked', userId, identityKey: key };\n}\n\nexport interface SignInOrLinkOptions extends LinkCallbacks {\n /** The user already signed in some other way (e.g. HandCash, email), if any. */\n currentUserId?: string | null;\n /** Make a new user for an unknown identity key. Without it, unknown keys return status 'unknown'. */\n createUser?(identityKey: string): Promise<string> | string;\n}\n\nexport type SignInOrLinkResult =\n | { status: 'signed-in' | 'linked' | 'already-linked' | 'created'; userId: string; identityKey: string }\n | { status: 'unknown'; userId: null; identityKey: string };\n\n/**\n * The usual verify-route logic: signed in already → link; known key → that user; else create (or report unknown).\n * Throws IdentityLinkConflictError when a signed-in user tries to link a key owned by another user.\n */\nexport async function signInOrLink(identityKey: string, o: SignInOrLinkOptions): Promise<SignInOrLinkResult> {\n const key = norm(identityKey);\n if (o.currentUserId) return linkIdentity(o.currentUserId, key, o);\n const owner = await o.findUserByIdentityKey(key);\n if (owner) return { status: 'signed-in', userId: owner, identityKey: key };\n if (!o.createUser) return { status: 'unknown', userId: null, identityKey: key };\n const userId = await o.createUser(key);\n await o.attach(userId, key);\n return { status: 'created', userId, identityKey: key };\n}\n","import { ProtoWallet, PublicKey, type WalletProtocol } from '@bsv/sdk';\n\n/** Security level 2, a protocol name used for nothing else. Keep it constant. */\nexport const LOGIN_PROTOCOL: WalletProtocol = [2, 'bwallet sign in'];\nexport const CHALLENGE_LIFETIME_MS = 2 * 60 * 1000;\n\nexport interface PendingChallenge {\n identityKey: string;\n origin: string;\n message: string;\n expiresAt: number;\n}\n\n/**\n * Where challenges wait between the two routes. Use Redis or a database table in production.\n * `take` must read and delete in one step, so each nonce can be tried once.\n */\nexport interface NonceStore {\n put(nonce: string, c: PendingChallenge): Promise<void> | void;\n take(nonce: string): Promise<PendingChallenge | null> | PendingChallenge | null;\n}\n\nlet warned = false;\n\n/**\n * In-memory store. For development and tests only: it is lost on restart and not shared between\n * server processes or serverless instances. Expired entries are pruned on each put.\n */\nexport function memoryStore(opts: { quiet?: boolean } = {}): NonceStore {\n const prod = typeof process !== 'undefined' && process.env?.NODE_ENV === 'production';\n if ((prod || !opts.quiet) && !warned) {\n warned = true;\n console.warn(\n prod\n ? '[@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.'\n : '[@bwalletx/connect] Using the in-memory nonce store. It is for development only; pass a shared store (redisStore, pgStore) in production.',\n );\n }\n const m = new Map<string, PendingChallenge>();\n return {\n put(nonce, c) {\n const now = Date.now();\n for (const [k, v] of m) if (v.expiresAt < now) m.delete(k);\n m.set(nonce, c);\n },\n take(nonce) {\n const c = m.get(nonce) ?? null;\n m.delete(nonce);\n return c;\n },\n };\n}\n\nlet defaultStore: NonceStore | null = null;\nconst storeOrDefault = (s?: NonceStore) => s ?? (defaultStore ??= memoryStore());\n\nexport function isIdentityKey(x: unknown): x is string {\n if (typeof x !== 'string' || !/^0[23][0-9a-fA-F]{64}$/.test(x)) return false;\n try {\n PublicKey.fromString(x);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction normalOrigin(origin: string): string {\n const u = new URL(origin);\n if (u.origin === 'null' || u.origin !== origin.replace(/\\/$/, '')) {\n throw new Error(`origin must be scheme://host[:port], got ${origin}`);\n }\n return u.origin;\n}\n\n/** The text the user signs. Lines joined with \\n, no trailing newline. */\nexport function loginMessage(origin: string, nonce: string, expiresAt: number): string {\n return [\n `Sign in to ${new URL(origin).host} with bWallet`,\n '',\n 'This proves you hold this wallet. It does not spend anything.',\n '',\n `Origin: ${origin}`,\n `Nonce: ${nonce}`,\n `Expires: ${new Date(expiresAt).toISOString()}`,\n ].join('\\n');\n}\n\nfunction randomNonce(): string {\n const b = new Uint8Array(16);\n globalThis.crypto.getRandomValues(b);\n let s = '';\n for (const x of b) s += String.fromCharCode(x);\n return btoa(s).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\nexport interface CreateChallengeOptions {\n /** YOUR site's origin from config, e.g. \"https://example.com\". Never take it from the request. */\n origin: string;\n /** The identity key the browser claims. Checked again at verify. */\n identityKey: unknown;\n /** Default: a process-wide in-memory store (dev only). */\n store?: NonceStore;\n}\n\nexport interface ChallengeResponse {\n nonce: string;\n message: string;\n protocolID: WalletProtocol;\n keyID: string;\n expiresAt: number;\n}\n\n/** Step 1. Throws if identityKey is not a valid compressed public key. Send the result to the browser. */\nexport async function createChallenge(opts: CreateChallengeOptions): Promise<ChallengeResponse> {\n if (!isIdentityKey(opts.identityKey)) throw new Error('identityKey must be a compressed public key (66 hex chars)');\n const origin = normalOrigin(opts.origin);\n const nonce = randomNonce();\n const expiresAt = Date.now() + CHALLENGE_LIFETIME_MS;\n const message = loginMessage(origin, nonce, expiresAt);\n await storeOrDefault(opts.store).put(nonce, { identityKey: opts.identityKey.toLowerCase(), origin, message, expiresAt });\n return { nonce, message, protocolID: LOGIN_PROTOCOL, keyID: nonce, expiresAt };\n}\n\nexport interface VerifySignInOptions {\n /** YOUR site's origin from config. Must equal the origin the challenge was made for. */\n origin: string;\n /** From the request body. */\n identityKey: unknown;\n nonce: unknown;\n signature: unknown;\n store?: NonceStore;\n}\n\n/**\n * Step 2. Returns the proven identity key (lowercase hex), or null.\n * The nonce is deleted before anything is checked, so each challenge can be tried once.\n */\nexport async function verifySignIn(opts: VerifySignInOptions): Promise<string | null> {\n if (typeof opts.nonce !== 'string' || opts.nonce.length > 64) return null;\n const c = await storeOrDefault(opts.store).take(opts.nonce);\n if (!c || Date.now() > c.expiresAt) return null;\n let origin: string;\n try {\n origin = normalOrigin(opts.origin);\n } catch {\n return null;\n }\n if (c.origin !== origin) return null;\n if (!isIdentityKey(opts.identityKey)) return null;\n const identityKey = opts.identityKey.toLowerCase();\n if (c.identityKey !== identityKey) return null;\n\n const sig = opts.signature;\n if (!Array.isArray(sig) || sig.length < 8 || sig.length > 80 || !sig.every((b) => Number.isInteger(b) && b >= 0 && b <= 255)) {\n return null;\n }\n try {\n const { valid } = await new ProtoWallet('anyone').verifySignature({\n protocolID: LOGIN_PROTOCOL,\n keyID: opts.nonce,\n counterparty: identityKey,\n data: Array.from(new TextEncoder().encode(c.message)),\n signature: sig as number[],\n });\n return valid ? identityKey : null;\n } catch {\n return null; // @bsv/sdk throws on a bad signature instead of returning valid: false\n }\n}\n\n/** True when a request's Origin header is exactly your configured origin. Check it on both routes. */\nexport function originAllowed(requestOrigin: string | null | undefined, origin: string): boolean {\n try {\n return !!requestOrigin && requestOrigin === normalOrigin(origin);\n } catch {\n return false;\n }\n}\n\nexport { redisStore, pgStore, pgNonceTableSql } from './nonce-stores.js';\nexport type { RedisLike, RedisStoreOptions, PgQuery, PgStoreOptions } from './nonce-stores.js';\nexport { signSession, verifySession, serializeCookie, readCookie, MIN_SECRET_LENGTH } from './session.js';\nexport type { SessionPayload, SignSessionOptions, CookieOptions } from './session.js';\nexport { verifyPayment, PaymentVerificationError } from './verify-payment.js';\nexport type { VerifyPaymentOptions, VerifyPaymentResult, ExpectedOutput, TxStatus } from './verify-payment.js';\nexport { linkIdentity, signInOrLink, IdentityLinkConflictError } from './link.js';\nexport type { LinkCallbacks, LinkResult, SignInOrLinkOptions, SignInOrLinkResult } from './link.js';\n","/**\n * Shared NonceStore adapters. No database driver is imported: you pass your own client or query\n * function. Every adapter makes `take` read-and-delete in one step, so each nonce works once.\n */\nimport type { NonceStore, PendingChallenge } from './server.js';\n\nconst ttlSeconds = (c: PendingChallenge) => Math.max(1, Math.ceil((c.expiresAt - Date.now()) / 1000));\n\nfunction parse(v: unknown): PendingChallenge | null {\n if (v == null) return null;\n try {\n const c = (typeof v === 'string' ? JSON.parse(v) : v) as PendingChallenge;\n if (!c || typeof c.identityKey !== 'string' || typeof c.message !== 'string' || typeof c.expiresAt !== 'number') return null;\n return c.expiresAt < Date.now() ? null : c;\n } catch {\n return null;\n }\n}\n\n/**\n * The Redis commands used. Fits @upstash/redis and node-redis v4+ as they are\n * (`set(key, value, { ex | EX })`, `getdel` / `getDel`). For ioredis pass `flavor: 'ioredis'`.\n */\nexport interface RedisLike {\n set(key: string, value: string, ...args: unknown[]): Promise<unknown>;\n getdel?(key: string): Promise<unknown>;\n getDel?(key: string): Promise<unknown>;\n}\n\nexport interface RedisStoreOptions {\n client: RedisLike;\n /** Key prefix. Default 'bwalletx:nonce:'. */\n prefix?: string;\n /** 'ioredis' uses positional `set(key, value, 'EX', s)`. Default 'object' (Upstash, node-redis). */\n flavor?: 'object' | 'ioredis';\n}\n\n/** Redis / Upstash / Vercel KV. Needs Redis 6.2+ for GETDEL. */\nexport function redisStore(opts: RedisStoreOptions): NonceStore {\n const { client } = opts;\n const prefix = opts.prefix ?? 'bwalletx:nonce:';\n const getdel = client.getdel?.bind(client) ?? client.getDel?.bind(client);\n if (!getdel) throw new Error('redisStore: the client needs getdel (or getDel). Redis 6.2+.');\n return {\n async put(nonce, c) {\n const s = ttlSeconds(c);\n if (opts.flavor === 'ioredis') await client.set(prefix + nonce, JSON.stringify(c), 'EX', s);\n else await client.set(prefix + nonce, JSON.stringify(c), { ex: s, EX: s });\n },\n async take(nonce) {\n return parse(await getdel(prefix + nonce));\n },\n };\n}\n\n/** `query(sql, params)` resolving to `{ rows }` (node-postgres, @vercel/postgres, Neon) or a bare array (postgres.js `sql.unsafe`). */\nexport type PgQuery = (sql: string, params: unknown[]) => Promise<{ rows: unknown[] } | unknown[]>;\n\nexport interface PgStoreOptions {\n query: PgQuery;\n /** Table name (letters, digits, _ and one optional schema dot). Default 'bwalletx_nonces'. */\n table?: string;\n}\n\n/** Run this once (a migration) before using pgStore. */\nexport function pgNonceTableSql(table = 'bwalletx_nonces'): string {\n const t = safeTable(table);\n return `create table if not exists ${t} (\n nonce text primary key,\n challenge jsonb not null,\n expires_at timestamptz not null\n);\ncreate index if not exists ${t.replace('.', '_')}_expires_idx on ${t} (expires_at);`;\n}\n\nfunction safeTable(t: string): string {\n 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}`);\n return t;\n}\n\n/** Postgres (e.g. self-hosted Supabase). Single-use via DELETE ... RETURNING. */\nexport function pgStore(opts: PgStoreOptions): NonceStore {\n const t = safeTable(opts.table ?? 'bwalletx_nonces');\n const rows = (r: { rows: unknown[] } | unknown[]) => (Array.isArray(r) ? r : r.rows);\n return {\n async put(nonce, c) {\n await opts.query(`delete from ${t} where expires_at < now()`, []);\n await opts.query(`insert into ${t} (nonce, challenge, expires_at) values ($1, $2, to_timestamp($3 / 1000.0))`, [\n nonce,\n JSON.stringify(c),\n c.expiresAt,\n ]);\n },\n async take(nonce) {\n const r = rows(await opts.query(`delete from ${t} where nonce = $1 returning challenge`, [nonce]));\n const row = r[0] as { challenge?: unknown } | undefined;\n return parse(row?.challenge);\n },\n };\n}\n","/**\n * Signed session tokens: base64url(JSON payload) + \".\" + base64url(HMAC-SHA256).\n * WebCrypto only, so it runs in Node 20+, Vercel Edge and Cloudflare Workers.\n * There is no default secret: pass one (32+ chars) or every call throws.\n */\n\nexport interface SessionPayload {\n /** The proven identity key (lowercase hex). */\n sub: string;\n /** Issued at, seconds since the epoch. */\n iat: number;\n /** Expires at, seconds since the epoch. */\n exp: number;\n /** Your app's user id, if the identity key is linked to one. */\n uid?: string;\n handle?: string;\n paymail?: string;\n [claim: string]: unknown;\n}\n\nexport const MIN_SECRET_LENGTH = 32;\n\nconst enc = new TextEncoder();\nconst dec = new TextDecoder();\n\nfunction b64u(bytes: Uint8Array): string {\n let s = '';\n for (const b of bytes) s += String.fromCharCode(b);\n return btoa(s).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\nfunction unb64u(s: string): Uint8Array<ArrayBuffer> {\n if (!/^[A-Za-z0-9_-]*$/.test(s)) throw new Error('bad base64url');\n const b = atob(s.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - (s.length % 4)) % 4));\n return Uint8Array.from(b, (c) => c.charCodeAt(0));\n}\n\nexport function assertSecret(secret: unknown): asserts secret is string {\n if (typeof secret !== 'string' || secret.length < MIN_SECRET_LENGTH) {\n throw new Error(\n `[@bwalletx/connect] A session secret of at least ${MIN_SECRET_LENGTH} characters is required. ` +\n 'Set it in an environment variable (e.g. BWALLETX_SESSION_SECRET). There is no default.',\n );\n }\n}\n\nconst keys = new Map<string, Promise<CryptoKey>>();\nfunction hmacKey(secret: string): Promise<CryptoKey> {\n let k = keys.get(secret);\n if (!k) {\n k = globalThis.crypto.subtle.importKey('raw', enc.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign', 'verify']);\n keys.set(secret, k);\n }\n return k;\n}\n\nexport interface SignSessionOptions {\n secret: string;\n /** Lifetime in seconds. Default 7 days. */\n maxAge?: number;\n /** For tests. */\n now?: number;\n}\n\n/** Sign a session. `claims.sub` (identity key) is required. */\nexport async function signSession(\n claims: Omit<SessionPayload, 'iat' | 'exp'> & Partial<Pick<SessionPayload, 'iat' | 'exp'>>,\n opts: SignSessionOptions,\n): Promise<string> {\n assertSecret(opts.secret);\n if (typeof claims.sub !== 'string' || !claims.sub) throw new Error('session needs a sub (identity key)');\n const iat = Math.floor((opts.now ?? Date.now()) / 1000);\n const payload: SessionPayload = { ...claims, sub: claims.sub, iat, exp: iat + (opts.maxAge ?? 7 * 24 * 3600) };\n const body = b64u(enc.encode(JSON.stringify(payload)));\n const sig = new Uint8Array(await globalThis.crypto.subtle.sign('HMAC', await hmacKey(opts.secret), enc.encode(body)));\n return `${body}.${b64u(sig)}`;\n}\n\n/** The payload if the token is authentic and unexpired, else null. Never throws on bad input (only on a missing secret). */\nexport async function verifySession(token: unknown, opts: { secret: string; now?: number }): Promise<SessionPayload | null> {\n assertSecret(opts.secret);\n if (typeof token !== 'string' || token.length > 8192) return null;\n const dot = token.indexOf('.');\n if (dot < 1 || dot !== token.lastIndexOf('.')) return null;\n const body = token.slice(0, dot);\n try {\n const sig = unb64u(token.slice(dot + 1));\n // crypto.subtle.verify compares in constant time.\n const ok = await globalThis.crypto.subtle.verify('HMAC', await hmacKey(opts.secret), sig, enc.encode(body));\n if (!ok) return null;\n const p = JSON.parse(dec.decode(unb64u(body))) as SessionPayload;\n if (!p || typeof p.sub !== 'string' || typeof p.exp !== 'number') return null;\n if (Math.floor((opts.now ?? Date.now()) / 1000) >= p.exp) return null;\n return p;\n } catch {\n return null;\n }\n}\n\nexport interface CookieOptions {\n name: string;\n maxAge: number;\n secure?: boolean;\n sameSite?: 'Lax' | 'Strict' | 'None';\n path?: string;\n domain?: string;\n}\n\n/** A Set-Cookie header value. Always HttpOnly. */\nexport function serializeCookie(value: string, o: CookieOptions): string {\n const parts = [`${o.name}=${value}`, `Path=${o.path ?? '/'}`, `Max-Age=${o.maxAge}`, 'HttpOnly', `SameSite=${o.sameSite ?? 'Lax'}`];\n if (o.secure !== false) parts.push('Secure');\n if (o.domain) parts.push(`Domain=${o.domain}`);\n return parts.join('; ');\n}\n\n/** Read one cookie from a Cookie header. */\nexport function readCookie(header: string | null | undefined, name: string): string | null {\n if (!header) return null;\n for (const part of header.split(';')) {\n const i = part.indexOf('=');\n if (i > 0 && part.slice(0, i).trim() === name) return part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E,IAAI,KAAK,GAAG,KAAK,EAAE,cAAc,OAAO,IAAI,CAAC,EAAE,CAAC;AAAA,IAChE;AAAA,IACA,MAAM,QAAQ,KAAK;AACjB,YAAM,IAAI,MAAM,KAAK,WAAW,GAAG;AACnC,aAAO,IAAI,KAAK,EAAE,aAAa,EAAE,KAAK,KAAK,EAAE,KAAK,QAAQ,EAAE,QAAQ,SAAS,EAAE,SAAS,KAAK,EAAE,IAAI,CAAC,IAAI,KAAK,EAAE,aAAa,KAAK,GAAG,GAAG;AAAA,IACzI;AAAA,IACA,MAAM,WAAW,QAAQ;AACvB,YAAM,MAAM,OAAO;AACnB,aAAO,cAAc,MAAM,WAAW,MAAM,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,IAChE;AAAA,IACA,MAAM,cAAc,QAAQ;AAC1B,aAAO,OAAO,MAAM,YAAY,QAAQ,EAAE,QAAQ,OAAO,GAAG,OAAO,CAAC,GAAG,MAAM;AAAA,IAC/E;AAAA,IACA,aAAa,MAAM,OAAO,IAAI,CAAC;AAAA,EACjC;AACA,SAAO;AACT;","names":["body","body"]}
|
package/dist/next.d.cts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { SessionPayload, NonceStore } from './server.cjs';
|
|
2
|
+
export { IdentityLinkConflictError, linkIdentity, memoryStore, pgNonceTableSql, pgStore, redisStore, signInOrLink } from './server.cjs';
|
|
3
|
+
import '@bsv/sdk';
|
|
4
|
+
|
|
5
|
+
interface VerifiedExtra {
|
|
6
|
+
/** Your user id (e.g. from signInOrLink). Stored in the session as `uid`. */
|
|
7
|
+
uid?: string;
|
|
8
|
+
handle?: string;
|
|
9
|
+
paymail?: string;
|
|
10
|
+
[claim: string]: unknown;
|
|
11
|
+
}
|
|
12
|
+
interface BwalletXAuthOptions {
|
|
13
|
+
/** YOUR origin from config, e.g. "https://example.com". Never from the request. */
|
|
14
|
+
origin: string;
|
|
15
|
+
/** A shared nonce store: redisStore or pgStore. memoryStore only in development. */
|
|
16
|
+
store: NonceStore;
|
|
17
|
+
/** HMAC secret, 32+ chars. Default: process.env[secretEnv]. There is no fallback; requests throw without it. */
|
|
18
|
+
secret?: string;
|
|
19
|
+
/** Env var holding the secret. Default 'BWALLETX_SESSION_SECRET'. */
|
|
20
|
+
secretEnv?: string;
|
|
21
|
+
/** Cookie name. Default 'bwx_session'. */
|
|
22
|
+
cookieName?: string;
|
|
23
|
+
/** Session lifetime in seconds. Default 7 days. */
|
|
24
|
+
maxAge?: number;
|
|
25
|
+
/** Default: true when origin is https. */
|
|
26
|
+
secureCookie?: boolean;
|
|
27
|
+
sameSite?: 'Lax' | 'Strict' | 'None';
|
|
28
|
+
cookieDomain?: string;
|
|
29
|
+
/**
|
|
30
|
+
* Runs after the signature is verified, before the cookie is set: link to your user, look up a
|
|
31
|
+
* handle. Throw IdentityLinkConflictError to answer 409; return false to refuse (403).
|
|
32
|
+
*/
|
|
33
|
+
onVerified?: (identityKey: string, req: Request) => Promise<VerifiedExtra | void | false> | VerifiedExtra | void | false;
|
|
34
|
+
}
|
|
35
|
+
interface BwalletXAuth {
|
|
36
|
+
challenge(req: Request): Promise<Response>;
|
|
37
|
+
verify(req: Request): Promise<Response>;
|
|
38
|
+
logout(req: Request): Promise<Response>;
|
|
39
|
+
session(req: Request): Promise<Response>;
|
|
40
|
+
/** The session, or null. With no argument it reads cookies() from next/headers. */
|
|
41
|
+
getSession(source?: Request | Headers | string | null): Promise<SessionPayload | null>;
|
|
42
|
+
/** Make a cookie for an identity you verified yourself (e.g. after account linking elsewhere). */
|
|
43
|
+
sessionCookie(claims: Omit<SessionPayload, 'iat' | 'exp'>): Promise<string>;
|
|
44
|
+
clearCookie(): string;
|
|
45
|
+
}
|
|
46
|
+
declare function createBwalletXAuth(o: BwalletXAuthOptions): BwalletXAuth;
|
|
47
|
+
|
|
48
|
+
export { type BwalletXAuth, type BwalletXAuthOptions, SessionPayload, type VerifiedExtra, createBwalletXAuth };
|
package/dist/next.d.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { SessionPayload, NonceStore } from './server.js';
|
|
2
|
+
export { IdentityLinkConflictError, linkIdentity, memoryStore, pgNonceTableSql, pgStore, redisStore, signInOrLink } from './server.js';
|
|
3
|
+
import '@bsv/sdk';
|
|
4
|
+
|
|
5
|
+
interface VerifiedExtra {
|
|
6
|
+
/** Your user id (e.g. from signInOrLink). Stored in the session as `uid`. */
|
|
7
|
+
uid?: string;
|
|
8
|
+
handle?: string;
|
|
9
|
+
paymail?: string;
|
|
10
|
+
[claim: string]: unknown;
|
|
11
|
+
}
|
|
12
|
+
interface BwalletXAuthOptions {
|
|
13
|
+
/** YOUR origin from config, e.g. "https://example.com". Never from the request. */
|
|
14
|
+
origin: string;
|
|
15
|
+
/** A shared nonce store: redisStore or pgStore. memoryStore only in development. */
|
|
16
|
+
store: NonceStore;
|
|
17
|
+
/** HMAC secret, 32+ chars. Default: process.env[secretEnv]. There is no fallback; requests throw without it. */
|
|
18
|
+
secret?: string;
|
|
19
|
+
/** Env var holding the secret. Default 'BWALLETX_SESSION_SECRET'. */
|
|
20
|
+
secretEnv?: string;
|
|
21
|
+
/** Cookie name. Default 'bwx_session'. */
|
|
22
|
+
cookieName?: string;
|
|
23
|
+
/** Session lifetime in seconds. Default 7 days. */
|
|
24
|
+
maxAge?: number;
|
|
25
|
+
/** Default: true when origin is https. */
|
|
26
|
+
secureCookie?: boolean;
|
|
27
|
+
sameSite?: 'Lax' | 'Strict' | 'None';
|
|
28
|
+
cookieDomain?: string;
|
|
29
|
+
/**
|
|
30
|
+
* Runs after the signature is verified, before the cookie is set: link to your user, look up a
|
|
31
|
+
* handle. Throw IdentityLinkConflictError to answer 409; return false to refuse (403).
|
|
32
|
+
*/
|
|
33
|
+
onVerified?: (identityKey: string, req: Request) => Promise<VerifiedExtra | void | false> | VerifiedExtra | void | false;
|
|
34
|
+
}
|
|
35
|
+
interface BwalletXAuth {
|
|
36
|
+
challenge(req: Request): Promise<Response>;
|
|
37
|
+
verify(req: Request): Promise<Response>;
|
|
38
|
+
logout(req: Request): Promise<Response>;
|
|
39
|
+
session(req: Request): Promise<Response>;
|
|
40
|
+
/** The session, or null. With no argument it reads cookies() from next/headers. */
|
|
41
|
+
getSession(source?: Request | Headers | string | null): Promise<SessionPayload | null>;
|
|
42
|
+
/** Make a cookie for an identity you verified yourself (e.g. after account linking elsewhere). */
|
|
43
|
+
sessionCookie(claims: Omit<SessionPayload, 'iat' | 'exp'>): Promise<string>;
|
|
44
|
+
clearCookie(): string;
|
|
45
|
+
}
|
|
46
|
+
declare function createBwalletXAuth(o: BwalletXAuthOptions): BwalletXAuth;
|
|
47
|
+
|
|
48
|
+
export { type BwalletXAuth, type BwalletXAuthOptions, SessionPayload, type VerifiedExtra, createBwalletXAuth };
|
package/dist/next.js
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import {
|
|
2
|
+
IdentityLinkConflictError,
|
|
3
|
+
assertSecret,
|
|
4
|
+
createChallenge,
|
|
5
|
+
linkIdentity,
|
|
6
|
+
memoryStore,
|
|
7
|
+
originAllowed,
|
|
8
|
+
pgNonceTableSql,
|
|
9
|
+
pgStore,
|
|
10
|
+
readCookie,
|
|
11
|
+
redisStore,
|
|
12
|
+
serializeCookie,
|
|
13
|
+
signInOrLink,
|
|
14
|
+
signSession,
|
|
15
|
+
verifySession,
|
|
16
|
+
verifySignIn
|
|
17
|
+
} from "./chunk-7NAKOJGZ.js";
|
|
18
|
+
|
|
19
|
+
// src/next.ts
|
|
20
|
+
var json = (body2, status = 200, headers = {}) => new Response(JSON.stringify(body2), { status, headers: { "content-type": "application/json", "cache-control": "no-store", ...headers } });
|
|
21
|
+
async function body(req) {
|
|
22
|
+
try {
|
|
23
|
+
const b = await req.json();
|
|
24
|
+
return b && typeof b === "object" ? b : null;
|
|
25
|
+
} catch {
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
function createBwalletXAuth(o) {
|
|
30
|
+
if (!o.store) throw new Error("createBwalletXAuth needs a nonce store (redisStore, pgStore; memoryStore for dev)");
|
|
31
|
+
const cookieName = o.cookieName ?? "bwx_session";
|
|
32
|
+
const maxAge = o.maxAge ?? 7 * 24 * 3600;
|
|
33
|
+
const secure = o.secureCookie ?? o.origin.startsWith("https:");
|
|
34
|
+
const secret = () => {
|
|
35
|
+
const s = o.secret ?? (typeof process !== "undefined" ? process.env?.[o.secretEnv ?? "BWALLETX_SESSION_SECRET"] : void 0);
|
|
36
|
+
assertSecret(s);
|
|
37
|
+
return s;
|
|
38
|
+
};
|
|
39
|
+
const cookie = (v, age) => serializeCookie(v, { name: cookieName, maxAge: age, secure, sameSite: o.sameSite, domain: o.cookieDomain });
|
|
40
|
+
const badOrigin = (req) => !originAllowed(req.headers.get("origin"), o.origin);
|
|
41
|
+
const fromSource = async (source) => {
|
|
42
|
+
if (typeof source === "string") return readCookie(source, cookieName);
|
|
43
|
+
if (source instanceof Headers) return readCookie(source.get("cookie"), cookieName);
|
|
44
|
+
if (source && typeof source.headers?.get === "function") return readCookie(source.headers.get("cookie"), cookieName);
|
|
45
|
+
const { cookies } = await import("next/headers");
|
|
46
|
+
const jar = await cookies();
|
|
47
|
+
return jar.get(cookieName)?.value ?? null;
|
|
48
|
+
};
|
|
49
|
+
const auth = {
|
|
50
|
+
async challenge(req) {
|
|
51
|
+
secret();
|
|
52
|
+
if (badOrigin(req)) return json({ error: "origin not allowed" }, 403);
|
|
53
|
+
const b = await body(req);
|
|
54
|
+
try {
|
|
55
|
+
return json(await createChallenge({ origin: o.origin, identityKey: b?.identityKey, store: o.store }));
|
|
56
|
+
} catch (e) {
|
|
57
|
+
return json({ error: e.message }, 400);
|
|
58
|
+
}
|
|
59
|
+
},
|
|
60
|
+
async verify(req) {
|
|
61
|
+
const key = secret();
|
|
62
|
+
if (badOrigin(req)) return json({ error: "origin not allowed" }, 403);
|
|
63
|
+
const b = await body(req);
|
|
64
|
+
const identityKey = await verifySignIn({ origin: o.origin, identityKey: b?.identityKey, nonce: b?.nonce, signature: b?.signature, store: o.store });
|
|
65
|
+
if (!identityKey) return json({ error: "sign-in failed" }, 401);
|
|
66
|
+
let extra = {};
|
|
67
|
+
try {
|
|
68
|
+
const r = await o.onVerified?.(identityKey, req);
|
|
69
|
+
if (r === false) return json({ error: "not allowed" }, 403);
|
|
70
|
+
if (r) extra = r;
|
|
71
|
+
} catch (e) {
|
|
72
|
+
if (e instanceof IdentityLinkConflictError) return json({ error: e.message, code: e.code }, 409);
|
|
73
|
+
throw e;
|
|
74
|
+
}
|
|
75
|
+
const token = await signSession({ ...extra, sub: identityKey }, { secret: key, maxAge });
|
|
76
|
+
return json({ identityKey, uid: extra.uid, handle: extra.handle, paymail: extra.paymail }, 200, { "set-cookie": cookie(token, maxAge) });
|
|
77
|
+
},
|
|
78
|
+
async logout(req) {
|
|
79
|
+
if (badOrigin(req)) return json({ error: "origin not allowed" }, 403);
|
|
80
|
+
return json({ ok: true }, 200, { "set-cookie": cookie("", 0) });
|
|
81
|
+
},
|
|
82
|
+
async session(req) {
|
|
83
|
+
const s = await auth.getSession(req);
|
|
84
|
+
return s ? json({ identityKey: s.sub, uid: s.uid, handle: s.handle, paymail: s.paymail, exp: s.exp }) : json({ identityKey: null }, 200);
|
|
85
|
+
},
|
|
86
|
+
async getSession(source) {
|
|
87
|
+
const key = secret();
|
|
88
|
+
return verifySession(await fromSource(source), { secret: key });
|
|
89
|
+
},
|
|
90
|
+
async sessionCookie(claims) {
|
|
91
|
+
return cookie(await signSession(claims, { secret: secret(), maxAge }), maxAge);
|
|
92
|
+
},
|
|
93
|
+
clearCookie: () => cookie("", 0)
|
|
94
|
+
};
|
|
95
|
+
return auth;
|
|
96
|
+
}
|
|
97
|
+
export {
|
|
98
|
+
IdentityLinkConflictError,
|
|
99
|
+
createBwalletXAuth,
|
|
100
|
+
linkIdentity,
|
|
101
|
+
memoryStore,
|
|
102
|
+
pgNonceTableSql,
|
|
103
|
+
pgStore,
|
|
104
|
+
redisStore,
|
|
105
|
+
signInOrLink
|
|
106
|
+
};
|
|
107
|
+
//# sourceMappingURL=next.js.map
|
package/dist/next.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/next.ts"],"sourcesContent":["/**\n * Next.js App Router adapter. Route handlers use standard Request/Response, so they also work in\n * any Fetch-API server (Hono, Remix, Bun, Workers).\n *\n * // lib/bwalletx.ts\n * export const auth = createBwalletXAuth({ origin: process.env.APP_ORIGIN!, store: pgStore({ query }) });\n * // app/api/bwalletx/challenge/route.ts → export const POST = auth.challenge;\n * // app/api/bwalletx/verify/route.ts → export const POST = auth.verify;\n * // app/api/bwalletx/logout/route.ts → export const POST = auth.logout;\n * // app/api/bwalletx/session/route.ts → export const GET = auth.session;\n * // server component: const s = await auth.getSession();\n */\nimport { IdentityLinkConflictError } from './link.js';\nimport { createChallenge, originAllowed, verifySignIn, type NonceStore } from './server.js';\nimport { assertSecret, readCookie, serializeCookie, signSession, verifySession, type SessionPayload } from './session.js';\n\nexport type { SessionPayload } from './session.js';\n\nexport interface VerifiedExtra {\n /** Your user id (e.g. from signInOrLink). Stored in the session as `uid`. */\n uid?: string;\n handle?: string;\n paymail?: string;\n [claim: string]: unknown;\n}\n\nexport interface BwalletXAuthOptions {\n /** YOUR origin from config, e.g. \"https://example.com\". Never from the request. */\n origin: string;\n /** A shared nonce store: redisStore or pgStore. memoryStore only in development. */\n store: NonceStore;\n /** HMAC secret, 32+ chars. Default: process.env[secretEnv]. There is no fallback; requests throw without it. */\n secret?: string;\n /** Env var holding the secret. Default 'BWALLETX_SESSION_SECRET'. */\n secretEnv?: string;\n /** Cookie name. Default 'bwx_session'. */\n cookieName?: string;\n /** Session lifetime in seconds. Default 7 days. */\n maxAge?: number;\n /** Default: true when origin is https. */\n secureCookie?: boolean;\n sameSite?: 'Lax' | 'Strict' | 'None';\n cookieDomain?: string;\n /**\n * Runs after the signature is verified, before the cookie is set: link to your user, look up a\n * handle. Throw IdentityLinkConflictError to answer 409; return false to refuse (403).\n */\n onVerified?: (identityKey: string, req: Request) => Promise<VerifiedExtra | void | false> | VerifiedExtra | void | false;\n}\n\nexport interface BwalletXAuth {\n challenge(req: Request): Promise<Response>;\n verify(req: Request): Promise<Response>;\n logout(req: Request): Promise<Response>;\n session(req: Request): Promise<Response>;\n /** The session, or null. With no argument it reads cookies() from next/headers. */\n getSession(source?: Request | Headers | string | null): Promise<SessionPayload | null>;\n /** Make a cookie for an identity you verified yourself (e.g. after account linking elsewhere). */\n sessionCookie(claims: Omit<SessionPayload, 'iat' | 'exp'>): Promise<string>;\n clearCookie(): string;\n}\n\nconst json = (body: unknown, status = 200, headers: Record<string, string> = {}) =>\n new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json', 'cache-control': 'no-store', ...headers } });\n\nasync function body(req: Request): Promise<Record<string, unknown> | null> {\n try {\n const b = await req.json();\n return b && typeof b === 'object' ? (b as Record<string, unknown>) : null;\n } catch {\n return null;\n }\n}\n\nexport function createBwalletXAuth(o: BwalletXAuthOptions): BwalletXAuth {\n if (!o.store) throw new Error('createBwalletXAuth needs a nonce store (redisStore, pgStore; memoryStore for dev)');\n const cookieName = o.cookieName ?? 'bwx_session';\n const maxAge = o.maxAge ?? 7 * 24 * 3600;\n const secure = o.secureCookie ?? o.origin.startsWith('https:');\n const secret = () => {\n const s = o.secret ?? (typeof process !== 'undefined' ? process.env?.[o.secretEnv ?? 'BWALLETX_SESSION_SECRET'] : undefined);\n assertSecret(s);\n return s;\n };\n const cookie = (v: string, age: number) => serializeCookie(v, { name: cookieName, maxAge: age, secure, sameSite: o.sameSite, domain: o.cookieDomain });\n const badOrigin = (req: Request) => !originAllowed(req.headers.get('origin'), o.origin);\n\n const fromSource = async (source?: Request | Headers | string | null): Promise<string | null> => {\n if (typeof source === 'string') return readCookie(source, cookieName);\n if (source instanceof Headers) return readCookie(source.get('cookie'), cookieName);\n if (source && typeof (source as Request).headers?.get === 'function') return readCookie((source as Request).headers.get('cookie'), cookieName);\n // Server components / route handlers: Next's cookies(). Imported lazily so the package does not require Next.\n const { cookies } = (await import('next/headers')) as { cookies: () => unknown };\n const jar = (await cookies()) as { get(n: string): { value: string } | undefined };\n return jar.get(cookieName)?.value ?? null;\n };\n\n const auth: BwalletXAuth = {\n async challenge(req) {\n secret();\n if (badOrigin(req)) return json({ error: 'origin not allowed' }, 403);\n const b = await body(req);\n try {\n return json(await createChallenge({ origin: o.origin, identityKey: b?.identityKey, store: o.store }));\n } catch (e) {\n return json({ error: (e as Error).message }, 400);\n }\n },\n async verify(req) {\n const key = secret();\n if (badOrigin(req)) return json({ error: 'origin not allowed' }, 403);\n const b = await body(req);\n const identityKey = await verifySignIn({ origin: o.origin, identityKey: b?.identityKey, nonce: b?.nonce, signature: b?.signature, store: o.store });\n if (!identityKey) return json({ error: 'sign-in failed' }, 401);\n let extra: VerifiedExtra = {};\n try {\n const r = await o.onVerified?.(identityKey, req);\n if (r === false) return json({ error: 'not allowed' }, 403);\n if (r) extra = r;\n } catch (e) {\n if (e instanceof IdentityLinkConflictError) return json({ error: e.message, code: e.code }, 409);\n throw e;\n }\n const token = await signSession({ ...extra, sub: identityKey }, { secret: key, maxAge });\n return json({ identityKey, uid: extra.uid, handle: extra.handle, paymail: extra.paymail }, 200, { 'set-cookie': cookie(token, maxAge) });\n },\n async logout(req) {\n if (badOrigin(req)) return json({ error: 'origin not allowed' }, 403);\n return json({ ok: true }, 200, { 'set-cookie': cookie('', 0) });\n },\n async session(req) {\n const s = await auth.getSession(req);\n return s ? json({ identityKey: s.sub, uid: s.uid, handle: s.handle, paymail: s.paymail, exp: s.exp }) : json({ identityKey: null }, 200);\n },\n async getSession(source) {\n const key = secret();\n return verifySession(await fromSource(source), { secret: key });\n },\n async sessionCookie(claims) {\n return cookie(await signSession(claims, { secret: secret(), maxAge }), maxAge);\n },\n clearCookie: () => cookie('', 0),\n };\n return auth;\n}\n\nexport { IdentityLinkConflictError, linkIdentity, signInOrLink } from './link.js';\nexport { memoryStore, redisStore, pgStore, pgN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