@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/LICENSE +21 -0
- package/README.md +362 -2
- package/dist/client.d.ts +27 -0
- package/dist/client.js +14 -0
- package/dist/core-B8q_n4sn.js +402 -0
- package/dist/core.d.ts +3 -0
- package/dist/core.js +1 -0
- package/dist/dbsc-plugin-CfQHYOZN.d.ts +781 -0
- package/dist/headers-KXqmHcXY.d.ts +161 -0
- package/dist/index-s7R-j-qI.d.ts +94 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +970 -0
- package/dist/package-ggl7V4ED.js +19 -0
- package/docs/threat-model.md +45 -0
- package/migrations/sqlite/0001_dbsc_session.sql +4 -0
- package/package.json +78 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 KinfeMichael Tariku
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,363 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @assistant-ui/better-auth-dbsc
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**Device Bound Session Credentials for Better Auth: a stolen session cookie stops working on any other machine.**
|
|
4
|
+
|
|
5
|
+
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.
|
|
6
|
+
|
|
7
|
+
Browsers without DBSC ignore the registration header and keep using the normal Better Auth session. Nothing changes for them.
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
pnpm add @assistant-ui/better-auth-dbsc
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
import { betterAuth } from "better-auth";
|
|
15
|
+
import { dbsc } from "@assistant-ui/better-auth-dbsc";
|
|
16
|
+
|
|
17
|
+
export const auth = betterAuth({
|
|
18
|
+
database,
|
|
19
|
+
emailAndPassword: { enabled: true },
|
|
20
|
+
plugins: [dbsc()],
|
|
21
|
+
});
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Then add the `dbscSession` table (see [Schema](#schema)).
|
|
25
|
+
|
|
26
|
+
## What it does not do
|
|
27
|
+
|
|
28
|
+
- It does not protect sessions in browsers without DBSC. They work exactly as before, unless you refuse them on chosen paths with [`freshProof`](#freshproof-sensitive-actions).
|
|
29
|
+
- 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.
|
|
30
|
+
- 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: Bearer` unless the same request also carries that session's live bound cookie. Unbound sessions keep working over bearer. See [Other ways a session arrives](#other-ways-a-session-arrives).
|
|
31
|
+
- It has not been tested against real Chrome. See [Limits](#limits).
|
|
32
|
+
|
|
33
|
+
The threats it covers, and the ones it doesn't, are mapped in [docs/threat-model.md](docs/threat-model.md).
|
|
34
|
+
|
|
35
|
+
## How it works
|
|
36
|
+
|
|
37
|
+
```
|
|
38
|
+
sign-in ──▶ 200 + Secure-Session-Registration: (ES256 RS256);path="/api/auth/dbsc/register";challenge="c1"
|
|
39
|
+
│
|
|
40
|
+
browser makes a TPM key, signs c1 ▼
|
|
41
|
+
POST /api/auth/dbsc/register Secure-Session-Response: <JWT, jti=c1, jwk=public key>
|
|
42
|
+
◀── 200 session config + Set-Cookie: better-auth.dbsc_token (5 min)
|
|
43
|
+
Secure-Session-Challenge: "c2";id="better-auth"
|
|
44
|
+
|
|
45
|
+
… 5 minutes later, before the next request …
|
|
46
|
+
POST /api/auth/dbsc/refresh Sec-Secure-Session-Id: "better-auth"
|
|
47
|
+
◀── 403 + Secure-Session-Challenge: "c3" (browser signs c3 and retries)
|
|
48
|
+
POST /api/auth/dbsc/refresh Secure-Session-Response: <JWT, jti=c3>
|
|
49
|
+
◀── 200 + fresh dbsc_token + next challenge
|
|
50
|
+
◀── 200 {"continue": false} when the session is gone, unbound, or DBSC is off
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
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.
|
|
54
|
+
|
|
55
|
+
Every request then goes through one check:
|
|
56
|
+
|
|
57
|
+
| Session | Bound cookie | Result |
|
|
58
|
+
|---|---|---|
|
|
59
|
+
| Not bound | any | Allowed. This is every browser without DBSC. |
|
|
60
|
+
| Bound | live, and minted for this session | Allowed. |
|
|
61
|
+
| 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`. |
|
|
62
|
+
|
|
63
|
+
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.
|
|
64
|
+
|
|
65
|
+
The check runs on every Better Auth endpoint and on `auth.api.*` calls from your own routes, such as `auth.api.getSession({ headers })`.
|
|
66
|
+
|
|
67
|
+
### Other ways a session arrives
|
|
68
|
+
|
|
69
|
+
The check reads every session token in the request, not only the session cookie, because plugins can hand an endpoint a different one:
|
|
70
|
+
|
|
71
|
+
- **`bearer()`** turns `Authorization: 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 with `Authorization: Bearer` that carries any bound session, through the cookie, the bearer token, a `multiSession()` cookie or `admin_session`, gets `401 DBSC_CREDENTIAL_REQUIRED` unless 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.
|
|
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
|
+
- **`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
|
+
|
|
75
|
+
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
|
+
|
|
77
|
+
## Schema
|
|
78
|
+
|
|
79
|
+
One table, one row per bound session, deleted with its session:
|
|
80
|
+
|
|
81
|
+
| Column | Type | Purpose |
|
|
82
|
+
|---|---|---|
|
|
83
|
+
| `sessionId` | string, unique, references `session.id` | The bound session. |
|
|
84
|
+
| `userId` | string, indexed, references `user.id` | Its user, for listing a user's bound devices. |
|
|
85
|
+
| `publicKey` | string | The device's public JWK, JSON-encoded, with `alg`. |
|
|
86
|
+
| `thumbprint` | string | RFC 7638 thumbprint of the key. |
|
|
87
|
+
| `lastRefreshAt` | date | Issue time of the newest refresh challenge spent. Older ones are refused. |
|
|
88
|
+
| `lastFreshProofAt` | date | Issue time of the newest fresh-proof challenge spent. |
|
|
89
|
+
| `proofCount` | number | How many proofs this binding has spent. |
|
|
90
|
+
| `createdAt` | date | When the session was bound. |
|
|
91
|
+
|
|
92
|
+
Generate the migration for your database the usual way:
|
|
93
|
+
|
|
94
|
+
```sh
|
|
95
|
+
npx @better-auth/cli generate # or: npx @better-auth/cli migrate
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
The SQLite output is checked in at [`migrations/sqlite/0001_dbsc_session.sql`](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" } } })`.
|
|
99
|
+
|
|
100
|
+
To keep bindings somewhere else, such as Redis, KV, or an existing table, pass a [`store`](#store).
|
|
101
|
+
|
|
102
|
+
## Options
|
|
103
|
+
|
|
104
|
+
Every option is optional. The shape follows Better Auth's own plugins:
|
|
105
|
+
- **Optional features** are an object with `enabled`, like `session.cookieCache`.
|
|
106
|
+
- **Durations** are `maxAge` or `expiresIn`, in seconds.
|
|
107
|
+
- **Callbacks:** `onEvent` gets every DBSC event, like the Stripe plugin's `onEvent`, and `shouldRegister` decides which sessions are offered DBSC.
|
|
108
|
+
- **Protocol details** live under `advanced`.
|
|
109
|
+
|
|
110
|
+
These are the defaults:
|
|
111
|
+
|
|
112
|
+
```ts
|
|
113
|
+
dbsc({
|
|
114
|
+
enabled: true, // or () => flags.dbsc, read on every request
|
|
115
|
+
algorithms: ["ES256", "RS256"],
|
|
116
|
+
boundCookieMaxAge: 300,
|
|
117
|
+
challengeExpiresIn: 300,
|
|
118
|
+
scope: { origin: undefined, includeSite: false, exclude: [], rules: [] },
|
|
119
|
+
enforcement: { enabled: true, exclude: [] },
|
|
120
|
+
freshProof: undefined, // { paths, unbound: "allow", expiresIn: 60 }
|
|
121
|
+
rateLimit: { enabled: true, window: 60, max: 600 },
|
|
122
|
+
onEvent: undefined, // (event) => void
|
|
123
|
+
shouldRegister: undefined, // (ctx) => boolean
|
|
124
|
+
now: Date.now, // the clock, for tests
|
|
125
|
+
store: undefined, // the dbscSession table through Better Auth's adapter
|
|
126
|
+
schema: undefined, // rename the model or its fields
|
|
127
|
+
advanced: {
|
|
128
|
+
sessionIdentifier: "better-auth",
|
|
129
|
+
allowedRefreshInitiators: ["*"],
|
|
130
|
+
headers: "both", // "standard" | "legacy" | "both"
|
|
131
|
+
},
|
|
132
|
+
});
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
Invalid options throw at startup with every problem listed at once:
|
|
136
|
+
|
|
137
|
+
```
|
|
138
|
+
BetterAuthError: Invalid dbsc() options:
|
|
139
|
+
- `boundCookieMaxAge` must be a positive integer.
|
|
140
|
+
- `onEvent` must be a function.
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
| Option | What it controls |
|
|
144
|
+
|---|---|
|
|
145
|
+
| `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. |
|
|
146
|
+
| `algorithms` | Signing algorithms offered, in preference order. Only `ES256` and `RS256` are accepted. |
|
|
147
|
+
| `boundCookieMaxAge` | Seconds a copied cookie keeps working. Shorter means more refreshes. |
|
|
148
|
+
| `challengeExpiresIn` | Seconds a registration or refresh challenge is accepted. |
|
|
149
|
+
| `scope.origin` | The origin the DBSC session covers. Defaults to the origin of Better Auth's `baseURL`. |
|
|
150
|
+
| `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. |
|
|
151
|
+
| `scope.exclude` | Path prefixes the browser never holds for a refresh, such as `/assets/`. The DBSC endpoints are always excluded. |
|
|
152
|
+
| `scope.rules` | Raw `scope_specification` entries, sent after `exclude`, for anything `exclude` can't express. |
|
|
153
|
+
| `enforcement.enabled` | `true` drops the cookie of a bound session that has no live bound cookie. `false` binds sessions but never drops or refuses anything. That's how to roll this out: watch `onEvent`, then turn it on. |
|
|
154
|
+
| `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. |
|
|
155
|
+
| `freshProof` | Paths that need a proof made after the request arrived. See [freshProof](#freshproof-sensitive-actions). |
|
|
156
|
+
| `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. |
|
|
157
|
+
| `onEvent` | Receives registrations, refreshes, refusals, and theft signals. See [Events](#events). |
|
|
158
|
+
| `shouldRegister` | Decides per sign-in whether to offer DBSC, for example only for some users. It runs only when a response issues a session token the request didn't carry. Return `false` to skip. |
|
|
159
|
+
| `now` | The clock in milliseconds, for tests. |
|
|
160
|
+
| `store` | A `DbscStore`, or `(ctx) => DbscStore`, to keep bindings outside the default table. See [Store](#store). |
|
|
161
|
+
| `schema` | Renames the `dbscSession` model or its fields. |
|
|
162
|
+
| `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. |
|
|
163
|
+
| `advanced.allowedRefreshInitiators` | Sites whose links and redirects may trigger a refresh. `["*"]` lets a user coming back from an OAuth provider arrive signed in. `[]` allows same-site only. |
|
|
164
|
+
| `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. |
|
|
165
|
+
|
|
166
|
+
## freshProof: sensitive actions
|
|
167
|
+
|
|
168
|
+
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:
|
|
169
|
+
|
|
170
|
+
```ts
|
|
171
|
+
dbsc({
|
|
172
|
+
freshProof: {
|
|
173
|
+
paths: {
|
|
174
|
+
"/change-email": {},
|
|
175
|
+
"/passkey/add-passkey": {},
|
|
176
|
+
"/delete-user": { unbound: "deny" }, // only from a device-bound session
|
|
177
|
+
},
|
|
178
|
+
unbound: "fresh-session", // everything else: plain sessions must be recent
|
|
179
|
+
expiresIn: 60,
|
|
180
|
+
},
|
|
181
|
+
});
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
On a bound session, the first attempt is refused with `403 DBSC_FRESH_PROOF_REQUIRED` and its bound cookie removed. The browser refreshes with its key, and the 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.
|
|
185
|
+
|
|
186
|
+
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.
|
|
187
|
+
|
|
188
|
+
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.
|
|
189
|
+
|
|
190
|
+
`unbound` decides what sessions that aren't bound get on those paths:
|
|
191
|
+
- `"allow"` passes them.
|
|
192
|
+
- `"fresh-session"` passes them only while they're younger than Better Auth's `session.freshAge`, else `403 SESSION_NOT_FRESH`.
|
|
193
|
+
- `"deny"` refuses them with `403 DBSC_BINDING_REQUIRED`.
|
|
194
|
+
|
|
195
|
+
For your own routes, call the same check from server code:
|
|
196
|
+
|
|
197
|
+
```ts
|
|
198
|
+
const { headers, response } = await auth.api.requireFreshProof({
|
|
199
|
+
headers: request.headers,
|
|
200
|
+
body: { action: "export-data" },
|
|
201
|
+
returnHeaders: true,
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
if (response.state === "challenge") {
|
|
205
|
+
// Send `headers` back with a 403. The browser refreshes with its key; the retry answers.
|
|
206
|
+
return new Response(null, { status: 403, headers });
|
|
207
|
+
}
|
|
208
|
+
// "answered": bound, and proven since the challenge.
|
|
209
|
+
// "unbound", "no-session", "off": apply your own policy.
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
`requireFreshProof` is server-only and has no HTTP route.
|
|
213
|
+
|
|
214
|
+
## Status
|
|
215
|
+
|
|
216
|
+
`GET /api/auth/dbsc/get-status`, `auth.api.getDbscStatus({ headers })`, or `authClient.dbsc.getStatus()` answers `{ state }`:
|
|
217
|
+
|
|
218
|
+
| `state` | Meaning |
|
|
219
|
+
|---|---|
|
|
220
|
+
| `"bound"` | Bound to a device key and proven by a live bound cookie. |
|
|
221
|
+
| `"unbound"` | A plain session. |
|
|
222
|
+
| `"no-session"` | Signed out, or a bound session without its cookie. |
|
|
223
|
+
| `"off"` | `enabled` is false. |
|
|
224
|
+
|
|
225
|
+
## Events
|
|
226
|
+
|
|
227
|
+
```ts
|
|
228
|
+
dbsc({
|
|
229
|
+
onEvent(event) {
|
|
230
|
+
if (event.type === "proof_rejected") revokeUserSessions(event.userId);
|
|
231
|
+
metrics.increment(`dbsc.${event.type}`);
|
|
232
|
+
},
|
|
233
|
+
shouldRegister: (ctx) => !ctx.context.newSession?.user.email.endsWith("@bots.example.com"),
|
|
234
|
+
});
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
| `type` | When |
|
|
238
|
+
|---|---|
|
|
239
|
+
| `registered` | A session was bound. |
|
|
240
|
+
| `registration_refused` | With a `reason`: `invalid_challenge`, `invalid_proof`, `bound_to_other_key`, or `disabled`. |
|
|
241
|
+
| `refreshed` | A bound cookie was renewed. |
|
|
242
|
+
| `refresh_challenged` | With a `reason`: `missing_proof` (normal), `stale_challenge`, or `replayed`. |
|
|
243
|
+
| `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. |
|
|
244
|
+
| `credential_missing` | A bound session arrived without its bound cookie, `via` `cookie`, `bearer`, `multi-session` or `admin-session`. Once per session per request. One now and then is normal. A burst means a copied cookie. |
|
|
245
|
+
| `fresh_proof_challenged`, `fresh_proof_answered` | The `freshProof` round trip, with the `action`. |
|
|
246
|
+
| `unbound_refused` | A plain session was refused on a `freshProof` path, with the `policy`. |
|
|
247
|
+
| `terminated` | The browser was told to end its DBSC session: `disabled`, `no_session`, `not_bound`, or `other_identifier`. |
|
|
248
|
+
|
|
249
|
+
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.
|
|
250
|
+
|
|
251
|
+
## Endpoints
|
|
252
|
+
|
|
253
|
+
| Path | Server | Client | Called by |
|
|
254
|
+
|---|---|---|---|
|
|
255
|
+
| `POST /dbsc/register` | `auth.api.registerDbscSession` | — | The browser, after sign-in. |
|
|
256
|
+
| `POST /dbsc/refresh` | `auth.api.refreshDbscSession` | — | The browser, when the bound cookie lapses. |
|
|
257
|
+
| `GET /dbsc/get-status` | `auth.api.getDbscStatus` | `authClient.dbsc.getStatus` | Your app. |
|
|
258
|
+
| none, server-only | `auth.api.requireFreshProof` | — | Your server code. |
|
|
259
|
+
|
|
260
|
+
The three HTTP endpoints carry OpenAPI metadata, so Better Auth's `openAPI()` plugin documents them.
|
|
261
|
+
|
|
262
|
+
## Error codes
|
|
263
|
+
|
|
264
|
+
`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.
|
|
265
|
+
|
|
266
|
+
| Code | Status | When |
|
|
267
|
+
|---|---|---|
|
|
268
|
+
| `DBSC_CREDENTIAL_REQUIRED` | 401 | A request with `Authorization: Bearer` carried a bound session without its live bound cookie, or alongside another session. |
|
|
269
|
+
| `DBSC_FRESH_PROOF_REQUIRED` | 403 | A `freshProof` path needs a proof the browser hasn't made yet. |
|
|
270
|
+
| `DBSC_BINDING_REQUIRED` | 403 | A `freshProof` path with `unbound: "deny"` got a plain session. |
|
|
271
|
+
| `SESSION_NOT_FRESH` | 403 | Better Auth's own code, for `unbound: "fresh-session"`. |
|
|
272
|
+
| `DBSC_CHALLENGE_REQUIRED` | 403 | A refresh needs a proof over the new challenge. The browser retries. |
|
|
273
|
+
| `DBSC_SESSION_ID_REQUIRED` | 400 | A refresh without `Sec-Secure-Session-Id`, so not from the browser. |
|
|
274
|
+
| `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`. |
|
|
275
|
+
| `DBSC_SESSION_REQUIRED` | 401 | A registration without a signed-in session. |
|
|
276
|
+
|
|
277
|
+
## Store
|
|
278
|
+
|
|
279
|
+
```ts
|
|
280
|
+
interface DbscStore {
|
|
281
|
+
find(sessionId: string): Promise<DbscBinding | null>;
|
|
282
|
+
bind(binding: DbscBinding): Promise<boolean>; // false if the session was already bound
|
|
283
|
+
spend(sessionId: string, kind: "refresh" | "fresh-proof", issuedAtMs: number): Promise<boolean>;
|
|
284
|
+
delete(sessionId: string): Promise<void>; // the session ended: drop the binding and its spend state
|
|
285
|
+
}
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
`delete` runs whenever Better Auth deletes a session: sign-out, `revoke-session(s)`, a deleted user, or an expired session it comes across. Better Auth leaves sessions that expire unseen in place, so prune bindings whose session is gone the way you prune sessions. 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.
|
|
289
|
+
|
|
290
|
+
`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.
|
|
291
|
+
|
|
292
|
+
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`.
|
|
293
|
+
|
|
294
|
+
## Client
|
|
295
|
+
|
|
296
|
+
The browser drives DBSC by itself, so the client needs no code. The client plugin adds types, the error codes, and `getStatus`:
|
|
297
|
+
|
|
298
|
+
```ts
|
|
299
|
+
import { createAuthClient } from "better-auth/react";
|
|
300
|
+
import { dbscClient } from "@assistant-ui/better-auth-dbsc/client";
|
|
301
|
+
|
|
302
|
+
export const authClient = createAuthClient({ plugins: [dbscClient()] });
|
|
303
|
+
const { data } = await authClient.dbsc.getStatus(); // { state: "bound" | ... }
|
|
304
|
+
```
|
|
305
|
+
|
|
306
|
+
## Building blocks
|
|
307
|
+
|
|
308
|
+
`@assistant-ui/better-auth-dbsc/core` exports the protocol pieces without Better Auth, for another framework or your own middleware:
|
|
309
|
+
|
|
310
|
+
```ts
|
|
311
|
+
import {
|
|
312
|
+
formatRegistrationHeader,
|
|
313
|
+
formatChallengeHeader,
|
|
314
|
+
verifyRegistrationProof,
|
|
315
|
+
verifyRefreshProof,
|
|
316
|
+
createDbscChallenge,
|
|
317
|
+
readDbscChallenge,
|
|
318
|
+
createBoundToken,
|
|
319
|
+
readBoundToken,
|
|
320
|
+
createFreshProofToken,
|
|
321
|
+
readFreshProofToken,
|
|
322
|
+
readFreshProofNonce,
|
|
323
|
+
} from "@assistant-ui/better-auth-dbsc/core";
|
|
324
|
+
|
|
325
|
+
const { publicKey, thumbprint } = await verifyRegistrationProof(jwt, {
|
|
326
|
+
challenge,
|
|
327
|
+
expectedOrigin: "https://app.example.com",
|
|
328
|
+
});
|
|
329
|
+
```
|
|
330
|
+
|
|
331
|
+
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`.
|
|
332
|
+
|
|
333
|
+
## Try it locally
|
|
334
|
+
|
|
335
|
+
You don't need Chrome to exercise the cryptography. The tests play the browser with [`jose`](https://github.com/panva/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.
|
|
336
|
+
|
|
337
|
+
```sh
|
|
338
|
+
pnpm install
|
|
339
|
+
pnpm test # registration, refresh, replay races, enforcement, freshProof, events, threat model
|
|
340
|
+
pnpm example # http://localhost:3000: a sign-up form and a protected /me route
|
|
341
|
+
# listens on 127.0.0.1 (HOST to change); random secret per run unless BETTER_AUTH_SECRET
|
|
342
|
+
```
|
|
343
|
+
|
|
344
|
+
CI 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.
|
|
345
|
+
|
|
346
|
+
## Releasing
|
|
347
|
+
|
|
348
|
+
```sh
|
|
349
|
+
pnpm release # bumpp: commits "chore: release vX.Y.Z", tags vX.Y.Z, pushes
|
|
350
|
+
```
|
|
351
|
+
|
|
352
|
+
The tag runs the release workflow in the `npm-publish` environment, which waits for a required reviewer to approve and accepts only `v*` tags. 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.
|
|
353
|
+
|
|
354
|
+
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`.
|
|
355
|
+
|
|
356
|
+
## Limits
|
|
357
|
+
|
|
358
|
+
- **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 (`jwk` or `key`) and a string `iat`. Try it on Chrome 146+ on Windows before relying on it.
|
|
359
|
+
- **Paths outside `freshProof` stay exposed for up to `boundCookieMaxAge`.** Someone who copies both cookies can use them until the bound cookie expires.
|
|
360
|
+
- **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 the `Sec-Secure-Session-Id` header, which a page can't send cross-site without a preflight.
|
|
361
|
+
- **Two database reads per request for each session token it carries.** The gate reads the session and its binding (`findSession`, then the `dbscSession` row) to know whether a bound cookie is required. This happens on every Better Auth call, `getSession` included, even with `session.cookieCache` on. Each `multiSession()` or `admin_session` cookie adds two more.
|
|
362
|
+
- **The `authorization` registration parameter isn't sent.** `verifyRegistrationProof` checks it when you pass one.
|
|
363
|
+
- **Only the SQLite migration is checked in.** Postgres and MySQL come from the Better Auth CLI and haven't been tested here.
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { h as DBSC_ERROR_CODES, p as dbsc } from "./dbsc-plugin-CfQHYOZN.js";
|
|
2
|
+
/**
|
|
3
|
+
* Client half of {@link dbsc}. The browser drives DBSC by itself; this adds
|
|
4
|
+
* `authClient.dbsc.getStatus()` and the plugin's error codes to the client.
|
|
5
|
+
*/
|
|
6
|
+
export declare const dbscClient: () => {
|
|
7
|
+
id: "dbsc";
|
|
8
|
+
version: string;
|
|
9
|
+
$InferServerPlugin: ReturnType<typeof dbsc>;
|
|
10
|
+
pathMethods: {
|
|
11
|
+
"/dbsc/get-status": "GET";
|
|
12
|
+
};
|
|
13
|
+
$ERROR_CODES: {
|
|
14
|
+
DBSC_BINDING_REQUIRED: import("better-auth").RawError<"DBSC_BINDING_REQUIRED">;
|
|
15
|
+
DBSC_BOUND_TO_OTHER_KEY: import("better-auth").RawError<"DBSC_BOUND_TO_OTHER_KEY">;
|
|
16
|
+
DBSC_CHALLENGE_REQUIRED: import("better-auth").RawError<"DBSC_CHALLENGE_REQUIRED">;
|
|
17
|
+
DBSC_CREDENTIAL_REQUIRED: import("better-auth").RawError<"DBSC_CREDENTIAL_REQUIRED">;
|
|
18
|
+
DBSC_DISABLED: import("better-auth").RawError<"DBSC_DISABLED">;
|
|
19
|
+
DBSC_FRESH_PROOF_REQUIRED: import("better-auth").RawError<"DBSC_FRESH_PROOF_REQUIRED">;
|
|
20
|
+
DBSC_INVALID_CHALLENGE: import("better-auth").RawError<"DBSC_INVALID_CHALLENGE">;
|
|
21
|
+
DBSC_INVALID_PROOF: import("better-auth").RawError<"DBSC_INVALID_PROOF">;
|
|
22
|
+
DBSC_PROOF_REQUIRED: import("better-auth").RawError<"DBSC_PROOF_REQUIRED">;
|
|
23
|
+
DBSC_SESSION_ID_REQUIRED: import("better-auth").RawError<"DBSC_SESSION_ID_REQUIRED">;
|
|
24
|
+
DBSC_SESSION_REQUIRED: import("better-auth").RawError<"DBSC_SESSION_REQUIRED">;
|
|
25
|
+
};
|
|
26
|
+
};
|
|
27
|
+
export { DBSC_ERROR_CODES };
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { n as DBSC_ERROR_CODES, t as version } from "./package-ggl7V4ED.js";
|
|
2
|
+
// src/client.ts
|
|
3
|
+
/**
|
|
4
|
+
* Client half of {@link dbsc}. The browser drives DBSC by itself; this adds
|
|
5
|
+
* `authClient.dbsc.getStatus()` and the plugin's error codes to the client.
|
|
6
|
+
*/
|
|
7
|
+
const dbscClient = () => ({
|
|
8
|
+
id: "dbsc",
|
|
9
|
+
version,
|
|
10
|
+
$InferServerPlugin: {},
|
|
11
|
+
pathMethods: { "/dbsc/get-status": "GET" },
|
|
12
|
+
$ERROR_CODES: DBSC_ERROR_CODES
|
|
13
|
+
});
|
|
14
|
+
export { DBSC_ERROR_CODES, dbscClient };
|