@rebasepro/server 0.30.0 → 0.30.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/index.es.js CHANGED
@@ -14,17 +14,17 @@ import { a as parseEnvBoolean, i as validateCronExpression, t as CronScheduler }
14
14
  import { c as simulationHeaders, t as AUTH_FLOW_HEADER } from "./auth_adapter-HFv5axIT.js";
15
15
  import { n as isValidAppHost, r as reservedPrefixFor, t as SCHEMA_VERSION_HEADER } from "./project_manifest-R6y_KHms.js";
16
16
  import { i as serializeCollections, n as createContractRoutes, r as computeSchemaVersion } from "./contract-routes-BGXR9D5C.js";
17
- import { A as isPublicObjectGrant, C as queryTokenAuth, D as userFromToken, E as requireAuth, F as decideImpersonation, G as isApiKeyToken, H as createApiKeyPreAuth, I as refuseUnhonouredImpersonation, J as extractBearerToken, K as resolveApiKey, M as storageObjectOfPath, N as storageRequestWildcard, O as PUBLIC_OBJECT_PRINCIPAL, Q as supportsRlsScoping, S as publicObjectAuth, T as requireAdmin, U as createFunctionScopeGuard, V as reportSimulatedContext, W as createTusScopeGuard, X as SERVICE_IDENTITY, Y as safeCompare, Z as scopeDataDriver, _ as createAuthMiddleware, at as httpMethodToOperation, b as fileTokenAuth, c as configureAccess, ct as isPublicStoragePath, d as keyOwnerResolverFor, et as isAccessTokenRevoked, f as processAccessControl, g as setDefaultAccessControl, h as requireScopeByMethod, it as refuseSimulatedWrite, j as requestedStorageObject, k as isDownloadTokenGrant, l as getAccessModel, lt as storageObjectPath, m as requireScope, n as accessModelFromCollections, ot as PUBLIC_STORAGE_PREFIX, q as validateApiKey, r as accessOf, s as callerScopes, st as isPublicStorageKey, u as hasScope, v as createRequireAuth, w as refuse$1, x as optionalAuth, y as extractUserFromToken } from "./access-BihomvkO.js";
17
+ import { A as isPublicObjectGrant, C as queryTokenAuth, D as userFromToken, E as requireAuth, F as decideImpersonation, G as isApiKeyToken, H as createApiKeyPreAuth, I as refuseUnhonouredImpersonation, J as extractBearerToken, K as resolveApiKey, M as storageObjectOfPath, N as storageRequestWildcard, O as PUBLIC_OBJECT_PRINCIPAL, Q as supportsRlsScoping, S as publicObjectAuth, T as requireAdmin, U as createFunctionScopeGuard, V as reportSimulatedContext, W as createTusScopeGuard, X as SERVICE_IDENTITY, Y as safeCompare, Z as scopeDataDriver, _ as createAuthMiddleware, at as httpMethodToOperation, b as fileTokenAuth, c as configureAccess, ct as isPublicStoragePath, d as keyOwnerResolverFor, et as isAccessTokenRevoked, f as processAccessControl, g as setDefaultAccessControl, h as requireScopeByMethod, it as refuseSimulatedWrite, j as requestedStorageObject, k as isDownloadTokenGrant, l as getAccessModel, lt as storageObjectPath, m as requireScope, n as accessModelFromCollections, ot as PUBLIC_STORAGE_PREFIX, q as validateApiKey, r as accessOf, s as callerScopes, st as isPublicStorageKey, u as hasScope, v as createRequireAuth, w as refuse$1, x as optionalAuth, y as extractUserFromToken } from "./access-1wrvwWls.js";
18
18
  import { a as parseWriteFilter, c as assertQueryFieldsReadable, d as cursorToStartAfter, f as decodeCursor$1, h as toDriverAggregateGroup, i as parseQueryOptions, l as assertReadableFields, m as toDriverAggregate, n as parseAggregateSelect, o as resolveListLimitParam, p as reconcileCursorOrder, r as parseGroupBy, s as assertNoHiddenAggregateNames, t as orderByEntriesToTuples, u as requestViewer } from "./query-parser-mFFiGEFV.js";
19
19
  import { a as logger, c as setLogLevel, d as hostEnv, i as logLevelEnabled, l as setLogOutput, o as rawQueryLoggingEnabled, r as describeCauseChain, s as redactSensitiveText, t as _setLogLineHook } from "./logger-SigQ2oZJ.js";
20
20
  import { n as suggestNearMiss, r as toSnakeCase } from "./strings.es-B7QLnHh2.js";
21
21
  import { a as restrictedFieldNames, c as getTableName, d as relationDeclaringProperty, f as resolveCollectionRelations, l as isJunctionBackedRelation, m as toWireKey, n as canReadField, o as fieldKeyForColumn, p as resolveRelation, r as canWriteField, s as findRelation, t as apiHiddenFieldNames } from "./field-access-BDyTY2D4.js";
22
22
  import { c as createTransport, d as parseRebaseJson, h as unref, l as defaultCodeForStatus, m as withETag, o as createCollectionClient, p as etagOf, r as SDKQueryBuilder, u as invalidBulkBody } from "./offline-store-B7F5mimt-Bh5f-dWu.js";
