@santi020k/auth-cloudflare 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,12 +1,50 @@
1
1
  import { passkey } from "@better-auth/passkey";
2
2
  import { APIError, betterAuth } from "better-auth";
3
- import { emailOTP } from "better-auth/plugins";
3
+ import { captcha, emailOTP } from "better-auth/plugins";
4
+ import { isPasskeyAuthenticationUserVerified, isPasskeyRegistrationUserVerified } from "./passkey-verification.js";
4
5
  const DEFAULT_SESSION_LIFETIME_SECONDS = 30 * 24 * 60 * 60;
5
6
  const DEFAULT_SESSION_UPDATE_AGE_SECONDS = 24 * 60 * 60;
7
+ const DEFAULT_RATE_LIMIT_RETENTION_SECONDS = 24 * 60 * 60;
6
8
  const MAX_EMAIL_LENGTH = 254;
9
+ const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/u;
10
+ const TABLE_PREFIX_PATTERN = /^[a-z][a-z0-9_]{0,30}$/u;
7
11
  const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);
8
12
  const CORS_METHODS = new Set(["GET", "HEAD", "POST"]);
9
13
  const CORS_HEADERS = new Set(["content-type"]);
14
+ /**
15
+ * Resolves the table names needed at runtime without making the already-public
16
+ * package depend on the still-private migration package. Contract tests keep
17
+ * this result aligned with `@santi020k/auth-migrations`.
18
+ */
19
+ export function resolveAuthTableNames(tablePrefix) {
20
+ let prefix = "";
21
+ if (tablePrefix !== undefined && tablePrefix !== "") {
22
+ if (!TABLE_PREFIX_PATTERN.test(tablePrefix))
23
+ throw new Error("auth_table_prefix_invalid");
24
+ prefix = `${tablePrefix}_`;
25
+ }
26
+ return {
27
+ account: `${prefix}account`,
28
+ passkey: `${prefix}passkey`,
29
+ rateLimit: `${prefix}rateLimit`,
30
+ session: `${prefix}session`,
31
+ user: `${prefix}user`,
32
+ verification: `${prefix}verification`,
33
+ };
34
+ }
35
+ /**
36
+ * Better Auth's own rate limiter never runs for a request this package rejects before
37
+ * calling `auth.handler` (an unauthorized email must never reach it, so no OTP row gets
38
+ * created for an address that will never receive one). Without an independent limit here,
39
+ * that rejection path — which still calls the consumer's `authorizeEmail`, a D1 lookup for
40
+ * multi-user consumers — would accept unlimited requests per IP. This backstop is deliberately
41
+ * more generous than Better Auth's own tight per-path special rules (window 60s, max 3): those
42
+ * still apply on top of this for any request that turns out to be authorized, so this only
43
+ * needs to turn "unlimited" into "bounded" without constraining legitimate retry bursts.
44
+ */
45
+ const PRE_AUTH_RATE_LIMIT_WINDOW_SECONDS = 60;
46
+ const PRE_AUTH_RATE_LIMIT_MAX = 20;
47
+ const NO_TRUSTED_IP_KEY = "no-trusted-ip";
10
48
  function errorResponse(status, code) {
11
49
  return Response.json({ code, message: code }, {
12
50
  headers: { "Cache-Control": "no-store" },
@@ -24,6 +62,12 @@ function deferLifecycleTask(task) {
24
62
  setTimeout(resolve, 0);
25
63
  }).then(task);
26
64
  }
65
+ function rateLimitedResponse() {
66
+ return Response.json({ code: "request_rate_limited", message: "request_rate_limited" }, {
67
+ headers: { "Cache-Control": "no-store", "Retry-After": String(PRE_AUTH_RATE_LIMIT_WINDOW_SECONDS) },
68
+ status: 429,
69
+ });
70
+ }
27
71
  function isRecord(value) {
28
72
  return typeof value === "object" && value !== null && !Array.isArray(value);
29
73
  }
@@ -43,16 +87,7 @@ function normalizeCookiePrefix(value) {
43
87
  }
44
88
  export function normalizeAuthEmail(value) {
45
89
  const email = value.trim().toLowerCase();
46
- const atIndex = email.indexOf("@");
47
- const domain = email.slice(atIndex + 1);
48
- const dotIndex = domain.indexOf(".");
49
- const isValid = email.length <= MAX_EMAIL_LENGTH &&
50
- atIndex > 0 &&
51
- atIndex === email.lastIndexOf("@") &&
52
- dotIndex > 0 &&
53
- dotIndex < domain.length - 1 &&
54
- !/\s/u.test(email);
55
- if (!isValid)
90
+ if (email.length > MAX_EMAIL_LENGTH || !EMAIL_PATTERN.test(email))
56
91
  throw new Error("owner_auth_email_invalid");
57
92
  return email;
58
93
  }
@@ -71,39 +106,24 @@ function resolveEmailOtpRateLimit(value) {
71
106
  window: positiveInteger(value?.window, 10 * 60, "owner_auth_email_otp_rate_limit_invalid"),
72
107
  };
73
108
  }
