@assistant-ui/better-auth-dbsc 0.1.0 → 0.1.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/README.md CHANGED
@@ -72,6 +72,8 @@ The check reads every session token in the request, not only the session cookie,
72
72
  - **`multiSession()`** keeps a `<session cookie>_multi-<token>` cookie per signed-in account. A copied one is dropped like the session cookie, so it can't list, switch to, or revoke the owner's session. In a DBSC browser only one session at a time has a live bound cookie, so switching back to another bound account there means signing in to it again, and sign-out revokes only the sessions the request proves. The others expire as usual.
73
73
  - **`admin()`** keeps the admin's own session token in an `admin_session` cookie while they impersonate someone, and `/admin/stop-impersonating` swaps it back in. A copied one naming a bound session without its live bound cookie is dropped too, so it can't hand the admin's session or profile to whoever holds a copy of the impersonation session.
74
74
 
75
+ With enforcement enabled, a server-side session lookup that finds no live session takes precedence over Better Auth's session cookie cache. DBSC status and fresh-proof helpers accept bearer authentication through Better Auth's installed bearer plugin and honor its signature policy.
76
+
75
77
  Helpers that read cookies without calling Better Auth are outside this check. `getCookieCache()` decodes the `session.cookieCache` cookie on its own, so in middleware it answers a copied pair of cookies with the owner's session; `getSessionCookie()` only says a cookie is there. Treat both as hints for redirects, and authorize with `auth.api.getSession({ headers })`. The same goes for a third-party plugin that carries a session token somewhere this list doesn't name.
76
78
 
77
79
  ## Schema