23
- import { $ as getEmailChangeNoticeTemplate, A as createDataRateLimitCheck, B as registerDevEmailSink, C as createJwksRoutes, D as AUTH_CONFIG_LIMIT, E as isBootstrapWindowOpen, F as activeDevEmailSink, G as validatePasswordStrength, H as createEmailService, I as clearActiveDevEmailSink, J as createAdapterAuthMiddleware, K as verifyPassword, L as createDevEmailSink, M as createRateLimiter, N as setSharedRateLimitStore, O as DEFAULT_FUNCTIONS_ANONYMOUS_LIMIT, P as MemoryRateLimitStore, Q as resolveEmailLinkBase, R as devEmailSinkFor, S as createApiKeyStore, T as configureUserPicking, U as resolveAuthHooks, V as SMTPEmailService, W as hashPassword, X as generateSecurePassword, Y as completeUserCreation, Z as assertEmailLinkBases, _ as oauthCodeFlowSchema, a as createBitbucketProvider, at as getUserInvitationTemplate, b as createApiKeyRoutes, c as createTwitterProvider, ct as RawHtml, d as createMicrosoftProvider, dt as raw, et as getEmailChangeTemplate, f as tryVerifyOidcIdToken, ft as createSqlRateLimitStore, g as createGoogleProvider, h as createLinkedinProvider, i as createSlackProvider, it as getPasswordResetTemplate, j as createDataRateLimiter, k as createAuthLimiters, l as createFacebookProvider, lt as escapeHtml, m as createGitHubProvider, mt as securityRuleToConditions, n as createCustomAuthAdapter, nt as getEmailVerificationTemplate, o as createGitLabProvider, ot as getWelcomeEmailTemplate, p as verifyOidcIdToken, pt as resolveRateLimitStoreKind, q as adapterRefusal, r as createSpotifyProvider, rt as getMagicLinkTemplate, s as createDiscordProvider, st as resolveEmailBranding, tt as getEmailOtpTemplate, u as createAppleProvider, ut as html, v as pkceTokenParams, w as createBuiltinAuthAdapter, x as createPersonalKeyRoutes, y as providerVerifiedEmail, z as extractLinks } from "./auth-C-RJT4VO.js";
23
+ import { $ as getEmailChangeNoticeTemplate, A as createDataRateLimitCheck, B as registerDevEmailSink, C as createJwksRoutes, D as AUTH_CONFIG_LIMIT, E as isBootstrapWindowOpen, F as activeDevEmailSink, G as validatePasswordStrength, H as createEmailService, I as clearActiveDevEmailSink, J as createAdapterAuthMiddleware, K as verifyPassword, L as createDevEmailSink, M as createRateLimiter, N as setSharedRateLimitStore, O as DEFAULT_FUNCTIONS_ANONYMOUS_LIMIT, P as MemoryRateLimitStore, Q as resolveEmailLinkBase, R as devEmailSinkFor, S as createApiKeyStore, T as configureUserPicking, U as resolveAuthHooks, V as SMTPEmailService, W as hashPassword, X as generateSecurePassword, Y as completeUserCreation, Z as assertEmailLinkBases, _ as oauthCodeFlowSchema, a as createBitbucketProvider, at as getUserInvitationTemplate, b as createApiKeyRoutes, c as createTwitterProvider, ct as RawHtml, d as createMicrosoftProvider, dt as raw, et as getEmailChangeTemplate, f as tryVerifyOidcIdToken, ft as createSqlRateLimitStore, g as createGoogleProvider, h as createLinkedinProvider, i as createSlackProvider, it as getPasswordResetTemplate, j as createDataRateLimiter, k as createAuthLimiters, l as createFacebookProvider, lt as escapeHtml, m as createGitHubProvider, mt as securityRuleToConditions, n as createCustomAuthAdapter, nt as getEmailVerificationTemplate, o as createGitLabProvider, ot as getWelcomeEmailTemplate, p as verifyOidcIdToken, pt as resolveRateLimitStoreKind, q as adapterRefusal, r as createSpotifyProvider, rt as getMagicLinkTemplate, s as createDiscordProvider, st as resolveEmailBranding, tt as getEmailOtpTemplate, u as createAppleProvider, ut as html, v as pkceTokenParams, w as createBuiltinAuthAdapter, x as createPersonalKeyRoutes, y as providerVerifiedEmail, z as extractLinks } from "./auth-Bzb_b1KY.js";
24
24
  import { a as warnDeprecated, n as FilesFailedToLoadError } from "./dynamic-import-Bi3XK5y-.js";
25
25
  import "./resumable-upload-threshold-CKv-Ry0l.js";
26
26
  import { i as revokeInternalTableSql, t as REBASE_INTERNAL_TABLES } from "./internal-tables-BmN-5QQr.js";
27
- import { C as randomHex, E as sha256Hex, S as constantTimeEqual, T as sha256Bytes, b as normalizePemFromEnv, d as hasAsymmetricSigningKey, g as setDefaultJwtService, h as processJwtService, l as getJwks, m as jwtOf, n as configureJwt, r as createJwtService, y as verifyJwt } from "./jwt-C3dwSo1U.js";
27
+ import { C as randomHex, E as sha256Hex, S as constantTimeEqual, T as sha256Bytes, b as normalizePemFromEnv, d as hasAsymmetricSigningKey, g as setDefaultJwtService, h as processJwtService, l as getJwks, m as jwtOf, n as configureJwt, r as createJwtService, y as verifyJwt } from "./jwt-DOyYtP0w.js";
28
28
  import { a as isConcurrentDdlRace, c as provisioningExec, l as withoutLeadingComments, o as isDuplicateObjectRace, r as createDdlBootstrapper, s as isSchemaChange, t as CONCURRENT_DDL_SQLSTATES } from "./ddl-bootstrap-DhCuwhHM.js";