74
- function resolveOrigin(value) {
75
- let url;
76
- try {
77
- url = new URL(value);
78
- }
79
- catch {
80
- throw new Error("owner_auth_origin_invalid");
81
- }
82
- const localHost = url.hostname === "localhost" || url.hostname === "127.0.0.1";
83
- const allowedProtocol = url.protocol === "https:" || (localHost && url.protocol === "http:");
84
- if (!allowedProtocol || url.pathname !== "/" || url.search || url.hash) {
85
- throw new Error("owner_auth_origin_invalid");
86
- }
87
- return url;
88
- }
89
- function assertSameSite(applicationOrigin, authServerOrigin) {
90
- const sameProtocol = applicationOrigin.protocol === authServerOrigin.protocol;
91
- const sameHost = applicationOrigin.hostname === authServerOrigin.hostname;
92
- const authServerIsApplicationSubdomain = authServerOrigin.hostname.endsWith(`.${applicationOrigin.hostname}`);
93
- if (!sameProtocol || (!sameHost && !authServerIsApplicationSubdomain)) {
94
- throw new Error("owner_auth_origins_not_same_site");
95
- }
96
- }
97
109
  function validateSecret(value) {
98
110
  if (value === undefined || value.trim().length < 32)
99
111
  throw new Error("owner_auth_secret_invalid");
100
112
  }
