@rebasepro/server 0.26.0 → 0.28.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.
Files changed (132) hide show
  1. package/dist/{GCSStorageController-40FyFeSx.js → GCSStorageController-LXeAF6Ks.js} +37 -4
  2. package/dist/GCSStorageController-LXeAF6Ks.js.map +1 -0
  3. package/dist/{S3StorageController-Bl5shp94.js → S3StorageController-CVKMUXo_.js} +59 -11
  4. package/dist/S3StorageController-CVKMUXo_.js.map +1 -0
  5. package/dist/{access-BFAUvsSs.js → access-BDz4FO9D.js} +7 -7
  6. package/dist/access-BDz4FO9D.js.map +1 -0
  7. package/dist/api/openapi-generator.d.ts +13 -1
  8. package/dist/api/rest/api-generator.d.ts +16 -0
  9. package/dist/api/rest/batch.d.ts +9 -0
  10. package/dist/{ast-schema-editor-madTa9Hh.js → ast-schema-editor-C4bDSb61.js} +2 -2
  11. package/dist/{ast-schema-editor-madTa9Hh.js.map → ast-schema-editor-C4bDSb61.js.map} +1 -1
  12. package/dist/auth/admin-users-route.d.ts +3 -0
  13. package/dist/auth/apple-oauth.d.ts +39 -10
  14. package/dist/auth/capabilities.d.ts +2 -0
  15. package/dist/auth/interfaces.d.ts +78 -4
  16. package/dist/auth/otp-routes.d.ts +10 -0
  17. package/dist/{auth-izI7AEzC.js → auth-CZGfVKcL.js} +350 -137
  18. package/dist/auth-CZGfVKcL.js.map +1 -0
  19. package/dist/auth_adapter-B7RUMk6e.js.map +1 -1
  20. package/dist/backend/options.d.ts +29 -1
  21. package/dist/backend-CaG_Jyso.js.map +1 -1
  22. package/dist/{backup-BVbHoKo8.js → backup-BmzY9xdN.js} +8 -8
  23. package/dist/{backup-BVbHoKo8.js.map → backup-BmzY9xdN.js.map} +1 -1
  24. package/dist/boot/env.d.ts +6 -0
  25. package/dist/{branch-routes-B2vvEx53.js → branch-routes-DpgaeTJl.js} +4 -4
  26. package/dist/{branch-routes-B2vvEx53.js.map → branch-routes-DpgaeTJl.js.map} +1 -1
  27. package/dist/{contract-routes-CU2A3JnF.js → contract-routes-vYiBHbjI.js} +3 -3
  28. package/dist/{contract-routes-CU2A3JnF.js.map → contract-routes-vYiBHbjI.js.map} +1 -1
  29. package/dist/cron/cron-loader.d.ts +16 -0
  30. package/dist/{cron-loader-mMhqbVsl.js → cron-loader-C_C-lNgG.js} +39 -10
  31. package/dist/cron-loader-C_C-lNgG.js.map +1 -0
  32. package/dist/{cron-routes-Cs33j_Kr.js → cron-routes-DlwOV6zl.js} +5 -5
  33. package/dist/{cron-routes-Cs33j_Kr.js.map → cron-routes-DlwOV6zl.js.map} +1 -1
  34. package/dist/{cron-scheduler-Be7CNghL.js → cron-scheduler-6ipIm5mm.js} +41 -28
  35. package/dist/cron-scheduler-6ipIm5mm.js.map +1 -0
  36. package/dist/{cron-store-DLn11M8H.js → cron-store-KIOM8LCC.js} +5 -5
  37. package/dist/{cron-store-DLn11M8H.js.map → cron-store-KIOM8LCC.js.map} +1 -1
  38. package/dist/{ddl-bootstrap-CjRrn12l.js → ddl-bootstrap-DhCuwhHM.js} +2 -2
  39. package/dist/{ddl-bootstrap-CjRrn12l.js.map → ddl-bootstrap-DhCuwhHM.js.map} +1 -1
  40. package/dist/dist-DVqwVrBQ.js +22 -0
  41. package/dist/dist-DVqwVrBQ.js.map +1 -0
  42. package/dist/{load-failure-L5hvfDoG.js → dynamic-import-Bi3XK5y-.js} +30 -18
  43. package/dist/dynamic-import-Bi3XK5y-.js.map +1 -0
  44. package/dist/{errors-OMWkKSH-.js → errors-DIWnZIDY.js} +2 -2
  45. package/dist/{errors-OMWkKSH-.js.map → errors-DIWnZIDY.js.map} +1 -1
  46. package/dist/{field-access-DYsvjI_P.js → field-access-KYk8RGOx.js} +3 -2
  47. package/dist/field-access-KYk8RGOx.js.map +1 -0
  48. package/dist/{filter-dialect-TrKFWLqT.js → filter-dialect-CE4bloug.js} +2 -2
  49. package/dist/{filter-dialect-TrKFWLqT.js.map → filter-dialect-CE4bloug.js.map} +1 -1
  50. package/dist/{function-loader-B8YzXEsQ.js → function-loader-CKB9b4uP.js} +15 -6
  51. package/dist/function-loader-CKB9b4uP.js.map +1 -0
  52. package/dist/{function-routes-RxrCHNuM.js → function-routes-DLaXaiQA.js} +2 -2
  53. package/dist/{function-routes-RxrCHNuM.js.map → function-routes-DLaXaiQA.js.map} +1 -1
  54. package/dist/functions/function-loader.d.ts +5 -0
  55. package/dist/functions/index.js +16 -9
  56. package/dist/functions/index.js.map +1 -1
  57. package/dist/{history-recorder-Bsau7h4X.js → history-recorder-BE4HWR-M.js} +4 -4
  58. package/dist/{history-recorder-Bsau7h4X.js.map → history-recorder-BE4HWR-M.js.map} +1 -1
  59. package/dist/{history-store-BQz5YCkW.js → history-store-D-jDz4Nv.js} +2 -2
  60. package/dist/{history-store-BQz5YCkW.js.map → history-store-D-jDz4Nv.js.map} +1 -1
  61. package/dist/index.d.ts +1 -1
  62. package/dist/index.es.js +1361 -232
  63. package/dist/index.es.js.map +1 -1
  64. package/dist/init/docs.d.ts +1 -1
  65. package/dist/init/health.d.ts +13 -0
  66. package/dist/{internal-tables-L2t39RdT.js → internal-tables-CRaBxJeE.js} +57 -2
  67. package/dist/{internal-tables-L2t39RdT.js.map → internal-tables-CRaBxJeE.js.map} +1 -1
  68. package/dist/{jobs-Co6Ni5HP.js → jobs-CXTs9qXH.js} +5 -5
  69. package/dist/{jobs-Co6Ni5HP.js.map → jobs-CXTs9qXH.js.map} +1 -1
  70. package/dist/{jwt-rDS0884_.js → jwt-5EvX3lQa.js} +3 -3
  71. package/dist/{jwt-rDS0884_.js.map → jwt-5EvX3lQa.js.map} +1 -1
  72. package/dist/{keys-BXcdRNhJ.js → keys-DJ1ZNcZi.js} +2 -2
  73. package/dist/{keys-BXcdRNhJ.js.map → keys-DJ1ZNcZi.js.map} +1 -1
  74. package/dist/{logger-CW8pmTS6.js → logger-SigQ2oZJ.js} +17 -10
  75. package/dist/logger-SigQ2oZJ.js.map +1 -0
  76. package/dist/{logs-routes-CBt7mMIL.js → logs-routes-DXLvMasE.js} +3 -3
  77. package/dist/{logs-routes-CBt7mMIL.js.map → logs-routes-DXLvMasE.js.map} +1 -1
  78. package/dist/mcp/mcp-apps.d.ts +53 -0
  79. package/dist/mcp/mcp-routes.d.ts +10 -1
  80. package/dist/mcp/mcp-tools.d.ts +10 -0
  81. package/dist/metrics/index.d.ts +8 -0
  82. package/dist/metrics/realtime.d.ts +25 -0
  83. package/dist/{offline-AvuEcg7u-DFHL98OT.js → offline-BjJdcVBb-BOzzsnrh.js} +35 -7
  84. package/dist/offline-BjJdcVBb-BOzzsnrh.js.map +1 -0
  85. package/dist/{offline-store-BhYXViha-YTmjBpo2.js → offline-store-Cxhh99Q--FB6fSf5A.js} +43 -9
  86. package/dist/offline-store-Cxhh99Q--FB6fSf5A.js.map +1 -0
  87. package/dist/{openapi-generator-CyxEtYEX.js → openapi-generator-B6aw_KuR.js} +41 -7
  88. package/dist/openapi-generator-B6aw_KuR.js.map +1 -0
  89. package/dist/{proxy-BYir8tWK.js → proxy-2nS5N63I.js} +3 -3
  90. package/dist/{proxy-BYir8tWK.js.map → proxy-2nS5N63I.js.map} +1 -1
  91. package/dist/{query-parser-CDXWf2hH.js → query-parser-DFVCjW5i.js} +6 -6
  92. package/dist/{query-parser-CDXWf2hH.js.map → query-parser-DFVCjW5i.js.map} +1 -1
  93. package/dist/{request-timeout-DVjo-c_8.js → request-timeout-Cqm4JXtZ.js} +3 -3
  94. package/dist/{request-timeout-DVjo-c_8.js.map → request-timeout-Cqm4JXtZ.js.map} +1 -1
  95. package/dist/{rls-simulator-routes-bEY7-5-u.js → rls-simulator-routes-D5-XfjzW.js} +4 -4
  96. package/dist/{rls-simulator-routes-bEY7-5-u.js.map → rls-simulator-routes-D5-XfjzW.js.map} +1 -1
  97. package/dist/{schema-editor-routes-Dc3DU_jm.js → schema-editor-routes-DzSe6V0a.js} +4 -4
  98. package/dist/{schema-editor-routes-Dc3DU_jm.js.map → schema-editor-routes-DzSe6V0a.js.map} +1 -1
  99. package/dist/services/routed-realtime-service.d.ts +1 -1
  100. package/dist/{soft-delete-params-BRONCOA2.js → soft-delete-params-9lKBAlDw.js} +2 -2
  101. package/dist/{soft-delete-params-BRONCOA2.js.map → soft-delete-params-9lKBAlDw.js.map} +1 -1
  102. package/dist/{sql-export-routes-QycX8W8S.js → sql-export-routes-BxMqgAFX.js} +4 -4
  103. package/dist/{sql-export-routes-QycX8W8S.js.map → sql-export-routes-BxMqgAFX.js.map} +1 -1
  104. package/dist/{src-Bh9LRPb9.js → src-JQNz7cWv.js} +19 -2
  105. package/dist/{src-Bh9LRPb9.js.map → src-JQNz7cWv.js.map} +1 -1
  106. package/dist/storage/GCSStorageController.d.ts +9 -1
  107. package/dist/storage/LocalStorageController.d.ts +8 -1
  108. package/dist/storage/S3StorageController.d.ts +4 -2
  109. package/dist/storage/index.d.ts +1 -0
  110. package/dist/storage/orphan-sweep.d.ts +67 -0
  111. package/dist/storage/policies.d.ts +1 -1
  112. package/dist/storage/streams.d.ts +17 -0
  113. package/dist/storage/types.d.ts +15 -33
  114. package/dist/{upload-validation-Bgo626uY.js → upload-validation-IYXn4xcm.js} +41 -3
  115. package/dist/upload-validation-IYXn4xcm.js.map +1 -0
  116. package/dist/utils/load-failure.d.ts +9 -0
  117. package/dist/utils/logger.d.ts +9 -4
  118. package/package.json +7 -6
  119. package/dist/GCSStorageController-40FyFeSx.js.map +0 -1
  120. package/dist/S3StorageController-Bl5shp94.js.map +0 -1
  121. package/dist/access-BFAUvsSs.js.map +0 -1
  122. package/dist/auth-izI7AEzC.js.map +0 -1
  123. package/dist/cron-loader-mMhqbVsl.js.map +0 -1
  124. package/dist/cron-scheduler-Be7CNghL.js.map +0 -1
  125. package/dist/field-access-DYsvjI_P.js.map +0 -1
  126. package/dist/function-loader-B8YzXEsQ.js.map +0 -1
  127. package/dist/load-failure-L5hvfDoG.js.map +0 -1
  128. package/dist/logger-CW8pmTS6.js.map +0 -1
  129. package/dist/offline-AvuEcg7u-DFHL98OT.js.map +0 -1
  130. package/dist/offline-store-BhYXViha-YTmjBpo2.js.map +0 -1
  131. package/dist/openapi-generator-CyxEtYEX.js.map +0 -1
  132. package/dist/upload-validation-Bgo626uY.js.map +0 -1