29
29
  import { t as createCronStore } from "./cron-store-iv5yn27j.js";
30
30
  import { a as isDataException, c as dbConnectionErrorCounts, i as errorHandler, n as DATABASE_UNAVAILABLE_MESSAGE, o as isDatabaseUnreachable, r as declaredErrorAnswer, s as schemaDriftRemedy, t as ApiError } from "./errors-DpTMfX77.js";
@@ -41,7 +41,7 @@ import "./request-timeout-DW2OBWfJ.js";
41
41
  import { t as FunctionSelectionError } from "./selection-CRpqKUbt.js";
42
42
  import { a as loadCrons, i as loadCronJobsWithDiagnostics, n as declareCrons, r as loadCronJobsFromDirectory } from "./cron-loader-BN24T-O1.js";
43
43
  import { t as createCronRoutes } from "./cron-routes-CjCWNcX6.js";
44
- import { a as listBackupObjects, c as readBackupBytes, i as backupStorageFromEnv, n as createBackupLinkRoutes, o as parseBackupDestination, r as createBackupRoutes, s as parseBackupTimestamp } from "./backup-D-ds7wml.js";
44
+ import { a as listBackupObjects, c as readBackupBytes, i as backupStorageFromEnv, n as createBackupLinkRoutes, o as parseBackupDestination, r as createBackupRoutes, s as parseBackupTimestamp } from "./backup-PN6AM4UK.js";
45
45
  import { a as defaultBackoff, i as createJobQueue, n as createJobStore, o as currentAmbientTransaction, r as PermanentJobError } from "./jobs-D9RBf3Yb.js";
46
46
  import { t as METRIC_SERIES } from "./history-store-Dbyvv1KZ.js";
47
47
  import { createHash, createSign, randomBytes } from "node:crypto";
@@ -6939,6 +6939,95 @@ function createAuth(transport, options) {
6939
6939
  };
6940
6940
  }
6941
6941
  /**
6942
+ * Start a device sign-in: the way something without a browser of its own —
6943
+ * a terminal — signs in through one (RFC 8628's device authorization
6944
+ * grant). Show the person `verificationUriComplete` and `userCode`, then
6945
+ * call {@link pollDeviceLogin} every `interval` seconds until it is
6946
+ * decided. Refused unless the backend has `auth.deviceLogin` on; its
6947
+ * `/auth/config` says `deviceLogin: true` when it does.
6948
+ *
6949
+ * @param options.clientName What the approval page calls this device.
6950
+ */
6951
+ async function startDeviceLogin(options) {
6952
+ const res = await getFetch()(authUrl("/device"), {
6953
+ method: "POST",
6954
+ headers: { "Content-Type": "application/json" },
6955
+ body: JSON.stringify({ clientName: options?.clientName })
6956
+ });
6957
+ const body = await res.json().catch(() => ({}));
6958
+ if (!res.ok) throwApiError(res.status, body, res.statusText);
6959
+ return body;
6960
+ }
6961
+ /**
6962
+ * Ask once whether a device sign-in has been decided. When it has been
6963
+ * approved, this client is signed in — the session is stored like any other
6964
+ * sign-in's is — and the answer carries it. Any other answer is what to do
6965
+ * next: wait `interval` seconds and ask again (`pending`, `slow_down`),
6966
+ * or stop (`denied`, `expired`).
6967
+ *
6968
+ * Rejects for anything else: a network failure, a rate limit, a device
6969
+ * code that has already been used.
6970
+ */
6971
+ async function pollDeviceLogin(deviceCode) {
6972
+ const res = await getFetch()(authUrl("/device/token"), {
6973
+ method: "POST",
6974
+ headers: { "Content-Type": "application/json" },
6975
+ body: JSON.stringify({ deviceCode })
6976
+ });
6977
+ const body = await res.json().catch(() => ({}));
6978
+ if (!res.ok) {
6979
+ const error = apiError(res.status, body, res.statusText);
6980
+ const details = error.details;
6981
+ const interval = typeof details === "object" && details !== null && "interval" in details && typeof details.interval === "number" ? details.interval : void 0;
6982
+ if (error.code === "authorization_pending") return {
6983
+ status: "pending",
6984
+ interval: interval ?? 5
6985
+ };
6986
+ if (error.code === "slow_down") return {
6987
+ status: "slow_down",
6988
+ interval: interval ?? 10
6989
+ };
6990
+ if (error.code === "access_denied") return { status: "denied" };
6991
+ if (error.code === "expired_token") return { status: "expired" };
6992
+ throw error;
6993
+ }
6994
+ const session = handleAuthResponse(body, "SIGNED_IN");
6995
+ return {
6996
+ status: "approved",
6997
+ user: session.user,
6998
+ accessToken: session.accessToken,
6999
+ refreshToken: session.refreshToken
7000
+ };
7001
+ }
7002
+ /**
7003
+ * What a device sign-in is, for the page that approves it: the code, what
7004
+ * the device calls itself and where it asked from. Needs this client to
7005
+ * be signed in. Rejects with `DEVICE_LOGIN_NOT_FOUND` (404) for a code no
7006
+ * sign-in has.
7007
+ */
7008
+ async function describeDeviceLogin(userCode) {
7009
+ return transport.request(`${authPath}/device/${encodeURIComponent(userCode)}`, { method: "GET" });
7010
+ }
7011
+ /**
7012
+ * Approve a device sign-in as the signed-in account: the device's next
7013
+ * poll gets a session for it. Rejects with `DEVICE_LOGIN_EXPIRED` (410),
7014
+ * `DEVICE_LOGIN_DECIDED` (409), or `AAL2_REQUIRED` (403) when the account
7015
+ * has two-factor authentication on and this session did not use it.
7016
+ */
7017
+ async function approveDeviceLogin(userCode) {
7018
+ await transport.request(`${authPath}/device/approve`, {
7019
+ method: "POST",
7020
+ body: JSON.stringify({ userCode })
7021
+ });
7022
+ }
7023
+ /** Deny a device sign-in: its next poll is told so, and it gets nothing. */
7024
+ async function denyDeviceLogin(userCode) {
7025
+ await transport.request(`${authPath}/device/deny`, {
7026
+ method: "POST",
7027
+ body: JSON.stringify({ userCode })
7028
+ });
7029
+ }
7030
+ /**
6942
7031
  * Sign in without credentials, as a throwaway account.
6943
7032
  *
6944
7033
  * The account is real — it has an id, roles and a session, so row-level
@@ -7264,6 +7353,11 @@ function createAuth(transport, options) {
7264
7353
  verifyMagicLink,
7265
7354
  sendEmailOtp,
7266
7355
  verifyEmailOtp,
7356
+ startDeviceLogin,
7357
+ pollDeviceLogin,
7358
+ describeDeviceLogin,
7359
+ approveDeviceLogin,
7360
+ denyDeviceLogin,
7267
7361
  getSessions,
7268
7362
  revokeSession,
7269
7363
  revokeAllSessions,
@@ -12550,7 +12644,7 @@ async function loadCollectionsFromDirectory(source, options = {}) {
12550
12644
  * anonymous request shares one principal, so honouring a key there would hand
12551
12645
  * one visitor's stored response to the next one who sent the same string.
12552
12646
  */
