@santi020k/auth-cloudflare 0.2.1 → 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
- import { betterAuth } from "better-auth";
3
- import { emailOTP } from "better-auth/plugins";
2
+ import { APIError, betterAuth } from "better-auth";
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;
8
+ const MAX_EMAIL_LENGTH = 254;
6
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
  }
@@ -41,12 +85,15 @@ function normalizeCookiePrefix(value) {
41
85
  }
42
86
  return cookiePrefix;
43
87
  }
44
- export function normalizeOwnerEmail(value) {
88
+ export function normalizeAuthEmail(value) {
45
89
  const email = value.trim().toLowerCase();
46
- if (!EMAIL_PATTERN.test(email))
90
+ if (email.length > MAX_EMAIL_LENGTH || !EMAIL_PATTERN.test(email))
47
91
  throw new Error("owner_auth_email_invalid");
48
92
  return email;
49
93
  }
94
+ export function normalizeOwnerEmail(value) {
95
+ return normalizeAuthEmail(value);
96
+ }
50
97
  function positiveInteger(value, fallback, code) {
51
98
  const result = value ?? fallback;
52
99
  if (!Number.isSafeInteger(result) || result <= 0)
@@ -59,39 +106,24 @@ function resolveEmailOtpRateLimit(value) {
59
106
  window: positiveInteger(value?.window, 10 * 60, "owner_auth_email_otp_rate_limit_invalid"),
60
107
  };
61
108
  }
62
- function resolveOrigin(value) {
63
- let url;
64
- try {
65
- url = new URL(value);
66
- }
67
- catch {
68
- throw new Error("owner_auth_origin_invalid");
69
- }
70
- const localHost = url.hostname === "localhost" || url.hostname === "127.0.0.1";
71
- const allowedProtocol = url.protocol === "https:" || (localHost && url.protocol === "http:");
72
- if (!allowedProtocol || url.pathname !== "/" || url.search || url.hash) {
73
- throw new Error("owner_auth_origin_invalid");
74
- }
75
- return url;
76
- }
77
- function assertSameSite(applicationOrigin, authServerOrigin) {
78
- const sameProtocol = applicationOrigin.protocol === authServerOrigin.protocol;
79
- const sameHost = applicationOrigin.hostname === authServerOrigin.hostname;
80
- const authServerIsApplicationSubdomain = authServerOrigin.hostname.endsWith(`.${applicationOrigin.hostname}`);
81
- if (!sameProtocol || (!sameHost && !authServerIsApplicationSubdomain)) {
82
- throw new Error("owner_auth_origins_not_same_site");
83
- }
84
- }
85
109
  function validateSecret(value) {
86
110
  if (value === undefined || value.trim().length < 32)
87
111
  throw new Error("owner_auth_secret_invalid");
88
112
  }
113
+ function hasConflictingSecretOptions(options) {
114
+ const usesVersionedSecrets = options.secrets !== undefined;
115
+ return ((usesVersionedSecrets && options.secret !== undefined) ||
116
+ (!usesVersionedSecrets && options.legacySecret !== undefined));
117
+ }
89
118
  function validateSecrets(options) {
119
+ if (hasConflictingSecretOptions(options)) {
120
+ throw new Error("owner_auth_secret_options_conflict");
121
+ }
90
122
  if (options.secrets === undefined) {
91
123
  validateSecret(options.secret);
92
124
  return;
93
125
  }
94
- if (options.secret !== undefined || options.secrets.length === 0)
126
+ if (options.secrets.length === 0)
95
127
  throw new Error("owner_auth_secrets_invalid");
96
128
  const versions = new Set();
97
129
  for (const secret of options.secrets) {
@@ -104,37 +136,139 @@ function validateSecrets(options) {
104
136
  if (options.legacySecret !== undefined)
105
137
  validateSecret(options.legacySecret);
106
138
  }
107
- export function resolveOwnerAuthPolicy(options) {
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
+ }
205
+ function resolveAuthPolicy(options) {
108
206
  if (!options.appName.trim())
109
207
  throw new Error("owner_auth_app_name_invalid");
110
208
  validateSecrets(options);
111
- const applicationOrigin = resolveOrigin(options.applicationOrigin);
112
- const authServerOrigin = resolveOrigin(options.authServerURL);
113
- assertSameSite(applicationOrigin, authServerOrigin);
209
+ const { baseURL, browserOrigin } = resolveConfiguredOrigins(options);
114
210
  return {
115
- applicationOrigin: applicationOrigin.origin,
116
- authServerOrigin: authServerOrigin.origin,
211
+ applicationOrigin: browserOrigin.origin,
212
+ authServerOrigin: baseURL.origin,
117
213
  basePath: normalizeBasePath(options.basePath),
214
+ baseURL: baseURL.origin,
118
215
  cookiePrefix: normalizeCookiePrefix(options.cookiePrefix),
119
216
  emailOtpRateLimit: resolveEmailOtpRateLimit(options.emailOtpRateLimit),
120
- ownerEmail: normalizeOwnerEmail(options.ownerEmail),
121
- relyingPartyId: applicationOrigin.hostname,
122
- secureCookies: authServerOrigin.protocol === "https:",
217
+ origin: browserOrigin.origin,
218
+ relyingPartyId: browserOrigin.hostname,
219
+ secureCookies: baseURL.protocol === "https:",
220
+ tableNames: resolveAuthTableNames(options.tablePrefix),
221
+ };
222
+ }
223
+ export function resolveMultiUserAuthPolicy(options) {
224
+ return resolveAuthPolicy(options);
225
+ }
226
+ export function resolveOwnerAuthPolicy(options) {
227
+ return {
228
+ ...resolveAuthPolicy(options),
229
+ ownerEmail: normalizeAuthEmail(options.ownerEmail),
123
230
  };
124
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
+ }
125
259
  function corsHeaders(policy) {
126
260
  return new Headers({
127
261
  "Access-Control-Allow-Credentials": "true",
128
- "Access-Control-Allow-Origin": policy.applicationOrigin,
262
+ "Access-Control-Allow-Origin": policy.origin,
129
263
  Vary: "Origin",
130
264
  });
131
265
  }
132
266
  function withCors(policy, request, response) {
133
- if (request.headers.get("Origin") !== policy.applicationOrigin)
267
+ if (request.headers.get("Origin") !== policy.origin)
134
268
  return response;
135
269
  const headers = new Headers(response.headers);
136
270
  headers.set("Access-Control-Allow-Credentials", "true");
137
- headers.set("Access-Control-Allow-Origin", policy.applicationOrigin);
271
+ headers.set("Access-Control-Allow-Origin", policy.origin);
138
272
  const vary = headers.get("Vary");
139
273
  if (vary === null)
140
274
  headers.set("Vary", "Origin");
@@ -163,64 +297,162 @@ function preflightResponse(policy, request) {
163
297
  headers.set("Access-Control-Max-Age", "600");
164
298
  return new Response(null, { headers, status: 204 });
165
299
  }
166
- async function requestEmail(request) {
167
- const contentType = request.headers.get("Content-Type") ?? "";
168
- if (!contentType.toLowerCase().includes("application/json"))
169
- return null;
170
- const body = await request
171
- .clone()
172
- .json()
173
- .catch(() => null);
174
- if (!isRecord(body) || typeof body.email !== "string")
175
- return null;
176
- try {
177
- return normalizeOwnerEmail(body.email);
178
- }
179
- catch {
180
- return "";
181
- }
182
- }
183
- 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);
184
303
  const origin = request.headers.get("Origin");
185
- if (url.origin !== policy.authServerOrigin || (origin !== null && origin !== policy.applicationOrigin)) {
186
- return errorResponse(403, "request_origin_not_allowed");
187
- }
188
- if (method === "OPTIONS") {
189
- if (origin !== policy.applicationOrigin)
190
- return errorResponse(403, "request_origin_not_allowed");
191
- return preflightResponse(policy, request);
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);
192
310
  }
193
- if (!SAFE_METHODS.has(method) && origin !== policy.applicationOrigin) {
194
- 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();
195
325
  }
196
- 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;
197
332
  }
198
- export async function enforceOwnerAuthRequest(policy, request) {
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();
360
+ }
361
+ async function enforceAuthRequest(policy, authorizeEmail, invalidCredentialsCode, request, emit, database) {
199
362
  const url = new URL(request.url);
200
363
  if (!url.pathname.startsWith(`${policy.basePath}/`) && url.pathname !== policy.basePath)
201
364
  return null;
202
- const method = request.method.toUpperCase();
203
- const boundaryResponse = enforceRequestBoundary(policy, request, url, method);
204
- if (boundaryResponse)
205
- return boundaryResponse;
206
- if (method !== "POST")
207
- return null;
208
- 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")
209
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;
210
379
  }
211
380
  const email = await requestEmail(request);
212
- if (email === null || email === policy.ownerEmail)
381
+ if (email === null || (email !== "" && (await authorizeEmail(email))))
213
382
  return null;
214
- return errorResponse(401, "invalid_owner_credentials");
383
+ return rejectUnauthorizedEmail(policy, url.pathname, email, invalidCredentialsCode, emit);
384
+ }
385
+ export function enforceOwnerAuthRequest(policy, request) {
386
+ return enforceAuthRequest(policy, (email) => email === policy.ownerEmail, "invalid_owner_credentials", request);
215
387
  }
