@rebasepro/server 0.33.2 → 0.34.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.
Files changed (103) hide show
  1. package/dist/{GCSStorageController-kCv5MH2B.js → GCSStorageController-DKv7oDo7.js} +3 -3
  2. package/dist/{GCSStorageController-kCv5MH2B.js.map → GCSStorageController-DKv7oDo7.js.map} +1 -1
  3. package/dist/{S3StorageController-DqK533Sl.js → S3StorageController-CIQ2_mC5.js} +3 -3
  4. package/dist/{S3StorageController-DqK533Sl.js.map → S3StorageController-CIQ2_mC5.js.map} +1 -1
  5. package/dist/{access-CRQBlEZY.js → access-BdsIXo_L.js} +4 -4
  6. package/dist/{access-CRQBlEZY.js.map → access-BdsIXo_L.js.map} +1 -1
  7. package/dist/api/rest/api-generator.d.ts +11 -1
  8. package/dist/auth/auth-hooks.d.ts +1 -1
  9. package/dist/auth/builtin-auth-adapter.d.ts +2 -0
  10. package/dist/auth/capabilities.d.ts +12 -0
  11. package/dist/auth/platform-signin-routes.d.ts +85 -0
  12. package/dist/auth/platform-token.d.ts +33 -0
  13. package/dist/auth/routes.d.ts +8 -0
  14. package/dist/auth/seed-admin.d.ts +2 -0
  15. package/dist/{auth-BanB_pZj.js → auth-CHOmnYwu.js} +358 -12
  16. package/dist/auth-CHOmnYwu.js.map +1 -0
  17. package/dist/{backup-CVNce2jz.js → backup-M37yPYpz.js} +6 -6
  18. package/dist/{backup-CVNce2jz.js.map → backup-M37yPYpz.js.map} +1 -1
  19. package/dist/boot/bundle.d.ts +12 -0
  20. package/dist/boot/env.d.ts +1 -0
  21. package/dist/{branch-routes-aLDaGOD1.js → branch-routes-Cl-Oa3CL.js} +2 -2
  22. package/dist/{branch-routes-aLDaGOD1.js.map → branch-routes-Cl-Oa3CL.js.map} +1 -1
  23. package/dist/{contract-routes-a4ZbN1h3.js → contract-routes-Dkxl-2B_.js} +3 -3
  24. package/dist/{contract-routes-a4ZbN1h3.js.map → contract-routes-Dkxl-2B_.js.map} +1 -1
  25. package/dist/{cron-loader-CWhyA5eR.js → cron-loader-BWahenzQ.js} +2 -2
  26. package/dist/{cron-loader-CWhyA5eR.js.map → cron-loader-BWahenzQ.js.map} +1 -1
  27. package/dist/{cron-routes-CMGAz1my.js → cron-routes-Cq6O3oPR.js} +4 -4
  28. package/dist/{cron-routes-CMGAz1my.js.map → cron-routes-Cq6O3oPR.js.map} +1 -1
  29. package/dist/{cron-scheduler-DQBdkkfb.js → cron-scheduler-B25NuV7o.js} +2 -2
  30. package/dist/{cron-scheduler-DQBdkkfb.js.map → cron-scheduler-B25NuV7o.js.map} +1 -1
  31. package/dist/{cron-store-CjUydRyp.js → cron-store-B1IStnKM.js} +2 -2
  32. package/dist/{cron-store-CjUydRyp.js.map → cron-store-B1IStnKM.js.map} +1 -1
  33. package/dist/dist-DDppJiwg.js +19354 -0
  34. package/dist/dist-DDppJiwg.js.map +1 -0
  35. package/dist/email/link-base.d.ts +21 -0
  36. package/dist/email/types.d.ts +4 -0
  37. package/dist/{filter-dialect-nsQ2ozPY.js → filter-dialect-DgWkoXt7.js} +2 -2
  38. package/dist/{filter-dialect-nsQ2ozPY.js.map → filter-dialect-DgWkoXt7.js.map} +1 -1
  39. package/dist/{function-loader-Cihj_r86.js → function-loader-C23HVFx8.js} +2 -2
  40. package/dist/{function-loader-Cihj_r86.js.map → function-loader-C23HVFx8.js.map} +1 -1
  41. package/dist/{function-routes-CWaldgEj.js → function-routes-DBKL2azw.js} +2 -2
  42. package/dist/{function-routes-CWaldgEj.js.map → function-routes-DBKL2azw.js.map} +1 -1
  43. package/dist/{history-recorder-B8TJMEfO.js → history-recorder-C5gixsU3.js} +16 -3
  44. package/dist/history-recorder-C5gixsU3.js.map +1 -0
  45. package/dist/history-store-c_cm9R3w.js +459 -0
  46. package/dist/history-store-c_cm9R3w.js.map +1 -0
  47. package/dist/index.d.ts +1 -1
  48. package/dist/index.es.js +273 -236
  49. package/dist/index.es.js.map +1 -1
  50. package/dist/{jobs-IJX3fE3X.js → jobs-uqvEGTfs.js} +2 -2
  51. package/dist/{jobs-IJX3fE3X.js.map → jobs-uqvEGTfs.js.map} +1 -1
  52. package/dist/{jwt-BuEprb39.js → jwt-B_5zx-7y.js} +3 -3
  53. package/dist/{jwt-BuEprb39.js.map → jwt-B_5zx-7y.js.map} +1 -1
  54. package/dist/{keys-C8gpPIOG.js → keys-C0g4vwP5.js} +2 -2
  55. package/dist/{keys-C8gpPIOG.js.map → keys-C0g4vwP5.js.map} +1 -1
  56. package/dist/{load-schema-BvRxAuaD.js → load-schema-aNynBztw.js} +2 -2
  57. package/dist/{load-schema-BvRxAuaD.js.map → load-schema-aNynBztw.js.map} +1 -1
  58. package/dist/{logs-routes-BAq2ZxuY.js → logs-routes-D2NGM5Pa.js} +2 -2
  59. package/dist/{logs-routes-BAq2ZxuY.js.map → logs-routes-D2NGM5Pa.js.map} +1 -1
  60. package/dist/metrics/history-recorder.d.ts +10 -1
  61. package/dist/metrics/history-store.d.ts +122 -7
  62. package/dist/metrics/index.d.ts +24 -2
  63. package/dist/{offline-ET6xI1ZO-CIdB1ilf.js → offline-ET6xI1ZO-Du75S8J1.js} +4 -4
  64. package/dist/{offline-ET6xI1ZO-CIdB1ilf.js.map → offline-ET6xI1ZO-Du75S8J1.js.map} +1 -1
  65. package/dist/{offline-store-DtmBwmKE-CzyvC_Zj.js → offline-store-DtmBwmKE-CEakGPWn.js} +3 -3
  66. package/dist/{offline-store-DtmBwmKE-CzyvC_Zj.js.map → offline-store-DtmBwmKE-CEakGPWn.js.map} +1 -1
  67. package/dist/{openapi-generator-CCLtAJ2s.js → openapi-generator-B7EbCjhN.js} +2 -2
  68. package/dist/{openapi-generator-CCLtAJ2s.js.map → openapi-generator-B7EbCjhN.js.map} +1 -1
  69. package/dist/{project-root-CuCOXvbk.js → project-root-BTQAiPki.js} +2 -2
  70. package/dist/{project-root-CuCOXvbk.js.map → project-root-BTQAiPki.js.map} +1 -1
  71. package/dist/{proxy-DUUXXoQo.js → proxy-0fGXJapt.js} +2 -2
  72. package/dist/{proxy-DUUXXoQo.js.map → proxy-0fGXJapt.js.map} +1 -1
  73. package/dist/{query-parser-C9l1eFov.js → query-parser-DwERE0rm.js} +3 -3
  74. package/dist/{query-parser-C9l1eFov.js.map → query-parser-DwERE0rm.js.map} +1 -1
  75. package/dist/{request-timeout-DOu8ItLQ.js → request-timeout-DdbFS6ef.js} +3 -3
  76. package/dist/{request-timeout-DOu8ItLQ.js.map → request-timeout-DdbFS6ef.js.map} +1 -1
  77. package/dist/{rls-simulator-routes-DIAjffhq.js → rls-simulator-routes-Cjv8yY1V.js} +3 -3
  78. package/dist/{rls-simulator-routes-DIAjffhq.js.map → rls-simulator-routes-Cjv8yY1V.js.map} +1 -1
  79. package/dist/{schema-editor-routes-qWGWBPi0.js → schema-editor-routes-CwdoGYKu.js} +4 -4
  80. package/dist/{schema-editor-routes-qWGWBPi0.js.map → schema-editor-routes-CwdoGYKu.js.map} +1 -1
  81. package/dist/{schema-tables-BneB2KZ7.js → schema-tables-DUThMxen.js} +3 -3
  82. package/dist/{schema-tables-BneB2KZ7.js.map → schema-tables-DUThMxen.js.map} +1 -1
  83. package/dist/{schema-tables-routes-BBZJK8_S.js → schema-tables-routes-Ch52xLqF.js} +4 -4
  84. package/dist/{schema-tables-routes-BBZJK8_S.js.map → schema-tables-routes-Ch52xLqF.js.map} +1 -1
  85. package/dist/{securityRuleToConditions-Cj5ZR7TS.js → securityRuleToConditions-DXPY_Z-x.js} +2 -2
  86. package/dist/{securityRuleToConditions-Cj5ZR7TS.js.map → securityRuleToConditions-DXPY_Z-x.js.map} +1 -1
  87. package/dist/{selection-BB8ejqa2.js → selection-BiTJ-Tiy.js} +2 -2
  88. package/dist/{selection-BB8ejqa2.js.map → selection-BiTJ-Tiy.js.map} +1 -1
  89. package/dist/{sql-export-routes-CPXI3qZ7.js → sql-export-routes-BYt7G2v-.js} +2 -2
  90. package/dist/{sql-export-routes-CPXI3qZ7.js.map → sql-export-routes-BYt7G2v-.js.map} +1 -1
  91. package/dist/{src-BdPKCs9u.js → src--EBfCtYm.js} +2 -2
  92. package/dist/src--EBfCtYm.js.map +1 -0
  93. package/dist/storage/routes.d.ts +6 -0
  94. package/dist/{table-source-editor-D3m_VMwN.js → table-source-editor-P5zp7lOn.js} +3 -3
  95. package/dist/{table-source-editor-D3m_VMwN.js.map → table-source-editor-P5zp7lOn.js.map} +1 -1
  96. package/package.json +5 -5
  97. package/dist/auth-BanB_pZj.js.map +0 -1
  98. package/dist/dist-C1vNURUy.js +0 -19354
  99. package/dist/dist-C1vNURUy.js.map +0 -1
  100. package/dist/history-recorder-B8TJMEfO.js.map +0 -1
  101. package/dist/history-store-DzrJeEKv.js +0 -233
  102. package/dist/history-store-DzrJeEKv.js.map +0 -1
  103. package/dist/src-BdPKCs9u.js.map +0 -1
