@assistant-ui/better-auth-dbsc 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +364 -2
- package/dist/client.d.ts +27 -0
- package/dist/client.js +14 -0
- package/dist/core-Crgd63SH.js +409 -0
- package/dist/core.d.ts +3 -0
- package/dist/core.js +1 -0
- package/dist/dbsc-plugin-D9MKOgZP.d.ts +784 -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 +977 -0
- package/dist/package-DTjet4zW.js +19 -0
- package/docs/threat-model.md +48 -0
- package/migrations/sqlite/0001_dbsc_session.sql +4 -0
- package/package.json +78 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,977 @@
|
|
|
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-Crgd63SH.js";
|
|
5
|
+
import { n as DBSC_ERROR_CODES, t as version } from "./package-DTjet4zW.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));
|
|
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
|
+
disableCookieCache: ctx.context.options.session?.cookieCache?.enabled === true && (cookieToken !== null && cookieState.kind === "none" || bearerToken !== null && bearerState.kind === "none"),
|
|
443
|
+
sessions: sessions.filter((state, i) => sessions.indexOf(state) === i)
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
/**
|
|
447
|
+
* A fresh proof for `action`: answered once by a bound cookie that a refresh minted
|
|
448
|
+
* while the browser held this action's challenge, or a new challenge with the bound
|
|
449
|
+
* cookie removed so the browser refreshes before the retry. The cookie names the
|
|
450
|
+
* challenge it answers: comparing issue times would trust clocks that differ between
|
|
451
|
+
* instances, and a copied cookie from a node running ahead would look newer.
|
|
452
|
+
*/
|
|
453
|
+
async function checkFreshProof(ctx, state, action) {
|
|
454
|
+
const { bound, freshProof } = cookies(ctx);
|
|
455
|
+
const challenge = await readFreshProofToken({
|
|
456
|
+
secret: ctx.context.secret,
|
|
457
|
+
sessionToken: state.token,
|
|
458
|
+
action,
|
|
459
|
+
token: ctx.getCookie(freshProof.name),
|
|
460
|
+
nowMs: config.now(),
|
|
461
|
+
ttlSeconds: config.freshProof.expiresIn
|
|
462
|
+
});
|
|
463
|
+
if (challenge && state.answers === challenge.nonce && await storeFor(ctx.context).spend(state.session.id, "fresh-proof", challenge.issuedAtMs)) {
|
|
464
|
+
ctx.setCookie(freshProof.name, "", {
|
|
465
|
+
...freshProof.attributes,
|
|
466
|
+
maxAge: 0
|
|
467
|
+
});
|
|
468
|
+
await emit(ctx, {
|
|
469
|
+
type: "fresh_proof_answered",
|
|
470
|
+
...ids(state.session),
|
|
471
|
+
action
|
|
472
|
+
});
|
|
473
|
+
return "answered";
|
|
474
|
+
}
|
|
475
|
+
const next = await createFreshProofToken({
|
|
476
|
+
secret: ctx.context.secret,
|
|
477
|
+
sessionToken: state.token,
|
|
478
|
+
action,
|
|
479
|
+
nowMs: config.now()
|
|
480
|
+
});
|
|
481
|
+
ctx.setCookie(bound.name, "", {
|
|
482
|
+
...bound.attributes,
|
|
483
|
+
maxAge: 0
|
|
484
|
+
});
|
|
485
|
+
ctx.setCookie(freshProof.name, next, freshProof.attributes);
|
|
486
|
+
await emit(ctx, {
|
|
487
|
+
type: "fresh_proof_challenged",
|
|
488
|
+
...ids(state.session),
|
|
489
|
+
action
|
|
490
|
+
});
|
|
491
|
+
return "challenge";
|
|
492
|
+
}
|
|
493
|
+
/** Applies a `freshProof` path's policy to a session that is not bound. */
|
|
494
|
+
async function unboundPolicy(ctx, state, action, policy) {
|
|
495
|
+
if (policy === "allow") return;
|
|
496
|
+
if (policy === "fresh-session") {
|
|
497
|
+
const freshAge = ctx.context.sessionConfig.freshAge;
|
|
498
|
+
if (freshAge === 0 || config.now() - new Date(state.session.createdAt).getTime() < freshAge * 1e3) return;
|
|
499
|
+
}
|
|
500
|
+
await emit(ctx, {
|
|
501
|
+
type: "unbound_refused",
|
|
502
|
+
...ids(state.session),
|
|
503
|
+
action,
|
|
504
|
+
policy
|
|
505
|
+
});
|
|
506
|
+
throw APIError.from("FORBIDDEN", policy === "deny" ? DBSC_ERROR_CODES.DBSC_BINDING_REQUIRED : BASE_ERROR_CODES.SESSION_NOT_FRESH);
|
|
507
|
+
}
|
|
508
|
+
function cookies(ctx) {
|
|
509
|
+
return {
|
|
510
|
+
bound: ctx.context.createAuthCookie(DBSC_COOKIE_KEYS.bound, { maxAge: config.boundCookieMaxAge }),
|
|
511
|
+
freshProof: ctx.context.createAuthCookie(DBSC_COOKIE_KEYS.freshProof, { maxAge: config.freshProof.expiresIn })
|
|
512
|
+
};
|
|
513
|
+
}
|
|
514
|
+
async function setBoundCookie(ctx, sessionToken, { expiresAtMs, answers = null }) {
|
|
515
|
+
const { bound } = cookies(ctx);
|
|
516
|
+
const value = await createBoundToken({
|
|
517
|
+
secret: ctx.context.secret,
|
|
518
|
+
sessionToken,
|
|
519
|
+
expiresAtMs,
|
|
520
|
+
answers
|
|
521
|
+
});
|
|
522
|
+
const maxAge = Math.max(0, Math.ceil((expiresAtMs - config.now()) / 1e3));
|
|
523
|
+
ctx.setCookie(bound.name, value, {
|
|
524
|
+
...bound.attributes,
|
|
525
|
+
maxAge
|
|
526
|
+
});
|
|
527
|
+
}
|
|
528
|
+
async function setRefreshChallenge(ctx, sessionToken) {
|
|
529
|
+
const challenge = await createDbscChallenge({
|
|
530
|
+
secret: ctx.context.secret,
|
|
531
|
+
purpose: "refresh",
|
|
532
|
+
sessionToken,
|
|
533
|
+
nowMs: config.now()
|
|
534
|
+
});
|
|
535
|
+
const value = formatChallengeHeader({
|
|
536
|
+
challenge,
|
|
537
|
+
sessionId: config.advanced.sessionIdentifier
|
|
538
|
+
});
|
|
539
|
+
for (const name of getDbscHeaderNames("challenge", config.advanced.headers)) ctx.setHeader(name, value);
|
|
540
|
+
}
|
|
541
|
+
function sessionConfig(ctx) {
|
|
542
|
+
const { bound } = cookies(ctx);
|
|
543
|
+
const base = basePath(ctx);
|
|
544
|
+
const exclude = [`${base}/dbsc/`, ...config.scope.exclude].map((path) => ({
|
|
545
|
+
type: "exclude",
|
|
546
|
+
path
|
|
547
|
+
}));
|
|
548
|
+
return {
|
|
549
|
+
session_identifier: config.advanced.sessionIdentifier,
|
|
550
|
+
refresh_url: `${base}${DBSC_REFRESH_PATH}`,
|
|
551
|
+
scope: {
|
|
552
|
+
origin: appOrigin(ctx),
|
|
553
|
+
include_site: config.scope.includeSite,
|
|
554
|
+
scope_specification: [...exclude, ...config.scope.rules]
|
|
555
|
+
},
|
|
556
|
+
...config.advanced.allowedRefreshInitiators.length > 0 ? { allowed_refresh_initiators: config.advanced.allowedRefreshInitiators } : {},
|
|
557
|
+
credentials: [{
|
|
558
|
+
type: "cookie",
|
|
559
|
+
name: bound.name,
|
|
560
|
+
attributes: formatCookieAttributes({
|
|
561
|
+
...bound.attributes,
|
|
562
|
+
sameSite: typeof bound.attributes.sameSite === "string" ? bound.attributes.sameSite : void 0
|
|
563
|
+
})
|
|
564
|
+
}]
|
|
565
|
+
};
|
|
566
|
+
}
|
|
567
|
+
async function terminate(ctx, reason) {
|
|
568
|
+
const { bound } = cookies(ctx);
|
|
569
|
+
ctx.setCookie(bound.name, "", {
|
|
570
|
+
...bound.attributes,
|
|
571
|
+
maxAge: 0
|
|
572
|
+
});
|
|
573
|
+
await emit(ctx, {
|
|
574
|
+
type: "terminated",
|
|
575
|
+
reason
|
|
576
|
+
});
|
|
577
|
+
return ctx.json(DBSC_TERMINATE);
|
|
578
|
+
}
|
|
579
|
+
function appOrigin(ctx) {
|
|
580
|
+
return config.scope.origin ?? new URL(ctx.context.baseURL).origin;
|
|
581
|
+
}
|
|
582
|
+
const enforced = (path) => config.enforcement.enabled && path !== "/dbsc/register" && path !== "/dbsc/refresh" && !isExcluded(path, config.enforcement.exclude);
|
|
583
|
+
return {
|
|
584
|
+
id: "dbsc",
|
|
585
|
+
version,
|
|
586
|
+
schema: mergeSchema(dbscSchema, options?.schema),
|
|
587
|
+
init(ctx) {
|
|
588
|
+
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().");
|
|
589
|
+
const skip = ctx.skipOriginCheck;
|
|
590
|
+
const paths = [DBSC_REGISTER_PATH, DBSC_REFRESH_PATH];
|
|
591
|
+
return {
|
|
592
|
+
options: { databaseHooks: { session: { delete: { async after(session) {
|
|
593
|
+
await storeFor(ctx).delete(session.id);
|
|
594
|
+
} } } } },
|
|
595
|
+
...skip === true ? {} : { context: { skipOriginCheck: Array.isArray(skip) ? [...skip, ...paths] : paths } }
|
|
596
|
+
};
|
|
597
|
+
},
|
|
598
|
+
endpoints: {
|
|
599
|
+
/**
|
|
600
|
+
* ### Endpoint
|
|
601
|
+
*
|
|
602
|
+
* POST `/dbsc/register`
|
|
603
|
+
*
|
|
604
|
+
* ### API Methods
|
|
605
|
+
*
|
|
606
|
+
* **server:**
|
|
607
|
+
* `auth.api.registerDbscSession`
|
|
608
|
+
*
|
|
609
|
+
* The browser calls this itself: it posts a proof signed by its new key over the
|
|
610
|
+
* challenge from the sign-in response. Your code never needs to.
|
|
611
|
+
*/
|
|
612
|
+
registerDbscSession: createAuthEndpoint(DBSC_REGISTER_PATH, {
|
|
613
|
+
method: "POST",
|
|
614
|
+
disableBody: true,
|
|
615
|
+
requireHeaders: true,
|
|
616
|
+
metadata: { openapi: {
|
|
617
|
+
summary: "Register a device-bound session",
|
|
618
|
+
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.",
|
|
619
|
+
responses: { 200: sessionConfigResponse }
|
|
620
|
+
} }
|
|
621
|
+
}, async (ctx) => {
|
|
622
|
+
if (!await config.enabled()) throw APIError.from("BAD_REQUEST", DBSC_ERROR_CODES.DBSC_DISABLED);
|
|
623
|
+
const proof = parseProofHeader(readDbscHeader(ctx.headers, "response"));
|
|
624
|
+
if (!proof) throw APIError.from("BAD_REQUEST", DBSC_ERROR_CODES.DBSC_PROOF_REQUIRED);
|
|
625
|
+
const token = await readSessionToken(ctx);
|
|
626
|
+
const found = token ? await ctx.context.internalAdapter.findSession(token) : null;
|
|
627
|
+
if (!token || !found || new Date(found.session.expiresAt).getTime() <= config.now()) throw APIError.from("UNAUTHORIZED", DBSC_ERROR_CODES.DBSC_SESSION_REQUIRED);
|
|
628
|
+
const jti = readUnverifiedChallenge(proof);
|
|
629
|
+
const challenge = await readDbscChallenge({
|
|
630
|
+
secret: ctx.context.secret,
|
|
631
|
+
purpose: "register",
|
|
632
|
+
sessionToken: token,
|
|
633
|
+
challenge: jti,
|
|
634
|
+
nowMs: config.now(),
|
|
635
|
+
ttlSeconds: config.challengeExpiresIn
|
|
636
|
+
});
|
|
637
|
+
const refused = async (reason, error, cause) => {
|
|
638
|
+
await emit(ctx, {
|
|
639
|
+
type: "registration_refused",
|
|
640
|
+
...ids(found.session),
|
|
641
|
+
reason
|
|
642
|
+
});
|
|
643
|
+
const refusal = APIError.from("BAD_REQUEST", error);
|
|
644
|
+
if (cause !== void 0) refusal.cause = cause;
|
|
645
|
+
return refusal;
|
|
646
|
+
};
|
|
647
|
+
if (!jti || !challenge) throw await refused("invalid_challenge", DBSC_ERROR_CODES.DBSC_INVALID_CHALLENGE);
|
|
648
|
+
let verified;
|
|
649
|
+
try {
|
|
650
|
+
verified = await verifyRegistrationProof(proof, {
|
|
651
|
+
challenge: jti,
|
|
652
|
+
algorithms: config.algorithms,
|
|
653
|
+
expectedOrigin: appOrigin(ctx)
|
|
654
|
+
});
|
|
655
|
+
} catch (error) {
|
|
656
|
+
throw await refused("invalid_proof", DBSC_ERROR_CODES.DBSC_INVALID_PROOF, error);
|
|
657
|
+
}
|
|
658
|
+
const store = storeFor(ctx.context);
|
|
659
|
+
const { session } = found;
|
|
660
|
+
const existing = await store.find(session.id);
|
|
661
|
+
if (!existing && await store.bind({
|
|
662
|
+
sessionId: session.id,
|
|
663
|
+
userId: session.userId,
|
|
664
|
+
publicKey: verified.publicKey,
|
|
665
|
+
thumbprint: verified.thumbprint
|
|
666
|
+
})) await emit(ctx, {
|
|
667
|
+
type: "registered",
|
|
668
|
+
...ids(session)
|
|
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);
|
|
671
|
+
await setBoundCookie(ctx, token, { expiresAtMs: challenge.issuedAtMs + config.boundCookieMaxAge * 1e3 });
|
|
672
|
+
await setRefreshChallenge(ctx, token);
|
|
673
|
+
return ctx.json(sessionConfig(ctx));
|
|
674
|
+
}),
|
|
675
|
+
/**
|
|
676
|
+
* ### Endpoint
|
|
677
|
+
*
|
|
678
|
+
* POST `/dbsc/refresh`
|
|
679
|
+
*
|
|
680
|
+
* ### API Methods
|
|
681
|
+
*
|
|
682
|
+
* **server:**
|
|
683
|
+
* `auth.api.refreshDbscSession`
|
|
684
|
+
*
|
|
685
|
+
* The browser calls this itself when the bound cookie lapses. No proof, or a stale
|
|
686
|
+
* one: 403 with a new challenge. The bound key's proof: a new cookie. A session that
|
|
687
|
+
* is over or not bound ends the browser's DBSC session.
|
|
688
|
+
*/
|
|
689
|
+
refreshDbscSession: createAuthEndpoint(DBSC_REFRESH_PATH, {
|
|
690
|
+
method: "POST",
|
|
691
|
+
disableBody: true,
|
|
692
|
+
requireHeaders: true,
|
|
693
|
+
metadata: { openapi: {
|
|
694
|
+
summary: "Refresh a device-bound session",
|
|
695
|
+
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.",
|
|
696
|
+
responses: {
|
|
697
|
+
200: sessionConfigResponse,
|
|
698
|
+
403: { description: "Sign the challenge in `Secure-Session-Challenge` and retry." }
|
|
699
|
+
}
|
|
700
|
+
} }
|
|
701
|
+
}, async (ctx) => {
|
|
702
|
+
const claimedId = readDbscHeader(ctx.headers, "sessionId");
|
|
703
|
+
if (claimedId === null) throw APIError.from("BAD_REQUEST", DBSC_ERROR_CODES.DBSC_SESSION_ID_REQUIRED);
|
|
704
|
+
if (!await config.enabled()) return terminate(ctx, "disabled");
|
|
705
|
+
if (parseSfString(claimedId) !== config.advanced.sessionIdentifier) return terminate(ctx, "other_identifier");
|
|
706
|
+
const token = await readSessionToken(ctx);
|
|
707
|
+
const found = token ? await ctx.context.internalAdapter.findSession(token) : null;
|
|
708
|
+
if (!token || !found || new Date(found.session.expiresAt).getTime() <= config.now()) return terminate(ctx, "no_session");
|
|
709
|
+
const store = storeFor(ctx.context);
|
|
710
|
+
const binding = await store.find(found.session.id);
|
|
711
|
+
if (!binding) return terminate(ctx, "not_bound");
|
|
712
|
+
const askAgain = async (reason) => {
|
|
713
|
+
await emit(ctx, {
|
|
714
|
+
type: "refresh_challenged",
|
|
715
|
+
...ids(found.session),
|
|
716
|
+
reason
|
|
717
|
+
});
|
|
718
|
+
await setRefreshChallenge(ctx, token);
|
|
719
|
+
throw APIError.from("FORBIDDEN", DBSC_ERROR_CODES.DBSC_CHALLENGE_REQUIRED);
|
|
720
|
+
};
|
|
721
|
+
const proof = parseProofHeader(readDbscHeader(ctx.headers, "response"));
|
|
722
|
+
if (!proof) return askAgain("missing_proof");
|
|
723
|
+
const jti = readUnverifiedChallenge(proof);
|
|
724
|
+
const challenge = await readDbscChallenge({
|
|
725
|
+
secret: ctx.context.secret,
|
|
726
|
+
purpose: "refresh",
|
|
727
|
+
sessionToken: token,
|
|
728
|
+
challenge: jti,
|
|
729
|
+
nowMs: config.now(),
|
|
730
|
+
ttlSeconds: config.challengeExpiresIn
|
|
731
|
+
});
|
|
732
|
+
if (!jti || !challenge) return askAgain("stale_challenge");
|
|
733
|
+
try {
|
|
734
|
+
await verifyRefreshProof(proof, {
|
|
735
|
+
publicKey: binding.publicKey,
|
|
736
|
+
challenge: jti,
|
|
737
|
+
expectedOrigin: appOrigin(ctx)
|
|
738
|
+
});
|
|
739
|
+
} catch (error) {
|
|
740
|
+
const reason = error instanceof Error && "code" in error ? String(error.code) : "INVALID_PROOF";
|
|
741
|
+
await emit(ctx, {
|
|
742
|
+
type: "proof_rejected",
|
|
743
|
+
...ids(found.session),
|
|
744
|
+
reason
|
|
745
|
+
});
|
|
746
|
+
await setRefreshChallenge(ctx, token);
|
|
747
|
+
throw APIError.from("FORBIDDEN", DBSC_ERROR_CODES.DBSC_CHALLENGE_REQUIRED);
|
|
748
|
+
}
|
|
749
|
+
if (!await store.spend(found.session.id, "refresh", challenge.issuedAtMs)) return askAgain("replayed");
|
|
750
|
+
await emit(ctx, {
|
|
751
|
+
type: "refreshed",
|
|
752
|
+
...ids(found.session)
|
|
753
|
+
});
|
|
754
|
+
await setBoundCookie(ctx, token, {
|
|
755
|
+
expiresAtMs: config.now() + config.boundCookieMaxAge * 1e3,
|
|
756
|
+
answers: readFreshProofNonce(ctx.getCookie(cookies(ctx).freshProof.name))
|
|
757
|
+
});
|
|
758
|
+
await setRefreshChallenge(ctx, token);
|
|
759
|
+
return ctx.json(sessionConfig(ctx));
|
|
760
|
+
}),
|
|
761
|
+
/**
|
|
762
|
+
* ### Endpoint
|
|
763
|
+
*
|
|
764
|
+
* GET `/dbsc/get-status`
|
|
765
|
+
*
|
|
766
|
+
* ### API Methods
|
|
767
|
+
*
|
|
768
|
+
* **server:**
|
|
769
|
+
* `auth.api.getDbscStatus`
|
|
770
|
+
*
|
|
771
|
+
* **client:**
|
|
772
|
+
* `authClient.dbsc.getStatus`
|
|
773
|
+
*
|
|
774
|
+
* Whether the current session is bound to this device:
|
|
775
|
+
* `{ state: "bound" | "unbound" | "no-session" | "off" }`. For a "this device is
|
|
776
|
+
* protected" line in account settings.
|
|
777
|
+
*/
|
|
778
|
+
getDbscStatus: createAuthEndpoint("/dbsc/get-status", {
|
|
779
|
+
method: "GET",
|
|
780
|
+
requireHeaders: true,
|
|
781
|
+
metadata: { openapi: {
|
|
782
|
+
summary: "Get the device binding of the current session",
|
|
783
|
+
description: "Answers whether the current session is bound to this device, proven by a live bound cookie.",
|
|
784
|
+
responses: { 200: {
|
|
785
|
+
description: "Successful response",
|
|
786
|
+
content: { "application/json": { schema: {
|
|
787
|
+
type: "object",
|
|
788
|
+
properties: { state: {
|
|
789
|
+
type: "string",
|
|
790
|
+
enum: [
|
|
791
|
+
"bound",
|
|
792
|
+
"unbound",
|
|
793
|
+
"no-session",
|
|
794
|
+
"off"
|
|
795
|
+
]
|
|
796
|
+
} },
|
|
797
|
+
required: ["state"]
|
|
798
|
+
} } }
|
|
799
|
+
} }
|
|
800
|
+
} }
|
|
801
|
+
}, async (ctx) => {
|
|
802
|
+
const answer = (state) => ctx.json({ state });
|
|
803
|
+
if (!await config.enabled()) return answer("off");
|
|
804
|
+
const session = await sessionState(ctx);
|
|
805
|
+
if (session.kind === "bound") return answer("bound");
|
|
806
|
+
if (session.kind === "plain") return answer("unbound");
|
|
807
|
+
return answer("no-session");
|
|
808
|
+
}),
|
|
809
|
+
/**
|
|
810
|
+
* ### Endpoint
|
|
811
|
+
*
|
|
812
|
+
* Server only. No HTTP route.
|
|
813
|
+
*
|
|
814
|
+
* ### API Methods
|
|
815
|
+
*
|
|
816
|
+
* **server:**
|
|
817
|
+
* `auth.api.requireFreshProof`
|
|
818
|
+
*
|
|
819
|
+
* A fresh proof for one of your own routes or server actions:
|
|
820
|
+
* `await auth.api.requireFreshProof({ headers, body: { action: "delete-account" } })`.
|
|
821
|
+
*
|
|
822
|
+
* - `answered`: a bound session proved itself after this action's challenge. Go on.
|
|
823
|
+
* - `challenge`: refuse the request and forward the `Set-Cookie` headers (call with
|
|
824
|
+
* `returnHeaders: true`, or use the `nextCookies()` plugin). The client retries once.
|
|
825
|
+
* - `unbound`: a plain session; apply whatever fresh-proof you use without DBSC.
|
|
826
|
+
* - `no-session` and `off`: nothing was checked.
|
|
827
|
+
*/
|
|
828
|
+
requireFreshProof: createAuthEndpoint("/dbsc/require-fresh-proof", {
|
|
829
|
+
method: "POST",
|
|
830
|
+
body: freshProofBody,
|
|
831
|
+
requireHeaders: true,
|
|
832
|
+
metadata: { SERVER_ONLY: true }
|
|
833
|
+
}, async (ctx) => {
|
|
834
|
+
const answer = (state) => ctx.json({ state });
|
|
835
|
+
if (!await config.enabled()) return answer("off");
|
|
836
|
+
const session = await sessionState(ctx);
|
|
837
|
+
if (session.kind === "none" || session.kind === "unproven") return answer("no-session");
|
|
838
|
+
if (session.kind === "plain") return answer("unbound");
|
|
839
|
+
return answer(await checkFreshProof(ctx, session, `app:${ctx.body.action}`));
|
|
840
|
+
})
|
|
841
|
+
},
|
|
842
|
+
hooks: {
|
|
843
|
+
before: [{
|
|
844
|
+
matcher: (ctx) => enforced(ctx.path),
|
|
845
|
+
handler: createAuthMiddleware(async (ctx) => {
|
|
846
|
+
if (!await config.enabled()) return;
|
|
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;
|
|
855
|
+
const policy = ctx.path ? config.freshProof.paths.get(ctx.path) : void 0;
|
|
856
|
+
if (!policy) return result;
|
|
857
|
+
for (const state of sessions) if (state.kind === "plain") await unboundPolicy(ctx, state, ctx.path, policy);
|
|
858
|
+
const state = sessions.find((state) => state.kind === "bound");
|
|
859
|
+
if (state?.kind === "bound") {
|
|
860
|
+
if (ctx.request && answeredRequests.has(ctx.request)) return result;
|
|
861
|
+
if (await checkFreshProof(ctx, state, ctx.path) === "answered") {
|
|
862
|
+
if (ctx.request) answeredRequests.add(ctx.request);
|
|
863
|
+
return result;
|
|
864
|
+
}
|
|
865
|
+
if (ctx.request && ctx.headers?.get("sec-fetch-mode") === "navigate") {
|
|
866
|
+
const url = new URL(ctx.request.url);
|
|
867
|
+
ctx.responseHeaders?.set("location", `${url.pathname}${url.search}`);
|
|
868
|
+
throw new APIError("TEMPORARY_REDIRECT", void 0, ctx.responseHeaders);
|
|
869
|
+
}
|
|
870
|
+
const { code, message } = DBSC_ERROR_CODES.DBSC_FRESH_PROOF_REQUIRED;
|
|
871
|
+
throw new APIError("FORBIDDEN", {
|
|
872
|
+
code,
|
|
873
|
+
message
|
|
874
|
+
}, ctx.responseHeaders);
|
|
875
|
+
}
|
|
876
|
+
return result;
|
|
877
|
+
})
|
|
878
|
+
}],
|
|
879
|
+
after: [{
|
|
880
|
+
matcher: () => true,
|
|
881
|
+
handler: createAuthMiddleware(async (ctx) => {
|
|
882
|
+
if (ctx.path === "/sign-out") {
|
|
883
|
+
const { bound, freshProof } = cookies(ctx);
|
|
884
|
+
ctx.setCookie(bound.name, "", {
|
|
885
|
+
...bound.attributes,
|
|
886
|
+
maxAge: 0
|
|
887
|
+
});
|
|
888
|
+
ctx.setCookie(freshProof.name, "", {
|
|
889
|
+
...freshProof.attributes,
|
|
890
|
+
maxAge: 0
|
|
891
|
+
});
|
|
892
|
+
return;
|
|
893
|
+
}
|
|
894
|
+
const issued = ctx.context.newSession;
|
|
895
|
+
if (!issued) return;
|
|
896
|
+
if (await readSessionToken(ctx) === issued.session.token) return;
|
|
897
|
+
if (!await config.enabled()) return;
|
|
898
|
+
if (config.shouldRegister && !await config.shouldRegister(ctx)) return;
|
|
899
|
+
const challenge = await createDbscChallenge({
|
|
900
|
+
secret: ctx.context.secret,
|
|
901
|
+
purpose: "register",
|
|
902
|
+
sessionToken: issued.session.token,
|
|
903
|
+
nowMs: config.now()
|
|
904
|
+
});
|
|
905
|
+
const value = formatRegistrationHeader({
|
|
906
|
+
algorithms: config.algorithms,
|
|
907
|
+
challenge,
|
|
908
|
+
path: `${basePath(ctx)}${DBSC_REGISTER_PATH}`
|
|
909
|
+
});
|
|
910
|
+
for (const name of getDbscHeaderNames("registration", config.advanced.headers)) ctx.setHeader(name, value);
|
|
911
|
+
})
|
|
912
|
+
}]
|
|
913
|
+
},
|
|
914
|
+
rateLimit: !config.rateLimit.enabled ? void 0 : [{
|
|
915
|
+
pathMatcher: (path) => path === "/dbsc/register" || path === "/dbsc/refresh",
|
|
916
|
+
window: config.rateLimit.window,
|
|
917
|
+
max: config.rateLimit.max
|
|
918
|
+
}],
|
|
919
|
+
$ERROR_CODES: DBSC_ERROR_CODES,
|
|
920
|
+
options
|
|
921
|
+
};
|
|
922
|
+
};
|
|
923
|
+
function ids(session) {
|
|
924
|
+
return {
|
|
925
|
+
sessionId: session.id,
|
|
926
|
+
userId: session.userId
|
|
927
|
+
};
|
|
928
|
+
}
|
|
929
|
+
async function readSessionToken(ctx) {
|
|
930
|
+
const token = await ctx.getSignedCookie(ctx.context.authCookies.sessionToken.name, ctx.context.secret);
|
|
931
|
+
return typeof token === "string" && token ? token : null;
|
|
932
|
+
}
|
|
933
|
+
/**
|
|
934
|
+
* The session token in `Authorization: Bearer`, read the way the `bearer()` plugin reads
|
|
935
|
+
* it, which turns it into the session cookie in its own hook. Not verified: here it can
|
|
936
|
+
* only cause a refusal, so a bad signature counts the same as a good one.
|
|
937
|
+
*/
|
|
938
|
+
function readBearerToken(ctx) {
|
|
939
|
+
const value = ctx.request?.headers.get("authorization") || ctx.headers?.get("authorization");
|
|
940
|
+
if (!value || value.slice(0, 7).toLowerCase() !== "bearer ") return null;
|
|
941
|
+
const token = value.slice(7).trim();
|
|
942
|
+
if (!token) return null;
|
|
943
|
+
return (token.includes(".") && token.includes("%") ? tryDecode(token) : token).split(".")[0] || null;
|
|
944
|
+
}
|
|
945
|
+
function tryDecode(value) {
|
|
946
|
+
try {
|
|
947
|
+
return decodeURIComponent(value);
|
|
948
|
+
} catch {
|
|
949
|
+
return value;
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
/** The names in the `Cookie` header. */
|
|
953
|
+
function cookieNames(headers) {
|
|
954
|
+
return (headers?.get("cookie") ?? "").split(";").map((pair) => pair.slice(0, Math.max(0, pair.indexOf("="))).trim()).filter(Boolean);
|
|
955
|
+
}
|
|
956
|
+
/** A copy of `headers` with every pair named in `names` removed from `Cookie`. */
|
|
957
|
+
function withoutCookies(headers, names) {
|
|
958
|
+
const copy = new Headers(headers);
|
|
959
|
+
const kept = (copy.get("cookie") ?? "").split(";").map((pair) => pair.trim()).filter((pair) => pair && !names.has(pair.slice(0, Math.max(0, pair.indexOf("="))).trim()));
|
|
960
|
+
copy.set("cookie", kept.join("; "));
|
|
961
|
+
return copy;
|
|
962
|
+
}
|
|
963
|
+
function basePath(ctx) {
|
|
964
|
+
return new URL(ctx.context.baseURL).pathname.replace(/\/+$/, "");
|
|
965
|
+
}
|
|
966
|
+
function isExcluded(path, exclude) {
|
|
967
|
+
if (!path) return false;
|
|
968
|
+
return exclude.some((entry) => entry.endsWith("/") ? path.startsWith(entry) : path === entry);
|
|
969
|
+
}
|
|
970
|
+
function isOrigin(value) {
|
|
971
|
+
try {
|
|
972
|
+
return new URL(value).origin === value;
|
|
973
|
+
} catch {
|
|
974
|
+
return false;
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
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 };
|