@@ -236,7 +238,7 @@ dbsc({
236
238
 
237
239
  | `type` | When |
238
240
  |---|---|
239
- | `registered` | A session was bound. |
241
+ | `registered` | The request created a session binding. Concurrent retries with the same key share that binding and emit one event. |
240
242
  | `registration_refused` | With a `reason`: `invalid_challenge`, `invalid_proof`, `bound_to_other_key`, or `disabled`. |
241
243
  | `refreshed` | A bound cookie was renewed. |
242
244
  | `refresh_challenged` | With a `reason`: `missing_proof` (normal), `stale_challenge`, or `replayed`. |
package/dist/client.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { h as DBSC_ERROR_CODES, p as dbsc } from "./dbsc-plugin-CfQHYOZN.js";
1
+ import { h as DBSC_ERROR_CODES, p as dbsc } from "./dbsc-plugin-D9MKOgZP.js";
2
2
  /**
3
3
  * Client half of {@link dbsc}. The browser drives DBSC by itself; this adds
4
4
  * `authClient.dbsc.getStatus()` and the plugin's error codes to the client.
package/dist/client.js CHANGED
@@ -1,4 +1,4 @@
1
- import { n as DBSC_ERROR_CODES, t as version } from "./package-ggl7V4ED.js";
1
+ import { n as DBSC_ERROR_CODES, t as version } from "./package-DTjet4zW.js";
2
2
  // src/client.ts
3
3
  /**
4
4
  * Client half of {@link dbsc}. The browser drives DBSC by itself; this adds
@@ -134,7 +134,10 @@ async function verifyRegistrationProof(jwt, input) {
134
134
  }
135
135
  /** Verifies a refresh proof against the key bound at registration. */
136
136
  async function verifyRefreshProof(jwt, input) {
137
- readAlgorithm(readHeader(jwt).alg, [input.publicKey.alg]);
137
+ const header = readHeader(jwt);
138
+ const algorithm = readAlgorithm(input.publicKey?.alg, DBSC_ALGORITHMS);
139
+ readAlgorithm(header.alg, [algorithm]);
140
+ toPublicKey(input.publicKey, algorithm);
138
141
  const claims = await verifySignature(jwt, input.publicKey);
139
142
  checkClaims(claims, input);
140
143
  return { claims };
@@ -236,6 +239,7 @@ function checkClaims(claims, input) {
236
239
  if (typeof claims.jti !== "string" || !timingSafeEqual(claims.jti, input.challenge)) throw new DbscError("CHALLENGE_MISMATCH", "The DBSC proof's `jti` does not match the current challenge.");
237
240
  if (input.expectedOrigin === void 0 || claims.aud === void 0) return;
238
241
  const audiences = Array.isArray(claims.aud) ? claims.aud : [claims.aud];
242
+ if (audiences.length === 0) throw new DbscError("AUDIENCE_MISMATCH", "A present DBSC `aud` must name an audience.");
239
243
  for (const audience of audiences) if (typeof audience !== "string" || originOf(audience) !== input.expectedOrigin) throw new DbscError("AUDIENCE_MISMATCH", `The DBSC proof's \`aud\` ${JSON.stringify(audience)} is not on ${input.expectedOrigin}.`);
240
244
  }
241
245
  function originOf(url) {
@@ -253,7 +257,10 @@ function timingSafeEqual(a, b) {
253
257
  }
254
258
  function modulusBits(n) {
255
259
  try {
256
- return base64UrlDecode$1(n).length * 8;
260
+ const bytes = base64UrlDecode$1(n);
261
+ const first = bytes[0];
262
+ if (!first) return 0;
263
+ return (bytes.length - 1) * 8 + 32 - Math.clz32(first);
257
264
  } catch {
258
265
  return 0;
259
266
  }
package/dist/core.js CHANGED
@@ -1 +1 @@
1
- export { c as DBSC_ALGORITHMS, g as DBSC_HEADERS, S as DBSC_TERMINATE, m as DbscError, t as createBoundToken, n as createDbscChallenge, r as createFreshProofToken, _ as formatChallengeHeader, C as formatCookieAttributes, v as formatRegistrationHeader, y as getDbscHeaderNames, h as isDbscError, l as parseProofHeader, b as parseSfString, u as parseStoredPublicKey, i as readBoundToken, a as readDbscChallenge, x as readDbscHeader, o as readFreshProofNonce, s as readFreshProofToken, d as readUnverifiedChallenge, f as verifyRefreshProof, p as verifyRegistrationProof } from "./core-B8q_n4sn.js";
1
+ export { c as DBSC_ALGORITHMS, g as DBSC_HEADERS, S as DBSC_TERMINATE, m as DbscError, t as createBoundToken, n as createDbscChallenge, r as createFreshProofToken, _ as formatChallengeHeader, C as formatCookieAttributes, v as formatRegistrationHeader, y as getDbscHeaderNames, h as isDbscError, l as parseProofHeader, b as parseSfString, u as parseStoredPublicKey, i as readBoundToken, a as readDbscChallenge, x as readDbscHeader, o as readFreshProofNonce, s as readFreshProofToken, d as readUnverifiedChallenge, f as verifyRefreshProof, p as verifyRegistrationProof } from "./core-Crgd63SH.js";
@@ -749,7 +749,10 @@ declare const dbsc: <O extends DbscOptions>(options?: O) => {
749
749
  matcher: (ctx: import("better-auth").HookEndpointContext) => boolean;
750
750
  handler: import("better-auth").Middleware<import("better-auth").MiddlewareOptions, (inputContext: import("better-auth").MiddlewareInputContext<import("better-auth").MiddlewareOptions>) => Promise<{
751
751
  context: {
752
- headers: Headers;
752
+ headers?: Headers | undefined;
753
+ query?: {
754
+ disableCookieCache: boolean;
755
+ } | undefined;
753
756
  };
754
757
  } | undefined>>;
755
758
  }[];
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  import { C as DBSC_TERMINATE, D as DbscSessionConfig, E as DbscScopeRule, O as formatCookieAttributes, S as verifyRegistrationProof, T as DbscCredential, _ as VerifyRegistrationProofResult, a as formatChallengeHeader, b as readUnverifiedChallenge, c as parseSfString, d as DbscAlgorithm, f as DbscProofClaims, g as VerifyRegistrationProofInput, h as VerifyRefreshProofResult, i as DbscRegistrationHeaderInput, l as readDbscHeader, m as VerifyRefreshProofInput, n as DbscChallengeHeaderInput, o as formatRegistrationHeader, p as DbscPublicKey, r as DbscHeaderNames, s as getDbscHeaderNames, t as DBSC_HEADERS, u as DBSC_ALGORITHMS, v as parseProofHeader, w as DbscCookieAttributes, x as verifyRefreshProof, y as parseStoredPublicKey } from "./headers-KXqmHcXY.js";
2
- import { C as dbscSchema, S as createMemoryDbscStore, _ as DbscBinding, a as DbscEvent, b as DbscStoreAdapter, c as DbscRefusalReason, d as FreshProofState, f as ResolvedDbscOptions, g as DBSC_MODEL, h as DBSC_ERROR_CODES, i as DbscCarrier, l as DbscStatusState, m as resolveDbscOptions, n as DBSC_REFRESH_PATH, o as DbscFreshProofRule, p as dbsc, r as DBSC_REGISTER_PATH, s as DbscOptions, t as DBSC_COOKIE_KEYS, u as DbscUnboundPolicy, v as DbscProofKind, x as createAdapterDbscStore, y as DbscStore } from "./dbsc-plugin-CfQHYOZN.js";
2
+ import { C as dbscSchema, S as createMemoryDbscStore, _ as DbscBinding, a as DbscEvent, b as DbscStoreAdapter, c as DbscRefusalReason, d as FreshProofState, f as ResolvedDbscOptions, g as DBSC_MODEL, h as DBSC_ERROR_CODES, i as DbscCarrier, l as DbscStatusState, m as resolveDbscOptions, n as DBSC_REFRESH_PATH, o as DbscFreshProofRule, p as dbsc, r as DBSC_REGISTER_PATH, s as DbscOptions, t as DBSC_COOKIE_KEYS, u as DbscUnboundPolicy, v as DbscProofKind, x as createAdapterDbscStore, y as DbscStore } from "./dbsc-plugin-D9MKOgZP.js";
3
3
  import { _ as isDbscError, a as ReadBoundTokenInput, c as createBoundToken, d as readBoundToken, f as readDbscChallenge, g as DbscErrorCode, h as DbscError, i as DbscChallengePurpose, l as createDbscChallenge, m as readFreshProofToken, n as CreateDbscChallengeInput, o as ReadDbscChallengeInput, p as readFreshProofNonce, r as CreateFreshProofTokenInput, s as ReadFreshProofTokenInput, t as CreateBoundTokenInput, u as createFreshProofToken } from "./index-s7R-j-qI.js";
4
4
  export { type CreateBoundTokenInput, type CreateDbscChallengeInput, type CreateFreshProofTokenInput, DBSC_ALGORITHMS, DBSC_COOKIE_KEYS, DBSC_ERROR_CODES, DBSC_HEADERS, DBSC_MODEL, DBSC_REFRESH_PATH, DBSC_REGISTER_PATH, DBSC_TERMINATE, type DbscAlgorithm, type DbscBinding, type DbscCarrier, type DbscChallengeHeaderInput, type DbscChallengePurpose, type DbscCookieAttributes, type DbscCredential, DbscError, type DbscErrorCode, type DbscEvent, type DbscFreshProofRule, type DbscHeaderNames, type DbscOptions, type DbscProofClaims, type DbscProofKind, type DbscPublicKey, type DbscRefusalReason, type DbscRegistrationHeaderInput, type DbscScopeRule, type DbscSessionConfig, type DbscStatusState, type DbscStore, type DbscStoreAdapter, type DbscUnboundPolicy, type FreshProofState, type ReadBoundTokenInput, type ReadDbscChallengeInput, type ReadFreshProofTokenInput, type ResolvedDbscOptions, type VerifyRefreshProofInput, type VerifyRefreshProofResult, type VerifyRegistrationProofInput, type VerifyRegistrationProofResult, createAdapterDbscStore, createBoundToken, createDbscChallenge, createFreshProofToken, createMemoryDbscStore, dbsc, dbscSchema, formatChallengeHeader, formatCookieAttributes, formatRegistrationHeader, getDbscHeaderNames, isDbscError, parseProofHeader, parseSfString, parseStoredPublicKey, readBoundToken, readDbscChallenge, readDbscHeader, readFreshProofNonce, readFreshProofToken, readUnverifiedChallenge, resolveDbscOptions, verifyRefreshProof, verifyRegistrationProof };
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import { BASE_ERROR_CODES, BetterAuthError } from "better-auth";
2
2
  import { APIError, createAuthEndpoint, createAuthMiddleware } from "better-auth/api";
3
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";
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-Crgd63SH.js";
5
+ import { n as DBSC_ERROR_CODES, t as version } from "./package-DTjet4zW.js";
6
6
  // src/store.ts
7
7
  const DBSC_MODEL = "dbscSession";
8
8
  const dbscSchema = { [DBSC_MODEL]: { fields: {
@@ -324,7 +324,7 @@ const dbsc = (options) => {
324
324
  const storeFor = (context) => config.store?.(context) ?? createAdapterDbscStore(context.adapter);
325
325
  /** Reads the session the request carries and whether it is proven. No writes. */
326
326
  async function sessionState(ctx) {
327
- return stateFor(ctx, await readSessionToken(ctx) ?? readBearerToken(ctx));
327
+ return stateFor(ctx, await readSessionToken(ctx));
328
328
  }
329
329
  /**
330
330
  * Reads one session token's session and whether the bound cookie proves it: two reads,
@@ -439,6 +439,7 @@ const dbsc = (options) => {
439
439
  const sessions = [cookieState, bearerState].filter((state) => state.kind === "plain" || state.kind === "bound");
440
440
  return {
441
441
  drop,
442
+ disableCookieCache: ctx.context.options.session?.cookieCache?.enabled === true && (cookieToken !== null && cookieState.kind === "none" || bearerToken !== null && bearerState.kind === "none"),
442
443
  sessions: sessions.filter((state, i) => sessions.indexOf(state) === i)
443
444
  };
444
445
  }
@@ -657,16 +658,16 @@ const dbsc = (options) => {
657
658
  const store = storeFor(ctx.context);
658
659
  const { session } = found;
659
660
  const existing = await store.find(session.id);
660
- if (!(existing ? existing.thumbprint === verified.thumbprint : await store.bind({
661
+ if (!existing && await store.bind({
661
662
  sessionId: session.id,
662
663
  userId: session.userId,
663
664
  publicKey: verified.publicKey,
664
665
  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, {
666
+ })) await emit(ctx, {
667
667
  type: "registered",
668
668
  ...ids(session)
669
669
  });
670
+ else if ((existing ?? await store.find(session.id))?.thumbprint !== verified.thumbprint) throw await refused("bound_to_other_key", DBSC_ERROR_CODES.DBSC_BOUND_TO_OTHER_KEY);
670
671
  await setBoundCookie(ctx, token, { expiresAtMs: challenge.issuedAtMs + config.boundCookieMaxAge * 1e3 });
671
672
  await setRefreshChallenge(ctx, token);
672
673
  return ctx.json(sessionConfig(ctx));
@@ -843,8 +844,14 @@ const dbsc = (options) => {
843
844
  matcher: (ctx) => enforced(ctx.path),
844
845
  handler: createAuthMiddleware(async (ctx) => {
845
846
  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;
847
+ const { drop, sessions, disableCookieCache } = await gate(ctx);
848
+ const result = drop.size > 0 || disableCookieCache ? { context: {
849
+ ...drop.size > 0 && { headers: withoutCookies(ctx.headers, drop) },
850
+ ...disableCookieCache && { query: {
851
+ ...ctx.query,
852
+ disableCookieCache: true
853
+ } }
854
+ } } : void 0;
848
855
  const policy = ctx.path ? config.freshProof.paths.get(ctx.path) : void 0;
849
856
  if (!policy) return result;
850
857
  for (const state of sessions) if (state.kind === "plain") await unboundPolicy(ctx, state, ctx.path, policy);
@@ -15,5 +15,5 @@ const DBSC_ERROR_CODES = defineErrorCodes({
15
15
  DBSC_BINDING_REQUIRED: "This action needs a device-bound session"
16
16
  });
17
17
  // package.json
18
- var version = "0.1.0";
18
+ var version = "0.1.1";
19
19
  export { DBSC_ERROR_CODES as n, version as t };
@@ -4,6 +4,9 @@ STRIDE, following the [dbsc-toolkit threat model](https://github.com/SulimanAbdu
4
4
 
5
5
  Every mitigation below names the test that proves it. The tests run against Better Auth on SQLite with keys generated by `jose`, not against Chrome.
6
6
 
7
+ Registration and refresh both validate the public key. This includes keys returned by custom stores. Both require an RS256 modulus of at least 2048 significant bits in minimal unsigned encoding.
8
+ When an expected origin is configured, a present audience list must contain at least one URL and every entry must match that origin.
9
+
7
10
  ## Assets
8
11
 
9
12
  - **The binding**: a `dbscSession` row tying a Better Auth session to the device's public key and its thumbprint.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@assistant-ui/better-auth-dbsc",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Device Bound Session Credentials (DBSC) for Better Auth.",
5
5
  "keywords": [
6
6
  "better-auth",