@@ -2,16 +2,16 @@ import { createRequire as __rebaseCreateRequire } from "module";
2
2
  import __rebaseProcess from "process";
3
3
  globalThis.process ??= __rebaseProcess;
4
4
  __rebaseCreateRequire(import.meta.url);
5
- import { Bn as __toESM, Dt as AUTH_FLOW_HEADER, Et as validateScopes, Rn as __exportAll, St as scopesBeyond, _n as isAnonymousUid, _t as parseScope, bn as policy, dt as hasAdminRole, gt as knownScopes, hn as ANONYMOUS_USER_ID, lt as KEY_MANAGEMENT_SCOPES, mt as isBuiltInScope, nn as isSQLAdmin, pt as isAdminScope, ut as SCOPE_TARGETS, vt as roleNameProblem, wt as summarizeRoles } from "./src-BdPKCs9u.js";
5
+ import { Ct as scopesBeyond, Dt as validateScopes, Ot as AUTH_FLOW_HEADER, Tt as summarizeRoles, Vn as __toESM, _t as knownScopes, dt as SCOPE_TARGETS, ft as hasAdminRole, gn as ANONYMOUS_USER_ID, ht as isBuiltInScope, mt as isAdminScope, ot as ADMIN_ROLE, rn as isSQLAdmin, ut as KEY_MANAGEMENT_SCOPES, vn as isAnonymousUid, vt as parseScope, xn as policy, yt as roleNameProblem, zn as __exportAll } from "./src--EBfCtYm.js";
6
6
  import { a as logger } from "./logger-SigQ2oZJ.js";