216
388
  function isEmailOtpSendRequest(policy, request) {
217
389
  const url = new URL(request.url);
218
390
  return (request.method.toUpperCase() === "POST" && url.pathname === `${policy.basePath}/email-otp/send-verification-otp`);
219
391
  }
220
- export function createOwnerAuth(options) {
221
- const policy = resolveOwnerAuthPolicy(options);
392
+ function isSessionIndependentRequest(policy, request) {
393
+ const method = request.method.toUpperCase();
394
+ const path = new URL(request.url).pathname;
395
+ return (path === `${policy.basePath}/sign-out` ||
396
+ (method === "POST" && path === `${policy.basePath}/email-otp/send-verification-otp`) ||
397
+ (method === "POST" && path === `${policy.basePath}/sign-in/email-otp`) ||
398
+ (method === "GET" && path === `${policy.basePath}/passkey/generate-authenticate-options`) ||
399
+ (method === "POST" && path === `${policy.basePath}/passkey/verify-authentication`));
400
+ }
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();
406
+ return user !== null && authorizeEmail(normalizeAuthEmail(user.email));
407
+ }
408
+ async function authorizePasskeyCredential(database, passkeyTable, userTable, credentialId, authorizeEmail) {
409
+ const user = await database
410
+ .prepare(`SELECT u."email" AS "email" FROM "${passkeyTable}" p INNER JOIN "${userTable}" u ON u."id" = p."userId" WHERE p."credentialID" = ?`)
411
+ .bind(credentialId)
412
+ .first();
413
+ return user !== null && authorizeEmail(normalizeAuthEmail(user.email));
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
+ }
452
+ function createConfiguredAuth(options, policy, authorizeEmail, invalidCredentialsCode) {
222
453
  const sessionExpiresIn = positiveInteger(options.sessionExpiresIn, DEFAULT_SESSION_LIFETIME_SECONDS, "owner_auth_session_lifetime_invalid");
223
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;
224
456
  const auth = betterAuth({
225
457
  advanced: {
226
458
  cookiePrefix: policy.cookiePrefix,
@@ -229,18 +461,35 @@ export function createOwnerAuth(options) {
229
461
  },
230
462
  appName: options.appName.trim(),
231
463
  basePath: policy.basePath,
232
- baseURL: policy.authServerOrigin,
464
+ baseURL: policy.baseURL,
233
465
  database: options.database,
234
466
  databaseHooks: {
467
+ session: {
468
+ create: {
469
+ before: async (session) => {
470
+ if (!(await authorizeUserId(options.database, policy.tableNames.user, session.userId, authorizeEmail))) {
471
+ throw new APIError("UNAUTHORIZED", { message: invalidCredentialsCode });
472
+ }
473
+ },
474
+ after: async (session) => {
475
+ await emitSecurityEvent(options.onSecurityEvent, {
476
+ sessionId: session.id,
477
+ type: "session_created",
478
+ userId: session.userId,
479
+ });
480
+ },
481
+ },
482
+ },
235
483
  user: {
236
484
  create: {
237
- before: (user) => Promise.resolve(normalizeOwnerEmail(user.email) === policy.ownerEmail),
485
+ before: async (user) => authorizeEmail(normalizeAuthEmail(user.email)),
238
486
  },
239
487
  update: {
240
- before: (user) => Promise.resolve(typeof user.email !== "string" || normalizeOwnerEmail(user.email) === policy.ownerEmail),
488
+ before: async (user) => typeof user.email !== "string" || authorizeEmail(normalizeAuthEmail(user.email)),
241
489
  },
242
490
  },
243
491
  },
492
+ account: { modelName: policy.tableNames.account },
244
493
  emailAndPassword: { enabled: false },
245
494
  plugins: [
246
495
  emailOTP({
@@ -250,54 +499,153 @@ export function createOwnerAuth(options) {
250
499
  otpLength: 6,
251
500
  rateLimit: policy.emailOtpRateLimit,
252
501
  sendVerificationOTP: ({ email, otp, type }) => {
253
- const shouldDeliver = type === "sign-in" && normalizeOwnerEmail(email) === policy.ownerEmail;
254
- const deliver = shouldDeliver
255
- ? () => options.sendVerificationOTP({ email: policy.ownerEmail, otp })
256
- : () => Promise.resolve();
257
- const deliveryTask = deferLifecycleTask(deliver);
258
- options.waitUntil(deliveryTask);
502
+ const deliver = async () => {
503
+ const normalizedEmail = normalizeAuthEmail(email);
504
+ if (type !== "sign-in" || !(await authorizeEmail(normalizedEmail)))
505
+ return;
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
+ }
516
+ };
517
+ const task = deferLifecycleTask(deliver);
518
+ options.waitUntil(task);
259
519
  return Promise.resolve();
260
520
  },
261
521
  storeOTP: "hashed",
262
522
  }),
263
523
  passkey({
264
524
  advanced: { webAuthnChallengeCookie: `${policy.cookiePrefix}-passkey` },
525
+ authentication: {
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 });
532
+ }
533
+ },
534
+ },
265
535
  authenticatorSelection: { residentKey: "required", userVerification: "required" },
266
- 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
+ },
267
544
  rpID: policy.relyingPartyId,
268
545
  rpName: options.appName.trim(),
546
+ schema: { passkey: { modelName: policy.tableNames.passkey } },
269
547
  }),