@@ -3,18 +3,18 @@ import __rebaseProcess from "process";
3
3
  globalThis.process ??= __rebaseProcess;
4
4
  __rebaseCreateRequire(import.meta.url);
5
5
  import { i as __toESM, n as __exportAll } from "./rolldown-runtime-dW7B1o5h.js";
6
- import { V as rewriteLegacyRlsFunctions, _ as scopesBeyond, a as KEY_MANAGEMENT_SCOPES, f as knownScopes, l as isAdminScope, m as roleNameProblem, o as SCOPE_TARGETS, p as parseScope, s as hasAdminRole, u as isBuiltInScope, x as validateScopes, y as summarizeRoles } from "./src-Bh9LRPb9.js";
6
+ import { V as rewriteLegacyRlsFunctions, _ as scopesBeyond, a as KEY_MANAGEMENT_SCOPES, f as knownScopes, l as isAdminScope, m as roleNameProblem, o as SCOPE_TARGETS, p as parseScope, s as hasAdminRole, u as isBuiltInScope, x as validateScopes, y as summarizeRoles } from "./src-JQNz7cWv.js";
7
7
  import { n as isAnonymousUid, r as policy, t as ANONYMOUS_USER_ID } from "./policy-PdzX-Opd.js";
8
8
  import { n as isSQLAdmin } from "./backend-CaG_Jyso.js";