7
- import { t as securityRuleToConditions } from "./securityRuleToConditions-Cj5ZR7TS.js";
7
+ import { t as securityRuleToConditions } from "./securityRuleToConditions-DXPY_Z-x.js";
8
8
  import { a as revokeInternalTableSql, r as REQUEST_ROLE_CANDIDATES_SQL } from "./internal-tables-XxM_NdR_.js";
9
9
  import { t as firstSqlRow } from "./sql-rows-CIThkmuF.js";
10
- import { o as resolveListLimitParam } from "./query-parser-C9l1eFov.js";
11
- 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$2, x as require_jsonwebtoken } from "./jwt-BuEprb39.js";
10
+ import { o as resolveListLimitParam } from "./query-parser-DwERE0rm.js";
11
+ 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$2, x as require_jsonwebtoken, y as verifyJwt } from "./jwt-B_5zx-7y.js";
12
12
  import { c as provisioningExec, n as SchemaChangeRefusedError, r as createDdlBootstrapper } from "./ddl-bootstrap-DhCuwhHM.js";
13
13
  import { a as isDataException, i as errorHandler, l as warnIfDatabaseClosed, o as isDatabaseUnreachable, r as declaredErrorAnswer, t as ApiError } from "./errors-NVbAQU25.js";
14
- import { D as requireAuth, E as requireAdmin, F as applyImpersonation, J as validateApiKey, K as isApiKeyToken, Q as scopeDataDriver, R as applySimulation, S as optionalAuth, T as refuse, X as safeCompare, Y as extractBearerToken, Z as SERVICE_IDENTITY, a as assertMayManageAccount, b as extractUserFromToken, c as configureAccess, et as accessTokenRefusalError, f as processAccessControl, h as requireScopeByMethod, i as assertMayGrantRoles, it as revokeAllSessions, l as getAccessModel, m as requireScope, n as accessModelFromAuthTable, nt as judgeAccessToken, o as callerIsAdmin, ot as httpMethodToOperation, p as readRoleNames, q as resolveApiKey, r as accessOf, rt as replaceUserPassword, s as callerScopes, t as AccessModelError, u as hasScope, v as createAuthMiddleware, w as queryTokenAuth, x as fileTokenAuth, y as createRequireAuth } from "./access-CRQBlEZY.js";
14
+ import { D as requireAuth, E as requireAdmin, F as applyImpersonation, J as validateApiKey, K as isApiKeyToken, Q as scopeDataDriver, R as applySimulation, S as optionalAuth, T as refuse, X as safeCompare, Y as extractBearerToken, Z as SERVICE_IDENTITY, a as assertMayManageAccount, b as extractUserFromToken, c as configureAccess, et as accessTokenRefusalError, f as processAccessControl, h as requireScopeByMethod, i as assertMayGrantRoles, it as revokeAllSessions, l as getAccessModel, m as requireScope, n as accessModelFromAuthTable, nt as judgeAccessToken, o as callerIsAdmin, ot as httpMethodToOperation, p as readRoleNames, q as resolveApiKey, r as accessOf, rt as replaceUserPassword, s as callerScopes, t as AccessModelError, u as hasScope, v as createAuthMiddleware, w as queryTokenAuth, x as fileTokenAuth, y as createRequireAuth } from "./access-BdsIXo_L.js";
15
15
  import { createHash, randomBytes, randomInt } from "node:crypto";
16
16
  import { Hono } from "hono";
17
17
  import { promisify } from "util";
@@ -1354,6 +1354,40 @@ function resolveEmailLinkBase(config, kind) {
1354
1354
  return "";
1355
1355
  }
1356
1356
  /**
1357
+ * Why a `magicLinkUrl` without `{token}` is probably a template that lost its
1358
+ * end, or `undefined` when it reads as the base it is.
1359
+ *
1360
+ * dotenv cuts an unquoted value at `#`, so
1361
+ * `MAGIC_LINK_URL=https://app.example.com/app.html#ml={token}` arrives as
1362
+ * `https://app.example.com/app.html`, which is read as a base: every email
1363
+ * then carries `…/app.html/auth/magic-link?token=…`, with no error anywhere.
1364
+ * A base names an origin, perhaps a path; a hash, or a path ending in a file
1365
+ * (`.html`), is the sign.
1366
+ */
1367
+ function magicLinkUrlProblem(value) {
1368
+ if (!value || value.includes("{token}")) return void 0;
1369
+ let url;
1370
+ try {
1371
+ url = new URL(value);
1372
+ } catch {
1373
+ return;
1374
+ }
1375
+ if (url.hash || /\.[a-z0-9]+$/i.test(url.pathname)) return `MAGIC_LINK_URL is "${value}", which has no {token}, so it is read as a base and every magic link becomes "${value.replace(/\/+$/, "")}/auth/magic-link?token=…". If it was meant as a template, quote it in .env (an unquoted # starts a comment there): MAGIC_LINK_URL="https://app.example.com/app.html#ml={token}".`;
1376
+ }
1377
+ /**
1378
+ * The magic link an email carries for `token`.
1379
+ *
1380
+ * `magicLinkUrl` with `{token}` in it is the whole link, the token put where
1381
+ * the placeholder is (`https://app.example.com/app.html#ml={token}`), for a
1382
+ * frontend that does not serve `/auth/magic-link`. Otherwise the link is the
1383
+ * magic-link base with `/auth/magic-link?token=` appended, as it always was.
1384
+ */
1385
+ function magicLinkHref(config, token) {
1386
+ const template = config?.magicLinkUrl;
1387
+ if (typeof template === "string" && template.includes("{token}") && isAbsoluteHttpUrl(template.replace(/\{token\}/g, "x"))) return template.replace(/\{token\}/g, encodeURIComponent(token));
1388
+ return `${resolveEmailLinkBase(config, "magicLink")}/auth/magic-link?token=${token}`;
1389
+ }
1390
+ /**
1357
1391
  * Throw when an email configuration cannot produce a followable link of every
1358
1392
  * kind it sends.
1359
1393
  *
@@ -3912,7 +3946,7 @@ async function isOnlyUser(repo, uid) {
3912
3946
  * shut. Named here so the register route and the bootstrap route say the same
3913
3947
  * thing.
3914
3948
  */