12553
- var TABLE$1 = "\"rebase\".\"idempotency_keys\"";
12647
+ var TABLE$2 = "\"rebase\".\"idempotency_keys\"";
12554
12648
  /**
12555
12649
  * How long a replay is recognised. Long enough to cover an offline stretch and
12556
12650
  * a retry schedule; short enough that the table stays small and a key cannot be
@@ -12669,13 +12763,13 @@ function createIdempotencyStore(driver, options = {}) {
12669
12763
  */
12670
12764
  const probe = async () => {
12671
12765
  try {
12672
- await exec(`SELECT key, uid, fingerprint, response, created_at FROM ${TABLE$1} WHERE false`);
12766
+ await exec(`SELECT key, uid, fingerprint, response, created_at FROM ${TABLE$2} WHERE false`);
12673
12767
  return true;
12674
12768
  } catch (error) {
12675
12769
  retryEnsureAt = Date.now() + ENSURE_RETRY_COOLDOWN_MS;
12676
12770
  if (!warnedMissing) {
12677
12771
  warnedMissing = true;
12678
- logger.warn(`Idempotency keys unavailable — ${TABLE$1} is missing or out of date, and this backend changes nothing in its database. Idempotency-Key is ignored, so a replayed offline write may insert a duplicate row, until the table is created by a provisioning run.`, { detail: error instanceof Error ? error.message : String(error) });
12772
+ logger.warn(`Idempotency keys unavailable — ${TABLE$2} is missing or out of date, and this backend changes nothing in its database. Idempotency-Key is ignored, so a replayed offline write may insert a duplicate row, until the table is created by a provisioning run.`, { detail: error instanceof Error ? error.message : String(error) });
12679
12773
  }
12680
12774
  return false;
12681
12775
  }
@@ -12694,7 +12788,7 @@ function createIdempotencyStore(driver, options = {}) {
12694
12788
  try {
12695
12789
  await exec("CREATE SCHEMA IF NOT EXISTS rebase");
12696
12790
  await exec(`
12697
- CREATE TABLE IF NOT EXISTS ${TABLE$1} (
12791
+ CREATE TABLE IF NOT EXISTS ${TABLE$2} (
12698
12792
  key TEXT NOT NULL,
12699
12793
  uid TEXT NOT NULL,
12700
12794
  response JSONB,
@@ -12702,8 +12796,8 @@ function createIdempotencyStore(driver, options = {}) {
12702
12796
  PRIMARY KEY (uid, key)
12703
12797
  )
12704
12798
  `);
12705
- await exec(`ALTER TABLE ${TABLE$1} ADD COLUMN IF NOT EXISTS fingerprint TEXT`);
12706
- await exec(`CREATE INDEX IF NOT EXISTS idx_idempotency_created ON ${TABLE$1}(created_at)`);
12799
+ await exec(`ALTER TABLE ${TABLE$2} ADD COLUMN IF NOT EXISTS fingerprint TEXT`);
12800
+ await exec(`CREATE INDEX IF NOT EXISTS idx_idempotency_created ON ${TABLE$2}(created_at)`);
12707
12801
  await exec(revokeInternalTableSql("rebase", "idempotency_keys"));
12708
12802
  return true;
12709
12803
  } catch (error) {
@@ -12723,20 +12817,20 @@ function createIdempotencyStore(driver, options = {}) {
12723
12817
  if (key && !owner) warnAnonymous();
12724
12818
  if (!key || !owner || !await ensure()) return { status: "claimed" };
12725
12819
  try {
12726
- if ((await exec(`INSERT INTO ${TABLE$1} (key, uid, fingerprint, response, created_at)
12820
+ if ((await exec(`INSERT INTO ${TABLE$2} (key, uid, fingerprint, response, created_at)
12727
12821
  VALUES ($1, $2, $3, NULL, NOW())
12728
12822
  ON CONFLICT (uid, key) DO UPDATE
12729
12823
  SET response = NULL, created_at = NOW(), fingerprint = EXCLUDED.fingerprint
12730
- WHERE (${TABLE$1}.response IS NULL
12731
- AND ${TABLE$1}.created_at < NOW() - INTERVAL '${PENDING_LEASE_SECONDS} seconds')
12732
- OR (${TABLE$1}.response IS NOT NULL
12733
- AND ${TABLE$1}.created_at < NOW() - INTERVAL '${TTL_HOURS} hours')
12824
+ WHERE (${TABLE$2}.response IS NULL
12825
+ AND ${TABLE$2}.created_at < NOW() - INTERVAL '${PENDING_LEASE_SECONDS} seconds')
12826
+ OR (${TABLE$2}.response IS NOT NULL
12827
+ AND ${TABLE$2}.created_at < NOW() - INTERVAL '${TTL_HOURS} hours')
12734
12828
  RETURNING 1 AS claimed`, [
12735
12829
  key,
12736
12830
  owner,
12737
12831
  fingerprint
12738
12832
  ])).length > 0) return { status: "claimed" };
12739
- const row = (await exec(`SELECT response, response IS NULL AS pending, fingerprint FROM ${TABLE$1}
12833
+ const row = (await exec(`SELECT response, response IS NULL AS pending, fingerprint FROM ${TABLE$2}
12740
12834
  WHERE uid = $1 AND key = $2`, [owner, key]))[0];
12741
12835
  if (!row) return { status: "claimed" };
12742
12836
  if (row.fingerprint != null && row.fingerprint !== fingerprint) return { status: "mismatch" };
@@ -12753,19 +12847,19 @@ function createIdempotencyStore(driver, options = {}) {
12753
12847
  const owner = principal(uid);
12754
12848
  if (!key || !owner || !await ensure()) return;
12755
12849
  try {
12756
- await exec(`UPDATE ${TABLE$1} SET response = $3::jsonb WHERE uid = $1 AND key = $2`, [
12850
+ await exec(`UPDATE ${TABLE$2} SET response = $3::jsonb WHERE uid = $1 AND key = $2`, [
12757
12851
  owner,
12758
12852
  key,
12759
12853
  JSON.stringify(response ?? null)
12760
12854
  ]);
12761
- if (Math.random() < .01) await exec(`DELETE FROM ${TABLE$1} WHERE created_at < NOW() - INTERVAL '${TTL_HOURS} hours'`);
12855
+ if (Math.random() < .01) await exec(`DELETE FROM ${TABLE$2} WHERE created_at < NOW() - INTERVAL '${TTL_HOURS} hours'`);
12762
12856
  } catch {}
12763
12857
  },
12764
12858
  async release(key, uid) {
12765
12859
  const owner = principal(uid);
12766
12860
  if (!key || !owner || !await ensure()) return;
12767
12861
  try {
12768
- await exec(`DELETE FROM ${TABLE$1} WHERE uid = $1 AND key = $2 AND response IS NULL`, [owner, key]);
12862
+ await exec(`DELETE FROM ${TABLE$2} WHERE uid = $1 AND key = $2 AND response IS NULL`, [owner, key]);
12769
12863
  } catch {}
12770
12864
  },
12771
12865
  ensureTable: ensure
@@ -24719,7 +24813,7 @@ var OAUTH_TABLES = [
24719
24813
  CONFIRMATIONS
24720
24814
  ];
24721
24815
  /** How often, at most, issuing a credential also sweeps expired codes and tokens. */
24722
- var SWEEP_INTERVAL_MS = 3600 * 1e3;
24816
+ var SWEEP_INTERVAL_MS$1 = 3600 * 1e3;
24723
24817
  /**
24724
24818
  * How long an authorization code lives.
24725
24819
  *
@@ -24747,7 +24841,7 @@ function createOAuthStore(driver, options = {}) {
24747
24841
  const sweepRefreshTokens = () => exec(`DELETE FROM ${REFRESH} WHERE expires_at < now() - interval '30 days'`);
24748
24842
  let lastSweep = Date.now();
24749
24843
  const sweepIfDue = () => {
24750
- if (Date.now() - lastSweep < SWEEP_INTERVAL_MS) return;
24844
+ if (Date.now() - lastSweep < SWEEP_INTERVAL_MS$1) return;
24751
24845
  lastSweep = Date.now();
24752
24846
  sweepCodes().then(sweepRefreshTokens).catch((error) => logger.warn("[oauth] Sweeping expired codes and tokens failed", { error }));
24753
24847
  };
@@ -25039,6 +25133,136 @@ function toStringArray(value) {
25039
25133
  }
25040
25134
  return [];
25041
25135
  }
25136
+ //#endregion
25137
+ //#region src/auth/device-login-store.ts
25138
+ var TABLE$1 = "rebase.auth_device_logins";
25139
+ /** How long a finished or abandoned sign-in is kept before the sweep removes it. */
25140
+ var KEEP_AFTER_EXPIRY = "1 day";
25141
+ /** How often, at most, starting a sign-in also sweeps old ones. */
25142
+ var SWEEP_INTERVAL_MS = 3600 * 1e3;
25143
+ /**
25144
+ * A store backed by the driver's SQL escape hatch, or null when the driver
25145
+ * cannot run SQL. Device sign-in is then not offered at all: a grant whose
25146
+ * pending state cannot be kept would hand a session to whoever polls first.
25147
+ */
25148
+ function createDeviceLoginStore(driver, options = {}) {
25149
+ const admin = driver.admin;
25150
+ if (!isSQLAdmin(admin)) return null;
25151
+ const run = provisioningExec((sql, execOptions) => admin.executeSql(sql, execOptions?.params ? { params: execOptions.params } : void 0), options.provision);
25152
+ const exec = (sql, params) => run(sql, params ? { params } : void 0);
25153
+ const ddl = createDdlBootstrapper(run, "device-login-store");
25154
+ const sweep = () => exec(`DELETE FROM ${TABLE$1} WHERE expires_at < now() - interval '${KEEP_AFTER_EXPIRY}'`);
25155
+ let lastSweep = Date.now();
25156
+ const sweepIfDue = () => {
25157
+ if (Date.now() - lastSweep < SWEEP_INTERVAL_MS) return;
25158
+ lastSweep = Date.now();
25159
+ sweep().catch((error) => logger.warn("[device-login] Sweeping old device sign-ins failed", { error }));
25160
+ };
25161
+ return {
25162
+ async ensureTables() {
25163
+ await ddl.ensureObject(TABLE$1, `
25164
+ CREATE TABLE IF NOT EXISTS ${TABLE$1} (
25165
+ device_code_hash text PRIMARY KEY,
25166
+ user_code text NOT NULL UNIQUE,
25167
+ client_name text NOT NULL,
25168
+ request_ip text NOT NULL,
25169
+ request_user_agent text NOT NULL,
25170
+ status text NOT NULL DEFAULT 'pending',
25171
+ uid text,
25172
+ aal text,
25173
+ interval_seconds integer NOT NULL,
25174
+ last_polled_at timestamptz,
25175
+ created_at timestamptz NOT NULL DEFAULT now(),
25176
+ decided_at timestamptz,
25177
+ expires_at timestamptz NOT NULL
25178
+ )
25179
+ `);
25180
+ const [schema, name] = TABLE$1.split(".");
25181
+ await ddl.step(`revoke ${TABLE$1}`, () => exec(revokeInternalTableSql(schema, name)));
25182
+ await ddl.step("sweep old device sign-ins", sweep);
25183
+ lastSweep = Date.now();
25184
+ if ((await exec(`SELECT to_regclass($1) AS present`, [TABLE$1]))[0]?.present == null) throw new Error(options.provision === false ? `The device sign-in table ${TABLE$1} does not exist, and this backend changes nothing in its database. A provisioning run with auth.deviceLogin on creates it.` : `The device sign-in table ${TABLE$1} was not created. Check the boot log above for the statement that failed, which is usually a permissions problem on the \`rebase\` schema.`);
25185
+ },
25186
+ async create(deviceCode, login) {
25187
+ sweepIfDue();
25188
+ return (await exec(`INSERT INTO ${TABLE$1}
25189
+ (device_code_hash, user_code, client_name, request_ip, request_user_agent, interval_seconds, expires_at)
25190
+ VALUES ($1, $2, $3, $4, $5, $6, $7)
25191
+ ON CONFLICT (user_code) DO NOTHING
25192
+ RETURNING device_code_hash`, [
25193
+ await sha256Hex(deviceCode),
25194
+ login.userCode,
25195
+ login.clientName,
25196
+ login.requestIp,
25197
+ login.requestUserAgent,
25198
+ login.intervalSeconds,
25199
+ login.expiresAt.toISOString()
25200
+ ])).length > 0;
25201
+ },
25202
+ async findByUserCode(userCode) {
25203
+ const row = (await exec(`SELECT user_code, client_name, request_ip, request_user_agent, status, created_at, expires_at,
25204
+ expires_at <= now() AS expired
25205
+ FROM ${TABLE$1} WHERE user_code = $1`, [userCode]))[0];
25206
+ if (!row) return null;
25207
+ return {
25208
+ userCode: String(row.user_code),
25209
+ clientName: String(row.client_name),
25210
+ requestIp: String(row.request_ip),
25211
+ requestUserAgent: String(row.request_user_agent),
25212
+ status: toStatus(row.status),
25213
+ createdAt: toDate(row.created_at),
25214
+ expiresAt: toDate(row.expires_at),
25215
+ expired: row.expired === true
25216
+ };
25217
+ },
25218
+ async decide(userCode, decision) {
25219
+ return (await exec(`UPDATE ${TABLE$1}
25220
+ SET status = $2, uid = $3, aal = $4, decided_at = now()
25221
+ WHERE user_code = $1 AND status = 'pending' AND expires_at > now()
25222
+ RETURNING user_code`, [
25223
+ userCode,
25224
+ decision.approve ? "approved" : "denied",
25225
+ decision.uid,
25226
+ decision.approve ? decision.aal : null
25227
+ ])).length > 0;
25228
+ },
25229
+ async poll(deviceCode) {
25230
+ const row = (await exec(`UPDATE ${TABLE$1} d
25231
+ SET last_polled_at = now()
25232
+ FROM (SELECT device_code_hash, last_polled_at FROM ${TABLE$1}
25233
+ WHERE device_code_hash = $1 FOR UPDATE) previous
25234
+ WHERE d.device_code_hash = previous.device_code_hash
25235
+ RETURNING d.status, d.interval_seconds, d.expires_at <= now() AS expired,
25236
+ EXTRACT(EPOCH FROM (now() - previous.last_polled_at))::float8 AS since_previous`, [await sha256Hex(deviceCode)]))[0];
25237
+ if (!row) return null;
25238
+ return {
25239
+ status: toStatus(row.status),
25240
+ expired: row.expired === true,
25241
+ intervalSeconds: Number(row.interval_seconds),
25242
+ secondsSincePreviousPoll: row.since_previous == null ? null : Number(row.since_previous)
25243
+ };
25244
+ },
25245
+ async slowDown(deviceCode, byStepSeconds) {
25246
+ await exec(`UPDATE ${TABLE$1} SET interval_seconds = interval_seconds + $2 WHERE device_code_hash = $1`, [await sha256Hex(deviceCode), byStepSeconds]);
25247
+ },
25248
+ async consume(deviceCode) {
25249
+ const row = (await exec(`UPDATE ${TABLE$1} SET status = 'consumed'
25250
+ WHERE device_code_hash = $1 AND status = 'approved' AND expires_at > now()
25251
+ RETURNING uid, aal`, [await sha256Hex(deviceCode)]))[0];
25252
+ if (!row || row.uid == null) return null;
25253
+ return {
25254
+ uid: String(row.uid),
25255
+ aal: row.aal === "aal2" ? "aal2" : "aal1"
25256
+ };
25257
+ }
25258
+ };
25259
+ }
25260
+ function toStatus(value) {
25261
+ return value === "approved" || value === "denied" || value === "consumed" ? value : "pending";
25262
+ }
25263
+ function toDate(value) {
25264
+ return value instanceof Date ? value : new Date(String(value));
25265
+ }
25042
25266
  /** The data-plane vocabulary: `/mcp`'s own, and every backend's unless it brings its own tools. */
25043
25267
  var DATA_SCOPE_VOCABULARY = {
25044
25268
  supported: [
@@ -31259,7 +31483,7 @@ async function buildRebaseBackend(options, announcements) {
31259
31483
  const platformTokenPreAuth = createPlatformTokenPreAuth(platformTokens);
31260
31484
  let backupLinkRouter;
31261
31485
  if (surfaces.admin) {
31262
- const { createBackupLinkRoutes, backupDestinationFromEnv } = await import("./backup-D-ds7wml.js").then((n) => n.t);
31486
+ const { createBackupLinkRoutes, backupDestinationFromEnv } = await import("./backup-PN6AM4UK.js").then((n) => n.t);
31263
31487
  backupLinkRouter = createBackupLinkRoutes({ getDestination: () => backupDestinationFromEnv(process.env) });
31264
31488
  }
31265
31489
  const apiKeyRouter = apiKeyStore && surfaces.admin ? createApiKeyRoutes({
@@ -31332,6 +31556,35 @@ async function buildRebaseBackend(options, announcements) {
31332
31556
  };
31333
31557
  let adapterAuthRouter;
31334
31558
  let adapterAdminRouter;
31559
+ /**
31560
+ * Device sign-in's store, its table made — or undefined, with one line
31561
+ * saying why, so the rest of auth boots without it. It is opt-in, and an
31562
+ * operator who switched it on should get a server that signs in every
31563
+ * other way and a log line naming what did not mount, as `/mcp` does.
31564
+ */
31565
+ const prepareDeviceLogin = async (option) => {
31566
+ if (!option) return void 0;
31567
+ try {
31568
+ new URL(option.verificationUrl);
31569
+ } catch {
31570
+ throw new Error(`auth.deviceLogin.verificationUrl is ${JSON.stringify(option.verificationUrl)}; give the absolute URL of the page that approves a device sign-in, e.g. https://app.example.com/device.`);
31571
+ }
31572
+ const store = createDeviceLoginStore(defaultDriver, { provision: provision.database });
31573
+ if (!store) {
31574
+ logger.error("[auth] auth.deviceLogin is set, but this data driver cannot run SQL to keep pending sign-ins — device sign-in is off.");
31575
+ return;
31576
+ }
31577
+ try {
31578
+ await store.ensureTables();
31579
+ } catch (error) {
31580
+ logger.error("[auth] Could not prepare the device sign-in table — device sign-in is off.", { error });
31581
+ return;
31582
+ }
31583
+ return {
31584
+ store,
31585
+ verificationUrl: option.verificationUrl
31586
+ };
31587
+ };
31335
31588
  if (config.auth) {
31336
31589
  if (!isAuthAdapter(config.auth)) {
31337
31590
  const safeAuthConfig = config.auth;
@@ -31404,13 +31657,14 @@ async function buildRebaseBackend(options, announcements) {
31404
31657
  ]) {
31405
31658
  const providerConfig = safeAuthConfig[key];
31406
31659
  if (providerConfig && requiredFields.every((f) => Boolean(providerConfig[f]))) {
31407
- const createFn = (await import("./auth-C-RJT4VO.js").then((n) => n.t))[factory];
31660
+ const createFn = (await import("./auth-Bzb_b1KY.js").then((n) => n.t))[factory];
31408
31661
  oauthProviders.push(createFn(providerConfig));
31409
31662
  }
31410
31663
  }
31411
31664
  const reCollectionAuth = safeAuthConfig.collection ? safeAuthConfig.collection.auth : void 0;
31412
31665
  const collectionAuthConfig = typeof reCollectionAuth === "object" && reCollectionAuth !== null ? reCollectionAuth : void 0;
31413
31666
  const cookieAuth = safeAuthConfig.cookieAuth === false ? void 0 : safeAuthConfig.cookieAuth ?? {};
31667
+ const deviceLogin = await prepareDeviceLogin(safeAuthConfig.deviceLogin);
31414
31668
  authAdapter = createBuiltinAuthAdapter({
31415
31669
  authRepository: authConfigResult.authRepository ?? authConfigResult.userService,
31416
31670
  jwt,
@@ -31431,6 +31685,7 @@ async function buildRebaseBackend(options, announcements) {
31431
31685
  collectionAuthConfig,
31432
31686
  enableMagicLink: safeAuthConfig.magicLink ?? false,
31433
31687
  enableEmailOtp: safeAuthConfig.emailOtp ?? false,
31688
+ deviceLogin,
31434
31689
  cookieAuth,
31435
31690
  requireEmailVerification: safeAuthConfig.requireEmailVerification ?? false,
31436
31691
  refreshTokenReuseIntervalSeconds: safeAuthConfig.refreshTokenReuseIntervalSeconds,
@@ -32248,7 +32503,7 @@ Use a driver that supports the job queue, or remove the declarations. Refusing t
32248
32503
  let logsSurface;
32249
32504
  let metaSurface;
32250
32505
  if (surfaces.admin) {
32251
- const { createBackupRoutes, backupDestinationFromEnv, readBackupSchedule } = await import("./backup-D-ds7wml.js").then((n) => n.t);
32506
+ const { createBackupRoutes, backupDestinationFromEnv, readBackupSchedule } = await import("./backup-PN6AM4UK.js").then((n) => n.t);
32252
32507
  const backupRouter = new Hono();
32253
32508
  applyAdminGate(backupRouter, "Backup", "backups:read");
32254
32509
  const scheduler = cronScheduler;
@@ -32270,7 +32525,7 @@ Use a driver that supports the job queue, or remove the declarations. Refusing t
32270
32525
  }
32271
32526
  let rlsSimulatorSurface;
32272
32527
  if (surfaces.admin) {
32273
- const { createRlsSimulatorRoutes } = await import("./rls-simulator-routes-C7C3f57E.js");
32528
+ const { createRlsSimulatorRoutes } = await import("./rls-simulator-routes-BTB1cjU4.js");
32274
32529
  const rlsSimulatorRouter = new Hono();
32275
32530
  applyAdminGate(rlsSimulatorRouter, "RLS simulator", "schema:read");
32276
32531
  rlsSimulatorRouter.route("/", createRlsSimulatorRoutes({
@@ -32726,7 +32981,7 @@ function realtimeSocketPath(basePath) {
32726
32981
  * backend no MCP client calls never loads it.
32727
32982
  */
32728
32983
  async function loadMcpApps() {
32729
- const { MCP_APPS } = await import("./dist-DH2xBfrC.js");
32984
+ const { MCP_APPS } = await import("./dist--rf-rq-r.js");
32730
32985
  return withProjectView(MCP_APPS, [...process.env.REBASE_MCP_VIEW ? [process.env.REBASE_MCP_VIEW] : [], ...servedFrontendPaths().map((frontend) => path.join(frontend, PROJECT_VIEW_FILE))], (file) => {
32731
32986
  try {
32732
32987
  return readFileSync(file, "utf8");
@@ -32740,7 +32995,7 @@ async function loadMcpApps() {
32740
32995
  * app to the modules and names every view serves (`MCP_APP_MODULES`).
32741
32996
  */
32742
32997
  async function loadAppCompiler() {
32743
- const { compileApp } = await import("./dist-DH2xBfrC.js");
32998
+ const { compileApp } = await import("./dist--rf-rq-r.js");
32744
32999
  return (source) => compileApp(source, MCP_APP_MODULES);
32745
33000
  }
32746
33001
  /** The collection registry a driver carries, if it has one: not part of `DataDriver`, so found by looking. */