@rebasepro/server 0.29.3 → 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/{access-BihomvkO.js → access-1wrvwWls.js} +2 -2
- package/dist/{access-BihomvkO.js.map → access-1wrvwWls.js.map} +1 -1
- package/dist/auth/auth-hooks.d.ts +3 -2
- package/dist/auth/builtin-auth-adapter.d.ts +2 -0
- package/dist/auth/capabilities.d.ts +2 -0
- package/dist/auth/device-login-routes.d.ts +100 -0
- package/dist/auth/device-login-store.d.ts +102 -0
- package/dist/auth/routes.d.ts +7 -0
- package/dist/{auth-C-RJT4VO.js → auth-Bzb_b1KY.js} +232 -7
- package/dist/auth-Bzb_b1KY.js.map +1 -0
- package/dist/auth_adapter-HFv5axIT.js.map +1 -1
- package/dist/backend/options.d.ts +32 -9
- package/dist/{backup-D-ds7wml.js → backup-PN6AM4UK.js} +2 -2
- package/dist/{backup-D-ds7wml.js.map → backup-PN6AM4UK.js.map} +1 -1
- package/dist/dist--rf-rq-r.js +19359 -0
- package/dist/dist--rf-rq-r.js.map +1 -0
- package/dist/index.es.js +287 -30
- package/dist/index.es.js.map +1 -1
- package/dist/{jwt-C3dwSo1U.js → jwt-DOyYtP0w.js} +3 -3
- package/dist/{jwt-C3dwSo1U.js.map → jwt-DOyYtP0w.js.map} +1 -1
- package/dist/{rls-simulator-routes-C7C3f57E.js → rls-simulator-routes-BTB1cjU4.js} +2 -2
- package/dist/{rls-simulator-routes-C7C3f57E.js.map → rls-simulator-routes-BTB1cjU4.js.map} +1 -1
- package/package.json +5 -5
- package/dist/auth-C-RJT4VO.js.map +0 -1
- package/dist/dist-BCMr0NfI.js +0 -19359
- package/dist/dist-BCMr0NfI.js.map +0 -1
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-
|
|
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-
|
|
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-
|
|
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-
|
|
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";
|
|
@@ -5848,8 +5848,9 @@ function detectStorage() {
|
|
|
5848
5848
|
/**
|
|
5849
5849
|
* The flow mode a client uses when `authFlowMode` is not set.
|
|
5850
5850
|
*
|
|
5851
|
-
* Cookie in a browser. A backend
|
|
5852
|
-
*
|
|
5851
|
+
* Cookie in a browser. A Rebase backend keeps the refresh token in a cookie
|
|
5852
|
+
* and answers the body's with `""` (the runtime always; one booted with
|
|
5853
|
+
* `initializeRebaseBackend` unless it sets `cookieAuth: false`), so a browser
|
|
5853
5854
|
* client defaulting to json held nothing to renew with, and was signed out
|
|
5854
5855
|
* without a word once its access token expired, about an hour after sign-in.
|
|
5855
5856
|
*
|
|
@@ -6938,6 +6939,95 @@ function createAuth(transport, options) {
|
|
|
6938
6939
|
};
|
|
6939
6940
|
}
|
|
6940
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
|
+
/**
|
|
6941
7031
|
* Sign in without credentials, as a throwaway account.
|
|
6942
7032
|
*
|
|
6943
7033
|
* The account is real — it has an id, roles and a session, so row-level
|
|
@@ -7263,6 +7353,11 @@ function createAuth(transport, options) {
|
|
|
7263
7353
|
verifyMagicLink,
|
|
7264
7354
|
sendEmailOtp,
|
|
7265
7355
|
verifyEmailOtp,
|
|
7356
|
+
startDeviceLogin,
|
|
7357
|
+
pollDeviceLogin,
|
|
7358
|
+
describeDeviceLogin,
|
|
7359
|
+
approveDeviceLogin,
|
|
7360
|
+
denyDeviceLogin,
|
|
7266
7361
|
getSessions,
|
|
7267
7362
|
revokeSession,
|
|
7268
7363
|
revokeAllSessions,
|
|
@@ -12549,7 +12644,7 @@ async function loadCollectionsFromDirectory(source, options = {}) {
|
|
|
12549
12644
|
* anonymous request shares one principal, so honouring a key there would hand
|
|
12550
12645
|
* one visitor's stored response to the next one who sent the same string.
|
|
12551
12646
|
*/
|
|
12552
|
-
var TABLE$
|
|
12647
|
+
var TABLE$2 = "\"rebase\".\"idempotency_keys\"";
|
|
12553
12648
|
/**
|
|
12554
12649
|
* How long a replay is recognised. Long enough to cover an offline stretch and
|
|
12555
12650
|
* a retry schedule; short enough that the table stays small and a key cannot be
|
|
@@ -12668,13 +12763,13 @@ function createIdempotencyStore(driver, options = {}) {
|
|
|
12668
12763
|
*/
|
|
12669
12764
|
const probe = async () => {
|
|
12670
12765
|
try {
|
|
12671
|
-
await exec(`SELECT key, uid, fingerprint, response, created_at FROM ${TABLE$
|
|
12766
|
+
await exec(`SELECT key, uid, fingerprint, response, created_at FROM ${TABLE$2} WHERE false`);
|
|
12672
12767
|
return true;
|
|
12673
12768
|
} catch (error) {
|
|
12674
12769
|
retryEnsureAt = Date.now() + ENSURE_RETRY_COOLDOWN_MS;
|
|
12675
12770
|
if (!warnedMissing) {
|
|
12676
12771
|
warnedMissing = true;
|
|
12677
|
-
logger.warn(`Idempotency keys unavailable — ${TABLE$
|
|
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) });
|
|
12678
12773
|
}
|
|
12679
12774
|
return false;
|
|
12680
12775
|
}
|
|
@@ -12693,7 +12788,7 @@ function createIdempotencyStore(driver, options = {}) {
|
|
|
12693
12788
|
try {
|
|
12694
12789
|
await exec("CREATE SCHEMA IF NOT EXISTS rebase");
|
|
12695
12790
|
await exec(`
|
|
12696
|
-
CREATE TABLE IF NOT EXISTS ${TABLE$
|
|
12791
|
+
CREATE TABLE IF NOT EXISTS ${TABLE$2} (
|
|
12697
12792
|
key TEXT NOT NULL,
|
|
12698
12793
|
uid TEXT NOT NULL,
|
|
12699
12794
|
response JSONB,
|
|
@@ -12701,8 +12796,8 @@ function createIdempotencyStore(driver, options = {}) {
|
|
|
12701
12796
|
PRIMARY KEY (uid, key)
|
|
12702
12797
|
)
|
|
12703
12798
|
`);
|
|
12704
|
-
await exec(`ALTER TABLE ${TABLE$
|
|
12705
|
-
await exec(`CREATE INDEX IF NOT EXISTS idx_idempotency_created ON ${TABLE$
|
|
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)`);
|
|
12706
12801
|
await exec(revokeInternalTableSql("rebase", "idempotency_keys"));
|
|
12707
12802
|
return true;
|
|
12708
12803
|
} catch (error) {
|
|
@@ -12722,20 +12817,20 @@ function createIdempotencyStore(driver, options = {}) {
|
|
|
12722
12817
|
if (key && !owner) warnAnonymous();
|
|
12723
12818
|
if (!key || !owner || !await ensure()) return { status: "claimed" };
|
|
12724
12819
|
try {
|
|
12725
|
-
if ((await exec(`INSERT INTO ${TABLE$
|
|
12820
|
+
if ((await exec(`INSERT INTO ${TABLE$2} (key, uid, fingerprint, response, created_at)
|
|
12726
12821
|
VALUES ($1, $2, $3, NULL, NOW())
|
|
12727
12822
|
ON CONFLICT (uid, key) DO UPDATE
|
|
12728
12823
|
SET response = NULL, created_at = NOW(), fingerprint = EXCLUDED.fingerprint
|
|
12729
|
-
WHERE (${TABLE$
|
|
12730
|
-
AND ${TABLE$
|
|
12731
|
-
OR (${TABLE$
|
|
12732
|
-
AND ${TABLE$
|
|
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')
|
|
12733
12828
|
RETURNING 1 AS claimed`, [
|
|
12734
12829
|
key,
|
|
12735
12830
|
owner,
|
|
12736
12831
|
fingerprint
|
|
12737
12832
|
])).length > 0) return { status: "claimed" };
|
|
12738
|
-
const row = (await exec(`SELECT response, response IS NULL AS pending, fingerprint FROM ${TABLE$
|
|
12833
|
+
const row = (await exec(`SELECT response, response IS NULL AS pending, fingerprint FROM ${TABLE$2}
|
|
12739
12834
|
WHERE uid = $1 AND key = $2`, [owner, key]))[0];
|
|
12740
12835
|
if (!row) return { status: "claimed" };
|
|
12741
12836
|
if (row.fingerprint != null && row.fingerprint !== fingerprint) return { status: "mismatch" };
|
|
@@ -12752,19 +12847,19 @@ function createIdempotencyStore(driver, options = {}) {
|
|
|
12752
12847
|
const owner = principal(uid);
|
|
12753
12848
|
if (!key || !owner || !await ensure()) return;
|
|
12754
12849
|
try {
|
|
12755
|
-
await exec(`UPDATE ${TABLE$
|
|
12850
|
+
await exec(`UPDATE ${TABLE$2} SET response = $3::jsonb WHERE uid = $1 AND key = $2`, [
|
|
12756
12851
|
owner,
|
|
12757
12852
|
key,
|
|
12758
12853
|
JSON.stringify(response ?? null)
|
|
12759
12854
|
]);
|
|
12760
|
-
if (Math.random() < .01) await exec(`DELETE FROM ${TABLE$
|
|
12855
|
+
if (Math.random() < .01) await exec(`DELETE FROM ${TABLE$2} WHERE created_at < NOW() - INTERVAL '${TTL_HOURS} hours'`);
|
|
12761
12856
|
} catch {}
|
|
12762
12857
|
},
|
|
12763
12858
|
async release(key, uid) {
|
|
12764
12859
|
const owner = principal(uid);
|
|
12765
12860
|
if (!key || !owner || !await ensure()) return;
|
|
12766
12861
|
try {
|
|
12767
|
-
await exec(`DELETE FROM ${TABLE$
|
|
12862
|
+
await exec(`DELETE FROM ${TABLE$2} WHERE uid = $1 AND key = $2 AND response IS NULL`, [owner, key]);
|
|
12768
12863
|
} catch {}
|
|
12769
12864
|
},
|
|
12770
12865
|
ensureTable: ensure
|
|
@@ -24718,7 +24813,7 @@ var OAUTH_TABLES = [
|
|
|
24718
24813
|
CONFIRMATIONS
|
|
24719
24814
|
];
|
|
24720
24815
|
/** How often, at most, issuing a credential also sweeps expired codes and tokens. */
|
|
24721
|
-
var SWEEP_INTERVAL_MS = 3600 * 1e3;
|
|
24816
|
+
var SWEEP_INTERVAL_MS$1 = 3600 * 1e3;
|
|
24722
24817
|
/**
|
|
24723
24818
|
* How long an authorization code lives.
|
|
24724
24819
|
*
|
|
@@ -24746,7 +24841,7 @@ function createOAuthStore(driver, options = {}) {
|
|
|
24746
24841
|
const sweepRefreshTokens = () => exec(`DELETE FROM ${REFRESH} WHERE expires_at < now() - interval '30 days'`);
|
|
24747
24842
|
let lastSweep = Date.now();
|
|
24748
24843
|
const sweepIfDue = () => {
|
|
24749
|
-
if (Date.now() - lastSweep < SWEEP_INTERVAL_MS) return;
|
|
24844
|
+
if (Date.now() - lastSweep < SWEEP_INTERVAL_MS$1) return;
|
|
24750
24845
|
lastSweep = Date.now();
|
|
24751
24846
|
sweepCodes().then(sweepRefreshTokens).catch((error) => logger.warn("[oauth] Sweeping expired codes and tokens failed", { error }));
|
|
24752
24847
|
};
|
|
@@ -25038,6 +25133,136 @@ function toStringArray(value) {
|
|
|
25038
25133
|
}
|
|
25039
25134
|
return [];
|
|
25040
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
|
+
}
|
|
25041
25266
|
/** The data-plane vocabulary: `/mcp`'s own, and every backend's unless it brings its own tools. */
|
|
25042
25267
|
var DATA_SCOPE_VOCABULARY = {
|
|
25043
25268
|
supported: [
|
|
@@ -31258,7 +31483,7 @@ async function buildRebaseBackend(options, announcements) {
|
|
|
31258
31483
|
const platformTokenPreAuth = createPlatformTokenPreAuth(platformTokens);
|
|
31259
31484
|
let backupLinkRouter;
|
|
31260
31485
|
if (surfaces.admin) {
|
|
31261
|
-
const { createBackupLinkRoutes, backupDestinationFromEnv } = await import("./backup-
|
|
31486
|
+
const { createBackupLinkRoutes, backupDestinationFromEnv } = await import("./backup-PN6AM4UK.js").then((n) => n.t);
|
|
31262
31487
|
backupLinkRouter = createBackupLinkRoutes({ getDestination: () => backupDestinationFromEnv(process.env) });
|
|
31263
31488
|
}
|
|
31264
31489
|
const apiKeyRouter = apiKeyStore && surfaces.admin ? createApiKeyRoutes({
|
|
@@ -31331,6 +31556,35 @@ async function buildRebaseBackend(options, announcements) {
|
|
|
31331
31556
|
};
|
|
31332
31557
|
let adapterAuthRouter;
|
|
31333
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
|
+
};
|
|
31334
31588
|
if (config.auth) {
|
|
31335
31589
|
if (!isAuthAdapter(config.auth)) {
|
|
31336
31590
|
const safeAuthConfig = config.auth;
|
|
@@ -31403,12 +31657,14 @@ async function buildRebaseBackend(options, announcements) {
|
|
|
31403
31657
|
]) {
|
|
31404
31658
|
const providerConfig = safeAuthConfig[key];
|
|
31405
31659
|
if (providerConfig && requiredFields.every((f) => Boolean(providerConfig[f]))) {
|
|
31406
|
-
const createFn = (await import("./auth-
|
|
31660
|
+
const createFn = (await import("./auth-Bzb_b1KY.js").then((n) => n.t))[factory];
|
|
31407
31661
|
oauthProviders.push(createFn(providerConfig));
|
|
31408
31662
|
}
|
|
31409
31663
|
}
|
|
31410
31664
|
const reCollectionAuth = safeAuthConfig.collection ? safeAuthConfig.collection.auth : void 0;
|
|
31411
31665
|
const collectionAuthConfig = typeof reCollectionAuth === "object" && reCollectionAuth !== null ? reCollectionAuth : void 0;
|
|
31666
|
+
const cookieAuth = safeAuthConfig.cookieAuth === false ? void 0 : safeAuthConfig.cookieAuth ?? {};
|
|
31667
|
+
const deviceLogin = await prepareDeviceLogin(safeAuthConfig.deviceLogin);
|
|
31412
31668
|
authAdapter = createBuiltinAuthAdapter({
|
|
31413
31669
|
authRepository: authConfigResult.authRepository ?? authConfigResult.userService,
|
|
31414
31670
|
jwt,
|
|
@@ -31429,7 +31685,8 @@ async function buildRebaseBackend(options, announcements) {
|
|
|
31429
31685
|
collectionAuthConfig,
|
|
31430
31686
|
enableMagicLink: safeAuthConfig.magicLink ?? false,
|
|
31431
31687
|
enableEmailOtp: safeAuthConfig.emailOtp ?? false,
|
|
31432
|
-
|
|
31688
|
+
deviceLogin,
|
|
31689
|
+
cookieAuth,
|
|
31433
31690
|
requireEmailVerification: safeAuthConfig.requireEmailVerification ?? false,
|
|
31434
31691
|
refreshTokenReuseIntervalSeconds: safeAuthConfig.refreshTokenReuseIntervalSeconds,
|
|
31435
31692
|
refreshTokenReuse: safeAuthConfig.refreshTokenReuse,
|
|
@@ -32246,7 +32503,7 @@ Use a driver that supports the job queue, or remove the declarations. Refusing t
|
|
|
32246
32503
|
let logsSurface;
|
|
32247
32504
|
let metaSurface;
|
|
32248
32505
|
if (surfaces.admin) {
|
|
32249
|
-
const { createBackupRoutes, backupDestinationFromEnv, readBackupSchedule } = await import("./backup-
|
|
32506
|
+
const { createBackupRoutes, backupDestinationFromEnv, readBackupSchedule } = await import("./backup-PN6AM4UK.js").then((n) => n.t);
|
|
32250
32507
|
const backupRouter = new Hono();
|
|
32251
32508
|
applyAdminGate(backupRouter, "Backup", "backups:read");
|
|
32252
32509
|
const scheduler = cronScheduler;
|
|
@@ -32268,7 +32525,7 @@ Use a driver that supports the job queue, or remove the declarations. Refusing t
|
|
|
32268
32525
|
}
|
|
32269
32526
|
let rlsSimulatorSurface;
|
|
32270
32527
|
if (surfaces.admin) {
|
|
32271
|
-
const { createRlsSimulatorRoutes } = await import("./rls-simulator-routes-
|
|
32528
|
+
const { createRlsSimulatorRoutes } = await import("./rls-simulator-routes-BTB1cjU4.js");
|
|
32272
32529
|
const rlsSimulatorRouter = new Hono();
|
|
32273
32530
|
applyAdminGate(rlsSimulatorRouter, "RLS simulator", "schema:read");
|
|
32274
32531
|
rlsSimulatorRouter.route("/", createRlsSimulatorRoutes({
|
|
@@ -32724,7 +32981,7 @@ function realtimeSocketPath(basePath) {
|
|
|
32724
32981
|
* backend no MCP client calls never loads it.
|
|
32725
32982
|
*/
|
|
32726
32983
|
async function loadMcpApps() {
|
|
32727
|
-
const { MCP_APPS } = await import("./dist-
|
|
32984
|
+
const { MCP_APPS } = await import("./dist--rf-rq-r.js");
|
|
32728
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) => {
|
|
32729
32986
|
try {
|
|
32730
32987
|
return readFileSync(file, "utf8");
|
|
@@ -32738,7 +32995,7 @@ async function loadMcpApps() {
|
|
|
32738
32995
|
* app to the modules and names every view serves (`MCP_APP_MODULES`).
|
|
32739
32996
|
*/
|
|
32740
32997
|
async function loadAppCompiler() {
|
|
32741
|
-
const { compileApp } = await import("./dist-
|
|
32998
|
+
const { compileApp } = await import("./dist--rf-rq-r.js");
|
|
32742
32999
|
return (source) => compileApp(source, MCP_APP_MODULES);
|
|
32743
33000
|
}
|
|
32744
33001
|
/** The collection registry a driver carries, if it has one: not part of `DataDriver`, so found by looking. */
|