9
- import { $ as accessTokenRefusalError, C as queryTokenAuth, E as requireAuth, G as isApiKeyToken, J as extractBearerToken, K as resolveApiKey, L as applySimulation, P as applyImpersonation, T as requireAdmin, X as SERVICE_IDENTITY, Y as safeCompare, Z as scopeDataDriver, _ as createAuthMiddleware, a as assertMayManageAccount, at as httpMethodToOperation, b as fileTokenAuth, c as configureAccess, f as processAccessControl, h as requireScopeByMethod, i as assertMayGrantRoles, l as getAccessModel, m as requireScope, n as accessModelFromCollections, nt as replaceUserPassword, o as callerIsAdmin, p as readRoleNames, q as validateApiKey, r as accessOf, rt as revokeAllSessions, s as callerScopes, t as AccessModelError, tt as judgeAccessToken, u as hasScope, v as createRequireAuth, w as refuse, x as optionalAuth, y as extractUserFromToken } from "./access-BFAUvsSs.js";
10
- import { a as logger } from "./logger-CW8pmTS6.js";
9
+ import { $ as accessTokenRefusalError, C as queryTokenAuth, E as requireAuth, G as isApiKeyToken, J as extractBearerToken, K as resolveApiKey, L as applySimulation, P as applyImpersonation, T as requireAdmin, X as SERVICE_IDENTITY, Y as safeCompare, Z as scopeDataDriver, _ as createAuthMiddleware, a as assertMayManageAccount, at as httpMethodToOperation, b as fileTokenAuth, c as configureAccess, f as processAccessControl, h as requireScopeByMethod, i as assertMayGrantRoles, l as getAccessModel, m as requireScope, n as accessModelFromCollections, nt as replaceUserPassword, o as callerIsAdmin, p as readRoleNames, q as validateApiKey, r as accessOf, rt as revokeAllSessions, s as callerScopes, t as AccessModelError, tt as judgeAccessToken, u as hasScope, v as createRequireAuth, w as refuse, x as optionalAuth, y as extractUserFromToken } from "./access-BDz4FO9D.js";
10
+ import { a as logger } from "./logger-SigQ2oZJ.js";
11
11
  import { r as toSnakeCase } from "./strings.es-B7QLnHh2.js";
12
- import { n as revokeInternalTableSql, t as REBASE_USER_ROLE } from "./internal-tables-L2t39RdT.js";
12
+ import { n as REBASE_USER_ROLE, r as revokeInternalTableSql } from "./internal-tables-CRaBxJeE.js";
13
13
  import { t as firstSqlRow } from "./sql-rows-C6GEc2oE.js";
14
- import { a as resolveListLimitParam } from "./query-parser-CDXWf2hH.js";
15
- import { _ as verifyAccessToken, a as generateAccessToken, c as getAccessTokenExpiry, d as hasAsymmetricSigningKey, f as hashRefreshToken, h as processJwtService, i as customClaimsOf, l as getJwks, m as jwtOf, n as configureJwt, o as generateDownloadToken, p as isJwtConfigured, s as generateRefreshToken, t as MAX_COOKIE_AGE_MS, u as getRefreshTokenExpiry, v as verifyDownloadToken, w as randomInt$1, x as require_jsonwebtoken } from "./jwt-rDS0884_.js";
16
- import { c as provisioningExec, n as SchemaChangeRefusedError, r as createDdlBootstrapper } from "./ddl-bootstrap-CjRrn12l.js";
17
- import { a as isDataException, c as warnIfDatabaseClosed, i as errorHandler, o as isDatabaseUnreachable, t as ApiError } from "./errors-OMWkKSH-.js";
14
+ import { a as resolveListLimitParam } from "./query-parser-DFVCjW5i.js";
15
+ import { _ as verifyAccessToken, a as generateAccessToken, c as getAccessTokenExpiry, d as hasAsymmetricSigningKey, f as hashRefreshToken, h as processJwtService, i as customClaimsOf, l as getJwks, m as jwtOf, n as configureJwt, o as generateDownloadToken, p as isJwtConfigured, s as generateRefreshToken, t as MAX_COOKIE_AGE_MS, u as getRefreshTokenExpiry, v as verifyDownloadToken, w as randomInt$1, x as require_jsonwebtoken } from "./jwt-5EvX3lQa.js";
16
+ import { c as provisioningExec, n as SchemaChangeRefusedError, r as createDdlBootstrapper } from "./ddl-bootstrap-DhCuwhHM.js";
17
+ import { a as isDataException, c as warnIfDatabaseClosed, i as errorHandler, o as isDatabaseUnreachable, r as declaredErrorAnswer, t as ApiError } from "./errors-DIWnZIDY.js";
18
18
  import { createHash, randomBytes, randomInt } from "node:crypto";
19
19
  import { Hono } from "hono";
20
20
  import { promisify } from "util";