3915
- var SETUP_REQUIRED_MESSAGE = "This deployment has no administrator yet, and in production the first account is not promoted automatically. Set REBASE_ADMIN_EMAIL and REBASE_ADMIN_PASSWORD before the first boot, or assign the admin role with the service key.";
3949
+ var SETUP_REQUIRED_MESSAGE = "This deployment has no administrator yet, and in production the first account is not promoted automatically. On Rebase Cloud, open the admin from the project's page in the console, which signs the project's owners in. Self-hosted, set REBASE_ADMIN_EMAIL and REBASE_ADMIN_PASSWORD before the first boot, or assign the admin role with the service key.";
3916
3950
  /** The full predicate, for callers that already know whether setup is needed. */
3917
3951
  function isRegistrationOpen(policy) {
3918
3952
  if (policy.disableSelfRegistration) return false;
@@ -4756,7 +4790,7 @@ function mountMagicLinkRoutes(deps) {
4756
4790
  const tokenHash = hashToken(token);
4757
4791
  const expiresAt = getMagicLinkExpiry();
4758
4792
  await authRepo.createMagicLinkToken(user.id, tokenHash, expiresAt);
4759
- const magicLinkUrl = `${resolveEmailLinkBase(emailConfig, "magicLink")}/auth/magic-link?token=${token}`;
4793
+ const magicLinkUrl = magicLinkHref(emailConfig, token);
4760
4794
  const { appName, logoUrl } = resolveEmailBranding(emailConfig);
4761
4795
  const templateFn = emailConfig?.templates?.magicLink;
4762
4796
  const emailContent = templateFn ? templateFn(magicLinkUrl, {
@@ -4810,6 +4844,279 @@ function mountMagicLinkRoutes(deps) {
4810
4844
  return c.json(redactRefreshToken(transformedResponse, c, refreshToken, config.cookieAuth));
4811
4845
  });
4812
4846
  }
4847
+ //#endregion
4848
+ //#region src/auth/platform-token.ts
4849
+ /** Marks a bearer token as a platform token. */
4850
+ var PLATFORM_TOKEN_PREFIX = "rpt_";
4851
+ /**
4852
+ * Everything a platform token can be granted on this server's admin surfaces.
4853
+ *
4854
+ * Adding a scope here is a decision about what the platform may do inside a
4855
+ * customer's app on a person's behalf, and belongs in its own change.
4856
+ * `cron:write` (run a job, switch one on or off) was added with the hosted
4857
+ * Rebase connector (docs/hosted-mcp-connector.md), whose `cron` tool takes a
4858
+ * confirmed second call before it sends one.
4859
+ */
4860
+ var PLATFORM_TOKEN_SCOPES = ["cron:read", "cron:write"];
4861
+ /**
4862
+ * What a platform token can be granted on the platform's MCP endpoint, and
4863
+ * only there: the app's own MCP data tools. Never on `/api/data`, the socket,
4864
+ * the public `/mcp`, or an admin surface. Added with the hosted connector, in
4865
+ * the same review as `cron:write`.
4866
+ */
4867
+ var PLATFORM_MCP_SCOPES = [
4868
+ "data:read",
4869
+ "data:write",
4870
+ "data:delete"
4871
+ ];
4872
+ /**
4873
+ * What a platform token can be granted at the sign-in door, and only there:
4874
+ * `POST /auth/platform-signin` (`platform-signin-routes.ts`), which turns it
4875
+ * into an ordinary session for the person it names, with the `admin` role.
4876
+ *
4877
+ * This is the one scope that makes a platform token worth a person of the app,
4878
+ * so it is held tighter than the others: the token must name the person's
4879
+ * email, carry a `jti`, live at most {@link PLATFORM_SIGNIN_MAX_LIFETIME_SECONDS},
4880
+ * and is spent by its first use. The control plane mints it only for an owner
4881
+ * or admin of the organization that owns the project — someone who could
4882
+ * already set `REBASE_ADMIN_EMAIL` and redeploy, which is the reach this
4883
+ * grants, without the password nobody knew to choose. Never on an admin
4884
+ * surface or the MCP endpoint: neither lists it.
4885
+ */
4886
+ var PLATFORM_SIGNIN_SCOPES = ["auth:admin-signin"];
4887
+ /** How far ahead of this server's clock an `iat` may sit. */
4888
+ var CLOCK_SKEW_SECONDS = 60;
4889
+ /** The environment variables a platform sets to turn platform tokens on. */
4890
+ var PLATFORM_TOKEN_KEY_ENV = "REBASE_PLATFORM_TOKEN_KEY";
4891
+ var PLATFORM_TOKEN_AUDIENCE_ENV = "REBASE_PLATFORM_TOKEN_AUDIENCE";
4892
+ /**
4893
+ * Where the admin panel's "Continue with Rebase Cloud" goes: the project's page
4894
+ * in the platform's console, which mints a sign-in token and comes back. Set by
4895
+ * the platform with the other two; optional.
4896
+ */
4897
+ var PLATFORM_SIGNIN_URL_ENV = "REBASE_PLATFORM_SIGNIN_URL";
4898
+ function isPlatformToken(token) {
4899
+ return token.startsWith(PLATFORM_TOKEN_PREFIX);
4900
+ }
4901
+ var PEM_BLOCK = /-----BEGIN PUBLIC KEY-----[\s\S]+?-----END PUBLIC KEY-----/g;
4902
+ /**
4903
+ * The PEM blocks in an env value: real newlines, `\n`-escaped ones (what a
4904
+ * one-line `.env` holds), or the whole thing base64-encoded.
4905
+ */
4906
+ function parsePublicKeys(value) {
4907
+ let text = value.trim();
4908
+ if (!text.includes("-----BEGIN")) try {
4909
+ text = atob(text);
4910
+ } catch {
4911
+ return [];
4912
+ }
4913
+ text = text.replace(/\\n/g, "\n");
4914
+ return [...text.matchAll(PEM_BLOCK)].map((match) => match[0]);
4915
+ }
4916
+ /** Whether a PEM block is an EC P-256 public key WebCrypto can verify with. */
4917
+ async function isP256PublicKey(pem) {
4918
+ const body = pem.replace(/-----(BEGIN|END) PUBLIC KEY-----/g, "").replace(/\s+/g, "");
4919
+ try {
4920
+ const der = Uint8Array.from(atob(body), (char) => char.charCodeAt(0));
4921
+ await crypto.subtle.importKey("spki", der, {
4922
+ name: "ECDSA",
4923
+ namedCurve: "P-256"
4924
+ }, false, ["verify"]);
4925
+ return true;
4926
+ } catch {
4927
+ return false;
4928
+ }
4929
+ }
4930
+ /**
4931
+ * Read the platform-token configuration from the environment.
4932
+ *
4933
+ * `undefined` when platform tokens are off — neither variable set, which is
4934
+ * every self-hosted server — or misconfigured. A misconfiguration is logged and
4935
+ * leaves them off rather than failing the boot: the platform set these values,
4936
+ * the app's owner cannot fix them, and the app serving traffic matters more
4937
+ * than its cron history being readable from the CLI.
4938
+ */
4939
+ async function platformTokensFromEnv(env) {
4940
+ const rawKey = env[PLATFORM_TOKEN_KEY_ENV]?.trim();
4941
+ const audience = env[PLATFORM_TOKEN_AUDIENCE_ENV]?.trim();
4942
+ if (!rawKey && !audience) return void 0;
4943
+ if (!rawKey || !audience) {
4944
+ logger.warn(`[Auth] Platform tokens are OFF: ${rawKey ? PLATFORM_TOKEN_AUDIENCE_ENV : PLATFORM_TOKEN_KEY_ENV} is not set. Both are needed — the key to verify a token with, the audience to bind it to this project.`);
4945
+ return;
4946
+ }
4947
+ const candidates = parsePublicKeys(rawKey);
4948
+ const publicKeys = [];
4949
+ for (const pem of candidates) if (await isP256PublicKey(pem)) publicKeys.push(pem);
4950
+ if (publicKeys.length === 0 || publicKeys.length !== candidates.length) {
4951
+ logger.warn(`[Auth] Platform tokens are OFF: ${PLATFORM_TOKEN_KEY_ENV} must hold one or more PEM-encoded EC P-256 public keys ("-----BEGIN PUBLIC KEY-----"); ${candidates.length === 0 ? "it holds none" : `${candidates.length - publicKeys.length} of its ${candidates.length} is not one`}.`);
4952
+ return;
4953
+ }
4954
+ const rawSignInUrl = env[PLATFORM_SIGNIN_URL_ENV]?.trim();
4955
+ let signInUrl;
4956
+ if (rawSignInUrl) {
4957
+ try {
4958
+ const parsed = new URL(rawSignInUrl);
4959
+ if (parsed.protocol === "https:" || parsed.protocol === "http:") signInUrl = parsed.toString();
4960
+ } catch {}
4961
+ if (!signInUrl) logger.warn(`[Auth] ${PLATFORM_SIGNIN_URL_ENV} is not an http(s) URL, so the login screen will not link to it.`);
4962
+ }
4963
+ logger.info("Platform tokens accepted on admin surfaces", {
4964
+ audience,
4965
+ keys: publicKeys.length,
4966
+ scopes: PLATFORM_TOKEN_SCOPES
4967
+ });
4968
+ return {
4969
+ publicKeys,
4970
+ audience,
4971
+ ...signInUrl ? { signInUrl } : {}
4972
+ };
4973
+ }
4974
+ /** Narrow a claim to a non-empty string. */
4975
+ function stringClaim(claims, name) {
4976
+ const value = claims[name];
4977
+ return typeof value === "string" && value.length > 0 ? value : void 0;
4978
+ }
4979
+ /**
4980
+ * Verify a presented platform token: signature, issuer, audience, lifetime, and
4981
+ * the scopes it may be granted here.
4982
+ */
4983
+ async function verifyPlatformToken(token, config, nowSeconds = Math.floor(Date.now() / 1e3), grantable = PLATFORM_TOKEN_SCOPES) {
4984
+ if (!isPlatformToken(token)) return { refusal: "Not a platform token" };
4985
+ const jws = token.slice(4);
4986
+ let claims;
4987
+ for (const key of config.publicKeys) try {
4988
+ claims = await verifyJwt(jws, key, { algorithms: ["ES256"] });
4989
+ break;
4990
+ } catch {}
4991
+ if (!claims) return { refusal: "Invalid or expired platform token" };
4992
+ if (claims.iss !== "rebase-cloud") return { refusal: "This platform token was not issued by the platform" };
4993
+ if (!(Array.isArray(claims.aud) ? claims.aud : [claims.aud]).includes(config.audience)) return { refusal: "This platform token was issued for a different project" };
4994
+ const iat = claims.iat;
4995
+ const exp = claims.exp;
4996
+ if (typeof iat !== "number" || typeof exp !== "number") return { refusal: "A platform token must carry iat and exp" };
4997
+ if (exp - iat > 600) return { refusal: `A platform token may live at most 600 seconds` };
4998
+ if (iat > nowSeconds + CLOCK_SKEW_SECONDS) return { refusal: "This platform token was issued in the future" };
4999
+ const subject = stringClaim(claims, "sub");
5000
+ if (!subject) return { refusal: "A platform token must name who it acts for (sub)" };
5001
+ const scopes = (stringClaim(claims, "scope") ?? "").split(/\s+/).filter(Boolean).filter((scope) => grantable.includes(scope));
5002
+ if (scopes.length === 0) return { refusal: `This platform token carries no scope this server grants to the platform here (${grantable.join(", ")})` };
5003
+ const tokenId = stringClaim(claims, "jti");
5004
+ const email = stringClaim(claims, "email");
5005
+ return {
5006
+ subject,
5007
+ scopes,
5008
+ issuedAt: iat,
5009
+ expiresAt: exp,
5010
+ ...tokenId ? { tokenId } : {},
5011
+ ...email ? { email } : {}
5012
+ };
5013
+ }
5014
+ /**
5015
+ * Authenticate an `rpt_` bearer token ahead of an admin gate.
5016
+ *
5017
+ * Mounted where the `rk_` pre-auth is, and shaped like it: a request it does not
5018
+ * recognise passes through untouched, a recognised one either becomes a caller
5019
+ * with narrowed `scopes` or is refused here. The gate's scope check then decides
5020
+ * — so a token holding `cron:read` reads cron, and is a 403 on every other
5021
+ * surface.
5022
+ *
5023
+ * With `config` undefined, platform tokens are off on this server; an `rpt_`
5024
+ * token is still recognised, so its holder learns that rather than the generic
5025
+ * "invalid token" a JWT parser would answer.
5026
+ */
5027
+ function createPlatformTokenPreAuth(config) {
5028
+ return async (c, next) => {
5029
+ if (c.get("user")) return next();
5030
+ const token = extractBearerToken(c.req.header("authorization"));
5031
+ if (token === void 0 || !isPlatformToken(token)) return next();
5032
+ if (!config) return errorHandler(new ApiError(401, "PLATFORM_TOKENS_OFF", `This server does not accept platform tokens: ${PLATFORM_TOKEN_KEY_ENV} and ${PLATFORM_TOKEN_AUDIENCE_ENV} are not set. The platform hosting it sets them when it deploys.`, void 0, true), c);
5033
+ const verified = await verifyPlatformToken(token, config);
5034
+ if ("refusal" in verified) return errorHandler(new ApiError(401, "INVALID_PLATFORM_TOKEN", verified.refusal, void 0, true), c);
5035
+ c.set("user", {
5036
+ uid: `platform:${verified.subject}`,
5037
+ roles: []
5038
+ });
5039
+ c.set("scopes", verified.scopes);
5040
+ logger.info("[Auth] Platform token accepted", {
5041
+ subject: verified.subject,
5042
+ jti: verified.tokenId,
5043
+ scopes: verified.scopes,
5044
+ method: c.req.method,
5045
+ path: c.req.path
5046
+ });
5047
+ return next();
5048
+ };
5049
+ }
5050
+ //#endregion
5051
+ //#region src/auth/platform-signin-routes.ts
5052
+ var platformSignInSchema = z.object({ token: z.string().min(1).max(8192) });
5053
+ /** The refusal every bad token gets, with the reason in the server's log rather than the response. */
5054
+ var invalid = () => ApiError.unauthorized("This sign-in link is invalid or has expired. Open the admin again from the project's page in the console.", "INVALID_PLATFORM_TOKEN");
5055
+ function mountPlatformSignInRoutes(deps) {
5056
+ const { router, config, platformSignIn, limiters, ops, parseBody, buildAuthResponse, createSessionAndTokens, applyTransformHook } = deps;
5057
+ const authRepo = config.authRepo;
5058
+ router.post("/platform-signin", limiters.strict, async (c) => {
5059
+ const { token } = parseBody(platformSignInSchema, await c.req.json().catch(() => void 0));
5060
+ const verified = await verifyPlatformToken(token, platformSignIn.tokens, void 0, PLATFORM_SIGNIN_SCOPES);
5061
+ if ("refusal" in verified) {
5062
+ logger.warn("[Auth] Platform sign-in refused", { reason: verified.refusal });
5063
+ throw invalid();
5064
+ }
5065
+ const lifetime = verified.expiresAt - verified.issuedAt;
5066
+ const email = verified.email ? normalizeEmail(verified.email) : void 0;
5067
+ const refusal = !verified.tokenId ? "the token carries no jti, so it could be used twice" : !email || !isDeliverableAddress(email) ? "the token names no usable email" : lifetime > 120 ? `a sign-in token may live at most 120 seconds` : void 0;
5068
+ if (refusal || !email || !verified.tokenId) {
5069
+ logger.warn("[Auth] Platform sign-in refused", {
5070
+ reason: refusal,
5071
+ subject: verified.subject,
5072
+ jti: verified.tokenId
5073
+ });
5074
+ throw invalid();
5075
+ }
5076
+ if (!(await platformSignIn.usedTokens.hit(`platform-signin:${verified.tokenId}`, 720 * 1e3, 1)).allowed) {
5077
+ logger.warn("[Auth] Platform sign-in refused", {
5078
+ reason: "token already used",
5079
+ subject: verified.subject,
5080
+ jti: verified.tokenId
5081
+ });
5082
+ throw invalid();
5083
+ }
5084
+ let user = await authRepo.getUserByEmail(email);
5085
+ const created = !user;
5086
+ if (!user) {
5087
+ let createData = {
5088
+ email,
5089
+ emailVerified: true
5090
+ };
5091
+ if (ops.beforeUserCreate) createData = await ops.beforeUserCreate(createData);
5092
+ user = await authRepo.createUser(createData);
5093
+ } else if (!user.emailVerified) {
5094
+ await confirmAddressOwnership(authRepo, user, null);
5095
+ user = {
5096
+ ...user,
5097
+ emailVerified: true,
5098
+ passwordHash: null
5099
+ };
5100
+ }
5101
+ const roleIds = await authRepo.getUserRoleIds(user.id);
5102
+ if (!roleIds.includes("admin")) await authRepo.setUserRoles(user.id, [...roleIds, ADMIN_ROLE]);
5103
+ const session = await createSessionAndTokens(user.id, c.req.header("user-agent") || "unknown", requestClientAddress(c), { method: "platform" });
5104
+ logger.info("[Auth] Platform sign-in", {
5105
+ subject: verified.subject,
5106
+ jti: verified.tokenId,
5107
+ uid: user.id,
5108
+ created,
5109
+ promoted: !roleIds.includes(ADMIN_ROLE)
5110
+ });
5111
+ if (ops.onAuthenticated) ops.onAuthenticated(user, "platform").catch((err) => {
5112
+ logger.error("[AuthHooks] onAuthenticated error", { error: err instanceof Error ? err.message : err });
5113
+ });
5114
+ const authResponse = buildAuthResponse(user, session.roleIds, session.accessToken, session.refreshToken, "platform");
5115
+ const transformed = await applyTransformHook(authResponse, "platform", c.req.raw, user.id);
5116
+ c.header("Cache-Control", "no-store");
5117
+ return c.json(redactRefreshToken(transformed, c, session.refreshToken, config.cookieAuth));
5118
+ });
5119
+ }
4813
5120
  /**
4814
5121
  * The slack allowed between two polls before the second counts as early. The
4815
5122
  * gap is measured between the requests' arrivals, and a device that sleeps
@@ -6052,6 +6359,17 @@ function createAuthRoutes(config) {
6052
6359
  createSessionAndTokens,
6053
6360
  applyTransformHook
6054
6361
  });
6362
+ if (config.platformSignIn) mountPlatformSignInRoutes({
6363
+ router,
6364
+ config,
6365
+ platformSignIn: config.platformSignIn,
6366
+ limiters,
6367
+ ops,
6368
+ parseBody,
6369
+ buildAuthResponse,
6370
+ createSessionAndTokens,
6371
+ applyTransformHook
6372
+ });
6055
6373
  return router;
6056
6374
  }
6057
6375
  //#endregion
@@ -6087,9 +6405,26 @@ function buildBuiltinAuthCapabilities(inputs) {
6087
6405
  }),
6088
6406
  enabledProviders,
6089
6407
  ...providerClientIds && Object.keys(providerClientIds).length > 0 ? { providerClientIds } : {},
6090
- needsSetup
6408
+ needsSetup,
6409
+ ...unavailableSignIn({
6410
+ enableMagicLink,
6411
+ enableEmailOtp,
6412
+ emailConfigured
6413
+ })
6091
6414
  };
6092
6415
  }
6416
+ /**
6417
+ * The sign-in methods switched on that cannot work, as `GET /auth/config`
6418
+ * reports them (`unavailable`). Spread into the capabilities only when one is
6419
+ * missing, so the document stays the same for every backend that is fine.
6420
+ */
6421
+ function unavailableSignIn(inputs) {
6422
+ if (inputs.emailConfigured) return {};
6423
+ const unavailable = {};
6424
+ if (inputs.enableMagicLink) unavailable.magicLink = "EMAIL_NOT_CONFIGURED";
6425
+ if (inputs.enableEmailOtp) unavailable.emailOtp = "EMAIL_NOT_CONFIGURED";
6426
+ return Object.keys(unavailable).length > 0 ? { unavailable } : {};
6427
+ }
6093
6428
  //#endregion
6094
6429
  //#region src/auth/reset-password-admin.ts
6095
6430
  /**
@@ -6515,13 +6850,22 @@ function createAdminUsersRoute(config) {
6515
6850
  const roles = body.roles === void 0 || body.roles === null ? void 0 : readRoleNames(body.roles);
6516
6851
  if (roles !== void 0) assertMayGrantRoles(c, roles);
6517
6852
  if (await authRepo.getUserByEmail(normalizeEmail(email))) throw ApiError.conflict("A user with this email already exists");
6518
- const prepResult = await prepareAdminUserValues(body, {
6853
+ if (body.invite !== void 0 && typeof body.invite !== "boolean") throw ApiError.badRequest("`invite` is true or false", "INVALID_INPUT");
6854
+ const prepared = await prepareAdminUserValues(body, {
6519
6855
  authRepo,
6520
6856
  emailService,
6521
6857
  emailConfig,
6522
6858
  resolvedHooks: ops,
6523
6859
  authTableHooks
6524
6860
  }, { mayWaivePasswordPolicy: callerIsAdmin(c) });
6861
+ const prepResult = body.invite === false && !body.password && !prepared.hookHandledEmail ? {
6862
+ ...prepared,
6863
+ values: {
6864
+ ...prepared.values,
6865
+ passwordHash: void 0
6866
+ },
6867
+ clearPassword: void 0
6868
+ } : prepared;
6525
6869
  let createData = {
6526
6870
  email: prepResult.values.email,
6527
6871
  passwordHash: prepResult.values.passwordHash,
@@ -6753,6 +7097,7 @@ function createBuiltinAuthAdapter(config) {
6753
7097
  const { authRepository, emailService, emailConfig, allowRegistration = false, disableSelfRegistration = false, allowAnonymous = false, allowUserLookup = false, captcha, defaultRole, oauthProviders = [], allowedRedirectUris, serviceKey, authHooks, authTableHooks, enableMagicLink = false, enableEmailOtp = false, deviceLogin, cookieAuth, requireEmailVerification = false, refreshTokenReuseIntervalSeconds, refreshTokenReuse, magicLinkCreatesUsers = false } = config;
6754
7098
  const jwt = config.jwt ?? processJwtService;
6755
7099
  const resolvedOps = resolveAuthHooks(authHooks);
7100
+ if ((enableMagicLink || enableEmailOtp) && !emailService?.isConfigured()) logger.warn(`[Auth] ${[enableMagicLink && "AUTH_MAGIC_LINK", enableEmailOtp && "AUTH_EMAIL_OTP"].filter(Boolean).join(" and ")} is on, but no email service is configured, so that sign-in is off (the route answers 503 EMAIL_NOT_CONFIGURED). Set SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASS and SMTP_FROM, or pass \`email\` to the backend.`);
6756
7101
  /**
6757
7102
  * The caller's roles as the database has them now.
6758
7103
  *
@@ -6914,7 +7259,8 @@ function createBuiltinAuthAdapter(config) {
6914
7259
  requireEmailVerification,
6915
7260
  refreshTokenReuseIntervalSeconds,
6916
7261
  refreshTokenReuse,
6917
- magicLinkCreatesUsers
7262
+ magicLinkCreatesUsers,
7263
+ platformSignIn: config.platformSignIn
6918
7264
  });
6919
7265
  },
6920
7266
  createAdminRoutes() {
@@ -9050,6 +9396,6 @@ var auth_exports = /* @__PURE__ */ __exportAll({
9050
9396
  verifyPassword: () => verifyPassword
9051
9397
  });
9052
9398
  //#endregion
9053
- export { assertEmailLinkBases as $, createDataRateLimitCheck as A, extractLinks as B, createJwksRoutes as C, AUTH_CONFIG_LIMIT as D, isBootstrapWindowOpen as E, MemoryRateLimitStore as F, hashPassword as G, SMTPEmailService as H, activeDevEmailSink as I, adapterRefusal as J, validatePasswordStrength as K, clearActiveDevEmailSink as L, createRateLimiter as M, requestClientAddress as N, DEFAULT_FUNCTIONS_ANONYMOUS_LIMIT as O, setSharedRateLimitStore as P, generateSecurePassword as Q, createDevEmailSink as R, createApiKeyStore as S, configureUserPicking as T, createEmailService as U, registerDevEmailSink as V, resolveAuthHooks as W, createAdapterCallerResolution as X, createAdapterAuthMiddleware as Y, completeUserCreation as Z, oauthCodeFlowSchema as _, walkJsonShape as _t, createBitbucketProvider as a, getMagicLinkTemplate as at, createApiKeyRoutes as b, createTwitterProvider as c, getWelcomeEmailTemplate as ct, createMicrosoftProvider as d, escapeHtml as dt, resolveEmailLinkBase as et, tryVerifyOidcIdToken as f, html as ft, createGoogleProvider as g, formatJsonPath as gt, createLinkedinProvider as h, resolveRateLimitStoreKind as ht, createSlackProvider as i, getEmailVerificationTemplate as it, createDataRateLimiter as j, createAuthLimiters as k, createFacebookProvider as l, resolveEmailBranding as lt, createGitHubProvider as m, createSqlRateLimitStore as mt, createCustomAuthAdapter as n, getEmailChangeTemplate as nt, createGitLabProvider as o, getPasswordResetTemplate as ot, verifyOidcIdToken as p, raw as pt, verifyPassword as q, createSpotifyProvider as r, getEmailOtpTemplate as rt, createDiscordProvider as s, getUserInvitationTemplate as st, auth_exports as t, getEmailChangeNoticeTemplate as tt, createAppleProvider as u, RawHtml as ut, pkceTokenParams as v, createBuiltinAuthAdapter as w, createPersonalKeyRoutes as x, providerVerifiedEmail as y, devEmailSinkFor as z };
9399
+ export { adapterRefusal as $, verifyPlatformToken as A, MemoryRateLimitStore as B, createJwksRoutes as C, walkJsonShape as Ct, createPlatformTokenPreAuth as D, PLATFORM_MCP_SCOPES as E, createDataRateLimitCheck as F, extractLinks as G, clearActiveDevEmailSink as H, createDataRateLimiter as I, createEmailService as J, registerDevEmailSink as K, createRateLimiter as L, AUTH_CONFIG_LIMIT as M, DEFAULT_FUNCTIONS_ANONYMOUS_LIMIT as N, isPlatformToken as O, createAuthLimiters as P, verifyPassword as Q, requestClientAddress as R, createApiKeyStore as S, formatJsonPath as St, configureUserPicking as T, createDevEmailSink as U, activeDevEmailSink as V, devEmailSinkFor as W, hashPassword as X, resolveAuthHooks as Y, validatePasswordStrength as Z, oauthCodeFlowSchema as _, escapeHtml as _t, createBitbucketProvider as a, magicLinkUrlProblem as at, createApiKeyRoutes as b, createSqlRateLimitStore as bt, createTwitterProvider as c, getEmailChangeTemplate as ct, createMicrosoftProvider as d, getMagicLinkTemplate as dt, createAdapterAuthMiddleware as et, tryVerifyOidcIdToken as f, getPasswordResetTemplate as ft, createGoogleProvider as g, RawHtml as gt, createLinkedinProvider as h, resolveEmailBranding as ht, createSlackProvider as i, assertEmailLinkBases as it, isBootstrapWindowOpen as j, platformTokensFromEnv as k, createFacebookProvider as l, getEmailOtpTemplate as lt, createGitHubProvider as m, getWelcomeEmailTemplate as mt, createCustomAuthAdapter as n, completeUserCreation as nt, createGitLabProvider as o, resolveEmailLinkBase as ot, verifyOidcIdToken as p, getUserInvitationTemplate as pt, SMTPEmailService as q, createSpotifyProvider as r, generateSecurePassword as rt, createDiscordProvider as s, getEmailChangeNoticeTemplate as st, auth_exports as t, createAdapterCallerResolution as tt, createAppleProvider as u, getEmailVerificationTemplate as ut, pkceTokenParams as v, html as vt, createBuiltinAuthAdapter as w, createPersonalKeyRoutes as x, resolveRateLimitStoreKind as xt, providerVerifiedEmail as y, raw as yt, setSharedRateLimitStore as z };
9054
9400
 
9055
- //# sourceMappingURL=auth-BanB_pZj.js.map
9401
+ //# sourceMappingURL=auth-CHOmnYwu.js.map