548
+ ...(turnstile ? [captcha(turnstile)] : []),
270
549
  ],
271
550
  rateLimit: {
272
551
  enabled: true,
273
552
  max: 100,
274
- modelName: "rateLimit",
553
+ modelName: policy.tableNames.rateLimit,
275
554
  storage: "database",
276
555
  window: 60,
277
556
  },
278
557
  secret: options.secrets === undefined ? options.secret : options.legacySecret,
279
558
  secrets: options.secrets,
559
+ ...(options.socialProviders ? { socialProviders: options.socialProviders } : {}),
280
560
  session: {
281
561
  expiresIn: sessionExpiresIn,
562
+ modelName: policy.tableNames.session,
282
563
  updateAge: sessionUpdateAge,
283
564
  },
284
- 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 },
285
583
  });
286
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
+ },
287
590
  handler: async (request) => {
288
- const rejection = await enforceOwnerAuthRequest(policy, request);
591
+ const rejection = await enforceAuthRequest(policy, authorizeEmail, invalidCredentialsCode, request, options.onSecurityEvent, options.database);
289
592
  if (rejection)
290
593
  return withCors(policy, request, rejection);
594
+ const currentSession = await auth.api.getSession({
595
+ headers: request.headers,
596
+ query: { disableCookieCache: true, disableRefresh: true },
597
+ });
598
+ if (currentSession &&
599
+ !(await authorizeEmail(normalizeAuthEmail(currentSession.user.email))) &&
600
+ !isSessionIndependentRequest(policy, request)) {
601
+ return withCors(policy, request, errorResponse(401, invalidCredentialsCode));
602
+ }
291
603
  const response = await auth.handler(request);
292
604
  return withCors(policy, request, isEmailOtpSendRequest(policy, request) ? genericEmailResponse() : response);
293
605
  },
