@assistant-ui/better-auth-dbsc 0.0.0-stage → 0.1.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/dist/index.js ADDED
@@ -0,0 +1,970 @@
1
+ import { BASE_ERROR_CODES, BetterAuthError } from "better-auth";
2
+ import { APIError, createAuthEndpoint, createAuthMiddleware } from "better-auth/api";
3
+ import { mergeSchema } from "better-auth/db";
4
+ import { C as formatCookieAttributes, S as DBSC_TERMINATE, _ as formatChallengeHeader, a as readDbscChallenge, b as parseSfString, c as DBSC_ALGORITHMS, d as readUnverifiedChallenge, f as verifyRefreshProof, g as DBSC_HEADERS, h as isDbscError, i as readBoundToken, l as parseProofHeader, m as DbscError, n as createDbscChallenge, o as readFreshProofNonce, p as verifyRegistrationProof, r as createFreshProofToken, s as readFreshProofToken, t as createBoundToken, u as parseStoredPublicKey, v as formatRegistrationHeader, x as readDbscHeader, y as getDbscHeaderNames } from "./core-B8q_n4sn.js";
5
+ import { n as DBSC_ERROR_CODES, t as version } from "./package-ggl7V4ED.js";
6
+ // src/store.ts
7
+ const DBSC_MODEL = "dbscSession";
8
+ const dbscSchema = { [DBSC_MODEL]: { fields: {
9
+ sessionId: {
10
+ type: "string",
11
+ required: true,
12
+ unique: true,
13
+ input: false,
14
+ references: {
15
+ model: "session",
16
+ field: "id",
17
+ onDelete: "cascade"
18
+ }
19
+ },
20
+ userId: {
21
+ type: "string",
22
+ required: true,
23
+ input: false,
24
+ index: true,
25
+ references: {
26
+ model: "user",
27
+ field: "id",
28
+ onDelete: "cascade"
29
+ }
30
+ },
31
+ /** The device's public JWK, JSON-encoded, with `alg`. */
32
+ publicKey: {
33
+ type: "string",
34
+ required: true,
35
+ input: false
36
+ },
37
+ thumbprint: {
38
+ type: "string",
39
+ required: true,
40
+ input: false
41
+ },
42
+ /** Issue time of the newest refresh challenge spent. Older ones are refused. */
43
+ lastRefreshAt: {
44
+ type: "date",
45
+ required: true,
46
+ input: false
47
+ },
48
+ /** Issue time of the newest fresh-proof challenge spent. */
49
+ lastFreshProofAt: {
50
+ type: "date",
51
+ required: true,
52
+ input: false
53
+ },
54
+ /** How many proofs this binding has spent. */
55
+ proofCount: {
56
+ type: "number",
57
+ required: true,
58
+ defaultValue: 0,
59
+ input: false
60
+ },
61
+ createdAt: {
62
+ type: "date",
63
+ required: true,
64
+ input: false
65
+ }
66
+ } } };
67
+ /**
68
+ * The default store: one `dbscSession` row per bound session, deleted with its session.
69
+ * `spend` is a guarded `incrementOne`, so a proof is spent once across every instance.
70
+ */
71
+ function createAdapterDbscStore(adapter) {
72
+ return {
73
+ async find(sessionId) {
74
+ const row = await adapter.findOne({
75
+ model: DBSC_MODEL,
76
+ where: [{
77
+ field: "sessionId",
78
+ value: sessionId
79
+ }]
80
+ });
81
+ if (!row) return null;
82
+ return {
83
+ sessionId: row.sessionId,
84
+ userId: row.userId,
85
+ publicKey: JSON.parse(row.publicKey),
86
+ thumbprint: row.thumbprint
87
+ };
88
+ },
89
+ async bind(binding) {
90
+ const epoch = /* @__PURE__ */ new Date(0);
91
+ try {
92
+ await adapter.create({
93
+ model: DBSC_MODEL,
94
+ data: {
95
+ sessionId: binding.sessionId,
96
+ userId: binding.userId,
97
+ publicKey: JSON.stringify(binding.publicKey),
98
+ thumbprint: binding.thumbprint,
99
+ lastRefreshAt: epoch,
100
+ lastFreshProofAt: epoch,
101
+ proofCount: 0,
102
+ createdAt: /* @__PURE__ */ new Date()
103
+ }
104
+ });
105
+ return true;
106
+ } catch (error) {
107
+ if (await adapter.findOne({
108
+ model: "dbscSession",
109
+ where: [{
110
+ field: "sessionId",
111
+ value: binding.sessionId
112
+ }]
113
+ })) return false;
114
+ throw error;
115
+ }
116
+ },
117
+ async spend(sessionId, kind, issuedAtMs) {
118
+ const field = kind === "refresh" ? "lastRefreshAt" : "lastFreshProofAt";
119
+ const issuedAt = new Date(issuedAtMs);
120
+ return await adapter.incrementOne({
121
+ model: DBSC_MODEL,
122
+ where: [{
123
+ field: "sessionId",
124
+ value: sessionId
125
+ }, {
126
+ field,
127
+ value: issuedAt,
128
+ operator: "lt"
129
+ }],
130
+ increment: { proofCount: 1 },
131
+ set: { [field]: issuedAt }
132
+ }) !== null;
133
+ },
134
+ async delete(sessionId) {
135
+ await adapter.delete({
136
+ model: DBSC_MODEL,
137
+ where: [{
138
+ field: "sessionId",
139
+ value: sessionId
140
+ }]
141
+ });
142
+ }
143
+ };
144
+ }
145
+ /** A store in process memory, for tests and single-instance development. */
146
+ function createMemoryDbscStore() {
147
+ const bindings = /* @__PURE__ */ new Map();
148
+ const spent = /* @__PURE__ */ new Map();
149
+ return {
150
+ bindings,
151
+ async find(sessionId) {
152
+ return bindings.get(sessionId) ?? null;
153
+ },
154
+ async bind(binding) {
155
+ if (bindings.has(binding.sessionId)) return false;
156
+ bindings.set(binding.sessionId, binding);
157
+ return true;
158
+ },
159
+ async spend(sessionId, kind, issuedAtMs) {
160
+ if (!bindings.has(sessionId)) return false;
161
+ const key = `${kind}:${sessionId}`;
162
+ if ((spent.get(key) ?? -1) >= issuedAtMs) return false;
163
+ spent.set(key, issuedAtMs);
164
+ return true;
165
+ },
166
+ async delete(sessionId) {
167
+ bindings.delete(sessionId);
168
+ for (const kind of ["refresh", "fresh-proof"]) spent.delete(`${kind}:${sessionId}`);
169
+ }
170
+ };
171
+ }
172
+ // src/dbsc-plugin.ts
173
+ const DBSC_REGISTER_PATH = "/dbsc/register";
174
+ const DBSC_REFRESH_PATH = "/dbsc/refresh";
175
+ /** Cookie keys passed to Better Auth's cookie factory, so `advanced.cookies.<key>` applies. */
176
+ const DBSC_COOKIE_KEYS = {
177
+ bound: "dbsc_token",
178
+ freshProof: "dbsc_fresh_proof"
179
+ };
180
+ /** Validates options and fills defaults. Every problem is reported at once. */
181
+ function resolveDbscOptions(options = {}) {
182
+ const issues = [];
183
+ const positiveInteger = (value, key) => {
184
+ if (!Number.isInteger(value) || value <= 0) issues.push(`\`${key}\` must be a positive integer.`);
185
+ };
186
+ const paths = (values, key) => {
187
+ if (values.some((path) => typeof path !== "string" || !path.startsWith("/"))) issues.push(`\`${key}\` entries must be paths starting with \`/\`, such as \`/admin/\`.`);
188
+ };
189
+ const enabled = options.enabled ?? true;
190
+ if (typeof enabled !== "boolean" && typeof enabled !== "function") issues.push("`enabled` must be a boolean or a function that returns one.");
191
+ const algorithms = options.algorithms ?? [...DBSC_ALGORITHMS];
192
+ if (algorithms.length === 0 || algorithms.some((alg) => !DBSC_ALGORITHMS.includes(alg))) issues.push("`algorithms` must be a non-empty list of \"ES256\" and/or \"RS256\".");
193
+ const boundCookieMaxAge = options.boundCookieMaxAge ?? 300;
194
+ positiveInteger(boundCookieMaxAge, "boundCookieMaxAge");
195
+ const challengeExpiresIn = options.challengeExpiresIn ?? 300;
196
+ positiveInteger(challengeExpiresIn, "challengeExpiresIn");
197
+ if (options.scope?.origin !== void 0 && !isOrigin(options.scope.origin)) issues.push("`scope.origin` must be an origin such as `https://app.example.com`, with no path.");
198
+ const scopeExclude = options.scope?.exclude ?? [];
199
+ paths(scopeExclude, "scope.exclude");
200
+ const enforcementExclude = options.enforcement?.exclude ?? [];
201
+ paths(enforcementExclude, "enforcement.exclude");
202
+ const unboundDefault = options.freshProof?.unbound ?? "allow";
203
+ const policies = [
204
+ "allow",
205
+ "fresh-session",
206
+ "deny"
207
+ ];
208
+ const freshProofEntries = Array.isArray(options.freshProof?.paths) ? options.freshProof.paths.map((path) => [path, unboundDefault]) : Object.entries(options.freshProof?.paths ?? {}).map(([path, rule]) => [path, rule.unbound ?? unboundDefault]);
209
+ paths(freshProofEntries.map(([path]) => path), "freshProof.paths");
210
+ if (freshProofEntries.some(([, policy]) => !policies.includes(policy)) || !policies.includes(unboundDefault)) issues.push("`freshProof.unbound` must be \"allow\", \"fresh-session\", or \"deny\".");
211
+ for (const [path] of freshProofEntries) {
212
+ const excludes = enforcementExclude.filter((entry) => typeof entry === "string");
213
+ if (typeof path === "string" && isExcluded(path, excludes)) issues.push(`\`freshProof.paths\` entry \`${path}\` is excluded by \`enforcement.exclude\`, which would skip its fresh proof. Remove it from one of them.`);
214
+ }
215
+ const freshProofExpiresIn = options.freshProof?.expiresIn ?? 60;
216
+ positiveInteger(freshProofExpiresIn, "freshProof.expiresIn");
217
+ const rateLimit = {
218
+ enabled: options.rateLimit?.enabled ?? true,
219
+ window: options.rateLimit?.window ?? 60,
220
+ max: options.rateLimit?.max ?? 600
221
+ };
222
+ positiveInteger(rateLimit.window, "rateLimit.window");
223
+ positiveInteger(rateLimit.max, "rateLimit.max");
224
+ for (const key of [
225
+ "onEvent",
226
+ "shouldRegister",
227
+ "now"
228
+ ]) if (options[key] !== void 0 && typeof options[key] !== "function") issues.push(`\`${key}\` must be a function.`);
229
+ const sessionIdentifier = options.advanced?.sessionIdentifier ?? "better-auth";
230
+ if (!/^[\x20-\x7e]+$/.test(sessionIdentifier)) issues.push("`advanced.sessionIdentifier` must be non-empty printable ASCII.");
231
+ const headers = options.advanced?.headers ?? "both";
232
+ if (![
233
+ "standard",
234
+ "legacy",
235
+ "both"
236
+ ].includes(headers)) issues.push("`advanced.headers` must be \"standard\", \"legacy\", or \"both\".");
237
+ if (issues.length > 0) throw new BetterAuthError(`Invalid dbsc() options:\n - ${issues.join("\n - ")}`);
238
+ const store = options.store;
239
+ return {
240
+ enabled: typeof enabled === "function" ? enabled : () => enabled,
241
+ algorithms,
242
+ boundCookieMaxAge,
243
+ challengeExpiresIn,
244
+ scope: {
245
+ origin: options.scope?.origin,
246
+ includeSite: options.scope?.includeSite ?? false,
247
+ exclude: scopeExclude,
248
+ rules: options.scope?.rules ?? []
249
+ },
250
+ enforcement: {
251
+ enabled: options.enforcement?.enabled ?? true,
252
+ exclude: enforcementExclude
253
+ },
254
+ freshProof: {
255
+ paths: new Map(freshProofEntries),
256
+ expiresIn: freshProofExpiresIn
257
+ },
258
+ rateLimit,
259
+ onEvent: options.onEvent,
260
+ shouldRegister: options.shouldRegister,
261
+ now: options.now ?? Date.now,
262
+ store: store === void 0 ? void 0 : typeof store === "function" ? store : () => store,
263
+ advanced: {
264
+ sessionIdentifier,
265
+ allowedRefreshInitiators: options.advanced?.allowedRefreshInitiators ?? ["*"],
266
+ headers
267
+ }
268
+ };
269
+ }
270
+ /** `{ action: string }`, as a Standard Schema so the endpoint is typed without a schema library. */
271
+ const freshProofBody = { "~standard": {
272
+ version: 1,
273
+ vendor: "@assistant-ui/better-auth-dbsc",
274
+ validate(value) {
275
+ const action = value?.action;
276
+ return typeof action === "string" && action.length > 0 ? { value: { action } } : { issues: [{
277
+ message: "`body.action` must name the action, such as `delete-account`.",
278
+ path: ["action"]
279
+ }] };
280
+ },
281
+ types: void 0
282
+ } };
283
+ const sessionConfigResponse = {
284
+ description: "The DBSC session config, as the browser expects it",
285
+ content: { "application/json": { schema: {
286
+ type: "object",
287
+ properties: {
288
+ session_identifier: { type: "string" },
289
+ refresh_url: { type: "string" },
290
+ scope: { type: "object" },
291
+ allowed_refresh_initiators: {
292
+ type: "array",
293
+ items: { type: "string" }
294
+ },
295
+ credentials: {
296
+ type: "array",
297
+ items: { type: "object" }
298
+ },
299
+ continue: { type: "boolean" }
300
+ }
301
+ } } }
302
+ };
303
+ /**
304
+ * Device Bound Session Credentials for Better Auth.
305
+ *
306
+ * Browsers that support DBSC bind the session to a hardware-backed key and keep a
307
+ * short-lived cookie fresh by signing server challenges. Browsers that do not ignore the
308
+ * registration header and keep using the plain session cookie.
309
+ */
310
+ const dbsc = (options) => {
311
+ const config = resolveDbscOptions(options);
312
+ /** Telemetry never changes a response: a throwing handler is logged, not rethrown. */
313
+ async function emit(ctx, event) {
314
+ const handler = config.onEvent;
315
+ if (!handler) return;
316
+ await ctx.context.runInBackgroundOrAwait(Promise.resolve().then(() => handler(event)));
317
+ }
318
+ /**
319
+ * Requests that answered a `freshProof` path. An endpoint dispatched inside the same
320
+ * request (the OAuth provider's consent re-enters `/oauth2/authorize` this way) is not
321
+ * challenged again: the answer was spent on the outer one, so it could never pass.
322
+ */
323
+ const answeredRequests = /* @__PURE__ */ new WeakSet();
324
+ const storeFor = (context) => config.store?.(context) ?? createAdapterDbscStore(context.adapter);
325
+ /** Reads the session the request carries and whether it is proven. No writes. */
326
+ async function sessionState(ctx) {
327
+ return stateFor(ctx, await readSessionToken(ctx) ?? readBearerToken(ctx));
328
+ }
329
+ /**
330
+ * Reads one session token's session and whether the bound cookie proves it: two reads,
331
+ * the session and its binding. No writes.
332
+ */
333
+ async function stateFor(ctx, token) {
334
+ if (!token) return { kind: "none" };
335
+ const found = await ctx.context.internalAdapter.findSession(token);
336
+ if (!found || new Date(found.session.expiresAt).getTime() <= config.now()) return { kind: "none" };
337
+ const binding = await storeFor(ctx.context).find(found.session.id);
338
+ if (!binding) return {
339
+ kind: "plain",
340
+ token,
341
+ session: found.session
342
+ };
343
+ const bound = await readBoundToken({
344
+ secret: ctx.context.secret,
345
+ sessionToken: token,
346
+ token: ctx.getCookie(cookies(ctx).bound.name),
347
+ nowMs: config.now()
348
+ });
349
+ if (!bound) return {
350
+ kind: "unproven",
351
+ session: found.session
352
+ };
353
+ return {
354
+ kind: "bound",
355
+ token,
356
+ session: found.session,
357
+ binding,
358
+ answers: bound.answers
359
+ };
360
+ }
361
+ /**
362
+ * Checks every session token the request carries, not only the one the endpoint will
363
+ * read: the session cookie, `Authorization: Bearer` (the `bearer()` plugin turns it into
364
+ * the session cookie in its own before hook, which may run after this one and rebuilds
365
+ * the cookie header from the original request), `multiSession()`'s per-session cookies,
366
+ * and `admin()`'s `admin_session` cookie while impersonating. A bound session that the
367
+ * bound cookie does not prove must not reach any endpoint by any of them.
368
+ *
369
+ * - With a bearer token, dropping cookies cannot work, because `bearer()` may write the
370
+ * cookie header after this hook. So a request that carries a bound session is refused
371
+ * with 401 unless the bound cookie proves every bound session in it and the bearer
372
+ * token and the session cookie, where they name a session, name that same one.
373
+ * - Without one, every cookie naming an unproven bound session is dropped.
374
+ *
375
+ * Returns the cookies to drop and the sessions an endpoint may act as.
376
+ */
377
+ async function gate(ctx) {
378
+ const sessionCookie = ctx.context.authCookies.sessionToken.name;
379
+ const cookieToken = await readSessionToken(ctx);
380
+ const bearerToken = readBearerToken(ctx);
381
+ const carried = [];
382
+ if (cookieToken) carried.push({
383
+ via: "cookie",
384
+ token: cookieToken,
385
+ cookie: sessionCookie
386
+ });
387
+ if (bearerToken) carried.push({
388
+ via: "bearer",
389
+ token: bearerToken
390
+ });
391
+ for (const name of cookieNames(ctx.headers)) {
392
+ if (!name.includes("_multi-")) continue;
393
+ const token = await ctx.getSignedCookie(name, ctx.context.secret);
394
+ if (typeof token === "string" && token) carried.push({
395
+ via: "multi-session",
396
+ token,
397
+ cookie: name
398
+ });
399
+ }
400
+ const adminCookie = ctx.context.createAuthCookie("admin_session").name;
401
+ const adminValue = await ctx.getSignedCookie(adminCookie, ctx.context.secret);
402
+ const adminToken = typeof adminValue === "string" ? adminValue.split(":")[0] : void 0;
403
+ if (adminToken) carried.push({
404
+ via: "admin-session",
405
+ token: adminToken,
406
+ cookie: adminCookie
407
+ });
408
+ const states = /* @__PURE__ */ new Map();
409
+ const stateOf = (token) => {
410
+ if (!token) return Promise.resolve({ kind: "none" });
411
+ let state = states.get(token);
412
+ if (!state) states.set(token, state = stateFor(ctx, token));
413
+ return state;
414
+ };
415
+ const resolved = await Promise.all(carried.map(async (carrier) => ({
416
+ ...carrier,
417
+ state: await stateOf(carrier.token)
418
+ })));
419
+ const unproven = resolved.filter(({ state }) => state.kind === "unproven");
420
+ const reported = /* @__PURE__ */ new Set();
421
+ for (const { via, token, state } of unproven) {
422
+ if (reported.has(token) || state.kind !== "unproven") continue;
423
+ reported.add(token);
424
+ await emit(ctx, {
425
+ type: "credential_missing",
426
+ ...ids(state.session),
427
+ via
428
+ });
429
+ }
430
+ const cookieState = await stateOf(cookieToken);
431
+ const bearerState = await stateOf(bearerToken);
432
+ if (bearerToken) {
433
+ if (resolved.some(({ state }) => state.kind === "bound" || state.kind === "unproven")) {
434
+ const proven = (state) => state.kind === "none" || state.kind === "bound";
435
+ if (unproven.length > 0 || !proven(bearerState) || !proven(cookieState)) throw APIError.from("UNAUTHORIZED", DBSC_ERROR_CODES.DBSC_CREDENTIAL_REQUIRED);
436
+ }
437
+ }
438
+ const drop = new Set(unproven.flatMap(({ cookie }) => cookie ? [cookie] : []));
439
+ const sessions = [cookieState, bearerState].filter((state) => state.kind === "plain" || state.kind === "bound");
440
+ return {
441
+ drop,
442
+ sessions: sessions.filter((state, i) => sessions.indexOf(state) === i)
443
+ };
444
+ }
445
+ /**
446
+ * A fresh proof for `action`: answered once by a bound cookie that a refresh minted
447
+ * while the browser held this action's challenge, or a new challenge with the bound
448
+ * cookie removed so the browser refreshes before the retry. The cookie names the
449
+ * challenge it answers: comparing issue times would trust clocks that differ between
450
+ * instances, and a copied cookie from a node running ahead would look newer.
451
+ */
452
+ async function checkFreshProof(ctx, state, action) {
453
+ const { bound, freshProof } = cookies(ctx);
454
+ const challenge = await readFreshProofToken({
455
+ secret: ctx.context.secret,
456
+ sessionToken: state.token,
457
+ action,
458
+ token: ctx.getCookie(freshProof.name),
459
+ nowMs: config.now(),
460
+ ttlSeconds: config.freshProof.expiresIn
461
+ });
462
+ if (challenge && state.answers === challenge.nonce && await storeFor(ctx.context).spend(state.session.id, "fresh-proof", challenge.issuedAtMs)) {
463
+ ctx.setCookie(freshProof.name, "", {
464
+ ...freshProof.attributes,
465
+ maxAge: 0
466
+ });
467
+ await emit(ctx, {
468
+ type: "fresh_proof_answered",
469
+ ...ids(state.session),
470
+ action
471
+ });
472
+ return "answered";
473
+ }
474
+ const next = await createFreshProofToken({
475
+ secret: ctx.context.secret,
476
+ sessionToken: state.token,
477
+ action,
478
+ nowMs: config.now()
479
+ });
480
+ ctx.setCookie(bound.name, "", {
481
+ ...bound.attributes,
482
+ maxAge: 0
483
+ });
484
+ ctx.setCookie(freshProof.name, next, freshProof.attributes);
485
+ await emit(ctx, {
486
+ type: "fresh_proof_challenged",
487
+ ...ids(state.session),
488
+ action
489
+ });
490
+ return "challenge";
491
+ }
492
+ /** Applies a `freshProof` path's policy to a session that is not bound. */
493
+ async function unboundPolicy(ctx, state, action, policy) {
494
+ if (policy === "allow") return;
495
+ if (policy === "fresh-session") {
496
+ const freshAge = ctx.context.sessionConfig.freshAge;
497
+ if (freshAge === 0 || config.now() - new Date(state.session.createdAt).getTime() < freshAge * 1e3) return;
498
+ }
499
+ await emit(ctx, {
500
+ type: "unbound_refused",
501
+ ...ids(state.session),
502
+ action,
503
+ policy
504
+ });
505
+ throw APIError.from("FORBIDDEN", policy === "deny" ? DBSC_ERROR_CODES.DBSC_BINDING_REQUIRED : BASE_ERROR_CODES.SESSION_NOT_FRESH);
506
+ }
507
+ function cookies(ctx) {
508
+ return {
509
+ bound: ctx.context.createAuthCookie(DBSC_COOKIE_KEYS.bound, { maxAge: config.boundCookieMaxAge }),
510
+ freshProof: ctx.context.createAuthCookie(DBSC_COOKIE_KEYS.freshProof, { maxAge: config.freshProof.expiresIn })
511
+ };
512
+ }
513
+ async function setBoundCookie(ctx, sessionToken, { expiresAtMs, answers = null }) {
514
+ const { bound } = cookies(ctx);
515
+ const value = await createBoundToken({
516
+ secret: ctx.context.secret,
517
+ sessionToken,
518
+ expiresAtMs,
519
+ answers
520
+ });
521
+ const maxAge = Math.max(0, Math.ceil((expiresAtMs - config.now()) / 1e3));
522
+ ctx.setCookie(bound.name, value, {
523
+ ...bound.attributes,
524
+ maxAge
525
+ });
526
+ }
527
+ async function setRefreshChallenge(ctx, sessionToken) {
528
+ const challenge = await createDbscChallenge({
529
+ secret: ctx.context.secret,
530
+ purpose: "refresh",
531
+ sessionToken,
532
+ nowMs: config.now()
533
+ });
534
+ const value = formatChallengeHeader({
535
+ challenge,
536
+ sessionId: config.advanced.sessionIdentifier
537
+ });
538
+ for (const name of getDbscHeaderNames("challenge", config.advanced.headers)) ctx.setHeader(name, value);
539
+ }
540
+ function sessionConfig(ctx) {
541
+ const { bound } = cookies(ctx);
542
+ const base = basePath(ctx);
543
+ const exclude = [`${base}/dbsc/`, ...config.scope.exclude].map((path) => ({
544
+ type: "exclude",
545
+ path
546
+ }));
547
+ return {
548
+ session_identifier: config.advanced.sessionIdentifier,
549
+ refresh_url: `${base}${DBSC_REFRESH_PATH}`,
550
+ scope: {
551
+ origin: appOrigin(ctx),
552
+ include_site: config.scope.includeSite,
553
+ scope_specification: [...exclude, ...config.scope.rules]
554
+ },
555
+ ...config.advanced.allowedRefreshInitiators.length > 0 ? { allowed_refresh_initiators: config.advanced.allowedRefreshInitiators } : {},
556
+ credentials: [{
557
+ type: "cookie",
558
+ name: bound.name,
559
+ attributes: formatCookieAttributes({
560
+ ...bound.attributes,
561
+ sameSite: typeof bound.attributes.sameSite === "string" ? bound.attributes.sameSite : void 0
562
+ })
563
+ }]
564
+ };
565
+ }
566
+ async function terminate(ctx, reason) {
567
+ const { bound } = cookies(ctx);
568
+ ctx.setCookie(bound.name, "", {
569
+ ...bound.attributes,
570
+ maxAge: 0
571
+ });
572
+ await emit(ctx, {
573
+ type: "terminated",
574
+ reason
575
+ });
576
+ return ctx.json(DBSC_TERMINATE);
577
+ }
578
+ function appOrigin(ctx) {
579
+ return config.scope.origin ?? new URL(ctx.context.baseURL).origin;
580
+ }
581
+ const enforced = (path) => config.enforcement.enabled && path !== "/dbsc/register" && path !== "/dbsc/refresh" && !isExcluded(path, config.enforcement.exclude);
582
+ return {
583
+ id: "dbsc",
584
+ version,
585
+ schema: mergeSchema(dbscSchema, options?.schema),
586
+ init(ctx) {
587
+ if (!config.store && ctx.options.secondaryStorage && !ctx.options.session?.storeSessionInDatabase) throw new BetterAuthError("dbsc() keeps bindings in a `dbscSession` table that references `session`, but sessions live only in `secondaryStorage`. Set `session.storeSessionInDatabase: true`, or pass your own `store` to dbsc().");
588
+ const skip = ctx.skipOriginCheck;
589
+ const paths = [DBSC_REGISTER_PATH, DBSC_REFRESH_PATH];
590
+ return {
591
+ options: { databaseHooks: { session: { delete: { async after(session) {
592
+ await storeFor(ctx).delete(session.id);
593
+ } } } } },
594
+ ...skip === true ? {} : { context: { skipOriginCheck: Array.isArray(skip) ? [...skip, ...paths] : paths } }
595
+ };
596
+ },
597
+ endpoints: {
598
+ /**
599
+ * ### Endpoint
600
+ *
601
+ * POST `/dbsc/register`
602
+ *
603
+ * ### API Methods
604
+ *
605
+ * **server:**
606
+ * `auth.api.registerDbscSession`
607
+ *
608
+ * The browser calls this itself: it posts a proof signed by its new key over the
609
+ * challenge from the sign-in response. Your code never needs to.
610
+ */
611
+ registerDbscSession: createAuthEndpoint(DBSC_REGISTER_PATH, {
612
+ method: "POST",
613
+ disableBody: true,
614
+ requireHeaders: true,
615
+ metadata: { openapi: {
616
+ summary: "Register a device-bound session",
617
+ description: "Called by the browser after sign-in. Takes a proof in `Secure-Session-Response`, binds the session to the device key, sets the bound cookie, and returns the DBSC session config.",
618
+ responses: { 200: sessionConfigResponse }
619
+ } }
620
+ }, async (ctx) => {
621
+ if (!await config.enabled()) throw APIError.from("BAD_REQUEST", DBSC_ERROR_CODES.DBSC_DISABLED);
622
+ const proof = parseProofHeader(readDbscHeader(ctx.headers, "response"));
623
+ if (!proof) throw APIError.from("BAD_REQUEST", DBSC_ERROR_CODES.DBSC_PROOF_REQUIRED);
624
+ const token = await readSessionToken(ctx);
625
+ const found = token ? await ctx.context.internalAdapter.findSession(token) : null;
626
+ if (!token || !found || new Date(found.session.expiresAt).getTime() <= config.now()) throw APIError.from("UNAUTHORIZED", DBSC_ERROR_CODES.DBSC_SESSION_REQUIRED);
627
+ const jti = readUnverifiedChallenge(proof);
628
+ const challenge = await readDbscChallenge({
629
+ secret: ctx.context.secret,
630
+ purpose: "register",
631
+ sessionToken: token,
632
+ challenge: jti,
633
+ nowMs: config.now(),
634
+ ttlSeconds: config.challengeExpiresIn
635
+ });
636
+ const refused = async (reason, error, cause) => {
637
+ await emit(ctx, {
638
+ type: "registration_refused",
639
+ ...ids(found.session),
640
+ reason
641
+ });
642
+ const refusal = APIError.from("BAD_REQUEST", error);
643
+ if (cause !== void 0) refusal.cause = cause;
644
+ return refusal;
645
+ };
646
+ if (!jti || !challenge) throw await refused("invalid_challenge", DBSC_ERROR_CODES.DBSC_INVALID_CHALLENGE);
647
+ let verified;
648
+ try {
649
+ verified = await verifyRegistrationProof(proof, {
650
+ challenge: jti,
651
+ algorithms: config.algorithms,
652
+ expectedOrigin: appOrigin(ctx)
653
+ });
654
+ } catch (error) {
655
+ throw await refused("invalid_proof", DBSC_ERROR_CODES.DBSC_INVALID_PROOF, error);
656
+ }
657
+ const store = storeFor(ctx.context);
658
+ const { session } = found;
659
+ const existing = await store.find(session.id);
660
+ if (!(existing ? existing.thumbprint === verified.thumbprint : await store.bind({
661
+ sessionId: session.id,
662
+ userId: session.userId,
663
+ publicKey: verified.publicKey,
664
+ thumbprint: verified.thumbprint
665
+ }) || (await store.find(session.id))?.thumbprint === verified.thumbprint)) throw await refused("bound_to_other_key", DBSC_ERROR_CODES.DBSC_BOUND_TO_OTHER_KEY);
666
+ if (!existing) await emit(ctx, {
667
+ type: "registered",
668
+ ...ids(session)
669
+ });
670
+ await setBoundCookie(ctx, token, { expiresAtMs: challenge.issuedAtMs + config.boundCookieMaxAge * 1e3 });
671
+ await setRefreshChallenge(ctx, token);
672
+ return ctx.json(sessionConfig(ctx));
673
+ }),
674
+ /**
675
+ * ### Endpoint
676
+ *
677
+ * POST `/dbsc/refresh`
678
+ *
679
+ * ### API Methods
680
+ *
681
+ * **server:**
682
+ * `auth.api.refreshDbscSession`
683
+ *
684
+ * The browser calls this itself when the bound cookie lapses. No proof, or a stale
685
+ * one: 403 with a new challenge. The bound key's proof: a new cookie. A session that
686
+ * is over or not bound ends the browser's DBSC session.
687
+ */
688
+ refreshDbscSession: createAuthEndpoint(DBSC_REFRESH_PATH, {
689
+ method: "POST",
690
+ disableBody: true,
691
+ requireHeaders: true,
692
+ metadata: { openapi: {
693
+ summary: "Refresh a device-bound session",
694
+ description: "Called by the browser when the bound cookie lapses. Answers 403 with a `Secure-Session-Challenge` until the request carries a proof signed by the bound key, then sets a new bound cookie.",
695
+ responses: {
696
+ 200: sessionConfigResponse,
697
+ 403: { description: "Sign the challenge in `Secure-Session-Challenge` and retry." }
698
+ }
699
+ } }
700
+ }, async (ctx) => {
701
+ const claimedId = readDbscHeader(ctx.headers, "sessionId");
702
+ if (claimedId === null) throw APIError.from("BAD_REQUEST", DBSC_ERROR_CODES.DBSC_SESSION_ID_REQUIRED);
703
+ if (!await config.enabled()) return terminate(ctx, "disabled");
704
+ if (parseSfString(claimedId) !== config.advanced.sessionIdentifier) return terminate(ctx, "other_identifier");
705
+ const token = await readSessionToken(ctx);
706
+ const found = token ? await ctx.context.internalAdapter.findSession(token) : null;
707
+ if (!token || !found || new Date(found.session.expiresAt).getTime() <= config.now()) return terminate(ctx, "no_session");
708
+ const store = storeFor(ctx.context);
709
+ const binding = await store.find(found.session.id);
710
+ if (!binding) return terminate(ctx, "not_bound");
711
+ const askAgain = async (reason) => {
712
+ await emit(ctx, {
713
+ type: "refresh_challenged",
714
+ ...ids(found.session),
715
+ reason
716
+ });
717
+ await setRefreshChallenge(ctx, token);
718
+ throw APIError.from("FORBIDDEN", DBSC_ERROR_CODES.DBSC_CHALLENGE_REQUIRED);
719
+ };
720
+ const proof = parseProofHeader(readDbscHeader(ctx.headers, "response"));
721
+ if (!proof) return askAgain("missing_proof");
722
+ const jti = readUnverifiedChallenge(proof);
723
+ const challenge = await readDbscChallenge({
724
+ secret: ctx.context.secret,
725
+ purpose: "refresh",
726
+ sessionToken: token,
727
+ challenge: jti,
728
+ nowMs: config.now(),
729
+ ttlSeconds: config.challengeExpiresIn
730
+ });
731
+ if (!jti || !challenge) return askAgain("stale_challenge");
732
+ try {
733
+ await verifyRefreshProof(proof, {
734
+ publicKey: binding.publicKey,
735
+ challenge: jti,
736
+ expectedOrigin: appOrigin(ctx)
737
+ });
738
+ } catch (error) {
739
+ const reason = error instanceof Error && "code" in error ? String(error.code) : "INVALID_PROOF";
740
+ await emit(ctx, {
741
+ type: "proof_rejected",
742
+ ...ids(found.session),
743
+ reason
744
+ });
745
+ await setRefreshChallenge(ctx, token);
746
+ throw APIError.from("FORBIDDEN", DBSC_ERROR_CODES.DBSC_CHALLENGE_REQUIRED);
747
+ }
748
+ if (!await store.spend(found.session.id, "refresh", challenge.issuedAtMs)) return askAgain("replayed");
749
+ await emit(ctx, {
750
+ type: "refreshed",
751
+ ...ids(found.session)
752
+ });
753
+ await setBoundCookie(ctx, token, {
754
+ expiresAtMs: config.now() + config.boundCookieMaxAge * 1e3,
755
+ answers: readFreshProofNonce(ctx.getCookie(cookies(ctx).freshProof.name))
756
+ });
757
+ await setRefreshChallenge(ctx, token);
758
+ return ctx.json(sessionConfig(ctx));
759
+ }),
760
+ /**
761
+ * ### Endpoint
762
+ *
763
+ * GET `/dbsc/get-status`
764
+ *
765
+ * ### API Methods
766
+ *
767
+ * **server:**
768
+ * `auth.api.getDbscStatus`
769
+ *
770
+ * **client:**
771
+ * `authClient.dbsc.getStatus`
772
+ *
773
+ * Whether the current session is bound to this device:
774
+ * `{ state: "bound" | "unbound" | "no-session" | "off" }`. For a "this device is
775
+ * protected" line in account settings.
776
+ */
777
+ getDbscStatus: createAuthEndpoint("/dbsc/get-status", {
778
+ method: "GET",
779
+ requireHeaders: true,
780
+ metadata: { openapi: {
781
+ summary: "Get the device binding of the current session",
782
+ description: "Answers whether the current session is bound to this device, proven by a live bound cookie.",
783
+ responses: { 200: {
784
+ description: "Successful response",
785
+ content: { "application/json": { schema: {
786
+ type: "object",
787
+ properties: { state: {
788
+ type: "string",
789
+ enum: [
790
+ "bound",
791
+ "unbound",
792
+ "no-session",
793
+ "off"
794
+ ]
795
+ } },
796
+ required: ["state"]
797
+ } } }
798
+ } }
799
+ } }
800
+ }, async (ctx) => {
801
+ const answer = (state) => ctx.json({ state });
802
+ if (!await config.enabled()) return answer("off");
803
+ const session = await sessionState(ctx);
804
+ if (session.kind === "bound") return answer("bound");
805
+ if (session.kind === "plain") return answer("unbound");
806
+ return answer("no-session");
807
+ }),
808
+ /**
809
+ * ### Endpoint
810
+ *
811
+ * Server only. No HTTP route.
812
+ *
813
+ * ### API Methods
814
+ *
815
+ * **server:**
816
+ * `auth.api.requireFreshProof`
817
+ *
818
+ * A fresh proof for one of your own routes or server actions:
819
+ * `await auth.api.requireFreshProof({ headers, body: { action: "delete-account" } })`.
820
+ *
821
+ * - `answered`: a bound session proved itself after this action's challenge. Go on.
822
+ * - `challenge`: refuse the request and forward the `Set-Cookie` headers (call with
823
+ * `returnHeaders: true`, or use the `nextCookies()` plugin). The client retries once.
824
+ * - `unbound`: a plain session; apply whatever fresh-proof you use without DBSC.
825
+ * - `no-session` and `off`: nothing was checked.
826
+ */
827
+ requireFreshProof: createAuthEndpoint("/dbsc/require-fresh-proof", {
828
+ method: "POST",
829
+ body: freshProofBody,
830
+ requireHeaders: true,
831
+ metadata: { SERVER_ONLY: true }
832
+ }, async (ctx) => {
833
+ const answer = (state) => ctx.json({ state });
834
+ if (!await config.enabled()) return answer("off");
835
+ const session = await sessionState(ctx);
836
+ if (session.kind === "none" || session.kind === "unproven") return answer("no-session");
837
+ if (session.kind === "plain") return answer("unbound");
838
+ return answer(await checkFreshProof(ctx, session, `app:${ctx.body.action}`));
839
+ })
840
+ },
841
+ hooks: {
842
+ before: [{
843
+ matcher: (ctx) => enforced(ctx.path),
844
+ handler: createAuthMiddleware(async (ctx) => {
845
+ if (!await config.enabled()) return;
846
+ const { drop, sessions } = await gate(ctx);
847
+ const result = drop.size > 0 ? { context: { headers: withoutCookies(ctx.headers, drop) } } : void 0;
848
+ const policy = ctx.path ? config.freshProof.paths.get(ctx.path) : void 0;
849
+ if (!policy) return result;
850
+ for (const state of sessions) if (state.kind === "plain") await unboundPolicy(ctx, state, ctx.path, policy);
851
+ const state = sessions.find((state) => state.kind === "bound");
852
+ if (state?.kind === "bound") {
853
+ if (ctx.request && answeredRequests.has(ctx.request)) return result;
854
+ if (await checkFreshProof(ctx, state, ctx.path) === "answered") {
855
+ if (ctx.request) answeredRequests.add(ctx.request);
856
+ return result;
857
+ }
858
+ if (ctx.request && ctx.headers?.get("sec-fetch-mode") === "navigate") {
859
+ const url = new URL(ctx.request.url);
860
+ ctx.responseHeaders?.set("location", `${url.pathname}${url.search}`);
861
+ throw new APIError("TEMPORARY_REDIRECT", void 0, ctx.responseHeaders);
862
+ }
863
+ const { code, message } = DBSC_ERROR_CODES.DBSC_FRESH_PROOF_REQUIRED;
864
+ throw new APIError("FORBIDDEN", {
865
+ code,
866
+ message
867
+ }, ctx.responseHeaders);
868
+ }
869
+ return result;
870
+ })
871
+ }],
872
+ after: [{
873
+ matcher: () => true,
874
+ handler: createAuthMiddleware(async (ctx) => {
875
+ if (ctx.path === "/sign-out") {
876
+ const { bound, freshProof } = cookies(ctx);
877
+ ctx.setCookie(bound.name, "", {
878
+ ...bound.attributes,
879
+ maxAge: 0
880
+ });
881
+ ctx.setCookie(freshProof.name, "", {
882
+ ...freshProof.attributes,
883
+ maxAge: 0
884
+ });
885
+ return;
886
+ }
887
+ const issued = ctx.context.newSession;
888
+ if (!issued) return;
889
+ if (await readSessionToken(ctx) === issued.session.token) return;
890
+ if (!await config.enabled()) return;
891
+ if (config.shouldRegister && !await config.shouldRegister(ctx)) return;
892
+ const challenge = await createDbscChallenge({
893
+ secret: ctx.context.secret,
894
+ purpose: "register",
895
+ sessionToken: issued.session.token,
896
+ nowMs: config.now()
897
+ });
898
+ const value = formatRegistrationHeader({
899
+ algorithms: config.algorithms,
900
+ challenge,
901
+ path: `${basePath(ctx)}${DBSC_REGISTER_PATH}`
902
+ });
903
+ for (const name of getDbscHeaderNames("registration", config.advanced.headers)) ctx.setHeader(name, value);
904
+ })
905
+ }]
906
+ },
907
+ rateLimit: !config.rateLimit.enabled ? void 0 : [{
908
+ pathMatcher: (path) => path === "/dbsc/register" || path === "/dbsc/refresh",
909
+ window: config.rateLimit.window,
910
+ max: config.rateLimit.max
911
+ }],
912
+ $ERROR_CODES: DBSC_ERROR_CODES,
913
+ options
914
+ };
915
+ };
916
+ function ids(session) {
917
+ return {
918
+ sessionId: session.id,
919
+ userId: session.userId
920
+ };
921
+ }
922
+ async function readSessionToken(ctx) {
923
+ const token = await ctx.getSignedCookie(ctx.context.authCookies.sessionToken.name, ctx.context.secret);
924
+ return typeof token === "string" && token ? token : null;
925
+ }
926
+ /**
927
+ * The session token in `Authorization: Bearer`, read the way the `bearer()` plugin reads
928
+ * it, which turns it into the session cookie in its own hook. Not verified: here it can
929
+ * only cause a refusal, so a bad signature counts the same as a good one.
930
+ */
931
+ function readBearerToken(ctx) {
932
+ const value = ctx.request?.headers.get("authorization") || ctx.headers?.get("authorization");
933
+ if (!value || value.slice(0, 7).toLowerCase() !== "bearer ") return null;
934
+ const token = value.slice(7).trim();
935
+ if (!token) return null;
936
+ return (token.includes(".") && token.includes("%") ? tryDecode(token) : token).split(".")[0] || null;
937
+ }
938
+ function tryDecode(value) {
939
+ try {
940
+ return decodeURIComponent(value);
941
+ } catch {
942
+ return value;
943
+ }
944
+ }
945
+ /** The names in the `Cookie` header. */
946
+ function cookieNames(headers) {
947
+ return (headers?.get("cookie") ?? "").split(";").map((pair) => pair.slice(0, Math.max(0, pair.indexOf("="))).trim()).filter(Boolean);
948
+ }
949
+ /** A copy of `headers` with every pair named in `names` removed from `Cookie`. */
950
+ function withoutCookies(headers, names) {
951
+ const copy = new Headers(headers);
952
+ const kept = (copy.get("cookie") ?? "").split(";").map((pair) => pair.trim()).filter((pair) => pair && !names.has(pair.slice(0, Math.max(0, pair.indexOf("="))).trim()));
953
+ copy.set("cookie", kept.join("; "));
954
+ return copy;
955
+ }
956
+ function basePath(ctx) {
957
+ return new URL(ctx.context.baseURL).pathname.replace(/\/+$/, "");
958
+ }
959
+ function isExcluded(path, exclude) {
960
+ if (!path) return false;
961
+ return exclude.some((entry) => entry.endsWith("/") ? path.startsWith(entry) : path === entry);
962
+ }
963
+ function isOrigin(value) {
964
+ try {
965
+ return new URL(value).origin === value;
966
+ } catch {
967
+ return false;
968
+ }
969
+ }
970
+ export { DBSC_ALGORITHMS, DBSC_COOKIE_KEYS, DBSC_ERROR_CODES, DBSC_HEADERS, DBSC_MODEL, DBSC_REFRESH_PATH, DBSC_REGISTER_PATH, DBSC_TERMINATE, DbscError, createAdapterDbscStore, createBoundToken, createDbscChallenge, createFreshProofToken, createMemoryDbscStore, dbsc, dbscSchema, formatChallengeHeader, formatCookieAttributes, formatRegistrationHeader, getDbscHeaderNames, isDbscError, parseProofHeader, parseSfString, parseStoredPublicKey, readBoundToken, readDbscChallenge, readDbscHeader, readFreshProofNonce, readFreshProofToken, readUnverifiedChallenge, resolveDbscOptions, verifyRefreshProof, verifyRegistrationProof };