113
+ function hasConflictingSecretOptions(options) {
114
+ const usesVersionedSecrets = options.secrets !== undefined;
115
+ return ((usesVersionedSecrets && options.secret !== undefined) ||
116
+ (!usesVersionedSecrets && options.legacySecret !== undefined));
117
+ }
101
118
  function validateSecrets(options) {
119
+ if (hasConflictingSecretOptions(options)) {
120
+ throw new Error("owner_auth_secret_options_conflict");
121
+ }
102
122
  if (options.secrets === undefined) {
103
123
  validateSecret(options.secret);
104
124
  return;
105
125
  }
106
- if (options.secret !== undefined || options.secrets.length === 0)
126
+ if (options.secrets.length === 0)
107
127
  throw new Error("owner_auth_secrets_invalid");
108
128
  const versions = new Set();
109
129
  for (const secret of options.secrets) {
@@ -116,21 +136,88 @@ function validateSecrets(options) {
116
136
  if (options.legacySecret !== undefined)
117
137
  validateSecret(options.legacySecret);
118
138
  }
139
+ function requireDate(value, code) {
140
+ const date = value instanceof Date ? value : new Date(value);
141
+ if (Number.isNaN(date.getTime()))
142
+ throw new Error(code);
143
+ return date.toISOString();
144
+ }
145
+ /** Returns whether a session is recent enough for a consumer-defined step-up boundary. */
146
+ export function isRecentAuthentication(identity, maxAgeSeconds, now = Date.now()) {
147
+ if (!Number.isSafeInteger(maxAgeSeconds) || maxAgeSeconds <= 0) {
148
+ throw new Error("auth_step_up_max_age_invalid");
149
+ }
150
+ if (!Number.isFinite(now))
151
+ throw new Error("auth_step_up_now_invalid");
152
+ const authenticatedAt = new Date(identity.authenticatedAt).getTime();
153
+ return Number.isFinite(authenticatedAt) && authenticatedAt <= now && now - authenticatedAt <= maxAgeSeconds * 1000;
154
+ }
155
+ function resolveTurnstileOptions(options, policy) {
156
+ const secretKey = options.secretKey.trim();
157
+ if (secretKey.length < 20)
158
+ throw new Error("auth_turnstile_secret_invalid");
159
+ const endpoints = [...(options.endpoints ?? ["/email-otp/send-verification-otp"])];
160
+ if (endpoints.length === 0 || endpoints.some((endpoint) => !/^\/[A-Za-z0-9/*_-]+$/u.test(endpoint))) {
161
+ throw new Error("auth_turnstile_endpoint_invalid");
162
+ }
163
+ const allowedHostnames = [...(options.allowedHostnames ?? [new URL(policy.origin).hostname])];
164
+ if (allowedHostnames.length === 0 || allowedHostnames.some((hostname) => hostname !== hostname.toLowerCase())) {
165
+ throw new Error("auth_turnstile_hostname_invalid");
166
+ }
167
+ return {
168
+ allowedHostnames,
169
+ endpoints,
170
+ ...(options.expectedAction ? { expectedAction: options.expectedAction } : {}),
171
+ provider: "cloudflare-turnstile",
172
+ secretKey,
173
+ };
174
+ }
175
+ function resolveOrigin(value) {
176
+ let url;
177
+ try {
178
+ url = new URL(value);
179
+ }
180
+ catch {
181
+ throw new Error("owner_auth_origin_invalid");
182
+ }
183
+ const localHost = url.hostname === "localhost" || url.hostname === "127.0.0.1";
184
+ const allowedProtocol = url.protocol === "https:" || (localHost && url.protocol === "http:");
185
+ if (!allowedProtocol || url.pathname !== "/" || url.search || url.hash) {
186
+ throw new Error("owner_auth_origin_invalid");
187
+ }
188
+ return url;
189
+ }
190
+ function resolveOriginAlias(preferred, legacy) {
191
+ if (preferred && legacy && preferred !== legacy)
192
+ throw new Error("owner_auth_origin_alias_conflict");
193
+ return preferred ?? legacy;
194
+ }
195
+ function resolveConfiguredOrigins(options) {
196
+ const baseURLValue = resolveOriginAlias(options.baseURL, options.authServerURL);
197
+ if (!baseURLValue)
198
+ throw new Error("owner_auth_origin_invalid");
199
+ const browserOriginValue = resolveOriginAlias(options.browserOrigin, options.applicationOrigin) ?? baseURLValue;
200
+ return {
201
+ baseURL: resolveOrigin(baseURLValue),
202
+ browserOrigin: resolveOrigin(browserOriginValue),
203
+ };
204
+ }
119
205
  function resolveAuthPolicy(options) {
120
206
  if (!options.appName.trim())
121
207
  throw new Error("owner_auth_app_name_invalid");
122
208
  validateSecrets(options);
123
- const applicationOrigin = resolveOrigin(options.applicationOrigin);
124
- const authServerOrigin = resolveOrigin(options.authServerURL);
125
- assertSameSite(applicationOrigin, authServerOrigin);
209
+ const { baseURL, browserOrigin } = resolveConfiguredOrigins(options);
126
210
  return {
127
- applicationOrigin: applicationOrigin.origin,
128
- authServerOrigin: authServerOrigin.origin,
211
+ applicationOrigin: browserOrigin.origin,
212
+ authServerOrigin: baseURL.origin,
129
213
  basePath: normalizeBasePath(options.basePath),
214
+ baseURL: baseURL.origin,
130
215
  cookiePrefix: normalizeCookiePrefix(options.cookiePrefix),
131
216
  emailOtpRateLimit: resolveEmailOtpRateLimit(options.emailOtpRateLimit),
132
- relyingPartyId: applicationOrigin.hostname,
133
- secureCookies: authServerOrigin.protocol === "https:",
217
+ origin: browserOrigin.origin,
218
+ relyingPartyId: browserOrigin.hostname,
219
+ secureCookies: baseURL.protocol === "https:",
220
+ tableNames: resolveAuthTableNames(options.tablePrefix),
134
221
  };
135
222
  }
136
223
  export function resolveMultiUserAuthPolicy(options) {
@@ -142,19 +229,46 @@ export function resolveOwnerAuthPolicy(options) {
142
229
  ownerEmail: normalizeAuthEmail(options.ownerEmail),
143
230
  };
144
231
  }
232
+ async function requestEmail(request) {
233
+ const contentType = request.headers.get("Content-Type") ?? "";
234
+ if (!contentType.toLowerCase().includes("application/json"))
235
+ return null;
236
+ const body = await request
237
+ .clone()
238
+ .json()
239
+ .catch(() => null);
240
+ if (!isRecord(body) || typeof body.email !== "string")
241
+ return null;
242
+ try {
243
+ return normalizeAuthEmail(body.email);
244
+ }
245
+ catch {
246
+ return "";
247
+ }
248
+ }
249
+ async function emitSecurityEvent(listener, event) {
250
+ if (!listener)
251
+ return;
252
+ try {
253
+ await listener(event);
254
+ }
255
+ catch {
256
+ // Consumer observability hooks must never break the authentication flow.
257
+ }
258
+ }
145
259
  function corsHeaders(policy) {
146
260
  return new Headers({
147
261
  "Access-Control-Allow-Credentials": "true",
148
- "Access-Control-Allow-Origin": policy.applicationOrigin,
262
+ "Access-Control-Allow-Origin": policy.origin,
149
263
  Vary: "Origin",
150
264
  });
151
265
  }
152
266
  function withCors(policy, request, response) {
153
- if (request.headers.get("Origin") !== policy.applicationOrigin)
267
+ if (request.headers.get("Origin") !== policy.origin)
154
268
  return response;
155
269
  const headers = new Headers(response.headers);
156
270
  headers.set("Access-Control-Allow-Credentials", "true");
157
- headers.set("Access-Control-Allow-Origin", policy.applicationOrigin);
271
+ headers.set("Access-Control-Allow-Origin", policy.origin);
158
272
  const vary = headers.get("Vary");
159
273
  if (vary === null)
160
274
  headers.set("Vary", "Origin");
@@ -183,55 +297,90 @@ function preflightResponse(policy, request) {
183
297
  headers.set("Access-Control-Max-Age", "600");
184
298
  return new Response(null, { headers, status: 204 });
185
299
  }
186
- async function requestEmail(request) {
187
- const contentType = request.headers.get("Content-Type") ?? "";
188
- if (!contentType.toLowerCase().includes("application/json"))
189
- return null;
190
- const body = await request
191
- .clone()
192
- .json()
193
- .catch(() => null);
194
- if (!isRecord(body) || typeof body.email !== "string")
195
- return null;
196
- try {
197
- return normalizeAuthEmail(body.email);
198
- }
199
- catch {
200
- return "";
201
- }
202
- }
203
- function enforceRequestBoundary(policy, request, url, method) {
300
+ async function enforceRequestBoundary(policy, request, path, emit) {
301
+ const method = request.method.toUpperCase();
302
+ const url = new URL(request.url);
204
303
  const origin = request.headers.get("Origin");
205
- if (url.origin !== policy.authServerOrigin || (origin !== null && origin !== policy.applicationOrigin)) {
206
- return errorResponse(403, "request_origin_not_allowed");
304
+ const rejected = url.origin !== policy.baseURL ||
305
+ (origin !== null && origin !== policy.origin) ||
306
+ (!SAFE_METHODS.has(method) && origin !== policy.origin);
307
+ if (!rejected && method === "OPTIONS") {
308
+ if (origin === policy.origin)
309
+ return preflightResponse(policy, request);
207
310
  }
208
- if (method === "OPTIONS") {
209
- if (origin !== policy.applicationOrigin)
210
- return errorResponse(403, "request_origin_not_allowed");
211
- return preflightResponse(policy, request);
212
- }
213
- if (!SAFE_METHODS.has(method) && origin !== policy.applicationOrigin) {
214
- return errorResponse(403, "request_origin_not_allowed");
311
+ else if (!rejected)
312
+ return null;
313
+ await emitSecurityEvent(emit, {
314
+ origin,
315
+ path,
316
+ type: "request_origin_rejected",
317
+ });
318
+ return errorResponse(403, "request_origin_not_allowed");
319
+ }
320
+ async function rejectUnauthorizedEmail(policy, path, email, invalidCredentialsCode, emit) {
321
+ if (path === `${policy.basePath}/email-otp/send-verification-otp`) {
322
+ if (email)
323
+ await emitSecurityEvent(emit, { email, type: "email_otp_delivery_suppressed" });
324
+ return genericEmailResponse();
215
325
  }
216
- return undefined;
326
+ if (email)
327
+ await emitSecurityEvent(emit, { email, path, type: "credentials_rejected" });
328
+ return errorResponse(401, invalidCredentialsCode);
329
+ }
330
+ function clientIp(request) {
331
+ return request.headers.get("cf-connecting-ip")?.trim() || NO_TRUSTED_IP_KEY;
332
+ }
333
+ /**
334
+ * Atomically increments (or starts) a fixed-window counter in one statement: SQLite evaluates
335
+ * the `ON CONFLICT` update as part of the same atomic operation as the insert attempt, so
336
+ * concurrent callers for the same key are serialized by the database rather than racing on a
337
+ * separate read-then-write pair. Returns the resulting count for this window.
338
+ */
339
+ async function consumePreAuthRateLimitCount(database, rateLimitTable, key) {
340
+ const now = Date.now();
341
+ const windowStart = now - PRE_AUTH_RATE_LIMIT_WINDOW_SECONDS * 1000;
342
+ const row = await database
343
+ .prepare(`INSERT INTO "${rateLimitTable}" ("id", "key", "count", "lastRequest")
344
+ VALUES (?1, ?2, 1, ?3)
345
+ ON CONFLICT("key") DO UPDATE SET
346
+ "count" = CASE WHEN "lastRequest" <= ?4 THEN 1 ELSE "count" + 1 END,
347
+ "lastRequest" = CASE WHEN "lastRequest" <= ?4 THEN ?3 ELSE "lastRequest" END
348
+ RETURNING "count"`)
349
+ .bind(crypto.randomUUID(), key, now, windowStart)
350
+ .first();
351
+ return row?.count ?? 0;
352
+ }
353
+ async function enforcePreAuthRateLimit(policy, database, request, path, emit) {
354
+ const key = `pre-auth:${clientIp(request)}:${path}`;
355
+ const count = await consumePreAuthRateLimitCount(database, policy.tableNames.rateLimit, key);
356
+ if (count <= PRE_AUTH_RATE_LIMIT_MAX)
357
+ return null;
358
+ await emitSecurityEvent(emit, { path, type: "request_rate_limited" });
359
+ return rateLimitedResponse();
217
360
  }
218
- async function enforceAuthRequest(policy, authorizeEmail, invalidCredentialsCode, request) {
361
+ async function enforceAuthRequest(policy, authorizeEmail, invalidCredentialsCode, request, emit, database) {
219
362
  const url = new URL(request.url);
220
363
  if (!url.pathname.startsWith(`${policy.basePath}/`) && url.pathname !== policy.basePath)
221
364
  return null;
222
- const method = request.method.toUpperCase();
223
- const boundaryResponse = enforceRequestBoundary(policy, request, url, method);
224
- if (boundaryResponse)
225
- return boundaryResponse;
226
- if (method !== "POST" || invalidCredentialsCode === undefined)
227
- return null;
228
- if (url.pathname === `${policy.basePath}/email-otp/send-verification-otp`) {
365
+ const originRejection = await enforceRequestBoundary(policy, request, url.pathname, emit);
366
+ if (originRejection)
367
+ return originRejection;
368
+ if (request.method.toUpperCase() !== "POST")
229
369
  return null;
370
+ // Better Auth's own rate limiter lives inside auth.handler and never runs for a request
371
+ // rejected here, so a request that will be rejected below for an unauthorized email must
372
+ // still be bounded — otherwise authorizeEmail (a D1 lookup for multi-user consumers) could
373
+ // be invoked without limit. Requests that pass through to auth.handler remain additionally
374
+ // bounded by Better Auth's own configured rate limit.
375
+ if (database) {
376
+ const rateLimitRejection = await enforcePreAuthRateLimit(policy, database, request, url.pathname, emit);
377
+ if (rateLimitRejection)
378
+ return rateLimitRejection;
230
379
  }
231
380
  const email = await requestEmail(request);
232
381
  if (email === null || (email !== "" && (await authorizeEmail(email))))
233
382
  return null;
234
- return errorResponse(401, invalidCredentialsCode);
383
+ return rejectUnauthorizedEmail(policy, url.pathname, email, invalidCredentialsCode, emit);
235
384
  }
236
385
  export function enforceOwnerAuthRequest(policy, request) {
237
386
  return enforceAuthRequest(policy, (email) => email === policy.ownerEmail, "invalid_owner_credentials", request);
@@ -249,20 +398,61 @@ function isSessionIndependentRequest(policy, request) {
249
398
  (method === "GET" && path === `${policy.basePath}/passkey/generate-authenticate-options`) ||
250
399
  (method === "POST" && path === `${policy.basePath}/passkey/verify-authentication`));
251
400
  }
252
- async function authorizeUserId(database, userId, authorizeEmail) {
253
- const user = await database.prepare("SELECT email FROM user WHERE id = ?").bind(userId).first();
401
+ async function authorizeUserId(database, userTable, userId, authorizeEmail) {
402
+ const user = await database
403
+ .prepare(`SELECT "email" FROM "${userTable}" WHERE "id" = ?`)
404
+ .bind(userId)
405
+ .first();
254
406
  return user !== null && authorizeEmail(normalizeAuthEmail(user.email));
255
407
  }
256
- async function authorizePasskeyCredential(database, credentialId, authorizeEmail) {
408
+ async function authorizePasskeyCredential(database, passkeyTable, userTable, credentialId, authorizeEmail) {
257
409
  const user = await database
258
- .prepare("SELECT user.email FROM passkey INNER JOIN user ON user.id = passkey.userId WHERE passkey.credentialID = ?")
410
+ .prepare(`SELECT u."email" AS "email" FROM "${passkeyTable}" p INNER JOIN "${userTable}" u ON u."id" = p."userId" WHERE p."credentialID" = ?`)
259
411
  .bind(credentialId)
260
412
  .first();
261
413
  return user !== null && authorizeEmail(normalizeAuthEmail(user.email));
262
414
  }
415
+ async function listAuthSessionsForUser(database, sessionTable, userId) {
416
+ const result = await database
417
+ .prepare(`SELECT "id", "createdAt", "updatedAt", "expiresAt", "ipAddress", "userAgent" FROM "${sessionTable}" WHERE "userId" = ? AND "expiresAt" > ? ORDER BY "createdAt" DESC`)
418
+ .bind(userId, Date.now())
419
+ .all();
420
+ return result.results.map((session) => ({
421
+ createdAt: new Date(session.createdAt).toISOString(),
422
+ expiresAt: new Date(session.expiresAt).toISOString(),
423
+ id: session.id,
424
+ ipAddress: session.ipAddress,
425
+ updatedAt: new Date(session.updatedAt).toISOString(),
426
+ userAgent: session.userAgent,
427
+ }));
428
+ }
429
+ async function revokeAuthSessionForUser(database, sessionTable, userId, sessionId) {
430
+ const result = await database
431
+ .prepare(`DELETE FROM "${sessionTable}" WHERE "userId" = ? AND "id" = ?`)
432
+ .bind(userId, sessionId)
433
+ .run();
434
+ return result.meta.changes > 0;
435
+ }
436
+ async function revokeAllAuthSessionsForUser(database, sessionTable, userId) {
437
+ const result = await database.prepare(`DELETE FROM "${sessionTable}" WHERE "userId" = ?`).bind(userId).run();
438
+ return result.meta.changes;
439
+ }
440
+ async function pruneAuthRateLimits(database, rateLimitTable, options = {}) {
441
+ const now = options.now ?? Date.now();
442
+ const retentionSeconds = options.retentionSeconds ?? DEFAULT_RATE_LIMIT_RETENTION_SECONDS;
443
+ if (!Number.isFinite(now) || !Number.isSafeInteger(retentionSeconds) || retentionSeconds <= 0) {
444
+ throw new Error("auth_rate_limit_retention_invalid");
445
+ }
446
+ const result = await database
447
+ .prepare(`DELETE FROM "${rateLimitTable}" WHERE "lastRequest" <= ?`)
448
+ .bind(now - retentionSeconds * 1000)
449
+ .run();
450
+ return result.meta.changes;
451
+ }
263
452
  function createConfiguredAuth(options, policy, authorizeEmail, invalidCredentialsCode) {
264
453
  const sessionExpiresIn = positiveInteger(options.sessionExpiresIn, DEFAULT_SESSION_LIFETIME_SECONDS, "owner_auth_session_lifetime_invalid");
265
454
  const sessionUpdateAge = positiveInteger(options.sessionUpdateAge, DEFAULT_SESSION_UPDATE_AGE_SECONDS, "owner_auth_session_update_age_invalid");
455
+ const turnstile = options.turnstile ? resolveTurnstileOptions(options.turnstile, policy) : null;
266
456
  const auth = betterAuth({
267
457
  advanced: {
268
458
  cookiePrefix: policy.cookiePrefix,
@@ -271,16 +461,23 @@ function createConfiguredAuth(options, policy, authorizeEmail, invalidCredential
271
461
  },
272
462
  appName: options.appName.trim(),
273
463
  basePath: policy.basePath,
274
- baseURL: policy.authServerOrigin,
464
+ baseURL: policy.baseURL,
275
465
  database: options.database,
276
466
  databaseHooks: {
277
467
  session: {
278
468
  create: {
279
469
  before: async (session) => {
280
- if (!(await authorizeUserId(options.database, session.userId, authorizeEmail))) {
281
- throw new APIError("UNAUTHORIZED", { message: invalidCredentialsCode ?? "invalid_credentials" });
470
+ if (!(await authorizeUserId(options.database, policy.tableNames.user, session.userId, authorizeEmail))) {
471
+ throw new APIError("UNAUTHORIZED", { message: invalidCredentialsCode });
282
472
  }
283
473
  },
474
+ after: async (session) => {
475
+ await emitSecurityEvent(options.onSecurityEvent, {
476
+ sessionId: session.id,
477
+ type: "session_created",
478
+ userId: session.userId,
479
+ });
480
+ },
284
481
  },
285
482
  },
286
483
  user: {
@@ -292,6 +489,7 @@ function createConfiguredAuth(options, policy, authorizeEmail, invalidCredential
292
489
  },
293
490
  },
294
491
  },
492
+ account: { modelName: policy.tableNames.account },
295
493
  emailAndPassword: { enabled: false },
296
494
  plugins: [
297
495
  emailOTP({
@@ -305,10 +503,19 @@ function createConfiguredAuth(options, policy, authorizeEmail, invalidCredential
305
503
  const normalizedEmail = normalizeAuthEmail(email);
306
504
  if (type !== "sign-in" || !(await authorizeEmail(normalizedEmail)))
307
505
  return;
308
- await options.sendVerificationOTP({ email: normalizedEmail, otp });
506
+ await emitSecurityEvent(options.onSecurityEvent, { email: normalizedEmail, type: "email_otp_requested" });
507
+ try {
508
+ await options.sendVerificationOTP({ email: normalizedEmail, otp });
509
+ }
510
+ catch {
511
+ await emitSecurityEvent(options.onSecurityEvent, {
512
+ email: normalizedEmail,
513
+ type: "email_otp_delivery_failed",
514
+ });
515
+ }
309
516
  };
310
- const deliveryTask = deferLifecycleTask(deliver);
311
- options.waitUntil(deliveryTask);
517
+ const task = deferLifecycleTask(deliver);
518
+ options.waitUntil(task);
312
519
  return Promise.resolve();
313
520
  },
314
521
  storeOTP: "hashed",
@@ -316,36 +523,72 @@ function createConfiguredAuth(options, policy, authorizeEmail, invalidCredential
316
523
  passkey({
317
524
  advanced: { webAuthnChallengeCookie: `${policy.cookiePrefix}-passkey` },
318
525
  authentication: {
319
- afterVerification: async ({ clientData }) => {
320
- if (!(await authorizePasskeyCredential(options.database, clientData.id, authorizeEmail))) {
321
- throw new APIError("UNAUTHORIZED", { message: invalidCredentialsCode ?? "invalid_credentials" });
526
+ afterVerification: async ({ clientData, verification }) => {
527
+ if (!isPasskeyAuthenticationUserVerified(verification)) {
528
+ throw new APIError("UNAUTHORIZED", { message: invalidCredentialsCode });
529
+ }
530
+ if (!(await authorizePasskeyCredential(options.database, policy.tableNames.passkey, policy.tableNames.user, clientData.id, authorizeEmail))) {
531
+ throw new APIError("UNAUTHORIZED", { message: invalidCredentialsCode });
322
532
  }
323
533
  },
324
534
  },
325
535
  authenticatorSelection: { residentKey: "required", userVerification: "required" },
326
- origin: policy.applicationOrigin,
536
+ origin: policy.origin,
537
+ registration: {
538
+ afterVerification: ({ verification }) => {
539
+ if (!isPasskeyRegistrationUserVerified(verification)) {
540
+ throw new APIError("UNAUTHORIZED", { message: invalidCredentialsCode });
541
+ }
542
+ },
543
+ },
327
544
  rpID: policy.relyingPartyId,
328
545
  rpName: options.appName.trim(),
546
+ schema: { passkey: { modelName: policy.tableNames.passkey } },
329
547
  }),
548
+ ...(turnstile ? [captcha(turnstile)] : []),
330
549
  ],
331
550
  rateLimit: {
332
551
  enabled: true,
333
552
  max: 100,
334
- modelName: "rateLimit",
553
+ modelName: policy.tableNames.rateLimit,
335
554
  storage: "database",
336
555
  window: 60,
337
556
  },
338
557
  secret: options.secrets === undefined ? options.secret : options.legacySecret,
339
558
  secrets: options.secrets,
559
+ ...(options.socialProviders ? { socialProviders: options.socialProviders } : {}),
340
560
  session: {
341
561
  expiresIn: sessionExpiresIn,
562
+ modelName: policy.tableNames.session,
342
563
  updateAge: sessionUpdateAge,
343
564
  },
344
- trustedOrigins: [policy.applicationOrigin],
565
+ trustedOrigins: [policy.origin],
566
+ user: {
567
+ modelName: policy.tableNames.user,
568
+ validateUserInfo: async ({ source, user }) => {
569
+ if (typeof user.email !== "string")
570
+ return { error: invalidCredentialsCode };
571
+ const email = normalizeAuthEmail(user.email);
572
+ if (await authorizeEmail(email))
573
+ return;
574
+ await emitSecurityEvent(options.onSecurityEvent, {
575
+ email,
576
+ path: source.method,
577
+ type: "credentials_rejected",
578
+ });
579
+ return { error: invalidCredentialsCode };
580
+ },
581
+ },
582
+ verification: { modelName: policy.tableNames.verification },
345
583
  });
346
584
  return {
585
+ emergencyLockout: async (userId) => {
586
+ const revokedSessions = await revokeAllAuthSessionsForUser(options.database, policy.tableNames.session, userId);
587
+ await emitSecurityEvent(options.onSecurityEvent, { revokedSessions, type: "emergency_lockout", userId });
588
+ return revokedSessions;
589
+ },
347
590
  handler: async (request) => {
348
- const rejection = await enforceAuthRequest(policy, authorizeEmail, invalidCredentialsCode, request);
591
+ const rejection = await enforceAuthRequest(policy, authorizeEmail, invalidCredentialsCode, request, options.onSecurityEvent, options.database);
349
592
  if (rejection)
350
593
  return withCors(policy, request, rejection);
351
594
  const currentSession = await auth.api.getSession({
@@ -355,12 +598,14 @@ function createConfiguredAuth(options, policy, authorizeEmail, invalidCredential
355
598
  if (currentSession &&
356
599
  !(await authorizeEmail(normalizeAuthEmail(currentSession.user.email))) &&
357
600
  !isSessionIndependentRequest(policy, request)) {
358
- return withCors(policy, request, errorResponse(401, invalidCredentialsCode ?? "invalid_credentials"));
601
+ return withCors(policy, request, errorResponse(401, invalidCredentialsCode));
359
602
  }
360
603
  const response = await auth.handler(request);
361
604
  return withCors(policy, request, isEmailOtpSendRequest(policy, request) ? genericEmailResponse() : response);
362
605
  },
606
+ listSessions: (userId) => listAuthSessionsForUser(options.database, policy.tableNames.session, userId),
363
607
  policy,
608
+ pruneRateLimits: (pruneOptions) => pruneAuthRateLimits(options.database, policy.tableNames.rateLimit, pruneOptions),
364
609
  resolveSession: async (headers) => {
365
610
  const session = await auth.api.getSession({
366
611
  headers,
@@ -371,13 +616,33 @@ function createConfiguredAuth(options, policy, authorizeEmail, invalidCredential
371
616
  const email = normalizeAuthEmail(session.user.email);
372
617
  if (!(await authorizeEmail(email)))
373
618
  return null;
374
- return { email, userId: session.user.id };
619
+ return {
620
+ authenticatedAt: requireDate(session.session.createdAt, "auth_session_created_at_invalid"),
621
+ email,
622
+ expiresAt: requireDate(session.session.expiresAt, "auth_session_expires_at_invalid"),
623
+ sessionId: session.session.id,
624
+ userId: session.user.id,
625
+ };
626
+ },
627
+ revokeAllSessions: async (userId) => {
628
+ const revokedSessions = await revokeAllAuthSessionsForUser(options.database, policy.tableNames.session, userId);
629
+ if (revokedSessions > 0) {
630
+ await emitSecurityEvent(options.onSecurityEvent, { revokedSessions, type: "sessions_revoked_all", userId });
631
+ }
632
+ return revokedSessions;
633
+ },
634
+ revokeSession: async (userId, sessionId) => {
635
+ const revoked = await revokeAuthSessionForUser(options.database, policy.tableNames.session, userId, sessionId);
636
+ if (revoked) {
637
+ await emitSecurityEvent(options.onSecurityEvent, { sessionId, type: "session_revoked", userId });
638
+ }
639
+ return revoked;
375
640
  },
376
641
  };
377
642
  }
378
643
  export function createMultiUserAuth(options) {
379
- const policy = resolveMultiUserAuthPolicy(options);
380
- return createConfiguredAuth(options, policy, (email) => options.authorizeEmail(email));
644
+ const policy = resolveAuthPolicy(options);
645
+ return createConfiguredAuth(options, policy, (email) => options.authorizeEmail(email), "invalid_credentials");
381
646
  }
382
647
  export function createOwnerAuth(options) {
383
648
  const policy = resolveOwnerAuthPolicy(options);