606
+ listSessions: (userId) => listAuthSessionsForUser(options.database, policy.tableNames.session, userId),
294
607
  policy,
608
+ pruneRateLimits: (pruneOptions) => pruneAuthRateLimits(options.database, policy.tableNames.rateLimit, pruneOptions),
295
609
  resolveSession: async (headers) => {
296
- const session = await auth.api.getSession({ headers });
297
- if (!session || normalizeOwnerEmail(session.user.email) !== policy.ownerEmail)
610
+ const session = await auth.api.getSession({
611
+ headers,
612
+ query: { disableCookieCache: true, disableRefresh: true },
613
+ });
614
+ if (!session)
615
+ return null;
616
+ const email = normalizeAuthEmail(session.user.email);
617
+ if (!(await authorizeEmail(email)))
298
618
  return null;
299
- return { email: policy.ownerEmail, 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;
300
640
  },
301
641
  };
302
642
  }
643
+ export function createMultiUserAuth(options) {
644
+ const policy = resolveAuthPolicy(options);
645
+ return createConfiguredAuth(options, policy, (email) => options.authorizeEmail(email), "invalid_credentials");
646
+ }
647
+ export function createOwnerAuth(options) {
648
+ const policy = resolveOwnerAuthPolicy(options);
649
+ return createConfiguredAuth(options, policy, (email) => email === policy.ownerEmail, "invalid_owner_credentials");
650
+ }
303
651
  //# sourceMappingURL=index.js.map