@@ -264,8 +264,7 @@ function parseOperand(str) {
264
264
  if (/^\(\s*select\s+rebase\.uid\(\)(?:\s+as\s+"?uid"?)?\s*\)$/i.test(str)) return policy.authUid();
265
265
  const literal = parseSingleQuoted(str);
266
266
  if (literal !== null) return policy.literal(literal);
267
- if (/^-?\d+$/.test(str)) return policy.literal(Number(str));
268
- if (/^-?\d*\.\d+$/.test(str)) return policy.literal(Number(str));
267
+ if (/^-?\d+$/.test(str) || /^-?\d*\.\d+$/.test(str)) return isExactNumber(str) ? policy.literal(Number(str)) : null;
269
268
  if (/^true$/i.test(str)) return policy.literal(true);
270
269
  if (/^false$/i.test(str)) return policy.literal(false);
271
270
  if (/^null$/i.test(str)) return policy.literal(null);
@@ -273,6 +272,19 @@ function parseOperand(str) {
273
272
  return null;
274
273
  }
275
274
  /**
275
+ * Whether the decimal numeral `str` survives a trip through a JS `number` and
276
+ * back to text with its value intact: `0.50` does (as `0.5`), `2^53 + 1` and
277
+ * a twentieth decimal place do not.
278
+ */
279
+ function isExactNumber(str) {
280
+ const [whole, fraction = ""] = (str.startsWith("-") ? str.slice(1) : str).split(".");
281
+ const digits = whole.replace(/^0+(?=\d)/, "") || "0";
282
+ const decimals = fraction.replace(/0+$/, "");
283
+ const canonical = decimals ? `${digits}.${decimals}` : digits;
284
+ const value = Number(str);
285
+ return String(Math.abs(value)) === canonical;
286
+ }
287
+ /**
276
288
  * Decode a single-quoted SQL literal, or null when `str` is not exactly one.
277
289
  *
278
290
  * Rejecting is as important as decoding: `'a' = 'b'` is two literals and an
@@ -418,7 +430,7 @@ function evaluateCompare(op, left, right, ctx) {
418
430
  if (!l.known || !r.known) return "unknown";
419
431
  const a = l.value;
420
432
  const b = r.value;
421
- if (a === null || b === null) return "unknown";
433
+ if (a === null || a === void 0 || b === null || b === void 0) return "unknown";
422
434
  if (op === "eq") return a === b;
423
435
  if (op === "neq") return a !== b;
424
436
  if (typeof a === "string" && typeof b === "string") {
@@ -3540,7 +3552,7 @@ function readRefreshToken(c, body, config) {
3540
3552
  for (const part of cookies) {
3541
3553
  const trimmed = part.trim();
3542
3554
  if (trimmed.startsWith(prefix)) {
3543
- const fromCookie = decodeURIComponent(trimmed.slice(prefix.length));
3555
+ const fromCookie = decodeCookieValue(trimmed.slice(prefix.length));
3544
3556
  if (fromCookie) return fromCookie;
3545
3557
  }
3546
3558
  }
@@ -3548,6 +3560,23 @@ function readRefreshToken(c, body, config) {
3548
3560
  return body.refreshToken || void 0;
3549
3561
  }
3550
3562
  /**
3563
+ * A cookie value as this server wrote it, or `undefined` when it is not valid
3564
+ * percent-encoding.
3565
+ *
3566
+ * `setRefreshCookie` encodes, so such a value is never one of ours: it is a
3567
+ * cookie of the same name set by somebody else — a sibling subdomain can set
3568
+ * one on the parent domain. It is no token, and the next cookie of the name
3569
+ * may be. A throw here would answer 500 on `/refresh` and on `/logout`, and
3570
+ * `/logout` would never reach the line that clears the cookie.
3571
+ */
3572
+ function decodeCookieValue(value) {
3573
+ try {
3574
+ return decodeURIComponent(value);
3575
+ } catch {
3576
+ return;
3577
+ }
3578
+ }
3579
+ /**
3551
3580
  * Redact the refresh token from the response body when cookie mode is active.
3552
3581
  */
3553
3582
  function redactRefreshToken(response, c, refreshToken, config) {
@@ -4265,6 +4294,7 @@ function mountEmailChangeRoutes(opts) {
4265
4294
  if (!updated) throw invalid();
4266
4295
  for (const identity of vouchingForOld) await authRepo.unlinkUserIdentity?.(user.id, identity.provider, identity.providerId);
4267
4296
  await authRepo.deleteAllPasswordResetTokensForUser(user.id);
4297
+ await authRepo.deleteAllMagicLinkTokensForUser?.(user.id);
4268
4298
  logger.info("[Security Audit] Email address changed", {
4269
4299
  eventType: "auth.email_change.confirmed",
4270
4300
  uid: user.id,
@@ -4604,103 +4634,6 @@ async function accountForPasswordlessRequest(config, ops, email) {
4604
4634
  return user;
4605
4635
  }
4606
4636
  //#endregion
4607
- //#region src/auth/magic-link-routes.ts
4608
- /**
4609
- * Magic link token expiry (15 minutes from now)
4610
- */
4611
- function getMagicLinkExpiry() {
4612
- return new Date(Date.now() + 900 * 1e3);
4613
- }
4614
- /**
4615
- * Mount magic link routes onto the auth router.
4616
- *
4617
- * Follows the same delegation pattern as `mountMfaRoutes()` and `mountSessionRoutes()`.
4618
- */
4619
- function mountMagicLinkRoutes(deps) {
4620
- const { router, config, limiters, ops, parseBody, buildAuthResponse, createSessionAndTokens, applyTransformHook, captchaMiddleware } = deps;
4621
- const { authRepo, emailService, emailConfig } = config;
4622
- const magicLinkSchema = z.object({ email: z.string().email("Invalid email address").max(255) });
4623
- const verifyMagicLinkSchema = z.object({ token: z.string().min(1, "Token is required") });
4624
- function isEmailConfigured() {
4625
- return !!(emailService && emailService.isConfigured());
4626
- }
4627
- /**
4628
- * POST /auth/magic-link
4629
- * Request a magic link email
4630
- *
4631
- * Answers the same words whether or not the address has an account, and
4632
- * is held to the same three things as its siblings `/otp` and
4633
- * `/forgot-password` so that nothing else answers the question either:
4634
- * the same response time, a per-address send limit, and `beforeLogin` on
4635
- * every attempt. This route had none of the three — the SMTP send was
4636
- * awaited only for a real account, and the only limit was per IP — so its
4637
- * timing named the customers and a spread-out run could fill one inbox.
4638
- */
4639
- router.post("/magic-link", limiters.strict, captureRecipientEmail, limiters.recipientEmail, ...captchaMiddleware ? [captchaMiddleware] : [], async (c) => {
4640
- const startedAt = Date.now();
4641
- const { email } = parseBody(magicLinkSchema, await c.req.json());
4642
- if (!isEmailConfigured()) throw ApiError.serviceUnavailable("Email service not configured. Magic link login is not available.", "EMAIL_NOT_CONFIGURED");
4643
- if (ops.beforeLogin) await ops.beforeLogin(email, "magic-link");
4644
- const user = await accountForPasswordlessRequest(config, ops, email);
4645
- if (user) {
4646
- const token = generateSecureToken();
4647
- const tokenHash = hashToken(token);
4648
- const expiresAt = getMagicLinkExpiry();
4649
- await authRepo.createMagicLinkToken(user.id, tokenHash, expiresAt);
4650
- const magicLinkUrl = `${resolveEmailLinkBase(emailConfig, "magicLink")}/auth/magic-link?token=${token}`;
4651
- const { appName, logoUrl } = resolveEmailBranding(emailConfig);
4652
- const templateFn = emailConfig?.templates?.magicLink;
4653
- const emailContent = templateFn ? templateFn(magicLinkUrl, {
4654
- email: user.email,
4655
- displayName: user.displayName
4656
- }) : getMagicLinkTemplate(magicLinkUrl, {
4657
- email: user.email,
4658
- displayName: user.displayName
4659
- }, appName, logoUrl);
4660
- emailService.send({
4661
- to: user.email,
4662
- subject: emailContent.subject,
4663
- html: emailContent.html,
4664
- text: emailContent.text
4665
- }).catch((emailError) => {
4666
- logger.error("Failed to send magic link email", { error: emailError instanceof Error ? emailError.message : emailError });
4667
- });
4668
- }
4669
- return notBefore$1(startedAt, 400, c.json({
4670
- success: true,
4671
- message: "If an account with that email exists, a magic link has been sent."
4672
- }));
4673
- });
4674
- /**
4675
- * POST /auth/magic-link/verify
4676
- * Verify magic link token and create session
4677
- */
4678
- router.post("/magic-link/verify", limiters.strict, async (c) => {
4679
- const { token } = parseBody(verifyMagicLinkSchema, await c.req.json());
4680
- const tokenHash = hashToken(token);
4681
- const storedToken = await authRepo.findValidMagicLinkToken(tokenHash);
4682
- if (!storedToken) throw ApiError.badRequest("Invalid or expired magic link", "INVALID_TOKEN");
4683
- await authRepo.markMagicLinkTokenUsed(tokenHash);
4684
- let user = await authRepo.getUserById(storedToken.uid);
4685
- if (!user) throw ApiError.badRequest("Invalid or expired magic link", "INVALID_TOKEN");
4686
- if (!user.emailVerified) {
4687
- await confirmAddressOwnership(authRepo, user, null);
4688
- user = {
4689
- ...user,
4690
- emailVerified: true,
4691
- passwordHash: null
4692
- };
4693
- }
4694
- const { roleIds, accessToken, refreshToken } = await createSessionAndTokens(user.id, c.req.header("user-agent") || "unknown", requestClientAddress(c), { method: "magic-link" });
4695
- if (ops.onAuthenticated) ops.onAuthenticated(user, "magic-link").catch((err) => {
4696
- logger.error("[AuthHooks] onAuthenticated error", { error: err instanceof Error ? err.message : err });
4697
- });
4698
- const authResponse = buildAuthResponse(user, roleIds, accessToken, refreshToken, "magic-link");
4699
- const transformedResponse = await applyTransformHook(authResponse, "magic-link", c.req.raw, user.id);
4700
- return c.json(redactRefreshToken(transformedResponse, c, refreshToken, config.cookieAuth));
4701
- });
4702
- }
4703
- //#endregion
4704
4637
  //#region src/auth/otp-routes.ts
4705
4638
  /** How long a code is good for. */
4706
4639
  var OTP_TTL_MS = 600 * 1e3;
@@ -4726,9 +4659,19 @@ function generateOtpCode() {
4726
4659
  * so that the address the user types matches the one they were mailed at.
4727
4660
  */
4728
4661
  function otpTokenMaterial(email, code) {
4729
- return `otp:${email.trim().toLowerCase()}:${code}`;
4662
+ return `${OTP_TOKEN_PREFIX}${email.trim().toLowerCase()}:${code}`;
4730
4663
  }
4731
4664
  /**
4665
+ * How every code's stored material begins.
4666
+ *
4667
+ * Codes share the magic-link token store, and `/magic-link/verify` hashes
4668
+ * whatever token it is handed — so the material of a code, which is the
4669
+ * address and six digits, is a token that route would find. It refuses
4670
+ * anything with this prefix, which no link token has, so a code is only ever
4671
+ * spent here, behind the per-address limit.
4672
+ */
4673
+ var OTP_TOKEN_PREFIX = "otp:";
4674
+ /**
4732
4675
  * Per-address throttle on code verification.
4733
4676
  *
4734
4677
  * Keyed on the address rather than the IP, for the reason
@@ -4873,7 +4816,7 @@ function mountOtpRoutes(deps) {
4873
4816
  const tokenHash = hashToken(otpTokenMaterial(email, code));
4874
4817
  const storedToken = await authRepo.findValidMagicLinkToken(tokenHash);
4875
4818
  if (!storedToken) throw ApiError.badRequest("Invalid or expired code", "INVALID_CODE");
4876
- await authRepo.markMagicLinkTokenUsed(tokenHash);
4819
+ if (await authRepo.markMagicLinkTokenUsed(tokenHash) === false) throw ApiError.badRequest("Invalid or expired code", "INVALID_CODE");
4877
4820
  let user = await authRepo.getUserById(storedToken.uid);
4878
4821
  if (!user) throw ApiError.badRequest("Invalid or expired code", "INVALID_CODE");
4879
4822
  if (!user.emailVerified) {
@@ -4894,6 +4837,104 @@ function mountOtpRoutes(deps) {
4894
4837
  });
4895
4838
  }
4896
4839
  //#endregion
4840
+ //#region src/auth/magic-link-routes.ts
4841
+ /**
4842
+ * Magic link token expiry (15 minutes from now)
4843
+ */
4844
+ function getMagicLinkExpiry() {
4845
+ return new Date(Date.now() + 900 * 1e3);
4846
+ }
4847
+ /**
4848
+ * Mount magic link routes onto the auth router.
4849
+ *
4850
+ * Follows the same delegation pattern as `mountMfaRoutes()` and `mountSessionRoutes()`.
4851
+ */
4852
+ function mountMagicLinkRoutes(deps) {
4853
+ const { router, config, limiters, ops, parseBody, buildAuthResponse, createSessionAndTokens, applyTransformHook, captchaMiddleware } = deps;
4854
+ const { authRepo, emailService, emailConfig } = config;
4855
+ const magicLinkSchema = z.object({ email: z.string().email("Invalid email address").max(255) });
4856
+ const verifyMagicLinkSchema = z.object({ token: z.string().min(1, "Token is required") });
4857
+ function isEmailConfigured() {
4858
+ return !!(emailService && emailService.isConfigured());
4859
+ }
4860
+ /**
4861
+ * POST /auth/magic-link
4862
+ * Request a magic link email
4863
+ *
4864
+ * Answers the same words whether or not the address has an account, and
4865
+ * is held to the same three things as its siblings `/otp` and
4866
+ * `/forgot-password` so that nothing else answers the question either:
4867
+ * the same response time, a per-address send limit, and `beforeLogin` on
4868
+ * every attempt. This route had none of the three — the SMTP send was
4869
+ * awaited only for a real account, and the only limit was per IP — so its
4870
+ * timing named the customers and a spread-out run could fill one inbox.
4871
+ */
4872
+ router.post("/magic-link", limiters.strict, captureRecipientEmail, limiters.recipientEmail, ...captchaMiddleware ? [captchaMiddleware] : [], async (c) => {
4873
+ const startedAt = Date.now();
4874
+ const { email } = parseBody(magicLinkSchema, await c.req.json());
4875
+ if (!isEmailConfigured()) throw ApiError.serviceUnavailable("Email service not configured. Magic link login is not available.", "EMAIL_NOT_CONFIGURED");
4876
+ if (ops.beforeLogin) await ops.beforeLogin(email, "magic-link");
4877
+ const user = await accountForPasswordlessRequest(config, ops, email);
4878
+ if (user) {
4879
+ const token = generateSecureToken();
4880
+ const tokenHash = hashToken(token);
4881
+ const expiresAt = getMagicLinkExpiry();
4882
+ await authRepo.createMagicLinkToken(user.id, tokenHash, expiresAt);
4883
+ const magicLinkUrl = `${resolveEmailLinkBase(emailConfig, "magicLink")}/auth/magic-link?token=${token}`;
4884
+ const { appName, logoUrl } = resolveEmailBranding(emailConfig);
4885
+ const templateFn = emailConfig?.templates?.magicLink;
4886
+ const emailContent = templateFn ? templateFn(magicLinkUrl, {
4887
+ email: user.email,
4888
+ displayName: user.displayName
4889
+ }) : getMagicLinkTemplate(magicLinkUrl, {
4890
+ email: user.email,
4891
+ displayName: user.displayName
4892
+ }, appName, logoUrl);
4893
+ emailService.send({
4894
+ to: user.email,
4895
+ subject: emailContent.subject,
4896
+ html: emailContent.html,
4897
+ text: emailContent.text
4898
+ }).catch((emailError) => {
4899
+ logger.error("Failed to send magic link email", { error: emailError instanceof Error ? emailError.message : emailError });
4900
+ });
4901
+ }
4902
+ return notBefore$1(startedAt, 400, c.json({
4903
+ success: true,
4904
+ message: "If an account with that email exists, a magic link has been sent."
4905
+ }));
4906
+ });
4907
+ /**
4908
+ * POST /auth/magic-link/verify
4909
+ * Verify magic link token and create session
4910
+ */
4911
+ router.post("/magic-link/verify", limiters.strict, async (c) => {
4912
+ const { token } = parseBody(verifyMagicLinkSchema, await c.req.json());
4913
+ if (token.startsWith("otp:")) throw ApiError.badRequest("Invalid or expired magic link", "INVALID_TOKEN");
4914
+ const tokenHash = hashToken(token);
4915
+ const storedToken = await authRepo.findValidMagicLinkToken(tokenHash);
4916
+ if (!storedToken) throw ApiError.badRequest("Invalid or expired magic link", "INVALID_TOKEN");
4917
+ if (await authRepo.markMagicLinkTokenUsed(tokenHash) === false) throw ApiError.badRequest("Invalid or expired magic link", "INVALID_TOKEN");
4918
+ let user = await authRepo.getUserById(storedToken.uid);
4919
+ if (!user) throw ApiError.badRequest("Invalid or expired magic link", "INVALID_TOKEN");
4920
+ if (!user.emailVerified) {
4921
+ await confirmAddressOwnership(authRepo, user, null);
4922
+ user = {
4923
+ ...user,
4924
+ emailVerified: true,
4925
+ passwordHash: null
4926
+ };
4927
+ }
4928
+ const { roleIds, accessToken, refreshToken } = await createSessionAndTokens(user.id, c.req.header("user-agent") || "unknown", requestClientAddress(c), { method: "magic-link" });
4929
+ if (ops.onAuthenticated) ops.onAuthenticated(user, "magic-link").catch((err) => {
4930
+ logger.error("[AuthHooks] onAuthenticated error", { error: err instanceof Error ? err.message : err });
4931
+ });
4932
+ const authResponse = buildAuthResponse(user, roleIds, accessToken, refreshToken, "magic-link");
4933
+ const transformedResponse = await applyTransformHook(authResponse, "magic-link", c.req.raw, user.id);
4934
+ return c.json(redactRefreshToken(transformedResponse, c, refreshToken, config.cookieAuth));
4935
+ });
4936
+ }
4937
+ //#endregion
4897
4938
  //#region src/auth/oauth-signin-policy.ts
4898
4939
  /**
4899
4940
  * May an OAuth identity be attached to a pre-existing account found *by email*?
@@ -5559,11 +5600,11 @@ function createAuthRoutes(config) {
5559
5600
  const tokenHash = hashToken(token);
5560
5601
  const storedToken = await authRepo.findValidPasswordResetToken(tokenHash);
5561
5602
  if (!storedToken) throw ApiError.badRequest("Invalid or expired reset token", "INVALID_TOKEN");
5603
+ if (await authRepo.markPasswordResetTokenUsed(tokenHash) === false) throw ApiError.badRequest("Invalid or expired reset token", "INVALID_TOKEN");
5562
5604
  const passwordHash = await ops.hashPassword(password);
5563
5605
  const account = await authRepo.getUserById(storedToken.uid);
5564
5606
  if (account && !account.emailVerified) await confirmAddressOwnership(authRepo, account, passwordHash);
5565
5607
  else await replaceUserPassword(authRepo, storedToken.uid, passwordHash);
5566
- await authRepo.markPasswordResetTokenUsed(tokenHash);
5567
5608
  if (ops.onAuthenticated && account) ops.onAuthenticated(account, "password-reset").catch((err) => {
5568
5609
  logger.error("[AuthHooks] onAuthenticated error", { error: err instanceof Error ? err.message : err });
5569
5610
  });
@@ -5576,10 +5617,28 @@ function createAuthRoutes(config) {
5576
5617
  });
5577
5618
  });
5578
5619
  /**
5620
+ * Per-account throttle on `/change-password`.
5621
+ *
5622
+ * The current password is what stands between a stolen access token and
5623
+ * the account: it is the one thing a token holder does not have, and
5624
+ * changing the password signs every other device out. Unthrottled, the
5625
+ * route would answer whether a guess is right as fast as the hash allows,
5626
+ * for as long as the token lives. Keyed on the account, not the address,
5627
+ * because the token is the attacker's to replay from anywhere. The same
5628
+ * numbers as `mfaVerificationLimiter`, which guards the other factor.
5629
+ */
5630
+ const passwordChangeLimiter = limiters.named({
5631
+ name: "auth-change-password",
5632
+ windowMs: 900 * 1e3,
5633
+ limit: 10,
5634
+ keyGenerator: (c) => `change-password:${c.get("user")?.uid ?? requestClientAddress(c)}`,
5635
+ message: "Too many password change attempts for this account, please try again later."
5636
+ });
5637
+ /**
5579
5638
  * POST /auth/change-password
5580
5639
  * Change password for authenticated user
5581
5640
  */
5582
- router.post("/change-password", requireLiveSession, async (c) => {
5641
+ router.post("/change-password", requireLiveSession, passwordChangeLimiter, async (c) => {
5583
5642
  const userCtx = c.get("user");
5584
5643
  if (!userCtx) throw ApiError.unauthorized("Not authenticated");
5585
5644
  const { oldPassword, newPassword } = parseBody(changePasswordSchema, await c.req.json());
@@ -5907,7 +5966,7 @@ function createAuthRoutes(config) {
5907
5966
  * `anonymousLogin` go through the shared predicates for exactly that reason.
5908
5967
  */
5909
5968
  function buildBuiltinAuthCapabilities(inputs) {
5910
- const { needsSetup, allowRegistration, disableSelfRegistration, allowAnonymous, enableMagicLink, enableEmailOtp, emailConfigured, enabledProviders } = inputs;
5969
+ const { needsSetup, allowRegistration, disableSelfRegistration, allowAnonymous, enableMagicLink, enableEmailOtp, emailConfigured, enabledProviders, providerClientIds } = inputs;
5911
5970
  return {
5912
5971
  hasBuiltInAuthRoutes: true,
5913
5972
  emailPasswordLogin: true,
@@ -5928,6 +5987,7 @@ function buildBuiltinAuthCapabilities(inputs) {
5928
5987
  disableSelfRegistration
5929
5988
  }),
5930
5989
  enabledProviders,
5990
+ ...providerClientIds && Object.keys(providerClientIds).length > 0 ? { providerClientIds } : {},
5931
5991
  needsSetup
5932
5992
  };
5933
5993
  }
@@ -6174,10 +6234,34 @@ function mayPickUsers(c) {
6174
6234
  * PUT /users/:uid
6175
6235
  * DELETE /users/:uid
6176
6236
  * DELETE /users/:uid/mfa
6237
+ * GET /guests
6238
+ * DELETE /guests
6239
+ * DELETE /guests/:uid
6177
6240
  * POST /bootstrap
6178
6241
  */
6179
6242
  /** Upper bound for `GET /users?ids=…`, so one request can't fan out unbounded. */
6180
6243
  var MAX_USER_IDS_PER_LOOKUP = 100;
6244
+ /**
6245
+ * How many guests one `DELETE /guests` takes, so a project with a million of
6246
+ * them is cleaned over many short requests. Each guest is a few statements.
6247
+ */
6248
+ var GUESTS_PER_DELETE = 200;
6249
+ /** A repository without the guest operations cannot answer these routes. */
6250
+ function requireGuestStore(repo) {
6251
+ if (typeof repo.listGuests !== "function" || typeof repo.deleteGuest !== "function") throw new ApiError(501, "NOT_SUPPORTED", "This backend's auth repository cannot list or delete guests.");
6252
+ }
6253
+ /** `?lastSeenBefore=`, which reaches the guests' deletion: a date in the past, or a refusal. */
6254
+ function readLastSeenBefore(c) {
6255
+ const value = c.req.query("lastSeenBefore");
6256
+ if (value === void 0) return void 0;
6257
+ const date = new Date(value);
6258
+ if (Number.isNaN(date.getTime()) || date.getTime() > Date.now()) throw ApiError.badRequest("`lastSeenBefore` must be a date in the past", "INVALID_INPUT");
6259
+ return date;
6260
+ }
6261
+ /** `?offset=`, as `GET /users` reads it. */
6262
+ function readOffset(c) {
6263
+ return Math.max(0, parseInt(c.req.query("offset") ?? "0", 10) || 0);
6264
+ }
6181
6265
  function createAdminUsersRoute(config) {
6182
6266
  const router = new Hono();
6183
6267
  const authRepo = config.authRepo;
@@ -6465,6 +6549,108 @@ function createAdminUsersRoute(config) {
6465
6549
  removedFactors: factors.length
6466
6550
  });
6467
6551
  });
6552
+ /**
6553
+ * Delete one guest under the rules and hooks of `DELETE /users/:uid`, and
6554
+ * say whether it went. It does not go when it is not a guest any more:
6555
+ * `deleteGuest` decides that in the statement that deletes. The sessions
6556
+ * end after it, not before as there: a guest who became an account a moment
6557
+ * ago keeps the ones it has.
6558
+ */
6559
+ async function removeGuest(c, repo, uid) {
6560
+ assertMayManageAccount(c, await authRepo.getUserRoleIds(uid));
6561
+ await assertUserDeletionsAllowed(authRepo, [uid]);
6562
+ if (ops.beforeUserDelete) await ops.beforeUserDelete(uid);
6563
+ if (!await repo.deleteGuest(uid)) return false;
6564
+ await authRepo.deleteAllRefreshTokensForUser(uid);
6565
+ runAfterUserDelete(ops, uid);
6566
+ return true;
6567
+ }
6568
+ /**
6569
+ * The guests anonymous sign-in left behind, the ones last seen longest ago
6570
+ * first, with how many there are. `?lastSeenBefore=` narrows them to the
6571
+ * ones `DELETE /guests` would take, which makes `total` its dry run.
6572
+ *
6573
+ * A route of its own, not a filter on `GET /users`: a runtime that does not
6574
+ * know a filter ignores it and answers with every account.
6575
+ */
6576
+ router.get("/guests", requireScope("users:read"), async (c) => {
6577
+ requireGuestStore(authRepo);
6578
+ const limit = resolveListLimitParam(c.req.query("limit"), { defaultLimit: 25 });
6579
+ const offset = readOffset(c);
6580
+ const { guests, total } = await authRepo.listGuests({
6581
+ limit,
6582
+ offset,
6583
+ lastSeenBefore: readLastSeenBefore(c)
6584
+ });
6585
+ const listed = guests.map((guest) => ({
6586
+ uid: guest.id,
6587
+ createdAt: guest.createdAt.toISOString(),
6588
+ lastSeenAt: guest.lastSeenAt.toISOString()
6589
+ }));
6590
+ return c.json({
6591
+ guests: listed,
6592
+ total,
6593
+ limit,
6594
+ offset
6595
+ });
6596
+ });
6597
+ /**
6598
+ * Delete one batch of the guests last seen before `?lastSeenBefore=`, which
6599
+ * is required: nothing here means "all of them". Every id comes from
6600
+ * `listGuests` and goes through `deleteGuest`, so no account can be reached.
6601
+ *
6602
+ * One guest that cannot go does not stop the rest: it is reported in
6603
+ * `skipped` and stays at the front of the order, which is why the caller
6604
+ * passes how many it has skipped as `?offset=`.
6605
+ */
6606
+ router.delete("/guests", requireScope("users:write"), async (c) => {
6607
+ requireGuestStore(authRepo);
6608
+ const lastSeenBefore = readLastSeenBefore(c);
6609
+ if (!lastSeenBefore) throw ApiError.badRequest("`lastSeenBefore` is required", "INVALID_INPUT");
6610
+ const offset = readOffset(c);
6611
+ const { guests, total } = await authRepo.listGuests({
6612
+ limit: GUESTS_PER_DELETE,
6613
+ offset,
6614
+ lastSeenBefore
6615
+ });
6616
+ const result = {
6617
+ deleted: 0,
6618
+ skipped: [],
6619
+ remaining: Math.max(0, total - offset - guests.length)
6620
+ };
6621
+ for (const { id } of guests) try {
6622
+ if (await removeGuest(c, authRepo, id)) result.deleted++;
6623
+ } catch (err) {
6624
+ const answer = declaredErrorAnswer(err);
6625
+ if (!answer) logger.error("Could not delete a guest", {
6626
+ uid: id,
6627
+ error: err instanceof Error ? err.message : err
6628
+ });
6629
+ result.skipped.push({
6630
+ uid: id,
6631
+ code: answer?.code ?? "INTERNAL_ERROR",
6632
+ message: answer?.message ?? "Could not delete this guest. See the server log."
6633
+ });
6634
+ }
6635
+ logger.info("[Security Audit] Guests deleted by an administrator", {
6636
+ eventType: "auth.guests.deleted",
6637
+ by: c.get("user")?.uid,
6638
+ lastSeenBefore: lastSeenBefore.toISOString(),
6639
+ deleted: result.deleted,
6640
+ skipped: result.skipped.length
6641
+ });
6642
+ return c.json(result);
6643
+ });
6644
+ router.delete("/guests/:uid", requireScope("users:write"), async (c) => {
6645
+ requireGuestStore(authRepo);
6646
+ const uid = c.req.param("uid");
6647
+ const existing = await authRepo.getUserById(uid);
6648
+ if (!existing) throw ApiError.notFound("User not found");
6649
+ const refuse = () => ApiError.badRequest("This user is an account, not a guest.", "NOT_ANONYMOUS");
6650
+ if (existing.isAnonymous !== true) throw refuse();
6651
+ if (!await removeGuest(c, authRepo, uid)) throw refuse();
6652
+ return c.json({ success: true });
6653
+ });
6468
6654
  router.delete("/users/:uid", requireScope("users:write"), async (c) => {
6469
6655
  const uid = c.req.param("uid");
6470
6656
  if (c.get("user")?.uid === uid) throw ApiError.badRequest("Cannot delete your own account", "SELF_DELETE");
@@ -6730,7 +6916,8 @@ function createBuiltinAuthAdapter(config) {
6730
6916
  enableMagicLink,
6731
6917
  enableEmailOtp,
6732
6918
  emailConfigured: !!emailService?.isConfigured(),
6733
- enabledProviders: oauthProviders.map((p) => p.id)
6919
+ enabledProviders: oauthProviders.map((p) => p.id),
6920
+ providerClientIds: Object.fromEntries(oauthProviders.flatMap((p) => p.publicClientId ? [[p.id, p.publicClientId]] : []))
6734
6921
  });
6735
6922
  }
6736
6923
  };
@@ -8120,53 +8307,79 @@ var APPLE_JWKS_URI = "https://appleid.apple.com/auth/keys";
8120
8307
  * token exchange (valid up to 6 months). This provider handles that automatically.
8121
8308
  *
8122
8309
  * Required Apple Developer configuration:
8123
- * - Services ID (clientId)
8310
+ * - Services ID (clientId) for web sign-in, and/or the bundle ids of the
8311
+ * native apps (bundleIds)
8124
8312
  * - Key ID from the private key registered with Apple
8125
8313
  * - Team ID from Apple Developer account
8126
8314
  * - Private key (.p8 file contents) downloaded from Apple Developer portal
8127
8315
  */
8128
8316
  function createAppleProvider(config) {
8317
+ const bundleIds = (config.bundleIds ?? []).map((id) => id.trim()).filter(Boolean);
8318
+ if (!config.clientId && bundleIds.length === 0) throw new Error("Apple sign-in needs a Services ID (clientId), at least one app bundle id (bundleIds), or both.");
8129
8319
  /**
8130
8320
  * Generate a client_secret JWT signed with the Apple private key.
8131
- * Apple requires this instead of a static client_secret.
8321
+ * Apple requires this instead of a static client_secret, and its `sub`
8322
+ * names the client the code was issued to.
8132
8323
  */
8133
- async function generateClientSecret() {
8324
+ async function generateClientSecret(clientId) {
8134
8325
  return import_jsonwebtoken.default.sign({}, config.privateKey, {
8135
8326
  algorithm: "ES256",
8136
8327
  keyid: config.keyId,
8137
8328
  issuer: config.teamId,
8138
8329
  expiresIn: "180d",
8139
8330
  audience: "https://appleid.apple.com",
8140
- subject: config.clientId
8331
+ subject: clientId
8141
8332
  });
8142
8333
  }
8334
+ /**
8335
+ * The client the code was issued to, or null when this backend does not
8336
+ * know it. The bundle id is the caller's claim, so it is only ever taken
8337
+ * from the configured list — and Apple refuses the exchange anyway if the
8338
+ * code was issued to a different client than the one named.
8339
+ */
8340
+ function resolveClient(payload) {
8341
+ if (payload.bundleId !== void 0) return bundleIds.includes(payload.bundleId) ? { clientId: payload.bundleId } : null;
8342
+ return config.clientId ? {
8343
+ clientId: config.clientId,
8344
+ redirectUri: payload.redirectUri
8345
+ } : null;
8346
+ }
8143
8347
  return {
8144
8348
  id: "apple",
8145
- schema: oauthCodeFlowSchema().extend({
8146
- /**
8147
- * Apple sends user info only on first authorization; the frontend
8148
- * must forward it. Only the *name* is accepted — an `email` here
8149
- * used to be promoted to the account's identity whenever the
8150
- * id_token had no `email` claim, and an attacker chooses whether
8151
- * that claim is absent simply by omitting the `email` scope from
8152
- * their own authorization request.
8153
- */
8154
- user: z.object({ name: z.object({
8155
- firstName: z.string().optional(),
8156
- lastName: z.string().optional()
8157
- }).optional() }).optional() }),
8349
+ publicClientId: config.clientId,
8350
+ schema: oauthCodeFlowSchema().extend({
8351
+ redirectUri: z.string().url("Valid redirect URI is required").optional(),
8352
+ bundleId: z.string().min(1).optional(),
8353
+ /**
8354
+ * Apple sends user info only on first authorization; the frontend
8355
+ * must forward it. Only the *name* is accepted — an `email` here
8356
+ * used to be promoted to the account's identity whenever the
8357
+ * id_token had no `email` claim, and an attacker chooses whether
8358
+ * that claim is absent simply by omitting the `email` scope from
8359
+ * their own authorization request.
8360
+ */
8361
+ user: z.object({ name: z.object({
8362
+ firstName: z.string().optional(),
8363
+ lastName: z.string().optional()
8364
+ }).optional() }).optional()
8365
+ }).refine((payload) => payload.redirectUri === void 0 !== (payload.bundleId === void 0), { message: "Send redirectUri for web sign-in or bundleId for a native app, not both" }),
8158
8366
  verify: async (payload) => {
8367
+ const client = resolveClient(payload);
8368
+ if (!client) {
8369
+ logger.error(payload.bundleId !== void 0 ? "Apple sign-in from an app bundle id this backend does not list in bundleIds" : "Apple web sign-in needs a Services ID (clientId), and none is configured");
8370
+ return null;
8371
+ }
8159
8372
  try {
8160
- const clientSecret = await generateClientSecret();
8373
+ const clientSecret = await generateClientSecret(client.clientId);
8161
8374
  const tokenResponse = await fetch("https://appleid.apple.com/auth/token", {
8162
8375
  method: "POST",
8163
8376
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
8164
8377
  body: new URLSearchParams({
8165
- client_id: config.clientId,
8378
+ client_id: client.clientId,
8166
8379
  client_secret: clientSecret,
8167
8380
  code: payload.code,
8168
8381
  grant_type: "authorization_code",
8169
- redirect_uri: payload.redirectUri,
8382
+ ...client.redirectUri ? { redirect_uri: client.redirectUri } : {},
8170
8383
  ...pkceTokenParams(payload.codeVerifier)
8171
8384
  })
8172
8385
  });
@@ -8179,7 +8392,7 @@ user: z.object({ name: z.object({
8179
8392
  idToken: tokenData.id_token,
8180
8393
  jwksUri: APPLE_JWKS_URI,
8181
8394
  issuer: APPLE_ISSUER,
8182
- audience: config.clientId
8395
+ audience: client.clientId
8183
8396
  }) : null;
8184
8397
  if (!decoded) {
8185
8398
  logger.error("Apple token exchange returned no verifiable id_token");
@@ -8760,4 +8973,4 @@ var auth_exports = /* @__PURE__ */ __exportAll({
8760
8973
  //#endregion
8761
8974
  export { getEmailChangeTemplate as $, createDataRateLimiter as A, SMTPEmailService as B, createJwksRoutes as C, DEFAULT_FUNCTIONS_ANONYMOUS_LIMIT as D, isBootstrapWindowOpen as E, clearActiveDevEmailSink as F, verifyPassword as G, resolveAuthHooks as H, createDevEmailSink as I, completeUserCreation as J, adapterRefusal as K, devEmailSinkFor as L, setSharedRateLimitStore as M, MemoryRateLimitStore as N, createAuthLimiters as O, activeDevEmailSink as P, getEmailChangeNoticeTemplate as Q, extractLinks as R, createApiKeyStore as S, configureUserPicking as T, hashPassword as U, createEmailService as V, validatePasswordStrength as W, assertEmailLinkBases as X, generateSecurePassword as Y, resolveEmailLinkBase as Z, oauthCodeFlowSchema as _, createBitbucketProvider as a, getWelcomeEmailTemplate as at, createApiKeyRoutes as b, createTwitterProvider as c, escapeHtml as ct, createMicrosoftProvider as d, createSqlRateLimitStore as dt, getEmailOtpTemplate as et, tryVerifyOidcIdToken as f, resolveRateLimitStoreKind as ft, createGoogleProvider as g, createLinkedinProvider as h, createSlackProvider as i, getUserInvitationTemplate as it, createRateLimiter as j, createDataRateLimitCheck as k, createFacebookProvider as l, html as lt, createGitHubProvider as m, createCustomAuthAdapter as n, getMagicLinkTemplate as nt, createGitLabProvider as o, resolveEmailBranding as ot, verifyOidcIdToken as p, securityRuleToConditions as pt, createAdapterAuthMiddleware as q, createSpotifyProvider as r, getPasswordResetTemplate as rt, createDiscordProvider as s, RawHtml as st, auth_exports as t, getEmailVerificationTemplate as tt, createAppleProvider as u, raw as ut, pkceTokenParams as v, createBuiltinAuthAdapter as w, createPersonalKeyRoutes as x, providerVerifiedEmail as y, registerDevEmailSink as z };
8762
8975
 
8763
- //# sourceMappingURL=auth-izI7AEzC.js.map
8976
+ //# sourceMappingURL=auth-CZGfVKcL.js.map