@rebasepro/server 0.27.0 → 0.28.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{GCSStorageController-BUClIfp0.js → GCSStorageController-LXeAF6Ks.js} +4 -4
- package/dist/{GCSStorageController-BUClIfp0.js.map → GCSStorageController-LXeAF6Ks.js.map} +1 -1
- package/dist/{S3StorageController-CixCQEky.js → S3StorageController-CVKMUXo_.js} +8 -4
- package/dist/S3StorageController-CVKMUXo_.js.map +1 -0
- package/dist/{access-BFAUvsSs.js → access-BDz4FO9D.js} +7 -7
- package/dist/{access-BFAUvsSs.js.map → access-BDz4FO9D.js.map} +1 -1
- package/dist/api/openapi-generator.d.ts +13 -1
- package/dist/api/rest/api-generator.d.ts +16 -0
- package/dist/api/rest/batch.d.ts +9 -0
- package/dist/{ast-schema-editor-madTa9Hh.js → ast-schema-editor-C4bDSb61.js} +2 -2
- package/dist/{ast-schema-editor-madTa9Hh.js.map → ast-schema-editor-C4bDSb61.js.map} +1 -1
- package/dist/auth/interfaces.d.ts +23 -4
- package/dist/auth/otp-routes.d.ts +10 -0
- package/dist/auth/platform-token.d.ts +24 -8
- package/dist/{auth-DDXPw0mn.js → auth-CZGfVKcL.js} +173 -114
- package/dist/auth-CZGfVKcL.js.map +1 -0
- package/dist/backend/options.d.ts +21 -0
- package/dist/{backup-B6brPSeB.js → backup-BmzY9xdN.js} +8 -8
- package/dist/{backup-B6brPSeB.js.map → backup-BmzY9xdN.js.map} +1 -1
- package/dist/{branch-routes-B2vvEx53.js → branch-routes-DpgaeTJl.js} +4 -4
- package/dist/{branch-routes-B2vvEx53.js.map → branch-routes-DpgaeTJl.js.map} +1 -1
- package/dist/{contract-routes-CU2A3JnF.js → contract-routes-vYiBHbjI.js} +3 -3
- package/dist/{contract-routes-CU2A3JnF.js.map → contract-routes-vYiBHbjI.js.map} +1 -1
- package/dist/cron/cron-loader.d.ts +12 -0
- package/dist/{cron-loader-CC1Jy_KN.js → cron-loader-C_C-lNgG.js} +27 -6
- package/dist/cron-loader-C_C-lNgG.js.map +1 -0
- package/dist/{cron-routes-BK60Rn1r.js → cron-routes-DlwOV6zl.js} +5 -5
- package/dist/{cron-routes-BK60Rn1r.js.map → cron-routes-DlwOV6zl.js.map} +1 -1
- package/dist/{cron-scheduler-DyCjPlQR.js → cron-scheduler-6ipIm5mm.js} +3 -3
- package/dist/{cron-scheduler-DyCjPlQR.js.map → cron-scheduler-6ipIm5mm.js.map} +1 -1
- package/dist/{cron-store-DLn11M8H.js → cron-store-KIOM8LCC.js} +5 -5
- package/dist/{cron-store-DLn11M8H.js.map → cron-store-KIOM8LCC.js.map} +1 -1
- package/dist/{ddl-bootstrap-CjRrn12l.js → ddl-bootstrap-DhCuwhHM.js} +2 -2
- package/dist/{ddl-bootstrap-CjRrn12l.js.map → ddl-bootstrap-DhCuwhHM.js.map} +1 -1
- package/dist/dist-CT9HJehq.js +22 -0
- package/dist/dist-CT9HJehq.js.map +1 -0
- package/dist/{errors-OMWkKSH-.js → errors-DIWnZIDY.js} +2 -2
- package/dist/{errors-OMWkKSH-.js.map → errors-DIWnZIDY.js.map} +1 -1
- package/dist/{field-access-DYsvjI_P.js → field-access-KYk8RGOx.js} +3 -2
- package/dist/field-access-KYk8RGOx.js.map +1 -0
- package/dist/{filter-dialect-TrKFWLqT.js → filter-dialect-CE4bloug.js} +2 -2
- package/dist/{filter-dialect-TrKFWLqT.js.map → filter-dialect-CE4bloug.js.map} +1 -1
- package/dist/{function-loader-eFigStYX.js → function-loader-CKB9b4uP.js} +2 -2
- package/dist/{function-loader-eFigStYX.js.map → function-loader-CKB9b4uP.js.map} +1 -1
- package/dist/{function-routes-RxrCHNuM.js → function-routes-DLaXaiQA.js} +2 -2
- package/dist/{function-routes-RxrCHNuM.js.map → function-routes-DLaXaiQA.js.map} +1 -1
- package/dist/functions/index.js +16 -9
- package/dist/functions/index.js.map +1 -1
- package/dist/{history-recorder-Bsau7h4X.js → history-recorder-BE4HWR-M.js} +4 -4
- package/dist/{history-recorder-Bsau7h4X.js.map → history-recorder-BE4HWR-M.js.map} +1 -1
- package/dist/{history-store-BQz5YCkW.js → history-store-D-jDz4Nv.js} +2 -2
- package/dist/{history-store-BQz5YCkW.js.map → history-store-D-jDz4Nv.js.map} +1 -1
- package/dist/index.d.ts +4 -0
- package/dist/index.es.js +1194 -249
- package/dist/index.es.js.map +1 -1
- package/dist/{internal-tables-L2t39RdT.js → internal-tables-CRaBxJeE.js} +57 -2
- package/dist/{internal-tables-L2t39RdT.js.map → internal-tables-CRaBxJeE.js.map} +1 -1
- package/dist/{jobs-Co6Ni5HP.js → jobs-CXTs9qXH.js} +5 -5
- package/dist/{jobs-Co6Ni5HP.js.map → jobs-CXTs9qXH.js.map} +1 -1
- package/dist/{jwt-rDS0884_.js → jwt-5EvX3lQa.js} +3 -3
- package/dist/{jwt-rDS0884_.js.map → jwt-5EvX3lQa.js.map} +1 -1
- package/dist/{keys-BXcdRNhJ.js → keys-DJ1ZNcZi.js} +2 -2
- package/dist/{keys-BXcdRNhJ.js.map → keys-DJ1ZNcZi.js.map} +1 -1
- package/dist/{logger-CW8pmTS6.js → logger-SigQ2oZJ.js} +17 -10
- package/dist/logger-SigQ2oZJ.js.map +1 -0
- package/dist/{logs-routes-CBt7mMIL.js → logs-routes-DXLvMasE.js} +3 -3
- package/dist/{logs-routes-CBt7mMIL.js.map → logs-routes-DXLvMasE.js.map} +1 -1
- package/dist/mcp/confirmation.d.ts +84 -0
- package/dist/mcp/consent-page.d.ts +17 -3
- package/dist/mcp/mcp-apps.d.ts +53 -0
- package/dist/mcp/mcp-routes.d.ts +42 -1
- package/dist/mcp/mcp-tools.d.ts +50 -6
- package/dist/mcp/oauth-metadata.d.ts +25 -3
- package/dist/mcp/oauth-routes.d.ts +4 -1
- package/dist/mcp/oauth-store.d.ts +7 -1
- package/dist/mcp/platform-mcp.d.ts +37 -0
- package/dist/{offline-AvuEcg7u-DFHL98OT.js → offline-BjJdcVBb-BOzzsnrh.js} +35 -7
- package/dist/offline-BjJdcVBb-BOzzsnrh.js.map +1 -0
- package/dist/{offline-store-BhYXViha-YTmjBpo2.js → offline-store-Cxhh99Q--FB6fSf5A.js} +43 -9
- package/dist/offline-store-Cxhh99Q--FB6fSf5A.js.map +1 -0
- package/dist/{openapi-generator-CyxEtYEX.js → openapi-generator-B6aw_KuR.js} +41 -7
- package/dist/openapi-generator-B6aw_KuR.js.map +1 -0
- package/dist/{proxy-BYir8tWK.js → proxy-2nS5N63I.js} +3 -3
- package/dist/{proxy-BYir8tWK.js.map → proxy-2nS5N63I.js.map} +1 -1
- package/dist/{query-parser-CDXWf2hH.js → query-parser-DFVCjW5i.js} +6 -6
- package/dist/{query-parser-CDXWf2hH.js.map → query-parser-DFVCjW5i.js.map} +1 -1
- package/dist/{request-timeout-DVjo-c_8.js → request-timeout-Cqm4JXtZ.js} +3 -3
- package/dist/{request-timeout-DVjo-c_8.js.map → request-timeout-Cqm4JXtZ.js.map} +1 -1
- package/dist/{rls-simulator-routes-bEY7-5-u.js → rls-simulator-routes-D5-XfjzW.js} +4 -4
- package/dist/{rls-simulator-routes-bEY7-5-u.js.map → rls-simulator-routes-D5-XfjzW.js.map} +1 -1
- package/dist/{schema-editor-routes-Dc3DU_jm.js → schema-editor-routes-DzSe6V0a.js} +4 -4
- package/dist/{schema-editor-routes-Dc3DU_jm.js.map → schema-editor-routes-DzSe6V0a.js.map} +1 -1
- package/dist/{soft-delete-params-BRONCOA2.js → soft-delete-params-9lKBAlDw.js} +2 -2
- package/dist/{soft-delete-params-BRONCOA2.js.map → soft-delete-params-9lKBAlDw.js.map} +1 -1
- package/dist/{sql-export-routes-QycX8W8S.js → sql-export-routes-BxMqgAFX.js} +4 -4
- package/dist/{sql-export-routes-QycX8W8S.js.map → sql-export-routes-BxMqgAFX.js.map} +1 -1
- package/dist/{src-Bh9LRPb9.js → src-JQNz7cWv.js} +19 -2
- package/dist/{src-Bh9LRPb9.js.map → src-JQNz7cWv.js.map} +1 -1
- package/dist/storage/orphan-sweep.d.ts +67 -0
- package/dist/{upload-validation-CkkQGs-j.js → upload-validation-IYXn4xcm.js} +2 -2
- package/dist/{upload-validation-CkkQGs-j.js.map → upload-validation-IYXn4xcm.js.map} +1 -1
- package/dist/utils/logger.d.ts +9 -4
- package/package.json +7 -6
- package/dist/S3StorageController-CixCQEky.js.map +0 -1
- package/dist/auth-DDXPw0mn.js.map +0 -1
- package/dist/cron-loader-CC1Jy_KN.js.map +0 -1
- package/dist/field-access-DYsvjI_P.js.map +0 -1
- package/dist/logger-CW8pmTS6.js.map +0 -1
- package/dist/offline-AvuEcg7u-DFHL98OT.js.map +0 -1
- package/dist/offline-store-BhYXViha-YTmjBpo2.js.map +0 -1
- package/dist/openapi-generator-CyxEtYEX.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-
|
|
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-
|
|
10
|
-
import { a as logger } from "./logger-
|
|
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
|
|
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-
|
|
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-
|
|
16
|
-
import { c as provisioningExec, n as SchemaChangeRefusedError, r as createDdlBootstrapper } from "./ddl-bootstrap-
|
|
17
|
-
import { a as isDataException, c as warnIfDatabaseClosed, i as errorHandler, o as isDatabaseUnreachable, r as declaredErrorAnswer, t as ApiError } from "./errors-
|
|
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 =
|
|
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
|
|
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());
|
|
@@ -8914,4 +8973,4 @@ var auth_exports = /* @__PURE__ */ __exportAll({
|
|
|
8914
8973
|
//#endregion
|
|
8915
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 };
|
|
8916
8975
|
|
|
8917
|
-
//# sourceMappingURL=auth-
|
|
8976
|
+
//# sourceMappingURL=auth-CZGfVKcL.js.map
|