@assistant-ui/better-auth-dbsc
v0.3.0
Published
Device Bound Session Credentials (DBSC) for Better Auth.
Readme
@assistant-ui/better-auth-dbsc
Device Bound Session Credentials for Better Auth: a stolen session cookie stops working on any other machine.
When a browser with DBSC support signs in, it creates a key in the TPM. Today that means Chrome 146+ on Windows. Every few minutes the browser proves it still holds the key. The server accepts the session only alongside a short-lived cookie that only that key can renew. Cookies copied to another machine stop working within five minutes.
Browsers without DBSC ignore the registration header and keep using the normal Better Auth session. Nothing changes for them.
pnpm add @assistant-ui/better-auth-dbscimport { betterAuth } from "better-auth";
import { dbsc } from "@assistant-ui/better-auth-dbsc";
export const auth = betterAuth({
database,
emailAndPassword: { enabled: true },
plugins: [dbsc()], // first, so no other plugin's hook sees a session before it
});Then add the dbscSession table (see Schema). If your own hooks.before reads the session, see Hook order.
What it does not do
- It does not protect sessions in browsers without DBSC. They work exactly as before, unless you refuse them on chosen paths with
freshProof. - It does not stop malware running on the user's machine right now, because that malware can ask the TPM to sign. It stops cookies from being stolen and used somewhere else later.
- It does not work for bearer-token clients. A bearer client can't renew the bound cookie, so a bound session is refused over
Authorization: Bearerunless the same request also carries that session's live bound cookie. Unbound sessions keep working over bearer. See Other ways a session arrives. - It has not been tested against real Chrome. See Limits.
The threats it covers, and the ones it doesn't, are mapped in docs/threat-model.md. Report a vulnerability privately, as described in SECURITY.md.
How it works
sign-in ──▶ 200 + Secure-Session-Registration: (ES256 RS256);path="/api/auth/dbsc/register";challenge="c1"
│
browser makes a TPM key, signs c1 ▼
POST /api/auth/dbsc/register Secure-Session-Response: <JWT, jti=c1, jwk=public key>
◀── 200 session config + Set-Cookie: better-auth.dbsc_token (5 min)
Secure-Session-Challenge: "c2";id="better-auth"
… 5 minutes later, before the next request …
POST /api/auth/dbsc/refresh Sec-Secure-Session-Id: "better-auth"
◀── 403 + Secure-Session-Challenge: "c3" (browser signs c3 and retries)
POST /api/auth/dbsc/refresh Secure-Session-Response: <JWT, jti=c3>
◀── 200 + fresh dbsc_token + next challenge
◀── 200 {"continue": false} when the session is gone, unbound, or DBSC is offOnly a session the request created is offered registration: sign-up, and sign-in by any method, a second factor included. A request that sets a session it didn't create gets no offer. That covers multiSession()'s /multi-session/set-active and oneTimeToken()'s /one-time-token/verify, which a copied cookie can reach, so offering them would let a thief bind the owner's session to the thief's key. The response must also set the new session as the session cookie, because DBSC binds a cookie. deviceAuthorization()'s /device/token hands its session out as an access_token instead, for a device code a copied cookie can approve, so it gets no offer either.
Some endpoints replace the session they're called with: twoFactor()'s enable, disable, and TOTP enrollment through /two-factor/verify-totp. With allowPasswordless, a user without a password needs nothing but the session cookie for those. So a session that replaces an unbound one stays unbound. It's offered registration only when the request carries a live bound cookie for the session it replaces.
Challenges are stateless: an HMAC under your Better Auth secret, bound to the session token and to one purpose (register or refresh). Issuing one writes nothing. A refresh proof is spent with one atomic write after its signature verifies, so a replay loses and garbage spends nothing.
Every request then goes through one check:
| Session | Bound cookie | Result |
|---|---|---|
| Not bound | any | Allowed. This is every browser without DBSC. |
| Bound | live, and minted for this session | Allowed. |
| Bound | missing, expired, or for another session | The session cookie is dropped from the request, so every endpoint sees a signed-out user and getSession returns null. With Authorization: Bearer: 401 DBSC_CREDENTIAL_REQUIRED. |
Dropping the cookie, rather than revoking the session, means someone holding a copied cookie can't sign the owner out. Sign-in and sign-up still work for that request, so a user whose key is gone signs in again and gets a new session.
The check runs on every Better Auth endpoint and on auth.api.* calls from your own routes, such as auth.api.getSession({ headers }). With enforcement.enabled: false it still runs and reports credential_missing, but drops and refuses nothing. See enforcement.enabled.
Other ways a session arrives
The check reads every session token in the request, not only the session cookie, because plugins can hand an endpoint a different one:
bearer()turnsAuthorization: Bearer <token>into the session cookie in its own hook. That hook may run after this one and rebuilds the cookie header from the original request, so dropping a cookie can't be relied on. The rule is: a request withAuthorization: Bearerthat carries any bound session, through the cookie, the bearer token, amultiSession()cookie oradmin_session, gets401 DBSC_CREDENTIAL_REQUIREDunless the bound cookie proves every bound session in it and the session cookie and the bearer token name that one session (or no session). So the bound browser can still send its own session as a bearer token, a bearer token that isn't a session token (an OAuth access token) is left alone, and plain sessions over bearer work as before. A stolen token is refused however it is sent: as a bearer token, next to the copied cookie, or next to the thief's own session cookie.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. Switching to a plain account doesn't offer DBSC either: sign in to it again to bind it. Every account registers under the samesession_identifier, so the browser keeps only the latest one, and each request reports every other bound account ascredential_missingwithvia: "multi-session". See Limits.admin()keeps the admin's own session token in anadmin_sessioncookie while they impersonate someone, and/admin/stop-impersonatingswaps 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. The impersonation session is never offered DBSC, because registering it under the samesession_identifierwould replace the admin's own DBSC session. While the admin impersonates, the browser keeps refreshing the admin's session throughadmin_session, still with the admin's key, so stopping restores it bound. See Limits.- A session already read in the request. Better Auth keeps the first session read in a request on
ctx.context.sessionand answers every later read from it,sessionMiddlewareincluded. A hook that runs before the check can fill it from a copied cookie. The check treats that session like the others: if the bound cookie doesn't prove it, or the server no longer has it, it's cleared and the endpoint reads the checked request again. Cookies are dropped from the request at once, so hooks that run after the check never see them. See Hook order. - A session another plugin builds from its own credential.
apiKey({ enableSessionForAPIKeys: true })from@better-auth/api-keyreads an API key header and puts a session for the key's user onctx.context.session, with no session row behind it. Nothing binds it, sofreshProoftreats it as plain:unbound: "deny"refuses it, and"fresh-session"passes it, becauseapiKey()dates it to the request. Better Auth's own fresh-session check passes it for the same reason. The check sees it only whenapiKey()'s hook runs first, so listapiKey()beforedbsc(): see Hook order.getDbscStatusandrequireFreshProofread the session cookie and the bearer token only, so a request that carries only an API key getsno-sessionfrom them. - A cookie name sent twice. Better Auth's readers disagree on which copy of a repeated name counts: most read the first, and
bearer()rebuilds the cookie header keeping the last. So the check reads every copy of the session cookie, eachmultiSession()cookie andadmin_session, and verifies each copy's signature on its own. A copy naming a bound session the request doesn't prove is dropped, the other copies stay, and the endpoint reads the first copy left. WithAuthorization: Bearer, such a copy gets the request401 DBSC_CREDENTIAL_REQUIREDinstead. Browsers send a name twice when two cookies differ by Path or Domain, such as a stale copy left after an app changescrossSubDomainCookiesor the cookie path. A stale copy naming a still-live bound session doesn't sign the user out, but it's reported ascredential_missingon every request, and over bearer every request is refused, until that session ends or the copy is cleared. Registration and refresh read every copy too, so the session bound since keeps refreshing: see Limits.
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.
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.
Hook order
Better Auth runs your hooks.before first, then each plugin's before hooks in the order of plugins. The check runs in dbsc()'s before hook. Any hook can read the session, and a hook that runs before the check sees the session as the request carried it, copied cookie included. The endpoint is safe either way, because the check clears that session, but that hook has already seen it.
- Put
dbsc()first inplugins. Then no other plugin's hook runs before the check. - Except
apiKey(), when it turns API keys into sessions: list it beforedbsc().freshProofapplies to the sessions that exist whendbsc()'s hook runs, andapiKey()builds its session in its own hook. Listed afterdbsc(), an API key passesunbound: "deny". Listing it first is safe: its hook reads only the API key header, looks the key up, and loads its user. It never reads a cookie or the session, so it can't pick up a copied cookie. Your owncustomAPIKeyGetterandcustomAPIKeyValidatorrun in that hook, so keep session reads out of them. Another plugin that builds a session from its own credential goes first too, once you've checked that its hook reads no cookie and no session.
plugins: [apiKey({ enableSessionForAPIKeys: true }), dbsc(), ...otherPlugins],- If your
hooks.beforereads the session, callenforcefirst. No plugin can run beforehooks.before, so it runs the check itself:
import { betterAuth } from "better-auth";
import { createAuthMiddleware, getSessionFromCtx } from "better-auth/api";
import { dbsc } from "@assistant-ui/better-auth-dbsc";
const dbscPlugin = dbsc();
export const auth = betterAuth({
plugins: [dbscPlugin],
hooks: {
before: createAuthMiddleware(async (ctx) => {
await dbscPlugin.enforce(ctx);
const session = await getSessionFromCtx(ctx); // null for a copied cookie
// ...your own checks
}),
},
});enforce(ctx) runs the check of dbsc()'s hook on the request in hand. It drops the same cookies and throws the same 401 DBSC_CREDENTIAL_REQUIRED for a bearer request, so let that error propagate. It does nothing where the hook does nothing: while enabled is off and on enforcement.exclude paths. With enforcement.enabled: false it does nothing either, and dbsc()'s hook reports what it finds, once. dbsc()'s own hook still runs later. It finds the request already checked, so nothing is dropped or reported twice, and it applies freshProof.
Schema
One table, one row per bound session, deleted with its session:
| Column | Type | Purpose |
|---|---|---|
| sessionId | string, unique, references session.id | The bound session. |
| userId | string, indexed, references user.id | Its user, for listing a user's bound devices. |
| publicKey | string | The device's public JWK, JSON-encoded, with alg. |
| thumbprint | string | RFC 7638 thumbprint of the key. |
| lastRefreshAt | date | Issue time of the newest refresh challenge spent. Older ones are refused. |
| lastFreshProofAt | date | Issue time of the newest fresh-proof challenge spent. |
| proofCount | number | How many proofs this binding has spent. |
| createdAt | date | When the session was bound. |
Generate the migration for your database the usual way:
npx @better-auth/cli generate # or: npx @better-auth/cli migrateThe SQLite output is checked in at migrations/sqlite/0001_dbsc_session.sql and regenerated with pnpm generate:migrations. Rename the model or its fields with schema, for example dbsc({ schema: { dbscSession: { modelName: "dbsc_session" } } }).
To keep bindings somewhere else, such as Redis, KV, or an existing table, pass a store.
Options
Every option is optional. The shape follows Better Auth's own plugins:
- Optional features are an object with
enabled, likesession.cookieCache. - Durations are
maxAgeorexpiresIn, in seconds. - Callbacks:
onEventgets every DBSC event, like the Stripe plugin'sonEvent, andshouldRegisterdecides which sessions are offered DBSC. - Protocol details live under
advanced.
These are the defaults:
dbsc({
enabled: true, // or () => flags.dbsc, read on every request
algorithms: ["ES256", "RS256"],
boundCookieMaxAge: 300,
challengeExpiresIn: 300,
scope: { origin: undefined, includeSite: false, exclude: [], rules: [] },
enforcement: { enabled: true, exclude: [] },
freshProof: undefined, // { paths, unbound: "allow", expiresIn: 60 }
rateLimit: { enabled: true, window: 60, max: 600 },
onEvent: undefined, // (event) => void
shouldRegister: undefined, // (ctx) => boolean
now: Date.now, // the clock, for tests
store: undefined, // the dbscSession table through Better Auth's adapter
schema: undefined, // rename the model or its fields
advanced: {
sessionIdentifier: "better-auth",
allowedRefreshInitiators: ["*"],
headers: "both", // "standard" | "legacy" | "both"
},
});Invalid options throw at startup with every problem listed at once:
BetterAuthError: Invalid dbsc() options:
- `boundCookieMaxAge` must be a positive integer.
- `onEvent` must be a function.| Option | What it controls |
|---|---|
| enabled | A kill switch, read on every request. Off means nothing is read, written, advertised, or refused. Bound sessions fall back to the plain cookie at once, and browsers are told to end their DBSC sessions at their next refresh. Turning it back on restores every binding. |
| algorithms | Signing algorithms offered, in preference order. Only ES256 and RS256 are accepted. |
| boundCookieMaxAge | Seconds a copied cookie keeps working. Shorter means more refreshes. |
| challengeExpiresIn | Seconds a registration or refresh challenge is accepted. |
| scope.origin | The origin the DBSC session covers. Defaults to the origin of Better Auth's baseURL. |
| scope.includeSite | Cover every subdomain of the site. On app.example.com the browser first checks https://example.com/.well-known/device-bound-sessions for a registering_origins entry. Only turn this on if you serve that file. |
| scope.exclude | Path prefixes the browser never holds for a refresh, such as /assets/. The DBSC endpoints are always excluded. |
| scope.rules | Raw scope_specification entries, sent after exclude, for anything exclude can't express. |
| enforcement.enabled | true drops the cookie of a bound session that has no live bound cookie. false is for rollouts: sessions are bound and every request is still checked, and onEvent gets credential_missing exactly as with enforcement, but nothing is dropped or refused and the endpoint gets the request as it arrived. Watch the events, then turn it on. The check costs the same reads either way: the session and its binding for each session token a request carries (see Limits). freshProof needs it on: dbsc() refuses to start rather than skip its proofs. |
| enforcement.exclude | Paths left alone, such as ["/health/"]. A trailing / matches child paths. A freshProof path can't be excluded: dbsc() refuses to start rather than skip its proof. |
| freshProof | Paths that need a proof made after the request arrived. See freshProof. |
| rateLimit | Per-address limit on /dbsc/register and /dbsc/refresh, through Better Auth's own limiter, which is on in production by default. Set it generously, because an office shares one address. |
| onEvent | Receives registrations, refreshes, refusals, and theft signals. See Events. |
| shouldRegister | Decides per sign-in whether to offer DBSC, for example only for some users. It runs only for a session the request created, not one it refreshed or switched to. Return false to skip. |
| now | The clock in milliseconds, for tests. |
| store | A DbscStore, or (ctx) => DbscStore, to keep bindings outside the default table. See Store. |
| schema | Renames the dbscSession model or its fields. |
| advanced.sessionIdentifier | The browser keys DBSC sessions by site and this value. One value per app means a new sign-in replaces the old DBSC session instead of adding another. Give apps that share a site different values. |
| advanced.allowedRefreshInitiators | Hosts whose links and redirects may trigger a refresh, besides the session's own origin (or its site, with scope.includeSite). Browsers compare each entry to the requesting page's host: * matches any host, *.example.com matches subdomains of example.com but not example.com itself, and any other entry must equal the host, lowercase, with no scheme, port, or path. Write idp.example.com, not https://idp.example.com. An entry no host can match makes dbsc() refuse to start, with the corrected form in the error. ["*"] lets a user coming back from an OAuth provider arrive signed in. [] adds no hosts. |
| advanced.headers | "standard" sends Secure-Session-*, from the W3C draft and shipping Chrome. "legacy" sends Sec-Session-*, from the origin trial. "both" sends both. Request headers are always read under both names. |
freshProof: sensitive actions
The bound cookie lives five minutes, so a thief who copies it inside that window can use it until it expires. For endpoints whose effects outlast that window, such as adding a passkey, changing the email, or deleting the account, ask for a proof made after the request arrived:
dbsc({
freshProof: {
paths: {
"/change-email": {},
"/passkey/add-passkey": {},
"/delete-user": { unbound: "deny" }, // only from a device-bound session
},
unbound: "fresh-session", // everything else: plain sessions must be recent
expiresIn: 60,
},
});With twoFactor(), list /two-factor/enable and /two-factor/disable too. Each replaces a bound session with one that's offered DBSC, so someone holding both cookies inside the bound-cookie window could bind the replacement to their own key and sign the owner out.
On a bound session, the first attempt is refused with 403 DBSC_FRESH_PROOF_REQUIRED and its bound cookie removed. The refusal comes before the endpoint runs, so nothing has changed yet. dbscClient() sends the call once more. The browser sees the bound cookie gone, holds the request, refreshes with its key, and then sends it, and that retry passes once. A copied cookie can't answer, however fresh it is: the refresh writes the challenge's nonce into the new bound cookie, and only a cookie that names the challenge answers it. No clocks are compared, so instances whose clocks differ can't make an old cookie look newer. A thief's retry is refused like the first attempt.
A navigation (Sec-Fetch-Mode: navigate), such as a link to /oauth2/authorize or a form post, gets 307 back to the same URL instead, because the browser would show a JSON 403 to the user. The browser holds the redirected request, refreshes with its key, and follows it. A 307 keeps a form post's method and body.
An endpoint that another endpoint runs inside the same request is checked once. The OAuth provider's consent and continue endpoints re-enter /oauth2/authorize through the hook pipeline, so listing both /oauth2/consent and /oauth2/authorize asks for one proof, not two.
Run one sensitive action at a time. The browser keeps one fresh-proof challenge, in one cookie, so when two different freshProof actions are sent together, the challenge set last replaces the other. One refresh answers only the challenge the browser kept: after the retries, one action has run and the other comes back 403 DBSC_FRESH_PROOF_REQUIRED with nothing changed. Sent again through dbscClient() or fetchWithFreshProof, it passes. The same action sent twice at once runs once, and the second copy is refused.
unbound decides what sessions that aren't bound get on those paths:
"allow"passes them."fresh-session"passes them only while they're younger than Better Auth'ssession.freshAge, else403 SESSION_NOT_FRESH."deny"refuses them with403 DBSC_BINDING_REQUIRED.
These see the sessions the session cookie and the bearer token carry. They see a session another plugin builds, such as apiKey()'s, only when that plugin's hook runs before dbsc()'s. See Hook order.
For your own routes, call the same check from server code, before the route changes anything:
import { DBSC_ERROR_CODES } from "@assistant-ui/better-auth-dbsc";
const { headers, response } = await auth.api.requireFreshProof({
headers: request.headers,
body: { action: "export-data" },
returnHeaders: true,
});
if (response.state === "challenge") {
// `headers` removes the bound cookie, so the browser refreshes before the retry.
return Response.json(DBSC_ERROR_CODES.DBSC_FRESH_PROOF_REQUIRED, { status: 403, headers });
}
// "answered": bound, and proven since the challenge.
// "unbound", "no-session", "off": apply your own policy.Then call the route with fetchWithFreshProof, which takes the same arguments as fetch:
import { fetchWithFreshProof } from "@assistant-ui/better-auth-dbsc/client";
const response = await fetchWithFreshProof("/api/export", { method: "POST" });It sends the request once more only when the answer is 403 with a JSON body whose code is DBSC_FRESH_PROOF_REQUIRED, and returns the second answer as it is. Every other answer comes back untouched, body unread. A Request is copied before the first send, so its body can go out again. A ReadableStream body can't be sent twice, so its refusal comes back as it is.
A server action returns a value, not a response, so neither dbscClient() nor fetchWithFreshProof sees its refusal. Return the code from the action, with its cookies sent through your framework (the nextCookies() plugin in Next.js), and call the action once more on the client when the code comes back.
requireFreshProof is server-only and has no HTTP route.
Status
GET /api/auth/dbsc/get-status, auth.api.getDbscStatus({ headers }), or authClient.dbsc.getStatus() answers { state }:
| state | Meaning |
|---|---|
| "bound" | Bound to a device key and proven by a live bound cookie. |
| "unbound" | A plain session. |
| "no-session" | Signed out, or a bound session without its cookie. Also a request that carries only another plugin's credential, such as an API key: status reads the session cookie and the bearer token. |
| "off" | enabled is false. |
Events
dbsc({
onEvent(event, ctx) {
if (event.type === "proof_rejected") revokeUserSessions(event.userId);
metrics.increment(`dbsc.${event.type}`);
auditLog.write({
...event,
// Your proxy's client-IP header: Better Auth doesn't export the one it uses.
ipAddress: ctx?.headers?.get("x-forwarded-for") ?? null,
userAgent: ctx?.headers?.get("user-agent") ?? null,
path: ctx?.path ?? null,
});
},
shouldRegister: (ctx) => !ctx.context.newSession?.user.email.endsWith("@bots.example.com"),
});proof_rejected alone doesn't prove theft. A browser sends one when its own session has ended but a stale copy of the session cookie, naming another bound session, is still in its jar (see Limits). Check the IP address and user agent before signing the user out everywhere.
The second argument is the request that caused the event, so an audit log can record where a theft signal came from. It's null only for released when Better Auth deletes a session outside a request. It holds the request's cookies, so copy fields from it and never log it whole.
| type | When |
|---|---|
| registered | The request created a session binding. Concurrent retries with the same key share that binding and emit one event. |
| released | A binding ended because Better Auth deleted its session: sign-out, revocation, a deleted user, or an expired session. The reverse of registered, so an audit log can show when a device stopped holding a session. Not reported for sessions a bulk delete removes past Better Auth's hook limit: see Store. |
| registration_refused | With a reason: invalid_challenge, invalid_proof, bound_to_other_key, or disabled. |
| refreshed | A bound cookie was renewed. |
| refresh_challenged | With a reason: missing_proof (normal), stale_challenge, or replayed. |
| proof_rejected | A refresh carried a proof the bound key didn't sign. This is the strongest theft signal. The binding is untouched, so revoke the session here if you'd rather sign the owner out. |
| credential_missing | A bound session arrived without its bound cookie, via cookie, bearer, multi-session or admin-session. Once per session per request, with enforcement.enabled: false too. One now and then is normal. A burst via cookie, bearer or admin-session points to a copied cookie. via: "multi-session" also comes on every request from a browser with several accounts bound through multiSession(), so filter alerts by via. |
| fresh_proof_challenged, fresh_proof_answered | The freshProof round trip, with the action. |
| unbound_refused | A plain session was refused on a freshProof path, with the policy. For a session another plugin built, sessionId is the id that plugin gave it: apiKey() uses the key's id. |
| terminated | The browser was told to end its DBSC session: disabled, no_session, not_bound, or other_identifier. |
Events carry session ids, user ids, and reason codes, never keys, challenges, or cookies. onEvent runs through Better Auth's background task handler when one is configured. If it throws, the error is logged and the response doesn't change.
Endpoints
| Path | Server | Client | Called by |
|---|---|---|---|
| POST /dbsc/register | auth.api.registerDbscSession | — | The browser, after sign-in. |
| POST /dbsc/refresh | auth.api.refreshDbscSession | — | The browser, when the bound cookie lapses. |
| GET /dbsc/get-status | auth.api.getDbscStatus | authClient.dbsc.getStatus | Your app. |
| none, server-only | auth.api.requireFreshProof | — | Your server code. |
The three HTTP endpoints carry OpenAPI metadata, so Better Auth's openAPI() plugin documents them.
Error codes
DBSC_ERROR_CODES is built with Better Auth's defineErrorCodes, and each entry is a { code, message }. Errors are thrown with APIError.from, and the codes are on $ERROR_CODES for both the server and the client plugin.
| Code | Status | When |
|---|---|---|
| DBSC_CREDENTIAL_REQUIRED | 401 | A request with Authorization: Bearer carried a bound session without its live bound cookie, or alongside another session. |
| DBSC_FRESH_PROOF_REQUIRED | 403 | A freshProof path needs a proof the browser hasn't made yet. |
| DBSC_BINDING_REQUIRED | 403 | A freshProof path with unbound: "deny" got a plain session. |
| SESSION_NOT_FRESH | 403 | Better Auth's own code, for unbound: "fresh-session". |
| DBSC_CHALLENGE_REQUIRED | 403 | A refresh needs a proof over the new challenge. The browser retries. |
| DBSC_SESSION_ID_REQUIRED | 400 | A refresh without Sec-Secure-Session-Id, so not from the browser. |
| DBSC_DISABLED, DBSC_PROOF_REQUIRED, DBSC_INVALID_CHALLENGE, DBSC_INVALID_PROOF, DBSC_BOUND_TO_OTHER_KEY | 400 | A registration was refused. DBSC_INVALID_PROOF carries the DbscError as its cause. |
| DBSC_SESSION_REQUIRED | 401 | A registration without a signed-in session. |
Store
interface DbscStore {
find(sessionId: string): Promise<DbscBinding | null>;
bind(binding: DbscBinding): Promise<boolean>; // false if the session was already bound
spend(sessionId: string, kind: "refresh" | "fresh-proof", issuedAtMs: number): Promise<boolean>;
delete(sessionId: string): Promise<void>; // the session ended: drop the binding and its spend state
}delete runs from Better Auth's session delete hook: sign-out, revoke-session(s), a deleted user, or an expired session it comes across. A bulk delete doesn't run it for every session. When one call deletes a user's sessions together (revoke-sessions, deleting the user, an admin ban, a password reset or change that revokes sessions), Better Auth runs the delete hooks only for the rows its findMany returns. That read stops at advanced.database.defaultFindManyLimit, 100 by default, and every matching session is deleted anyway. So for a user with more sessions than that, the rest get no delete call and no released event, whichever store you use. Their bindings can't be used, because their sessions are gone, but a custom store keeps them until you prune them.
The default dbscSession table doesn't need the hook for this. Its sessionId references session.id with on delete cascade, so the database removes the row with its session. That holds only where the database enforces foreign keys. Better Auth's MongoDB and memory adapters, and SQLite with PRAGMA foreign_keys off, don't, so treat the default table there like a custom store.
Prune bindings whose session is gone or expired, the way you prune sessions. That covers what a bulk delete leaves behind, and sessions that expire unseen, which Better Auth leaves in place. Don't expire a binding on a fixed TTL: sessions roll forward, and a binding that lapses before its session turns it back into a plain session. If sessions live only in secondaryStorage, Better Auth runs no delete hooks, so pruning is all there is.
bind and spend must be atomic. Of two racing registrations, at most one binds, and of two requests carrying the same proof, at most one spends. spend also refuses a challenge older than the newest one spent. The default store does this with one guarded incrementOne. createMemoryDbscStore() is there for tests and single-instance development.
With onEvent set, find can run inside a Better Auth transaction. The session delete hook calls it to know whether to report released, and since Better Auth 1.7.8, /change-password and password resets that revoke sessions delete them in a transaction. The default store reads through that transaction. A store that reads through Better Auth's adapter has to do the same: get the adapter from getCurrentAdapter(context.adapter), exported by better-auth, on each call. Inside a transaction it returns the transaction's adapter, and outside one it returns context.adapter. Reading through context.adapter inside the transaction waits for a connection the transaction holds: forever on SQLite, and on a connection pool whenever every connection is taken. delete runs after the transaction commits, and a store on its own connection, such as Redis, isn't affected.
If sessions live only in secondaryStorage, the default store refuses to start, because its rows reference session.id. Set session.storeSessionInDatabase: true or pass a store.
Client
The browser drives DBSC by itself. The client plugin adds types, the error codes, getStatus, and the freshProof retry:
import { createAuthClient } from "better-auth/react";
import { dbscClient } from "@assistant-ui/better-auth-dbsc/client";
export const authClient = createAuthClient({ plugins: [dbscClient()] });
const { data } = await authClient.dbsc.getStatus(); // { state: "bound" | ... }With dbscClient() installed, any authClient call refused with 403 DBSC_FRESH_PROOF_REQUIRED, such as authClient.changeEmail() on a freshProof path, is sent once more with the same method, headers, and body. The call returns the second answer, refusal or not. Other answers are untouched. onResponse hooks in fetchOptions run before the retry and see the first answer; onSuccess and onError see the second. For your own routes, use fetchWithFreshProof.
Building blocks
@assistant-ui/better-auth-dbsc/core exports the protocol pieces without Better Auth, for another framework or your own middleware:
import {
formatRegistrationHeader,
formatChallengeHeader,
verifyRegistrationProof,
verifyRefreshProof,
createDbscChallenge,
readDbscChallenge,
createBoundToken,
readBoundToken,
createFreshProofToken,
readFreshProofToken,
readFreshProofNonce,
} from "@assistant-ui/better-auth-dbsc/core";
const { publicKey, thumbprint } = await verifyRegistrationProof(jwt, {
challenge,
expectedOrigin: "https://app.example.com",
});Failures throw DbscError with a stable code: MALFORMED_PROOF, UNSUPPORTED_ALGORITHM, UNSUPPORTED_TYPE, INVALID_PUBLIC_KEY, INVALID_SIGNATURE, CHALLENGE_MISMATCH, AUTHORIZATION_MISMATCH, or AUDIENCE_MISMATCH.
Try it locally
You don't need Chrome to exercise the cryptography. The tests play the browser with jose. They create ES256 and RS256 key pairs, sign registration and refresh proofs, and send them to a real Better Auth instance on in-memory SQLite.
pnpm install
pnpm test # registration, refresh, replay races, enforcement, freshProof, events, threat model
pnpm example # http://localhost:3000: a sign-up form and a protected /me route
# listens on 127.0.0.1 (HOST to change); random secret per run unless BETTER_AUTH_SECRETCI runs lint, format, typecheck, tests, the build and a check of the packed tarball on Node 22 and 24, plus the tests against Better Auth 1.7.0, the oldest release peerDependencies admits.
Releasing
main only takes pull requests, so a release is a pull request plus a tag:
git switch -c release/vX.Y.Z origin/main
pnpm release # bumpp: asks for the version, bumps package.json, commits "chore: release vX.Y.Z"
# or, without prompts:
pnpm release --release X.Y.Z --yes
git push -u origin HEAD && gh pr create --fill
# once the pull request is squash-merged:
git fetch origin && git tag vX.Y.Z origin/main && git push origin vX.Y.ZThe tag runs the release workflow in the npm-publish environment, which waits for a required reviewer other than whoever pushed the tag, and accepts only v* tags. Only maintainers can create v* tags, and nobody can move or delete one. It checks the tag against package.json, runs every check again, publishes to npm with provenance through trusted publishing (no npm token), and creates the GitHub release. A version already on npm (such as a first release published by hand) skips the publish and still gets its GitHub release. A prerelease such as 0.2.0-beta.1 publishes under the next dist-tag.
npm's trusted publisher must name the environment: npm trust github @assistant-ui/better-auth-dbsc --repo assistant-ui/better-auth-dbsc --file release.yml --env npm-publish --allow-publish.
Limits
- Not tested against real Chrome. The wire format follows the W3C Editor's Draft (November 2026). Because Chrome builds have differed, the proof parser also accepts the key in the payload (
jwkorkey) and a stringiat. Try it on Chrome 146+ on Windows before relying on it. - One sensitive action at a time. Of two different
freshProofactions sent together, one is still refused after the client's retry, with nothing changed, and passes when sent again (see freshProof). The browser keeps one challenge cookie, andspendrefuses a challenge older than the newest one spent, so even two kept challenges would both pass only if their retries arrived in the order they were issued. Answering both needs spend state per action, a change toDbscStoreand thedbscSessiontable. - Paths outside
freshProofstay exposed for up toboundCookieMaxAge. Someone who copies both cookies can use them until the bound cookie expires. freshProofsees another plugin's session only when that plugin runs first. WithapiKey()listed afterdbsc(), an API key reaches a path withunbound: "deny". List it first: see Hook order.- Impersonation sessions aren't bound.
admin()'s impersonation session is never offered DBSC, so a copy of it works on another machine as the impersonated user until it ends: an hour by default, set byimpersonationSessionDuration. The admin's own session stays bound. - One bound account per browser. With
multiSession(), only the latest account to register stays bound in a browser. Every request then reports each other bound account ascredential_missingwithvia: "multi-session", so don't alert on thatviaalone. - DBSC requests skip Better Auth's origin check. The browser's registration and refresh requests aren't guaranteed to carry
Origin. On those two endpoints the CSRF defense is the signed proof over a server challenge, and refresh also requires theSec-Secure-Session-Idheader, which a page can't send cross-site without a preflight. - Two database reads per request for each session token it carries. The gate reads the session and its binding (
findSession, then thedbscSessionrow) to know whether a bound cookie is required. This happens on every Better Auth call,getSessionincluded, even withsession.cookieCacheon, and withenforcement.enabled: falsetoo, where it only reports. EachmultiSession()oradmin_sessioncookie adds two more, and so does a session that an earlier hook cached from somewhere the request doesn't carry a session token, such as an API key. WithoutmultiSession()installed,_multi-cookies cost nothing: nothing else in Better Auth reads them, so the check skips them. - Only a session the request created, and set as the session cookie, is offered DBSC. A session reached through
multiSession()'s/multi-session/set-activeoroneTimeToken()'s/one-time-token/verifystays unbound until the user signs in again in that browser. So does a session an endpoint creates in place of the unbound one it was called with, such astwoFactor()'s enable or disable, or/change-passwordwithrevokeOtherSessions. Signing in again still gets an offer, thoughmultiSession()then deletes the browser's older session of that user. A session handed out only as a token, such asdeviceAuthorization()'saccess_token, is never bound, sounbound: "deny"refuses it overAuthorization: Bearertoo. /device/approvehands out a new session. WithdeviceAuthorization(), approving a device code gives whatever device polls for it a session for the approving user, and a copied cookie can approve a code the thief started. That session stays unbound, but it is a new one. If you useunbound: "deny", put/device/approveinfreshProoftoo, so a copied cookie can't approve a device for itself.- A stale copy of the session cookie can cost a refresh round trip, and send a false
proof_rejectedafter sign-out. After an app changescrossSubDomainCookiesor the cookie path, a browser can keep the old cookie and send it first. Registration binds the copy its challenge was issued for, and refresh renews the copy whose bound key signed the proof, so the session bound since keeps working. Register and refresh answers carry a challenge for that session, so a browser that signs the last challenge it got refreshes in one request. Without one, it gets the first copy's challenge, then a second 403 with its own session's, then the cookie. Chrome's handling of a second 403 in a row hasn't been tested. Once the user signs out, the browser's key still answers refreshes, now for the stale copy alone, and every proof it signs reportsproof_rejected. A stale copy naming a plain session isn't dropped, so endpoints act as that session, as Better Auth does withoutdbsc(). Expire the old cookie under its old Path or Domain when you make that change. - A bulk delete past 100 sessions skips
deleteandreleasedfor the rest. Better Auth runs session delete hooks only for the firstadvanced.database.defaultFindManyLimitrows. The default table's cascade still removes those bindings where the database enforces foreign keys. A custom store has to prune them. See Store. - The
authorizationregistration parameter isn't sent.verifyRegistrationProofchecks it when you pass one. - Only the SQLite migration is checked in. Postgres and MySQL come from the Better Auth CLI and haven't been tested here.
