@rebasepro/server 0.26.0 → 0.27.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{GCSStorageController-40FyFeSx.js → GCSStorageController-BUClIfp0.js} +35 -2
- package/dist/GCSStorageController-BUClIfp0.js.map +1 -0
- package/dist/{S3StorageController-Bl5shp94.js → S3StorageController-CixCQEky.js} +53 -9
- package/dist/S3StorageController-CixCQEky.js.map +1 -0
- package/dist/access-BFAUvsSs.js.map +1 -1
- package/dist/auth/admin-users-route.d.ts +3 -0
- package/dist/auth/apple-oauth.d.ts +39 -10
- package/dist/auth/capabilities.d.ts +2 -0
- package/dist/auth/interfaces.d.ts +55 -0
- package/dist/{auth-izI7AEzC.js → auth-DDXPw0mn.js} +179 -25
- package/dist/{auth-izI7AEzC.js.map → auth-DDXPw0mn.js.map} +1 -1
- package/dist/auth_adapter-B7RUMk6e.js.map +1 -1
- package/dist/backend/options.d.ts +29 -1
- package/dist/backend-CaG_Jyso.js.map +1 -1
- package/dist/{backup-BVbHoKo8.js → backup-B6brPSeB.js} +4 -4
- package/dist/{backup-BVbHoKo8.js.map → backup-B6brPSeB.js.map} +1 -1
- package/dist/boot/env.d.ts +6 -0
- package/dist/cron/cron-loader.d.ts +4 -0
- package/dist/{cron-loader-mMhqbVsl.js → cron-loader-CC1Jy_KN.js} +13 -5
- package/dist/cron-loader-CC1Jy_KN.js.map +1 -0
- package/dist/{cron-routes-Cs33j_Kr.js → cron-routes-BK60Rn1r.js} +2 -2
- package/dist/{cron-routes-Cs33j_Kr.js.map → cron-routes-BK60Rn1r.js.map} +1 -1
- package/dist/{cron-scheduler-Be7CNghL.js → cron-scheduler-DyCjPlQR.js} +39 -26
- package/dist/cron-scheduler-DyCjPlQR.js.map +1 -0
- package/dist/{load-failure-L5hvfDoG.js → dynamic-import-Bi3XK5y-.js} +30 -18
- package/dist/dynamic-import-Bi3XK5y-.js.map +1 -0
- package/dist/{function-loader-B8YzXEsQ.js → function-loader-eFigStYX.js} +14 -5
- package/dist/function-loader-eFigStYX.js.map +1 -0
- package/dist/functions/function-loader.d.ts +5 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.es.js +596 -87
- package/dist/index.es.js.map +1 -1
- package/dist/init/docs.d.ts +1 -1
- package/dist/init/health.d.ts +13 -0
- package/dist/metrics/index.d.ts +8 -0
- package/dist/metrics/realtime.d.ts +25 -0
- package/dist/services/routed-realtime-service.d.ts +1 -1
- package/dist/storage/GCSStorageController.d.ts +9 -1
- package/dist/storage/LocalStorageController.d.ts +8 -1
- package/dist/storage/S3StorageController.d.ts +4 -2
- package/dist/storage/index.d.ts +1 -0
- package/dist/storage/policies.d.ts +1 -1
- package/dist/storage/streams.d.ts +17 -0
- package/dist/storage/types.d.ts +15 -33
- package/dist/{upload-validation-Bgo626uY.js → upload-validation-CkkQGs-j.js} +40 -2
- package/dist/upload-validation-CkkQGs-j.js.map +1 -0
- package/dist/utils/load-failure.d.ts +9 -0
- package/package.json +5 -5
- package/dist/GCSStorageController-40FyFeSx.js.map +0 -1
- package/dist/S3StorageController-Bl5shp94.js.map +0 -1
- package/dist/cron-loader-mMhqbVsl.js.map +0 -1
- package/dist/cron-scheduler-Be7CNghL.js.map +0 -1
- package/dist/function-loader-B8YzXEsQ.js.map +0 -1
- package/dist/load-failure-L5hvfDoG.js.map +0 -1
- package/dist/upload-validation-Bgo626uY.js.map +0 -1
package/dist/index.es.js
CHANGED
|
@@ -10,7 +10,7 @@ import { a as nestCollectionPatchPaths, c as ADMIN_PROPERTY_KEYS, i as isCollect
|
|
|
10
10
|
import { a as softDeleteFieldOf, c as JUNCTION_PIVOT_KEY, i as restoresSoftDeletedRow, l as hasForeignKeyOnTarget, n as buildCollectionSchema, o as buildTenantSecurityRule, s as INCLUDE_COUNT_KEY, t as buildCollectionInputSchema, u as isManyToMany } from "./openapi-generator-CyxEtYEX.js";
|
|
11
11
|
import { n as isAnonymousUid, r as policy } from "./policy-PdzX-Opd.js";
|
|
12
12
|
import { n as isSQLAdmin, r as isSchemaEditingAdmin } from "./backend-CaG_Jyso.js";
|
|
13
|
-
import { a as parseEnvBoolean, i as validateCronExpression, t as CronScheduler } from "./cron-scheduler-
|
|
13
|
+
import { a as parseEnvBoolean, i as validateCronExpression, t as CronScheduler } from "./cron-scheduler-DyCjPlQR.js";
|
|
14
14
|
import { s as simulationHeaders } from "./auth_adapter-B7RUMk6e.js";
|
|
15
15
|
import { n as isValidAppHost, r as reservedPrefixFor, t as SCHEMA_VERSION_HEADER } from "./project_manifest-R6y_KHms.js";
|
|
16
16
|
import { n as createContractRoutes, r as computeSchemaVersion } from "./contract-routes-CU2A3JnF.js";
|
|
@@ -19,10 +19,10 @@ import { a as logger, c as setLogLevel, d as hostEnv, i as logLevelEnabled, l as
|
|
|
19
19
|
import { n as suggestNearMiss, r as toSnakeCase } from "./strings.es-B7QLnHh2.js";
|
|
20
20
|
import { a as findRelation, d as resolveRelation, f as toWireKey, i as fieldKeyForColumn, l as relationDeclaringProperty, o as getTableName, r as restrictedFieldNames, s as isJunctionBackedRelation, t as apiHiddenFieldNames, u as resolveCollectionRelations } from "./field-access-DYsvjI_P.js";
|
|
21
21
|
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-BhYXViha-YTmjBpo2.js";
|
|
22
|
-
import { $ as getEmailChangeTemplate, A as createDataRateLimiter, B as SMTPEmailService, C as createJwksRoutes, D as DEFAULT_FUNCTIONS_ANONYMOUS_LIMIT, E as isBootstrapWindowOpen, F as clearActiveDevEmailSink, G as verifyPassword, H as resolveAuthHooks, I as createDevEmailSink, J as completeUserCreation, K as adapterRefusal, L as devEmailSinkFor, M as setSharedRateLimitStore, N as MemoryRateLimitStore, O as createAuthLimiters, P as activeDevEmailSink, Q as getEmailChangeNoticeTemplate, R as extractLinks, S as createApiKeyStore, T as configureUserPicking, U as hashPassword, V as createEmailService, W as validatePasswordStrength, X as assertEmailLinkBases, Y as generateSecurePassword, Z as resolveEmailLinkBase, _ as oauthCodeFlowSchema, a as createBitbucketProvider, at as getWelcomeEmailTemplate, b as createApiKeyRoutes, c as createTwitterProvider, ct as escapeHtml, d as createMicrosoftProvider, dt as createSqlRateLimitStore, et as getEmailOtpTemplate, f as tryVerifyOidcIdToken, ft as resolveRateLimitStoreKind, g as createGoogleProvider, h as createLinkedinProvider, i as createSlackProvider, it as getUserInvitationTemplate, j as createRateLimiter, k as createDataRateLimitCheck, l as createFacebookProvider, lt as html, m as createGitHubProvider, n as createCustomAuthAdapter, nt as getMagicLinkTemplate, o as createGitLabProvider, ot as resolveEmailBranding, p as verifyOidcIdToken, pt as securityRuleToConditions, q as createAdapterAuthMiddleware, r as createSpotifyProvider, rt as getPasswordResetTemplate, s as createDiscordProvider, st as RawHtml, tt as getEmailVerificationTemplate, u as createAppleProvider, ut as raw, v as pkceTokenParams, w as createBuiltinAuthAdapter, x as createPersonalKeyRoutes, y as providerVerifiedEmail, z as registerDevEmailSink } from "./auth-
|
|
22
|
+
import { $ as getEmailChangeTemplate, A as createDataRateLimiter, B as SMTPEmailService, C as createJwksRoutes, D as DEFAULT_FUNCTIONS_ANONYMOUS_LIMIT, E as isBootstrapWindowOpen, F as clearActiveDevEmailSink, G as verifyPassword, H as resolveAuthHooks, I as createDevEmailSink, J as completeUserCreation, K as adapterRefusal, L as devEmailSinkFor, M as setSharedRateLimitStore, N as MemoryRateLimitStore, O as createAuthLimiters, P as activeDevEmailSink, Q as getEmailChangeNoticeTemplate, R as extractLinks, S as createApiKeyStore, T as configureUserPicking, U as hashPassword, V as createEmailService, W as validatePasswordStrength, X as assertEmailLinkBases, Y as generateSecurePassword, Z as resolveEmailLinkBase, _ as oauthCodeFlowSchema, a as createBitbucketProvider, at as getWelcomeEmailTemplate, b as createApiKeyRoutes, c as createTwitterProvider, ct as escapeHtml, d as createMicrosoftProvider, dt as createSqlRateLimitStore, et as getEmailOtpTemplate, f as tryVerifyOidcIdToken, ft as resolveRateLimitStoreKind, g as createGoogleProvider, h as createLinkedinProvider, i as createSlackProvider, it as getUserInvitationTemplate, j as createRateLimiter, k as createDataRateLimitCheck, l as createFacebookProvider, lt as html, m as createGitHubProvider, n as createCustomAuthAdapter, nt as getMagicLinkTemplate, o as createGitLabProvider, ot as resolveEmailBranding, p as verifyOidcIdToken, pt as securityRuleToConditions, q as createAdapterAuthMiddleware, r as createSpotifyProvider, rt as getPasswordResetTemplate, s as createDiscordProvider, st as RawHtml, tt as getEmailVerificationTemplate, u as createAppleProvider, ut as raw, v as pkceTokenParams, w as createBuiltinAuthAdapter, x as createPersonalKeyRoutes, y as providerVerifiedEmail, z as registerDevEmailSink } from "./auth-DDXPw0mn.js";
|
|
23
23
|
import "./resumable-upload-threshold-CKv-Ry0l.js";
|
|
24
24
|
import { n as revokeInternalTableSql } from "./internal-tables-L2t39RdT.js";
|
|
25
|
-
import {
|
|
25
|
+
import { a as warnDeprecated, n as FilesFailedToLoadError } from "./dynamic-import-Bi3XK5y-.js";
|
|
26
26
|
import { a as resolveListLimitParam, c as assertReadableFields, d as decodeCursor$1, f as reconcileCursorOrder, i as parseQueryOptions, l as requestViewer, n as parseAggregateSelect, o as assertNoHiddenAggregateNames, r as parseGroupBy, s as assertQueryFieldsReadable, t as orderByEntriesToTuples, u as cursorToStartAfter } from "./query-parser-CDXWf2hH.js";
|
|
27
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-rDS0884_.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-CjRrn12l.js";
|
|
@@ -31,17 +31,17 @@ import { a as isDataException, i as errorHandler, n as DATABASE_UNAVAILABLE_MESS
|
|
|
31
31
|
import { n as HARD_DELETE_QUERY_PARAM, r as parseHardDelete } from "./soft-delete-params-BRONCOA2.js";
|
|
32
32
|
import { a as canonicalStorageId, i as canonicalStorageBucket, n as InvalidStorageBucketError, o as canonicalStorageKey, r as InvalidStorageKeyError, t as InvalidListOptionsError } from "./keys-BXcdRNhJ.js";
|
|
33
33
|
import { t as logMiddleware } from "./logs-routes-CBt7mMIL.js";
|
|
34
|
-
import { a as
|
|
35
|
-
import { t as S3StorageController } from "./S3StorageController-
|
|
36
|
-
import { t as GCSStorageController } from "./GCSStorageController-
|
|
37
|
-
import { a as isHonoLike, i as loadFunctionsWithDiagnostics, n as loadFunctions, r as loadFunctionsFromDirectory } from "./function-loader-
|
|
34
|
+
import { a as fileWebStream, d as IMAGE_MIME_TYPES, i as bytesView, l as DEFAULT_MAX_FILE_SIZE, n as ObjectTooLargeError, o as meteredChunks, s as readStreamFully, t as validateUploadedFile, u as DOCUMENT_MIME_TYPES } from "./upload-validation-CkkQGs-j.js";
|
|
35
|
+
import { t as S3StorageController } from "./S3StorageController-CixCQEky.js";
|
|
36
|
+
import { t as GCSStorageController } from "./GCSStorageController-BUClIfp0.js";
|
|
37
|
+
import { a as isHonoLike, i as loadFunctionsWithDiagnostics, n as loadFunctions, r as loadFunctionsFromDirectory } from "./function-loader-eFigStYX.js";
|
|
38
38
|
import { a as getDriver, c as getUser, d as identityResolved, f as isAdmin, i as getApiKey, l as getUserId, m as requireDriver, o as getRequestId, p as isAuthenticated, r as requireRole, s as getRoles, t as createFunctionRoutes, u as hasRole } from "./function-routes-RxrCHNuM.js";
|
|
39
39
|
import "./proxy-BYir8tWK.js";
|
|
40
40
|
import "./request-timeout-DVjo-c_8.js";
|
|
41
41
|
import { t as FunctionSelectionError } from "./selection-CRpqKUbt.js";
|
|
42
|
-
import { a as loadCrons, i as loadCronJobsWithDiagnostics, n as declareCrons, r as loadCronJobsFromDirectory } from "./cron-loader-
|
|
43
|
-
import { t as createCronRoutes } from "./cron-routes-
|
|
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-
|
|
42
|
+
import { a as loadCrons, i as loadCronJobsWithDiagnostics, n as declareCrons, r as loadCronJobsFromDirectory } from "./cron-loader-CC1Jy_KN.js";
|
|
43
|
+
import { t as createCronRoutes } from "./cron-routes-BK60Rn1r.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-B6brPSeB.js";
|
|
45
45
|
import { a as defaultBackoff, i as createJobQueue, n as createJobStore, o as currentAmbientTransaction, r as PermanentJobError } from "./jobs-Co6Ni5HP.js";
|
|
46
46
|
import { t as METRIC_SERIES } from "./history-store-BQz5YCkW.js";
|
|
47
47
|
import { createHash, createSign, randomBytes } from "node:crypto";
|
|
@@ -66,6 +66,8 @@ import fs$1, { createWriteStream } from "node:fs";
|
|
|
66
66
|
import { csrf } from "hono/csrf";
|
|
67
67
|
import { COMPRESSIBLE_CONTENT_TYPE_REGEX, compress } from "hono/compress";
|
|
68
68
|
import { pipeline } from "stream/promises";
|
|
69
|
+
import { Readable as Readable$1 } from "node:stream";
|
|
70
|
+
import { pipeline as pipeline$1 } from "node:stream/promises";
|
|
69
71
|
import * as fs$2 from "node:fs/promises";
|
|
70
72
|
import fsp from "node:fs/promises";
|
|
71
73
|
import os from "node:os";
|
|
@@ -82,8 +84,6 @@ import { secureHeaders } from "hono/secure-headers";
|
|
|
82
84
|
import { createServer } from "http";
|
|
83
85
|
import { getRequestListener } from "@hono/node-server";
|
|
84
86
|
import { cors } from "hono/cors";
|
|
85
|
-
import { Readable as Readable$1 } from "node:stream";
|
|
86
|
-
import { pipeline as pipeline$1 } from "node:stream/promises";
|
|
87
87
|
//#region ../types/src/types/schema_editing.ts
|
|
88
88
|
/**
|
|
89
89
|
* The SQL `db push` and `db generate` render — `schema.sql`, `policies.sql` and
|
|
@@ -4599,6 +4599,107 @@ function buildRoutedRebaseData({ defaultData, sources, resolveKey, resolveAccess
|
|
|
4599
4599
|
}
|
|
4600
4600
|
//#endregion
|
|
4601
4601
|
//#region ../client/dist/index.es.js
|
|
4602
|
+
/**
|
|
4603
|
+
* The browser half of Sign in with Apple.
|
|
4604
|
+
*
|
|
4605
|
+
* Apple is the one provider a single-page app cannot take through the usual
|
|
4606
|
+
* redirect: asking for the `name` or `email` scope obliges
|
|
4607
|
+
* `response_mode=form_post`, so Apple answers with a cross-site POST to the
|
|
4608
|
+
* redirect URI — a request a static page never sees. Apple's own JS SDK has a
|
|
4609
|
+
* popup mode that hands the answer back to the opening page with
|
|
4610
|
+
* `postMessage` instead, and that is what this uses. The redirect URI still
|
|
4611
|
+
* has to be listed under the Services ID's Return URLs (HTTPS, no
|
|
4612
|
+
* `localhost`), because Apple matches it and the token exchange repeats it.
|
|
4613
|
+
*
|
|
4614
|
+
* `state` is generated and checked here, which is what binds the code that
|
|
4615
|
+
* comes back to the click that started it.
|
|
4616
|
+
*/
|
|
4617
|
+
/** Apple's JS SDK, the only way into its popup mode. */
|
|
4618
|
+
var APPLE_JS_SDK_URL = "https://appleid.cdn-apple.com/appleauth/static/jsapi/appleid/1/en_US/appleauth.js";
|
|
4619
|
+
/** Apple's popup answers with `{ error }` when the visitor backs out. */
|
|
4620
|
+
var APPLE_CANCELLATIONS = /* @__PURE__ */ new Set(["popup_closed_by_user", "user_cancelled_authorize"]);
|
|
4621
|
+
var sdkLoad = null;
|
|
4622
|
+
function appleIdGlobal() {
|
|
4623
|
+
return globalThis.AppleID;
|
|
4624
|
+
}
|
|
4625
|
+
/**
|
|
4626
|
+
* Load Apple's SDK once per page. A failed load is forgotten, so a retry tries
|
|
4627
|
+
* again. A tag someone else added and that has not finished yet is not waited
|
|
4628
|
+
* on — it may already have failed, and its events would never come — so a
|
|
4629
|
+
* second, cached copy is added instead, which is harmless.
|
|
4630
|
+
*/
|
|
4631
|
+
function loadAppleSdk() {
|
|
4632
|
+
const loaded = appleIdGlobal();
|
|
4633
|
+
if (loaded) return Promise.resolve(loaded);
|
|
4634
|
+
if (sdkLoad) return sdkLoad;
|
|
4635
|
+
sdkLoad = new Promise((resolve, reject) => {
|
|
4636
|
+
const script = document.createElement("script");
|
|
4637
|
+
script.src = APPLE_JS_SDK_URL;
|
|
4638
|
+
script.async = true;
|
|
4639
|
+
script.onload = () => {
|
|
4640
|
+
const apple = appleIdGlobal();
|
|
4641
|
+
if (apple) resolve(apple);
|
|
4642
|
+
else reject(/* @__PURE__ */ new Error("Apple's sign-in script loaded without defining AppleID"));
|
|
4643
|
+
};
|
|
4644
|
+
script.onerror = () => reject(/* @__PURE__ */ new Error("Apple's sign-in script could not be loaded"));
|
|
4645
|
+
document.head.appendChild(script);
|
|
4646
|
+
}).catch((err) => {
|
|
4647
|
+
sdkLoad = null;
|
|
4648
|
+
throw new RebaseClientError("Sign in with Apple could not be loaded. Check your connection or any script blockers, then try again.", {
|
|
4649
|
+
code: "APPLE_SIGN_IN_UNAVAILABLE",
|
|
4650
|
+
cause: err
|
|
4651
|
+
});
|
|
4652
|
+
});
|
|
4653
|
+
return sdkLoad;
|
|
4654
|
+
}
|
|
4655
|
+
function randomState() {
|
|
4656
|
+
const bytes = /* @__PURE__ */ new Uint8Array(16);
|
|
4657
|
+
crypto.getRandomValues(bytes);
|
|
4658
|
+
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
4659
|
+
}
|
|
4660
|
+
/**
|
|
4661
|
+
* Open Apple's sign-in popup and return the authorization code, without
|
|
4662
|
+
* spending it. Call it from a click handler: browsers block a popup that no
|
|
4663
|
+
* gesture opened. Call {@link preloadAppleSignIn} first (on mount) so the
|
|
4664
|
+
* popup does not wait on a script download.
|
|
4665
|
+
*
|
|
4666
|
+
* Throws a `RebaseClientError` whose `code` is `APPLE_SIGN_IN_CANCELLED` when
|
|
4667
|
+
* the visitor closes the popup or declines, `APPLE_SIGN_IN_UNAVAILABLE` when
|
|
4668
|
+
* Apple's script cannot load or this is not a browser, and
|
|
4669
|
+
* `APPLE_SIGN_IN_FAILED` otherwise.
|
|
4670
|
+
*/
|
|
4671
|
+
async function requestAppleAuthorization(request) {
|
|
4672
|
+
if (typeof window === "undefined" || typeof document === "undefined") throw new RebaseClientError("Sign in with Apple's popup needs a browser. A native app gets the code from ASAuthorizationController and passes it to signInWithApple({ code, bundleId }).", { code: "APPLE_SIGN_IN_UNAVAILABLE" });
|
|
4673
|
+
const apple = appleIdGlobal() ?? await loadAppleSdk();
|
|
4674
|
+
const redirectUri = request.redirectUri ?? `${window.location.origin}/`;
|
|
4675
|
+
const state = randomState();
|
|
4676
|
+
apple.auth.init({
|
|
4677
|
+
clientId: request.clientId,
|
|
4678
|
+
scope: "name email",
|
|
4679
|
+
redirectURI: redirectUri,
|
|
4680
|
+
state,
|
|
4681
|
+
usePopup: true
|
|
4682
|
+
});
|
|
4683
|
+
let response;
|
|
4684
|
+
try {
|
|
4685
|
+
response = await apple.auth.signIn();
|
|
4686
|
+
} catch (err) {
|
|
4687
|
+
const reason = typeof err === "object" && err !== null && "error" in err && typeof err.error === "string" ? err.error : void 0;
|
|
4688
|
+
if (reason && APPLE_CANCELLATIONS.has(reason)) throw new RebaseClientError("Sign in with Apple was cancelled.", { code: "APPLE_SIGN_IN_CANCELLED" });
|
|
4689
|
+
throw new RebaseClientError(reason ? `Sign in with Apple failed: ${reason}` : "Sign in with Apple failed. Please try again.", {
|
|
4690
|
+
code: "APPLE_SIGN_IN_FAILED",
|
|
4691
|
+
cause: err
|
|
4692
|
+
});
|
|
4693
|
+
}
|
|
4694
|
+
const authorization = response.authorization;
|
|
4695
|
+
if (!authorization?.code) throw new RebaseClientError("Apple returned no authorization code.", { code: "APPLE_SIGN_IN_FAILED" });
|
|
4696
|
+
if (authorization.state !== state) throw new RebaseClientError("This Apple sign-in could not be verified as one started on this page. Please try again.", { code: "APPLE_SIGN_IN_FAILED" });
|
|
4697
|
+
return {
|
|
4698
|
+
code: authorization.code,
|
|
4699
|
+
redirectUri,
|
|
4700
|
+
...response.user?.name ? { user: { name: response.user.name } } : {}
|
|
4701
|
+
};
|
|
4702
|
+
}
|
|
4602
4703
|
/** Map a raw user object from an auth response (`/login`, `/refresh`, `/me`) to a `User`. */
|
|
4603
4704
|
function mapRawUser(raw) {
|
|
4604
4705
|
return {
|
|
@@ -4647,13 +4748,31 @@ function detectStorage() {
|
|
|
4647
4748
|
} catch (e) {}
|
|
4648
4749
|
return createMemoryStorage();
|
|
4649
4750
|
}
|
|
4751
|
+
/**
|
|
4752
|
+
* The flow mode a client uses when `authFlowMode` is not set.
|
|
4753
|
+
*
|
|
4754
|
+
* Cookie in a browser. A backend run by the Rebase runtime always keeps the
|
|
4755
|
+
* refresh token in a cookie and answers the body's with `""`, so a browser
|
|
4756
|
+
* client defaulting to json held nothing to renew with, and was signed out
|
|
4757
|
+
* without a word once its access token expired, about an hour after sign-in.
|
|
4758
|
+
*
|
|
4759
|
+
* Json off the browser (Node, a worker, React Native), where there is no
|
|
4760
|
+
* cookie jar to keep it in — and in a browser that passes its own `storage`,
|
|
4761
|
+
* which says where the session is to be kept: a second client on the page
|
|
4762
|
+
* that keeps its own sign-in apart from the page's cookie. In cookie mode
|
|
4763
|
+
* nothing would be kept there, and every reload would lose that sign-in.
|
|
4764
|
+
*/
|
|
4765
|
+
function resolveAuthFlowMode(options) {
|
|
4766
|
+
if (options?.authFlowMode) return options.authFlowMode;
|
|
4767
|
+
return typeof document !== "undefined" && !options?.storage ? "cookie" : "json";
|
|
4768
|
+
}
|
|
4650
4769
|
function createAuth(transport, options) {
|
|
4651
4770
|
const opts = options || {};
|
|
4652
4771
|
const storage = opts.storage || detectStorage();
|
|
4653
4772
|
const authPath = opts.authPath || "/auth";
|
|
4654
4773
|
const autoRefresh = opts.autoRefresh !== false;
|
|
4655
4774
|
const persistSession = opts.persistSession !== false;
|
|
4656
|
-
const authFlowMode = opts
|
|
4775
|
+
const authFlowMode = resolveAuthFlowMode(opts);
|
|
4657
4776
|
const STORAGE_KEY = "rebase_auth";
|
|
4658
4777
|
const REFRESH_BUFFER_MS = 12e4;
|
|
4659
4778
|
/**
|
|
@@ -4725,6 +4844,25 @@ function createAuth(transport, options) {
|
|
|
4725
4844
|
if (authFlowMode === "cookie") return "";
|
|
4726
4845
|
return received || currentSession?.refreshToken || "";
|
|
4727
4846
|
}
|
|
4847
|
+
let flowMismatchReported = false;
|
|
4848
|
+
/**
|
|
4849
|
+
* Say so at sign-in, once, when the server's answer shows this client
|
|
4850
|
+
* cannot renew the session it is starting.
|
|
4851
|
+
*
|
|
4852
|
+
* A server with `cookieAuth` answers `refreshToken: ""` and puts the token
|
|
4853
|
+
* in the cookie; one without it puts the token in the body. A client in
|
|
4854
|
+
* the other mode holds nothing it can renew with, and finds out when the
|
|
4855
|
+
* access token expires — in json mode by dropping the session without a
|
|
4856
|
+
* word. The answer to the sign-in is the first moment it is known.
|
|
4857
|
+
*/
|
|
4858
|
+
function reportFlowMismatch(received, expiresAt) {
|
|
4859
|
+
if (flowMismatchReported || received === void 0) return;
|
|
4860
|
+
const serverUsesCookie = received === "";
|
|
4861
|
+
if (serverUsesCookie === (authFlowMode === "cookie")) return;
|
|
4862
|
+
flowMismatchReported = true;
|
|
4863
|
+
const ends = Number.isFinite(expiresAt) ? `in about ${Math.max(1, Math.round((expiresAt - Date.now()) / 6e4))} minutes` : "when its access token expires";
|
|
4864
|
+
console.error(serverUsesCookie ? `[rebase] This server keeps the refresh token in an HttpOnly cookie (its \`auth.cookieAuth\`), but this client is in json mode and was handed none, so the session it just started cannot be renewed and ends ${ends}. Create the client with \`auth: { authFlowMode: "cookie" }\`.` : `[rebase] This server returned the refresh token in the response body, so it does not use \`auth.cookieAuth\`, and this client, in cookie mode, cannot renew the session it just started: it ends ${ends}. Turn on \`auth.cookieAuth\` on the server, or create the client with \`auth: { authFlowMode: "json" }\`.`);
|
|
4865
|
+
}
|
|
4728
4866
|
/**
|
|
4729
4867
|
* Whether the server refused a refresh as malformed: a 400, which says the
|
|
4730
4868
|
* request this client built is not one that server accepts.
|
|
@@ -4863,6 +5001,15 @@ function createAuth(transport, options) {
|
|
|
4863
5001
|
*/
|
|
4864
5002
|
const SPENT_TOKEN_MARGIN_MS = 1e4;
|
|
4865
5003
|
/**
|
|
5004
|
+
* Whether a request about to carry this session's token should first get a
|
|
5005
|
+
* fresh one: the token has expired or is about to, and can be renewed.
|
|
5006
|
+
*/
|
|
5007
|
+
function needsFreshToken(session) {
|
|
5008
|
+
if (!Number.isFinite(session.expiresAt)) return false;
|
|
5009
|
+
if (session.expiresAt > Date.now() + SPENT_TOKEN_MARGIN_MS) return false;
|
|
5010
|
+
return authFlowMode === "cookie" || !!session.refreshToken;
|
|
5011
|
+
}
|
|
5012
|
+
/**
|
|
4866
5013
|
* The transport's {@link TokenRefresher}: whether a request should wait for
|
|
4867
5014
|
* a fresher token than the one held, and which token to send when it does.
|
|
4868
5015
|
*
|
|
@@ -4890,9 +5037,7 @@ function createAuth(transport, options) {
|
|
|
4890
5037
|
if (refreshOwnRequests > 0) return void 0;
|
|
4891
5038
|
const session = currentSession;
|
|
4892
5039
|
if (!session) return cookieRestore?.then(() => void 0);
|
|
4893
|
-
if (!
|
|
4894
|
-
if (session.expiresAt > Date.now() + SPENT_TOKEN_MARGIN_MS) return void 0;
|
|
4895
|
-
if (authFlowMode !== "cookie" && !session.refreshToken) return void 0;
|
|
5040
|
+
if (!needsFreshToken(session)) return void 0;
|
|
4896
5041
|
const epoch = sessionEpoch;
|
|
4897
5042
|
return refreshSession().then((fresh) => epoch === sessionEpoch ? fresh.accessToken : void 0, () => epoch === sessionEpoch ? session.accessToken : void 0);
|
|
4898
5043
|
}
|
|
@@ -4964,6 +5109,7 @@ function createAuth(transport, options) {
|
|
|
4964
5109
|
}
|
|
4965
5110
|
function handleAuthResponse(data, event) {
|
|
4966
5111
|
sessionEpoch++;
|
|
5112
|
+
reportFlowMismatch(data.tokens.refreshToken, data.tokens.accessTokenExpiresAt);
|
|
4967
5113
|
const user = mapRawUser(data.user);
|
|
4968
5114
|
const session = {
|
|
4969
5115
|
accessToken: data.tokens.accessToken,
|
|
@@ -5101,13 +5247,55 @@ function createAuth(transport, options) {
|
|
|
5101
5247
|
redirectUri
|
|
5102
5248
|
});
|
|
5103
5249
|
}
|
|
5104
|
-
|
|
5105
|
-
|
|
5106
|
-
|
|
5250
|
+
/**
|
|
5251
|
+
* Sign in with an Apple authorization code.
|
|
5252
|
+
*
|
|
5253
|
+
* - Web: `signInWithApple({ code, redirectUri, user })` — or let
|
|
5254
|
+
* {@link signInWithApplePopup} obtain the code for you.
|
|
5255
|
+
* - Native (iOS, iPadOS, macOS): `signInWithApple({ code, bundleId, user })`
|
|
5256
|
+
* with the `authorizationCode` from `ASAuthorizationController`. The
|
|
5257
|
+
* bundle id must be in the backend's `APPLE_BUNDLE_IDS`.
|
|
5258
|
+
*
|
|
5259
|
+
* `user` carries the name Apple reports on the first authorization only.
|
|
5260
|
+
* The positional `(code, redirectUri, user)` form is the web call, kept for
|
|
5261
|
+
* existing callers.
|
|
5262
|
+
*/
|
|
5263
|
+
async function signInWithApple(payloadOrCode, redirectUri, user) {
|
|
5264
|
+
const payload = typeof payloadOrCode === "string" ? {
|
|
5265
|
+
code: payloadOrCode,
|
|
5107
5266
|
redirectUri,
|
|
5108
5267
|
user
|
|
5268
|
+
} : payloadOrCode;
|
|
5269
|
+
return signInWithOAuth("apple", {
|
|
5270
|
+
code: payload.code,
|
|
5271
|
+
...payload.redirectUri !== void 0 ? { redirectUri: payload.redirectUri } : {},
|
|
5272
|
+
...payload.bundleId !== void 0 ? { bundleId: payload.bundleId } : {},
|
|
5273
|
+
...payload.user?.name ? { user: { name: payload.user.name } } : {}
|
|
5109
5274
|
});
|
|
5110
5275
|
}
|
|
5276
|
+
/**
|
|
5277
|
+
* Sign in with Apple in a browser: opens Apple's popup, then spends the
|
|
5278
|
+
* code it returns. Call it from a click handler, since browsers block a
|
|
5279
|
+
* popup that no gesture opened.
|
|
5280
|
+
*
|
|
5281
|
+
* `clientId` defaults to the Services ID the backend publishes in
|
|
5282
|
+
* `GET /auth/config` — but pass it when you can: fetching it first delays
|
|
5283
|
+
* the popup past the click, which Safari blocks. Call
|
|
5284
|
+
* `preloadAppleSignIn()` on mount for the same reason. `redirectUri`
|
|
5285
|
+
* defaults to this page's origin plus `/`; either way it must be a Return
|
|
5286
|
+
* URL registered on the Services ID.
|
|
5287
|
+
*
|
|
5288
|
+
* A closed popup rejects with a `RebaseClientError` whose `code` is
|
|
5289
|
+
* `APPLE_SIGN_IN_CANCELLED` — an answer, not a failure.
|
|
5290
|
+
*/
|
|
5291
|
+
async function signInWithApplePopup(options = {}) {
|
|
5292
|
+
const clientId = options.clientId ?? (await getAuthConfig()).providerClientIds?.apple;
|
|
5293
|
+
if (!clientId) throw new RebaseClientError("Sign in with Apple needs a Services ID: set APPLE_CLIENT_ID on the backend, or pass clientId.", { code: "APPLE_SIGN_IN_UNAVAILABLE" });
|
|
5294
|
+
return signInWithApple(await requestAppleAuthorization({
|
|
5295
|
+
clientId,
|
|
5296
|
+
redirectUri: options.redirectUri
|
|
5297
|
+
}));
|
|
5298
|
+
}
|
|
5111
5299
|
async function signInWithFacebook(code, redirectUri) {
|
|
5112
5300
|
return signInWithOAuth("facebook", {
|
|
5113
5301
|
code,
|
|
@@ -5804,9 +5992,49 @@ function createAuth(transport, options) {
|
|
|
5804
5992
|
if (!res.ok) throwApiError(res.status, body, res.statusText);
|
|
5805
5993
|
return body;
|
|
5806
5994
|
}
|
|
5995
|
+
/**
|
|
5996
|
+
* The session as it is now, or `null`.
|
|
5997
|
+
*
|
|
5998
|
+
* A snapshot: every renewal of the access token (about hourly) replaces
|
|
5999
|
+
* the session with a new object, so one kept from an earlier call carries
|
|
6000
|
+
* a token the server refuses once it expires. Read it when you need it.
|
|
6001
|
+
* For a token to send, use {@link getAccessToken}.
|
|
6002
|
+
*/
|
|
5807
6003
|
function getSession() {
|
|
5808
6004
|
return currentSession;
|
|
5809
6005
|
}
|
|
6006
|
+
/**
|
|
6007
|
+
* The access token to put on a request of your own — a route outside
|
|
6008
|
+
* Rebase, a header for an upload — renewed first when it has expired or
|
|
6009
|
+
* is about to. `null` when no one is signed in.
|
|
6010
|
+
*
|
|
6011
|
+
* Ask for it for each request rather than keeping it: every renewal
|
|
6012
|
+
* replaces it. A Rebase function needs none of this, since
|
|
6013
|
+
* `functions.invoke` renews before sending and retries once on a 401.
|
|
6014
|
+
*
|
|
6015
|
+
* Waits for the session restored on load, and calls made together share
|
|
6016
|
+
* one renewal. A renewal the server refuses ends the session, as a refused
|
|
6017
|
+
* request does, and answers `null`. One that cannot reach the server
|
|
6018
|
+
* answers the token held, for the server to judge.
|
|
6019
|
+
*/
|
|
6020
|
+
async function getAccessToken() {
|
|
6021
|
+
await isInitialized;
|
|
6022
|
+
const session = currentSession;
|
|
6023
|
+
if (!session) return null;
|
|
6024
|
+
if (!needsFreshToken(session)) return session.accessToken;
|
|
6025
|
+
const epoch = sessionEpoch;
|
|
6026
|
+
try {
|
|
6027
|
+
const fresh = await refreshSession();
|
|
6028
|
+
return epoch === sessionEpoch ? fresh.accessToken : currentSession?.accessToken ?? null;
|
|
6029
|
+
} catch (err) {
|
|
6030
|
+
if (epoch !== sessionEpoch) return currentSession?.accessToken ?? null;
|
|
6031
|
+
if (isFatalRefreshError(err)) {
|
|
6032
|
+
abandonSessionLocally();
|
|
6033
|
+
return null;
|
|
6034
|
+
}
|
|
6035
|
+
return session.accessToken;
|
|
6036
|
+
}
|
|
6037
|
+
}
|
|
5810
6038
|
function onAuthStateChange(callback) {
|
|
5811
6039
|
listeners.add(callback);
|
|
5812
6040
|
return () => listeners.delete(callback);
|
|
@@ -5857,6 +6085,7 @@ function createAuth(transport, options) {
|
|
|
5857
6085
|
signInWithGitHub,
|
|
5858
6086
|
signInWithMicrosoft,
|
|
5859
6087
|
signInWithApple,
|
|
6088
|
+
signInWithApplePopup,
|
|
5860
6089
|
signInWithFacebook,
|
|
5861
6090
|
signInWithTwitter,
|
|
5862
6091
|
signInWithDiscord,
|
|
@@ -5891,6 +6120,7 @@ function createAuth(transport, options) {
|
|
|
5891
6120
|
revokeAllSessions,
|
|
5892
6121
|
getAuthConfig,
|
|
5893
6122
|
getSession,
|
|
6123
|
+
getAccessToken,
|
|
5894
6124
|
onAuthStateChange,
|
|
5895
6125
|
canRestoreSession: () => persistSession || authFlowMode === "cookie",
|
|
5896
6126
|
isInitialized: () => isInitialized,
|
|
@@ -5903,6 +6133,7 @@ function createAuth(transport, options) {
|
|
|
5903
6133
|
restoreOutcome: () => restoreOutcome
|
|
5904
6134
|
};
|
|
5905
6135
|
}
|
|
6136
|
+
var isoDate = (date) => date instanceof Date ? date.toISOString() : date;
|
|
5906
6137
|
function createAdmin(transport, options) {
|
|
5907
6138
|
const adminPath = (options || {}).adminPath || "/admin";
|
|
5908
6139
|
/**
|
|
@@ -5966,6 +6197,29 @@ function createAdmin(transport, options) {
|
|
|
5966
6197
|
async function resetMfa(userId) {
|
|
5967
6198
|
return transport.request(adminPath + "/users/" + encodeURIComponent(userId) + "/mfa", { method: "DELETE" });
|
|
5968
6199
|
}
|
|
6200
|
+
/** One page of guests, the ones last seen longest ago first, with the `total` matching. */
|
|
6201
|
+
async function listGuests(options) {
|
|
6202
|
+
const params = new URLSearchParams();
|
|
6203
|
+
if (options?.limit !== void 0) params.set("limit", String(options.limit));
|
|
6204
|
+
if (options?.offset !== void 0) params.set("offset", String(options.offset));
|
|
6205
|
+
if (options?.lastSeenBefore !== void 0) params.set("lastSeenBefore", isoDate(options.lastSeenBefore));
|
|
6206
|
+
const qs = params.toString();
|
|
6207
|
+
return transport.request(adminPath + "/guests" + (qs ? "?" + qs : ""), { method: "GET" });
|
|
6208
|
+
}
|
|
6209
|
+
/** Delete one guest. An account is refused with `NOT_ANONYMOUS`; {@link deleteUser} deletes those. */
|
|
6210
|
+
async function deleteGuest(userId) {
|
|
6211
|
+
return transport.request(adminPath + "/guests/" + encodeURIComponent(userId), { method: "DELETE" });
|
|
6212
|
+
}
|
|
6213
|
+
/**
|
|
6214
|
+
* Delete one batch of the guests last seen before a date. It can only ever
|
|
6215
|
+
* touch guests. Repeat it while `remaining` is not 0, passing how many have
|
|
6216
|
+
* been skipped so far as `offset`.
|
|
6217
|
+
*/
|
|
6218
|
+
async function deleteGuests(options) {
|
|
6219
|
+
const params = new URLSearchParams({ lastSeenBefore: isoDate(options.lastSeenBefore) });
|
|
6220
|
+
if (options.offset) params.set("offset", String(options.offset));
|
|
6221
|
+
return transport.request(adminPath + "/guests?" + params.toString(), { method: "DELETE" });
|
|
6222
|
+
}
|
|
5969
6223
|
async function resetPassword(userId, options) {
|
|
5970
6224
|
return transport.request(adminPath + "/users/" + encodeURIComponent(userId) + "/reset-password", {
|
|
5971
6225
|
method: "POST",
|
|
@@ -5986,6 +6240,9 @@ function createAdmin(transport, options) {
|
|
|
5986
6240
|
updateUser,
|
|
5987
6241
|
deleteUser,
|
|
5988
6242
|
resetMfa,
|
|
6243
|
+
listGuests,
|
|
6244
|
+
deleteGuest,
|
|
6245
|
+
deleteGuests,
|
|
5989
6246
|
resetPassword,
|
|
5990
6247
|
listRoles,
|
|
5991
6248
|
bootstrap
|
|
@@ -6779,15 +7036,31 @@ var SOCKET_OPT_INS = [
|
|
|
6779
7036
|
"channel_seq",
|
|
6780
7037
|
"cancel_sql"
|
|
6781
7038
|
];
|
|
7039
|
+
/**
|
|
7040
|
+
* The query parameter naming the group a socket belongs to. A platform that
|
|
7041
|
+
* routes on it sends sockets with the same value to the same instance; the
|
|
7042
|
+
* server itself never reads it.
|
|
7043
|
+
*/
|
|
7044
|
+
var SOCKET_AFFINITY_PARAM = "affinity";
|
|
6782
7045
|
/** Slack on top of two heartbeat intervals before a silent socket is given up on. */
|
|
6783
7046
|
var HEARTBEAT_GRACE_MS = 5e3;
|
|
6784
7047
|
/**
|
|
6785
|
-
* `url` with the opt-ins named on it
|
|
6786
|
-
* `URL`, which would rewrite the address
|
|
6787
|
-
* a `/`).
|
|
7048
|
+
* `url` with the opt-ins named on it, and `affinity` when there is one.
|
|
7049
|
+
* Appended rather than rebuilt through `URL`, which would rewrite the address
|
|
7050
|
+
* the caller gave (a bare origin gains a `/`).
|
|
7051
|
+
*
|
|
7052
|
+
* `affinity` replaces one already in `url`: a router takes one value, and it
|
|
7053
|
+
* may not be the last.
|
|
6788
7054
|
*/
|
|
6789
|
-
function withOptIns(url) {
|
|
6790
|
-
|
|
7055
|
+
function withOptIns(url, affinity) {
|
|
7056
|
+
const queryAt = url.indexOf("?");
|
|
7057
|
+
const address = queryAt === -1 ? url : url.slice(0, queryAt);
|
|
7058
|
+
const params = queryAt === -1 ? [] : url.slice(queryAt + 1).split("&");
|
|
7059
|
+
return `${address}?${[
|
|
7060
|
+
...affinity ? params.filter((param) => !param.startsWith(`${SOCKET_AFFINITY_PARAM}=`)) : params,
|
|
7061
|
+
...affinity ? [`${SOCKET_AFFINITY_PARAM}=${encodeURIComponent(affinity)}`] : [],
|
|
7062
|
+
`${SOCKET_OPT_IN_PARAM}=${SOCKET_OPT_INS.join(",")}`
|
|
7063
|
+
].join("&")}`;
|
|
6791
7064
|
}
|
|
6792
7065
|
/**
|
|
6793
7066
|
* Broadcast and presence frames.
|
|
@@ -6875,8 +7148,15 @@ function isCollectionUpdate(message) {
|
|
|
6875
7148
|
function isChannelMessage(message) {
|
|
6876
7149
|
return typeof message.channel === "string" && CHANNEL_FRAME_TYPES.has(message.type);
|
|
6877
7150
|
}
|
|
7151
|
+
/** The code of a channel `ERROR` frame, if it is one and carries a code. */
|
|
7152
|
+
function channelErrorCode(message) {
|
|
7153
|
+
if (message.type !== "ERROR" && message.type !== "error") return void 0;
|
|
7154
|
+
const raw = message.payload?.error;
|
|
7155
|
+
if (raw && typeof raw === "object" && "code" in raw && typeof raw.code === "string") return raw.code;
|
|
7156
|
+
}
|
|
6878
7157
|
var RebaseWebSocketClient = class {
|
|
6879
7158
|
websocketUrl;
|
|
7159
|
+
affinity;
|
|
6880
7160
|
ws = null;
|
|
6881
7161
|
/**
|
|
6882
7162
|
* Where the socket's token comes from. A client built by
|
|
@@ -7068,6 +7348,7 @@ var RebaseWebSocketClient = class {
|
|
|
7068
7348
|
}
|
|
7069
7349
|
constructor(config) {
|
|
7070
7350
|
this.websocketUrl = config.websocketUrl;
|
|
7351
|
+
this.affinity = config.affinity;
|
|
7071
7352
|
this.getAuthToken = config.getAuthToken;
|
|
7072
7353
|
this.onUnauthorized = config.onUnauthorized;
|
|
7073
7354
|
this.impersonate = config.impersonate;
|
|
@@ -7075,6 +7356,13 @@ var RebaseWebSocketClient = class {
|
|
|
7075
7356
|
this.WebSocketConstructor = config.WebSocket || (typeof WebSocket !== "undefined" ? WebSocket : void 0);
|
|
7076
7357
|
}
|
|
7077
7358
|
/**
|
|
7359
|
+
* Name the group this socket belongs to, or clear it with `null`. Read at
|
|
7360
|
+
* each dial, so a socket already open stays where it is until it redials.
|
|
7361
|
+
*/
|
|
7362
|
+
setAffinity(key) {
|
|
7363
|
+
this.affinity = key ?? void 0;
|
|
7364
|
+
}
|
|
7365
|
+
/**
|
|
7078
7366
|
* Open the socket if it is not open (or opening) already.
|
|
7079
7367
|
*
|
|
7080
7368
|
* Idempotent, synchronous, and safe to call on every operation that needs a
|
|
@@ -7178,6 +7466,55 @@ var RebaseWebSocketClient = class {
|
|
|
7178
7466
|
/**
|
|
7179
7467
|
* Authenticate the WebSocket connection
|
|
7180
7468
|
*/
|
|
7469
|
+
/**
|
|
7470
|
+
* {@link authenticate}, asked again a few times when the server could not
|
|
7471
|
+
* answer (its auth store busy, `ROLE_LOOKUP_FAILED`, a timeout) — not when
|
|
7472
|
+
* it refused the session or the socket ceiling, which a retry cannot
|
|
7473
|
+
* change. Stops as soon as `socket` is no longer this client's.
|
|
7474
|
+
*/
|
|
7475
|
+
async authenticateRetrying(token, socket) {
|
|
7476
|
+
const delays = [
|
|
7477
|
+
500,
|
|
7478
|
+
1500,
|
|
7479
|
+
3500
|
|
7480
|
+
];
|
|
7481
|
+
for (let attempt = 0;; attempt++) try {
|
|
7482
|
+
await this.authenticate(token);
|
|
7483
|
+
return;
|
|
7484
|
+
} catch (error) {
|
|
7485
|
+
if (attempt >= delays.length || this.ws !== socket || isSocketCeilingRefusal(error) || isSessionRefusal(error)) throw error;
|
|
7486
|
+
await new Promise((resolve) => setTimeout(resolve, delays[attempt]));
|
|
7487
|
+
if (this.ws !== socket) throw error;
|
|
7488
|
+
}
|
|
7489
|
+
}
|
|
7490
|
+
/** A sign-in again after a channel was refused for not being signed in, in flight. */
|
|
7491
|
+
channelAuthRecovery = null;
|
|
7492
|
+
/**
|
|
7493
|
+
* A channel frame refused `UNAUTHORIZED` while this client holds a way to
|
|
7494
|
+
* get a token: the socket is open but not signed in (an authentication that
|
|
7495
|
+
* failed on a reconnect, a token that expired). Nothing else signs it in —
|
|
7496
|
+
* channel frames expect no answer, so the refusal reaches only the channel —
|
|
7497
|
+
* and every later frame is refused the same way. Sign in again, once for
|
|
7498
|
+
* all the channels that noticed, and have them re-join.
|
|
7499
|
+
*/
|
|
7500
|
+
recoverChannelAuth() {
|
|
7501
|
+
if (this.channelAuthRecovery || !this.getAuthToken || this.isAuthenticated) return;
|
|
7502
|
+
const socket = this.ws;
|
|
7503
|
+
this.channelAuthRecovery = (async () => {
|
|
7504
|
+
try {
|
|
7505
|
+
const token = await this.getAuthToken();
|
|
7506
|
+
if (!token || !socket || this.ws !== socket) return;
|
|
7507
|
+
await this.authenticateRetrying(token, socket);
|
|
7508
|
+
if (this.ws === socket) this.emit("reconnect");
|
|
7509
|
+
} catch (error) {
|
|
7510
|
+
this.connectionDebug("Could not sign the socket in again for a channel:", error?.message || error);
|
|
7511
|
+
} finally {
|
|
7512
|
+
setTimeout(() => {
|
|
7513
|
+
this.channelAuthRecovery = null;
|
|
7514
|
+
}, 2e3);
|
|
7515
|
+
}
|
|
7516
|
+
})();
|
|
7517
|
+
}
|
|
7181
7518
|
async authenticate(token) {
|
|
7182
7519
|
return new Promise((resolve, reject) => {
|
|
7183
7520
|
const requestId = `auth_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
|
|
@@ -7274,7 +7611,7 @@ var RebaseWebSocketClient = class {
|
|
|
7274
7611
|
this.ws = null;
|
|
7275
7612
|
}
|
|
7276
7613
|
try {
|
|
7277
|
-
const socket = new this.WebSocketConstructor(withOptIns(this.websocketUrl));
|
|
7614
|
+
const socket = new this.WebSocketConstructor(withOptIns(this.websocketUrl, this.affinity));
|
|
7278
7615
|
this.ws = socket;
|
|
7279
7616
|
this.ws.onopen = async () => {
|
|
7280
7617
|
this.connectionDebug("Connected to PostgreSQL backend");
|
|
@@ -7289,7 +7626,7 @@ var RebaseWebSocketClient = class {
|
|
|
7289
7626
|
try {
|
|
7290
7627
|
token = await this.getAuthToken();
|
|
7291
7628
|
if (token) {
|
|
7292
|
-
await this.
|
|
7629
|
+
await this.authenticateRetrying(token, socket);
|
|
7293
7630
|
this.connectionDebug("WebSocket auto-authenticated");
|
|
7294
7631
|
}
|
|
7295
7632
|
} catch (error) {
|
|
@@ -7297,7 +7634,13 @@ var RebaseWebSocketClient = class {
|
|
|
7297
7634
|
this.noteSocketCeiling(error);
|
|
7298
7635
|
return;
|
|
7299
7636
|
}
|
|
7300
|
-
if (!(token && this.noteSessionRefused(token, error)))
|
|
7637
|
+
if (!(token && this.noteSessionRefused(token, error))) {
|
|
7638
|
+
this.connectionDebug("WebSocket connected, not signed in yet:", error?.message || error);
|
|
7639
|
+
if (token && this.ws === socket && !this.refusedSession) {
|
|
7640
|
+
socket.close(4e3, "Could not authenticate; reconnecting");
|
|
7641
|
+
return;
|
|
7642
|
+
}
|
|
7643
|
+
}
|
|
7301
7644
|
}
|
|
7302
7645
|
}
|
|
7303
7646
|
if (this.ws !== socket) return;
|
|
@@ -7600,6 +7943,7 @@ var RebaseWebSocketClient = class {
|
|
|
7600
7943
|
return;
|
|
7601
7944
|
}
|
|
7602
7945
|
if (isChannelMessage(message)) {
|
|
7946
|
+
if (channelErrorCode(message) === "UNAUTHORIZED") this.recoverChannelAuth();
|
|
7603
7947
|
const handlers = this.channelHandlers.get(message.channel);
|
|
7604
7948
|
if (handlers) for (const handler of [...handlers]) try {
|
|
7605
7949
|
handler(message);
|
|
@@ -8642,6 +8986,28 @@ var RebaseRealtimeChannel = class {
|
|
|
8642
8986
|
await this.send("presence_state");
|
|
8643
8987
|
if (this.wantsHistory) await this.requestHistory();
|
|
8644
8988
|
}
|
|
8989
|
+
/** Consecutive re-joins asked for by refusals, for the backoff; reset after a quiet minute. */
|
|
8990
|
+
rejoinAttempts = 0;
|
|
8991
|
+
rejoinTimer;
|
|
8992
|
+
lastRejoinAt = 0;
|
|
8993
|
+
/**
|
|
8994
|
+
* Re-join after the server refused this channel for a reason a retry can
|
|
8995
|
+
* change: it could not check permissions at that moment, or it has no record
|
|
8996
|
+
* of the join (a join that was itself refused, so every broadcast after it
|
|
8997
|
+
* came back "not a member"). The join was fire-and-forget and `joined` was
|
|
8998
|
+
* already set, so nothing else would ever send it again. Backs off 1, 2, 4…
|
|
8999
|
+
* up to 30 seconds, one re-join at a time.
|
|
9000
|
+
*/
|
|
9001
|
+
scheduleRejoin() {
|
|
9002
|
+
if (this.rejoinTimer || !this.joined) return;
|
|
9003
|
+
if (Date.now() - this.lastRejoinAt > 6e4) this.rejoinAttempts = 0;
|
|
9004
|
+
const delay = Math.min(3e4, 1e3 * 2 ** this.rejoinAttempts++);
|
|
9005
|
+
this.rejoinTimer = setTimeout(() => {
|
|
9006
|
+
this.rejoinTimer = void 0;
|
|
9007
|
+
this.lastRejoinAt = Date.now();
|
|
9008
|
+
if (this.joined) this.rejoin();
|
|
9009
|
+
}, delay);
|
|
9010
|
+
}
|
|
8645
9011
|
async rejoin() {
|
|
8646
9012
|
try {
|
|
8647
9013
|
await this.send("join_channel");
|
|
@@ -8829,6 +9195,10 @@ var RebaseRealtimeChannel = class {
|
|
|
8829
9195
|
/** Leave the channel and release every listener and timer. */
|
|
8830
9196
|
async leave() {
|
|
8831
9197
|
this.stopHeartbeat();
|
|
9198
|
+
if (this.rejoinTimer) {
|
|
9199
|
+
clearTimeout(this.rejoinTimer);
|
|
9200
|
+
this.rejoinTimer = void 0;
|
|
9201
|
+
}
|
|
8832
9202
|
this.trackedState = null;
|
|
8833
9203
|
this.presences = {};
|
|
8834
9204
|
this.presenceHandlers.clear();
|
|
@@ -8972,6 +9342,7 @@ var RebaseRealtimeChannel = class {
|
|
|
8972
9342
|
const asObject = typeof raw === "object" ? raw : void 0;
|
|
8973
9343
|
const text = asObject?.message ?? (typeof raw === "string" ? raw : void 0) ?? message.error ?? "The server refused a channel operation.";
|
|
8974
9344
|
this.emitError(new RebaseApiError(text, { ...asObject?.code ? { code: asObject.code } : {} }));
|
|
9345
|
+
if (this.joined && rejoinsAfter(asObject?.code, text)) this.scheduleRejoin();
|
|
8975
9346
|
break;
|
|
8976
9347
|
}
|
|
8977
9348
|
}
|
|
@@ -9047,6 +9418,16 @@ var RebaseRealtimeChannel = class {
|
|
|
9047
9418
|
}
|
|
9048
9419
|
};
|
|
9049
9420
|
/**
|
|
9421
|
+
* Whether a channel refusal is one a re-join can recover from: the server's
|
|
9422
|
+
* auth store could not answer (`ROLE_LOOKUP_FAILED`, `DATABASE_UNAVAILABLE`), or
|
|
9423
|
+
* it no longer counts this client a member. A channel the client may not use
|
|
9424
|
+
* (any other `CHANNEL_FORBIDDEN`) is not retried.
|
|
9425
|
+
*/
|
|
9426
|
+
function rejoinsAfter(code, message) {
|
|
9427
|
+
if (code === "ROLE_LOOKUP_FAILED" || code === "DATABASE_UNAVAILABLE") return true;
|
|
9428
|
+
return code === "CHANNEL_FORBIDDEN" && /not a member/i.test(message);
|
|
9429
|
+
}
|
|
9430
|
+
/**
|
|
9050
9431
|
* `createRebaseClient({ offline })`'s handle on the sync engine, which it
|
|
9051
9432
|
* fetches with `import()` the moment the client is created.
|
|
9052
9433
|
*
|
|
@@ -9263,7 +9644,7 @@ function deriveWebSocketUrl(baseUrl) {
|
|
|
9263
9644
|
return toWsProtocol(baseUrl);
|
|
9264
9645
|
}
|
|
9265
9646
|
function createRebaseClient(options) {
|
|
9266
|
-
const transport = createTransport(options, { credentialOutOfBand: options.auth
|
|
9647
|
+
const transport = createTransport(options, { credentialOutOfBand: resolveAuthFlowMode(options.auth) === "cookie" });
|
|
9267
9648
|
const auth = createAuth(transport, options.auth);
|
|
9268
9649
|
const admin = createAdmin(transport, options.admin);
|
|
9269
9650
|
const cron = createCron(transport, options.cron);
|
|
@@ -9311,6 +9692,7 @@ function createRebaseClient(options) {
|
|
|
9311
9692
|
if (resolvedWsUrl) {
|
|
9312
9693
|
ws = new RebaseWebSocketClient({
|
|
9313
9694
|
websocketUrl: resolvedWsUrl,
|
|
9695
|
+
affinity: options.realtime && options.realtime !== true ? options.realtime.affinity : void 0,
|
|
9314
9696
|
getAuthToken: () => transport.resolveToken(),
|
|
9315
9697
|
onUnauthorized: () => onUnauthorized(),
|
|
9316
9698
|
impersonate: options.impersonate,
|
|
@@ -9492,24 +9874,26 @@ function createRebaseClient(options) {
|
|
|
9492
9874
|
createStorageSource,
|
|
9493
9875
|
fetchStorageSources,
|
|
9494
9876
|
ws,
|
|
9495
|
-
realtime: {
|
|
9496
|
-
|
|
9497
|
-
|
|
9498
|
-
|
|
9499
|
-
|
|
9500
|
-
|
|
9501
|
-
|
|
9502
|
-
|
|
9503
|
-
|
|
9504
|
-
channel: (name, options) => {
|
|
9505
|
-
|
|
9506
|
-
|
|
9507
|
-
|
|
9508
|
-
|
|
9509
|
-
|
|
9510
|
-
|
|
9511
|
-
|
|
9512
|
-
|
|
9877
|
+
realtime: {
|
|
9878
|
+
/**
|
|
9879
|
+
* Join a broadcast/presence channel.
|
|
9880
|
+
*
|
|
9881
|
+
* Repeated calls with the same name return the same channel, so
|
|
9882
|
+
* separate components can attach handlers without each opening its
|
|
9883
|
+
* own membership — and `leave()` from one would otherwise silently
|
|
9884
|
+
* cut off the others.
|
|
9885
|
+
*/
|
|
9886
|
+
channel: (name, options) => {
|
|
9887
|
+
if (!ws) throw new RebaseClientError(realtimeUnreachable ? `Realtime is enabled but ${unreachableReason}` : "Realtime is disabled on this client (realtime: false), so channels are unavailable.", { code: "REALTIME_DISABLED" });
|
|
9888
|
+
let existing = realtimeChannels.get(name);
|
|
9889
|
+
if (!existing) {
|
|
9890
|
+
existing = new RebaseRealtimeChannel(name, ws, options);
|
|
9891
|
+
realtimeChannels.set(name, existing);
|
|
9892
|
+
} else if (options?.history) existing.enableHistory();
|
|
9893
|
+
return existing;
|
|
9894
|
+
},
|
|
9895
|
+
setAffinity: (key) => ws?.setAffinity(key)
|
|
9896
|
+
},
|
|
9513
9897
|
/**
|
|
9514
9898
|
* Release every handle that can keep a process alive — see the
|
|
9515
9899
|
* `close` docblock on the client interface.
|
|
@@ -10400,6 +10784,10 @@ function checkTenant(collection, at, collect) {
|
|
|
10400
10784
|
* function Rebase has never created — not by a generator, not at boot, not in
|
|
10401
10785
|
* a migration — so the column has never had a working default on Postgres and
|
|
10402
10786
|
* the first insert relying on it failed with `function cuid() does not exist`.
|
|
10787
|
+
* - **A strategy keyword on a type that cannot honour it.** `"increment"` on
|
|
10788
|
+
* anything but a number, or `"uuid"` on anything but a string, fell through to
|
|
10789
|
+
* "any other string is raw SQL" and emitted `DEFAULT increment` or `DEFAULT
|
|
10790
|
+
* uuid` — a reference to a column that does not exist.
|
|
10403
10791
|
* - **`columnType` beside `isId: "increment"`.** An identity key is INTEGER,
|
|
10404
10792
|
* because every column that points at a numeric primary key is INTEGER; a
|
|
10405
10793
|
* BIGINT one would be referenced by int4 foreign keys. The width is ignored
|
|
@@ -10415,6 +10803,10 @@ function checkPrimaryKeyStrategy(collection, at, collect) {
|
|
|
10415
10803
|
const ids = Object.entries(collection.properties).filter(([, property]) => isPlainObject$2(property) && Boolean(property.isId)).map(([key, property]) => [key, property]);
|
|
10416
10804
|
for (const [key, property] of ids) {
|
|
10417
10805
|
if (property.isId === "cuid") collect.error(`${at}.properties.${key}.isId`, "`isId: \"cuid\"` cannot be honoured on Postgres: the generated column gets `DEFAULT cuid()`, and no `cuid()` function is ever created, so every insert that relies on it fails. Use `isId: \"uuid\"`, or give the strategy as SQL — ``isId: \"sql`my_id()`\"`` — and create that function in a migration.");
|
|
10806
|
+
if (property.isId === "increment" && property.type !== "number" || property.isId === "uuid" && property.type !== "string") {
|
|
10807
|
+
const needs = property.isId === "increment" ? "number" : "string";
|
|
10808
|
+
collect.error(`${at}.properties.${key}.isId`, `\`isId: "${property.isId}"\` needs a ${needs} property, and this one is \`type: "${String(property.type)}"\`. Any other string is read as a raw SQL default, so the column would get \`DEFAULT ${property.isId}\`, which Postgres refuses. ` + (property.isId === "increment" ? "Make the key `type: \"number\"`, or use `isId: \"uuid\"` for a string key." : "Make the key `type: \"string\"`, or use `isId: \"increment\"` for a number key."));
|
|
10809
|
+
}
|
|
10418
10810
|
if (property.isId === "increment" && property.columnType !== void 0) collect.warn(`${at}.properties.${key}.columnType`, `\`columnType: "${String(property.columnType)}"\` is not read beside \`isId: "increment"\`. An increment key is \`INTEGER GENERATED BY DEFAULT AS IDENTITY\` on every path, because every foreign key and junction column that points at a numeric primary key is INTEGER — a wider key would be referenced by narrower columns. Remove the \`columnType\`.`);
|
|
10419
10811
|
}
|
|
10420
10812
|
}
|
|
@@ -12011,6 +12403,23 @@ function createRoutedRealtimeService(opts) {
|
|
|
12011
12403
|
...listener,
|
|
12012
12404
|
name: `${key}:${listener.name}`
|
|
12013
12405
|
})));
|
|
12406
|
+
},
|
|
12407
|
+
counts() {
|
|
12408
|
+
const counts = {
|
|
12409
|
+
sockets: 0,
|
|
12410
|
+
channels: 0,
|
|
12411
|
+
busFramesPublished: {},
|
|
12412
|
+
busFramesSkipped: 0
|
|
12413
|
+
};
|
|
12414
|
+
for (const p of all()) {
|
|
12415
|
+
const source = p.counts?.();
|
|
12416
|
+
if (!source) continue;
|
|
12417
|
+
counts.sockets = Math.max(counts.sockets, source.sockets);
|
|
12418
|
+
counts.channels += source.channels;
|
|
12419
|
+
counts.busFramesSkipped += source.busFramesSkipped;
|
|
12420
|
+
for (const [kind, frames] of Object.entries(source.busFramesPublished)) counts.busFramesPublished[kind] = (counts.busFramesPublished[kind] ?? 0) + frames;
|
|
12421
|
+
}
|
|
12422
|
+
return counts;
|
|
12014
12423
|
}
|
|
12015
12424
|
};
|
|
12016
12425
|
}
|
|
@@ -16023,22 +16432,42 @@ var LocalStorageController = class {
|
|
|
16023
16432
|
}
|
|
16024
16433
|
async putObject({ file, key, metadata, bucket }, options) {
|
|
16025
16434
|
if (options?.uploadLimits !== false) this.validateFile(file);
|
|
16435
|
+
return this.writeObject(blobChunks(file), key, bucket, {
|
|
16436
|
+
...metadata || {},
|
|
16437
|
+
contentType: file.type,
|
|
16438
|
+
size: file.size
|
|
16439
|
+
});
|
|
16440
|
+
}
|
|
16441
|
+
/** See {@link StorageController.putObjectStream}. */
|
|
16442
|
+
async putObjectStream({ stream, key, contentType, bucket, maxBytes }) {
|
|
16443
|
+
const metered = meteredChunks(stream, maxBytes);
|
|
16444
|
+
return {
|
|
16445
|
+
...await this.writeObject(metered.chunks, key, bucket, () => ({
|
|
16446
|
+
contentType: contentType ?? "application/octet-stream",
|
|
16447
|
+
size: metered.size()
|
|
16448
|
+
})),
|
|
16449
|
+
size: metered.size()
|
|
16450
|
+
};
|
|
16451
|
+
}
|
|
16452
|
+
/**
|
|
16453
|
+
* Write an object and its metadata sidecar. `metadata` is a function when
|
|
16454
|
+
* the size is only known once the bytes have been written.
|
|
16455
|
+
*/
|
|
16456
|
+
async writeObject(chunks, key, bucket, metadata) {
|
|
16026
16457
|
const usedBucket = bucket || "default";
|
|
16027
16458
|
const fullStoragePath = key;
|
|
16028
16459
|
const fullPath = this.getFullPath(fullStoragePath, usedBucket);
|
|
16029
16460
|
await this.ensureDir(path$3.dirname(fullPath));
|
|
16030
16461
|
const partial = path$3.join(path$3.dirname(fullPath), `.${path$3.basename(fullPath)}.${randomUUID$1()}${PARTIAL_SUFFIX}`);
|
|
16031
16462
|
try {
|
|
16032
|
-
await pipeline(Readable.from(
|
|
16463
|
+
await pipeline(Readable.from(chunks), fs$3.createWriteStream(partial));
|
|
16033
16464
|
await fs$3.promises.rename(partial, fullPath);
|
|
16034
16465
|
} catch (error) {
|
|
16035
16466
|
await fs$3.promises.rm(partial, { force: true });
|
|
16036
16467
|
throw error;
|
|
16037
16468
|
}
|
|
16038
16469
|
await writeFile$1(`${fullPath}.metadata.json`, JSON.stringify({
|
|
16039
|
-
...metadata
|
|
16040
|
-
contentType: file.type,
|
|
16041
|
-
size: file.size,
|
|
16470
|
+
...typeof metadata === "function" ? metadata() : metadata,
|
|
16042
16471
|
uploadedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
16043
16472
|
}, null, 2));
|
|
16044
16473
|
return {
|
|
@@ -18621,7 +19050,7 @@ function createStorageRoutes(config) {
|
|
|
18621
19050
|
const { bucket, key: resolvedPath } = requestedObjectOrBadRequest(rawPath);
|
|
18622
19051
|
await checkAuthorized(c, "read", resolvedPath, bucket, storageId);
|
|
18623
19052
|
c.header("X-Content-Type-Options", "nosniff");
|
|
18624
|
-
const transformKeyPrefix = `${storageId
|
|
19053
|
+
const transformKeyPrefix = `${canonicalStorageId(storageId)}/${bucket}/${resolvedPath}`;
|
|
18625
19054
|
const sharedCacheable = publicRead === true || isPublicStorageKey(resolvedPath);
|
|
18626
19055
|
const cachePolicy = (maxAgeSeconds) => ({
|
|
18627
19056
|
isPublic: sharedCacheable,
|
|
@@ -19001,9 +19430,9 @@ function createStorageRoutes(config) {
|
|
|
19001
19430
|
}
|
|
19002
19431
|
return c.json({ message: "Folder created" }, 201);
|
|
19003
19432
|
});
|
|
19004
|
-
const tusHandler = new TusHandler(defaultCtrl?.getType() === "local" ? defaultCtrl.getBasePath() : process.env.STORAGE_PATH || "./uploads", defaultCtrl, registry,
|
|
19433
|
+
const tusHandler = new TusHandler(defaultCtrl?.getType() === "local" ? defaultCtrl.getBasePath() : process.env.STORAGE_PATH || "./uploads", defaultCtrl, registry, async (c, key, bucket, storageId) => {
|
|
19005
19434
|
await checkAuthorized(c, "write", key, bucket, storageId);
|
|
19006
|
-
}
|
|
19435
|
+
}, fireTrigger ? async (event) => {
|
|
19007
19436
|
await fireTrigger({
|
|
19008
19437
|
event: "finalize",
|
|
19009
19438
|
key: event.key,
|
|
@@ -19070,11 +19499,11 @@ async function createStorageController(config) {
|
|
|
19070
19499
|
switch (config.type) {
|
|
19071
19500
|
case "local": return new LocalStorageController(config);
|
|
19072
19501
|
case "s3": {
|
|
19073
|
-
const { S3StorageController } = await import("./S3StorageController-
|
|
19502
|
+
const { S3StorageController } = await import("./S3StorageController-CixCQEky.js").then((n) => n.n);
|
|
19074
19503
|
return new S3StorageController(config);
|
|
19075
19504
|
}
|
|
19076
19505
|
case "gcs": {
|
|
19077
|
-
const { GCSStorageController } = await import("./GCSStorageController-
|
|
19506
|
+
const { GCSStorageController } = await import("./GCSStorageController-BUClIfp0.js").then((n) => n.n);
|
|
19078
19507
|
return new GCSStorageController(config);
|
|
19079
19508
|
}
|
|
19080
19509
|
default: throw new Error(`Unknown storage type: ${config.type}. Built-in types: local, s3, gcs. For other providers, implement the StorageController interface directly.`);
|
|
@@ -19159,7 +19588,7 @@ async function initializeStorage(storageConfig, isProduction) {
|
|
|
19159
19588
|
* The one message the boot guard emits, factored out so the production throw
|
|
19160
19589
|
* and the development warning say exactly the same thing.
|
|
19161
19590
|
*/
|
|
19162
|
-
var STORAGE_NO_ACCESS_CONTROL_MESSAGE = "Storage is configured WITHOUT any access-control model. Keys share one flat namespace and no `storageAuthorize` hook is set, so any authenticated user can list every key (GET /storage/list?prefix=) and then read, overwrite or delete any other user's files. Fix one of:\n • add a `storageAuthorize` hook that scopes access per user/tenant (recommended), or\n • set `storagePublicRead: true` if this bucket is genuinely a public read-only CDN, or\n • set `storageInsecureAllowAnyAuthenticated: true` to keep the legacy shared-namespace\n behaviour on purpose (single-tenant apps where every signed-in user is trusted).";
|
|
19591
|
+
var STORAGE_NO_ACCESS_CONTROL_MESSAGE = "Storage is configured WITHOUT any access-control model. Keys share one flat namespace and no `storageAuthorize` hook is set, so any authenticated user can list every key (GET /storage/list?prefix=) and then read, overwrite or delete any other user's files. Fix one of:\n • add a `storageAuthorize` hook that scopes access per user/tenant (recommended), or\n • declare `storagePolicies`, path patterns saying who may do what, or\n • set `storagePublicRead: true` if this bucket is genuinely a public read-only CDN, or\n • set `storageInsecureAllowAnyAuthenticated: true` to keep the legacy shared-namespace\n behaviour on purpose (single-tenant apps where every signed-in user is trusted).";
|
|
19163
19592
|
/**
|
|
19164
19593
|
* Refuse to boot storage in production with no access-control model.
|
|
19165
19594
|
*
|
|
@@ -19225,10 +19654,12 @@ function compileStoragePolicies(policies, fallback) {
|
|
|
19225
19654
|
if (!Array.isArray(policies)) throw new StoragePolicyError("`storagePolicies` must be an array.");
|
|
19226
19655
|
const compiled = policies.map(compile);
|
|
19227
19656
|
return async (ctx) => {
|
|
19657
|
+
let matched = false;
|
|
19228
19658
|
for (const policy of compiled) {
|
|
19229
19659
|
if (!policy.operations.has(ctx.operation)) continue;
|
|
19230
19660
|
const params = matchStoragePattern(policy.pattern, ctx.key);
|
|
19231
19661
|
if (!params) continue;
|
|
19662
|
+
matched = true;
|
|
19232
19663
|
if (policy.allow === "public") return true;
|
|
19233
19664
|
if (policy.allow === "authenticated") {
|
|
19234
19665
|
if (ctx.user?.uid) return true;
|
|
@@ -19239,6 +19670,7 @@ function compileStoragePolicies(policies, fallback) {
|
|
|
19239
19670
|
params
|
|
19240
19671
|
})) return true;
|
|
19241
19672
|
}
|
|
19673
|
+
if (matched) return false;
|
|
19242
19674
|
if (fallback) return await fallback(ctx);
|
|
19243
19675
|
return false;
|
|
19244
19676
|
};
|
|
@@ -19317,7 +19749,7 @@ async function loadOpenApiGenerator() {
|
|
|
19317
19749
|
return generateOpenApiSpec;
|
|
19318
19750
|
}
|
|
19319
19751
|
/**
|
|
19320
|
-
* Serve the OpenAPI document, and Swagger UI outside production.
|
|
19752
|
+
* Serve the OpenAPI document, and Swagger UI outside production when swagger is on.
|
|
19321
19753
|
*/
|
|
19322
19754
|
function mountOpenApiDocs(app, basePath, options) {
|
|
19323
19755
|
const { enableSwagger, serverCollections, requireAuth, adminGate, generate, unprotectedTables = [] } = options;
|
|
@@ -19361,7 +19793,7 @@ function mountOpenApiDocs(app, basePath, options) {
|
|
|
19361
19793
|
app.use(`${basePath}/docs`, ...adminGate);
|
|
19362
19794
|
app.get(`${basePath}/docs`, (c) => spec(c));
|
|
19363
19795
|
}
|
|
19364
|
-
if (process.env.NODE_ENV !== "production") {
|
|
19796
|
+
if (isPublic && process.env.NODE_ENV !== "production") {
|
|
19365
19797
|
app.get(`${basePath}/swagger`, (c) => {
|
|
19366
19798
|
return c.html(`<!DOCTYPE html>
|
|
19367
19799
|
<html>
|
|
@@ -19404,21 +19836,40 @@ function mountOpenApiDocs(app, basePath, options) {
|
|
|
19404
19836
|
*/
|
|
19405
19837
|
var REALTIME_LISTENER_GRACE_MS = 6e4;
|
|
19406
19838
|
/**
|
|
19839
|
+
* How long the database probe may take, in ms: under the readiness probe's own
|
|
19840
|
+
* timeout (3 s on the managed runtime), so a slow answer is reported by this
|
|
19841
|
+
* check rather than by the probe giving up on the request.
|
|
19842
|
+
*/
|
|
19843
|
+
var DATABASE_PROBE_TIMEOUT_MS = 2500;
|
|
19844
|
+
/**
|
|
19407
19845
|
* @param realtimeProviders — optional; each reports the LISTEN connections it
|
|
19408
19846
|
* depends on. One down past {@link REALTIME_LISTENER_GRACE_MS} makes the
|
|
19409
19847
|
* check unhealthy; one down for less is reported but not failed on.
|
|
19410
19848
|
*/
|
|
19411
19849
|
function createHealthCheck(defaultDriver, authSchemaCheck, realtimeProviders = []) {
|
|
19850
|
+
let authHealthyAt = 0;
|
|
19851
|
+
let authHealthy;
|
|
19852
|
+
const checkAuthSchema = async () => {
|
|
19853
|
+
if (!authSchemaCheck) return void 0;
|
|
19854
|
+
if (authHealthy && Date.now() - authHealthyAt < 6e4) return authHealthy;
|
|
19855
|
+
const answer = await authSchemaCheck();
|
|
19856
|
+
if (answer.healthy) {
|
|
19857
|
+
authHealthy = answer;
|
|
19858
|
+
authHealthyAt = Date.now();
|
|
19859
|
+
} else authHealthy = void 0;
|
|
19860
|
+
return answer;
|
|
19861
|
+
};
|
|
19412
19862
|
return async () => {
|
|
19413
19863
|
const start = performance.now();
|
|
19414
19864
|
try {
|
|
19415
19865
|
const admin = defaultDriver.admin;
|
|
19416
|
-
if (isSQLAdmin(admin)) await admin.
|
|
19866
|
+
if (isSQLAdmin(admin) && admin.probe) await admin.probe(DATABASE_PROBE_TIMEOUT_MS);
|
|
19867
|
+
else if (isSQLAdmin(admin)) await admin.executeSql("SELECT 1");
|
|
19417
19868
|
else await defaultDriver.fetchCollection({
|
|
19418
19869
|
path: "__health_check_nonexistent__",
|
|
19419
19870
|
limit: 1
|
|
19420
19871
|
});
|
|
19421
|
-
const auth = await
|
|
19872
|
+
const auth = await checkAuthSchema();
|
|
19422
19873
|
const latencyMs = Math.round(performance.now() - start);
|
|
19423
19874
|
if (auth && !auth.healthy) {
|
|
19424
19875
|
logger.error("Health check failed: auth schema mismatch", {
|
|
@@ -27875,7 +28326,7 @@ async function buildRebaseBackend(options, announcements) {
|
|
|
27875
28326
|
const platformTokenPreAuth = createPlatformTokenPreAuth(await platformTokensFromEnv(process.env));
|
|
27876
28327
|
let backupLinkRouter;
|
|
27877
28328
|
if (surfaces.admin) {
|
|
27878
|
-
const { createBackupLinkRoutes, backupDestinationFromEnv } = await import("./backup-
|
|
28329
|
+
const { createBackupLinkRoutes, backupDestinationFromEnv } = await import("./backup-B6brPSeB.js").then((n) => n.t);
|
|
27879
28330
|
backupLinkRouter = createBackupLinkRoutes({ getDestination: () => backupDestinationFromEnv(process.env) });
|
|
27880
28331
|
}
|
|
27881
28332
|
const apiKeyRouter = apiKeyStore && surfaces.admin ? createApiKeyRoutes({
|
|
@@ -27976,7 +28427,6 @@ async function buildRebaseBackend(options, announcements) {
|
|
|
27976
28427
|
key: "apple",
|
|
27977
28428
|
factory: "createAppleProvider",
|
|
27978
28429
|
requiredFields: [
|
|
27979
|
-
"clientId",
|
|
27980
28430
|
"teamId",
|
|
27981
28431
|
"keyId",
|
|
27982
28432
|
"privateKey"
|
|
@@ -28020,7 +28470,7 @@ async function buildRebaseBackend(options, announcements) {
|
|
|
28020
28470
|
]) {
|
|
28021
28471
|
const providerConfig = safeAuthConfig[key];
|
|
28022
28472
|
if (providerConfig && requiredFields.every((f) => Boolean(providerConfig[f]))) {
|
|
28023
|
-
const createFn = (await import("./auth-
|
|
28473
|
+
const createFn = (await import("./auth-DDXPw0mn.js").then((n) => n.t))[factory];
|
|
28024
28474
|
oauthProviders.push(createFn(providerConfig));
|
|
28025
28475
|
}
|
|
28026
28476
|
}
|
|
@@ -28592,14 +29042,18 @@ async function buildRebaseBackend(options, announcements) {
|
|
|
28592
29042
|
for (const provider of realtimeProviders) provider.setScopeRunner?.(runInOwnScope);
|
|
28593
29043
|
injectCallbackClient(driverResults.values(), serverClient);
|
|
28594
29044
|
let functionsSurface;
|
|
29045
|
+
/** Function and cron files that failed to import, for `requireFilesLoaded`. */
|
|
29046
|
+
const loadFailures = [];
|
|
28595
29047
|
if ((config.functionsDir || config.functions) && surfaces.functions) {
|
|
28596
|
-
const { functionList, readFunctionsDirectory } = await import("./function-loader-
|
|
29048
|
+
const { functionList, readFunctionsDirectory } = await import("./function-loader-eFigStYX.js").then((n) => n.t);
|
|
28597
29049
|
const { createFunctionRoutes } = await import("./function-routes-RxrCHNuM.js").then((n) => n.n);
|
|
28598
29050
|
const { createFunctionsRequestTimeout, resolveFunctionsTimeoutMs } = await import("./request-timeout-DVjo-c_8.js").then((n) => n.t);
|
|
28599
|
-
const { functions: functionRecord, problems } = config.functions ? {
|
|
29051
|
+
const { functions: functionRecord, problems, failed } = config.functions ? {
|
|
28600
29052
|
functions: config.functions,
|
|
28601
|
-
problems: []
|
|
29053
|
+
problems: [],
|
|
29054
|
+
failed: []
|
|
28602
29055
|
} : await readFunctionsDirectory(config.functionsDir);
|
|
29056
|
+
loadFailures.push(...failed);
|
|
28603
29057
|
const allFunctions = functionList(functionRecord);
|
|
28604
29058
|
const { selectFunctions } = await import("./selection-CRpqKUbt.js").then((n) => n.n);
|
|
28605
29059
|
const loadedFunctions = selectFunctions(allFunctions, config.functionsSelection);
|
|
@@ -28655,17 +29109,20 @@ async function buildRebaseBackend(options, announcements) {
|
|
|
28655
29109
|
/** How many cron jobs `start()` schedules in this process. */
|
|
28656
29110
|
let cronJobsToSchedule = 0;
|
|
28657
29111
|
if (surfaces.cron || (config.cronsDir || config.crons) && ownership.cronScheduler) {
|
|
28658
|
-
const { cronJobsFrom, readCronsDirectory } = await import("./cron-loader-
|
|
28659
|
-
const { CronScheduler } = await import("./cron-scheduler-
|
|
28660
|
-
const { createCronRoutes } = await import("./cron-routes-
|
|
29112
|
+
const { cronJobsFrom, readCronsDirectory } = await import("./cron-loader-CC1Jy_KN.js").then((n) => n.t);
|
|
29113
|
+
const { CronScheduler } = await import("./cron-scheduler-DyCjPlQR.js").then((n) => n.n);
|
|
29114
|
+
const { createCronRoutes } = await import("./cron-routes-BK60Rn1r.js").then((n) => n.n);
|
|
28661
29115
|
const { createCronStore } = await import("./cron-store-DLn11M8H.js").then((n) => n.n);
|
|
28662
|
-
const { crons: cronRecord, problems: cronProblems } = config.crons ? {
|
|
29116
|
+
const { crons: cronRecord, problems: cronProblems, failed: cronFailures } = config.crons ? {
|
|
28663
29117
|
crons: config.crons,
|
|
28664
|
-
problems: []
|
|
29118
|
+
problems: [],
|
|
29119
|
+
failed: []
|
|
28665
29120
|
} : config.cronsDir ? await readCronsDirectory(config.cronsDir) : {
|
|
28666
29121
|
crons: {},
|
|
28667
|
-
problems: []
|
|
29122
|
+
problems: [],
|
|
29123
|
+
failed: []
|
|
28668
29124
|
};
|
|
29125
|
+
loadFailures.push(...cronFailures);
|
|
28669
29126
|
const loadedCronJobs = cronJobsFrom(cronRecord).map((job) => ({
|
|
28670
29127
|
...job,
|
|
28671
29128
|
definition: {
|
|
@@ -28700,6 +29157,7 @@ async function buildRebaseBackend(options, announcements) {
|
|
|
28700
29157
|
} else if (config.cronsDir && !config.crons) logger.warn(`Cron routes are served, but no jobs loaded from ${config.cronsDir}. ` + (cronProblems.length > 0 ? `Nothing is scheduled — ${cronProblems.length} file(s) were skipped, see the messages above.` : "The directory holds no .ts/.js cron files, so nothing is scheduled."));
|
|
28701
29158
|
else logger.debug("Cron routes are served. This project has no cron jobs, so the list is empty.");
|
|
28702
29159
|
}
|
|
29160
|
+
if (config.requireFilesLoaded && loadFailures.length > 0) throw new FilesFailedToLoadError(loadFailures);
|
|
28703
29161
|
const declaredTopics = graphTopics(buildResourceGraph());
|
|
28704
29162
|
const declaredQueues = graphQueues(buildResourceGraph());
|
|
28705
29163
|
const topicTasks = declaredTopics.length > 0 ? topicJobHandlers() : {};
|
|
@@ -28773,7 +29231,7 @@ Use a driver that supports the job queue, or remove the declarations. Refusing t
|
|
|
28773
29231
|
let logsSurface;
|
|
28774
29232
|
let metaSurface;
|
|
28775
29233
|
if (surfaces.admin) {
|
|
28776
|
-
const { createBackupRoutes, backupDestinationFromEnv, readBackupSchedule } = await import("./backup-
|
|
29234
|
+
const { createBackupRoutes, backupDestinationFromEnv, readBackupSchedule } = await import("./backup-B6brPSeB.js").then((n) => n.t);
|
|
28777
29235
|
const backupRouter = new Hono();
|
|
28778
29236
|
applyAdminGate(backupRouter, "Backup", "backups:read");
|
|
28779
29237
|
const scheduler = cronScheduler;
|
|
@@ -29970,11 +30428,6 @@ function loadEnv(options) {
|
|
|
29970
30428
|
message: "CORS_ORIGINS or FRONTEND_URL must be set in production to secure the API.",
|
|
29971
30429
|
path: ["CORS_ORIGINS"]
|
|
29972
30430
|
});
|
|
29973
|
-
if (d.NODE_ENV === "production" && autoGeneratedSecrets.length > 0) ctx.addIssue({
|
|
29974
|
-
code: z$1.ZodIssueCode.custom,
|
|
29975
|
-
message: `${autoGeneratedSecrets.join(", ")} must be explicitly set in production. Do not rely on auto-generated secrets outside development.`,
|
|
29976
|
-
path: [autoGeneratedSecrets[0]]
|
|
29977
|
-
});
|
|
29978
30431
|
if (d.NODE_ENV === "production" && !d.ALLOW_LOCALHOST_IN_PRODUCTION) for (const [key, value] of Object.entries(data)) {
|
|
29979
30432
|
if (key === "CORS_ORIGINS") continue;
|
|
29980
30433
|
if (typeof value === "string" && isLocalhostOrLoopback(value)) ctx.addIssue({
|
|
@@ -31865,6 +32318,16 @@ var bootEnvExtension = z$1.object({
|
|
|
31865
32318
|
"false",
|
|
31866
32319
|
""
|
|
31867
32320
|
]).default("false").transform((v) => v === "true"),
|
|
32321
|
+
/**
|
|
32322
|
+
* `true`: stop the boot when a function or cron file failed while importing,
|
|
32323
|
+
* rather than serve without it. Off by default: see `requireFilesLoaded` on
|
|
32324
|
+
* `createRebaseBackend`.
|
|
32325
|
+
*/
|
|
32326
|
+
REBASE_REQUIRE_FILES_LOADED: z$1.enum([
|
|
32327
|
+
"true",
|
|
32328
|
+
"false",
|
|
32329
|
+
""
|
|
32330
|
+
]).default("false").transform((v) => v === "true"),
|
|
31868
32331
|
/** Expose Prometheus metrics at `/metrics`. Off unless asked for. */
|
|
31869
32332
|
REBASE_METRICS: z$1.enum([
|
|
31870
32333
|
"true",
|
|
@@ -32041,12 +32504,18 @@ var bootEnvExtension = z$1.object({
|
|
|
32041
32504
|
SPOTIFY_CLIENT_SECRET: z$1.string().optional(),
|
|
32042
32505
|
/**
|
|
32043
32506
|
* Apple is the one provider with no static client secret: Apple wants a
|
|
32044
|
-
* short-lived ES256 JWT, which `createAppleProvider` signs from
|
|
32045
|
-
* So `APPLE_CLIENT_SECRET` does not exist, and
|
|
32046
|
-
* together —
|
|
32047
|
-
* why `resolveAuthOptions` configures Apple
|
|
32507
|
+
* short-lived ES256 JWT, which `createAppleProvider` signs from the team id,
|
|
32508
|
+
* key id and private key. So `APPLE_CLIENT_SECRET` does not exist, and
|
|
32509
|
+
* those three are required together — two of them is a provider that
|
|
32510
|
+
* cannot mint a secret, which is why `resolveAuthOptions` configures Apple
|
|
32511
|
+
* only when it has all three.
|
|
32512
|
+
*
|
|
32513
|
+
* Beside them, Apple needs at least one client: `APPLE_CLIENT_ID` (the
|
|
32514
|
+
* Services ID, for web sign-in) and/or `APPLE_BUNDLE_IDS` (comma-separated
|
|
32515
|
+
* bundle ids of the iOS/macOS apps whose native codes are accepted).
|
|
32048
32516
|
*/
|
|
32049
32517
|
APPLE_CLIENT_ID: z$1.string().optional(),
|
|
32518
|
+
APPLE_BUNDLE_IDS: z$1.string().optional(),
|
|
32050
32519
|
APPLE_TEAM_ID: z$1.string().optional(),
|
|
32051
32520
|
APPLE_KEY_ID: z$1.string().optional(),
|
|
32052
32521
|
APPLE_PRIVATE_KEY: z$1.string().optional(),
|
|
@@ -33096,8 +33565,10 @@ function resolveAuthOptions(env, usersCollection) {
|
|
|
33096
33565
|
clientSecret
|
|
33097
33566
|
};
|
|
33098
33567
|
}
|
|
33099
|
-
|
|
33100
|
-
|
|
33568
|
+
const appleBundleIds = (env.APPLE_BUNDLE_IDS ?? "").split(",").map((id) => id.trim()).filter(Boolean);
|
|
33569
|
+
if ((env.APPLE_CLIENT_ID || appleBundleIds.length > 0) && env.APPLE_TEAM_ID && env.APPLE_KEY_ID && env.APPLE_PRIVATE_KEY) auth.apple = {
|
|
33570
|
+
...env.APPLE_CLIENT_ID ? { clientId: env.APPLE_CLIENT_ID } : {},
|
|
33571
|
+
...appleBundleIds.length > 0 ? { bundleIds: appleBundleIds } : {},
|
|
33101
33572
|
teamId: env.APPLE_TEAM_ID,
|
|
33102
33573
|
keyId: env.APPLE_KEY_ID,
|
|
33103
33574
|
privateKey: normalizePemFromEnv(env.APPLE_PRIVATE_KEY)
|
|
@@ -33257,6 +33728,7 @@ var MetricsRegistry = class MetricsRegistry {
|
|
|
33257
33728
|
gauges = /* @__PURE__ */ new Map();
|
|
33258
33729
|
counters = /* @__PURE__ */ new Map();
|
|
33259
33730
|
histograms = /* @__PURE__ */ new Map();
|
|
33731
|
+
renderHooks = [];
|
|
33260
33732
|
startedAt = Date.now();
|
|
33261
33733
|
static labelKey(labels) {
|
|
33262
33734
|
return Object.entries(labels).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => `${k}=${v}`).join(LABEL_SEP);
|
|
@@ -33313,6 +33785,12 @@ var MetricsRegistry = class MetricsRegistry {
|
|
|
33313
33785
|
if (!this.counters.has(key) && this.counters.size >= MAX_SERIES) return;
|
|
33314
33786
|
this.counters.set(key, (this.counters.get(key) ?? 0) + by);
|
|
33315
33787
|
}
|
|
33788
|
+
/** Set a counter whose running total is kept elsewhere. See {@link onRender}. */
|
|
33789
|
+
setCounter(name, value, labels = {}) {
|
|
33790
|
+
const key = MetricsRegistry.namedKey(name, labels);
|
|
33791
|
+
if (!this.counters.has(key) && this.counters.size >= MAX_SERIES) return;
|
|
33792
|
+
this.counters.set(key, value);
|
|
33793
|
+
}
|
|
33316
33794
|
setGauge(name, value, labels = {}) {
|
|
33317
33795
|
const key = MetricsRegistry.namedKey(name, labels);
|
|
33318
33796
|
if (!this.gauges.has(key) && this.gauges.size >= MAX_SERIES) return;
|
|
@@ -33341,6 +33819,13 @@ var MetricsRegistry = class MetricsRegistry {
|
|
|
33341
33819
|
if (bucket === -1) bucket = hist.buckets.length;
|
|
33342
33820
|
hist.counts[bucket] += 1;
|
|
33343
33821
|
}
|
|
33822
|
+
/**
|
|
33823
|
+
* Run `read` before each render, to set numbers another part of the process
|
|
33824
|
+
* keeps. Nothing is paid between scrapes.
|
|
33825
|
+
*/
|
|
33826
|
+
onRender(read) {
|
|
33827
|
+
this.renderHooks.push(read);
|
|
33828
|
+
}
|
|
33344
33829
|
/** Prometheus escaping: backslash, quote and newline, in that order. */
|
|
33345
33830
|
static formatLabels(labels, extra) {
|
|
33346
33831
|
const all = {
|
|
@@ -33363,6 +33848,7 @@ var MetricsRegistry = class MetricsRegistry {
|
|
|
33363
33848
|
return grouped;
|
|
33364
33849
|
}
|
|
33365
33850
|
render() {
|
|
33851
|
+
for (const read of this.renderHooks) read();
|
|
33366
33852
|
const lines = [];
|
|
33367
33853
|
lines.push("# HELP rebase_uptime_seconds Seconds since this runtime started.");
|
|
33368
33854
|
lines.push("# TYPE rebase_uptime_seconds gauge");
|
|
@@ -33589,6 +34075,27 @@ function recordPoolWaits(registry, sources) {
|
|
|
33589
34075
|
}
|
|
33590
34076
|
}
|
|
33591
34077
|
//#endregion
|
|
34078
|
+
//#region src/metrics/realtime.ts
|
|
34079
|
+
var REALTIME_SOCKETS_METRIC = "rebase_realtime_sockets";
|
|
34080
|
+
var REALTIME_CHANNELS_METRIC = "rebase_realtime_channels";
|
|
34081
|
+
var REALTIME_BUS_PUBLISHED_METRIC = "rebase_realtime_bus_frames_published_total";
|
|
34082
|
+
var REALTIME_BUS_SKIPPED_METRIC = "rebase_realtime_bus_frames_skipped_total";
|
|
34083
|
+
/**
|
|
34084
|
+
* Report `provider`'s counts in `registry` at each render. A deployment with no
|
|
34085
|
+
* realtime, or a provider that keeps no counts, emits none of these series.
|
|
34086
|
+
*/
|
|
34087
|
+
function recordRealtimeCounts(registry, provider) {
|
|
34088
|
+
if (!provider?.counts) return;
|
|
34089
|
+
registry.onRender(() => {
|
|
34090
|
+
const counts = provider.counts?.();
|
|
34091
|
+
if (!counts) return;
|
|
34092
|
+
registry.setGauge(REALTIME_SOCKETS_METRIC, counts.sockets);
|
|
34093
|
+
registry.setGauge(REALTIME_CHANNELS_METRIC, counts.channels);
|
|
34094
|
+
for (const [kind, frames] of Object.entries(counts.busFramesPublished)) registry.setCounter(REALTIME_BUS_PUBLISHED_METRIC, frames, { kind });
|
|
34095
|
+
registry.setCounter(REALTIME_BUS_SKIPPED_METRIC, counts.busFramesSkipped);
|
|
34096
|
+
});
|
|
34097
|
+
}
|
|
34098
|
+
//#endregion
|
|
33592
34099
|
//#region src/boot/fetch-bundle.ts
|
|
33593
34100
|
/**
|
|
33594
34101
|
* Fetching a bundle at boot.
|
|
@@ -34508,6 +35015,7 @@ async function bootFromBundle(options = {}) {
|
|
|
34508
35015
|
collectionsDir: bundle.collectionsDir,
|
|
34509
35016
|
functionsDir: bundle.functionsDir,
|
|
34510
35017
|
cronsDir: bundle.cronsDir,
|
|
35018
|
+
requireFilesLoaded: env.REBASE_REQUIRE_FILES_LOADED,
|
|
34511
35019
|
surfaces: runtimeRole.surfaces,
|
|
34512
35020
|
ownership: runtimeRole.ownership,
|
|
34513
35021
|
functionsSelection: runtimeRole.functionsSelection,
|
|
@@ -34571,6 +35079,7 @@ async function bootFromBundle(options = {}) {
|
|
|
34571
35079
|
app.get("/livez", (c) => c.json({ status: "ok" }));
|
|
34572
35080
|
if (metrics) {
|
|
34573
35081
|
if (!env.REBASE_METRICS_TOKEN) logger.warn("Metrics are enabled without REBASE_METRICS_TOKEN — /metrics is readable by anyone who can reach this port. Set a token, or keep the port on a private network.");
|
|
35082
|
+
recordRealtimeCounts(metrics.registry, backend.realtimeService);
|
|
34574
35083
|
app.route("/metrics", createMetricsRoutes(metrics.registry, env.REBASE_METRICS_TOKEN, backend.metricsHistory?.read));
|
|
34575
35084
|
}
|
|
34576
35085
|
if (env.REBASE_SERVE_STATIC) {
|
|
@@ -34798,13 +35307,13 @@ async function runFromBundle(options = {}) {
|
|
|
34798
35307
|
/**
|
|
34799
35308
|
* A configuration problem the project can fix, as opposed to a bug.
|
|
34800
35309
|
*
|
|
34801
|
-
* These
|
|
35310
|
+
* These have a message that IS the answer — it names the file, the key and
|
|
34802
35311
|
* the fix — so the fatal path prints it and nothing else. The reader is looking
|
|
34803
35312
|
* at a process that will not start; a stack through the framework's own frames
|
|
34804
35313
|
* is noise when the answer is "two of your collections claim the same slug".
|
|
34805
35314
|
*/
|
|
34806
35315
|
function isConfigurationFailure(err) {
|
|
34807
|
-
return err instanceof BundleError || err instanceof RoleConfigurationError || err instanceof FunctionSelectionError || err instanceof CollectionConfigError;
|
|
35316
|
+
return err instanceof BundleError || err instanceof RoleConfigurationError || err instanceof FunctionSelectionError || err instanceof CollectionConfigError || err instanceof FilesFailedToLoadError;
|
|
34808
35317
|
}
|
|
34809
35318
|
/**
|
|
34810
35319
|
* Say why the boot failed, in the form the reader can act on.
|
|
@@ -34952,6 +35461,6 @@ function warnOnUnusableBundleShape(bundle) {
|
|
|
34952
35461
|
logger.warn(`This bundle declares collections at "${bundle.manifest.entry.collections}", but that directory did not resolve, so no collections were loaded and no tables will be created. Rebuild with \`rebase build\`.`);
|
|
34953
35462
|
}
|
|
34954
35463
|
//#endregion
|
|
34955
|
-
export { ACCOUNT_SCOPED_STORAGE_BASES, ApiError, BATCH_REF_KEY, BlockedUrlError, BundleError, CONCURRENT_DDL_SQLSTATES, CORS_EXPOSED_HEADERS, CollectionConfigError, CronScheduler, DATABASE_UNAVAILABLE_MESSAGE, DEFAULT_DRIVER_ID, DEFAULT_MAX_FILE_SIZE, DEFAULT_REFERRER_POLICY, DEFAULT_STORAGE_ID, DOCUMENT_MIME_TYPES, DefaultDriverRegistry, DefaultStorageRegistry, ETAG_HEADER, FIELD_OPERATORS, GCSStorageController, IF_MATCH_HEADER, IMAGE_MIME_TYPES, LocalStorageController, MetricsRegistry, RUNTIME_BUNDLE_MOUNT, RUNTIME_DEFAULT_MAX_BODY_SIZE, RUNTIME_HEALTH_PATH, RUNTIME_LIVENESS_PATH, RUNTIME_MIN_TERMINATION_GRACE_SECONDS, RUNTIME_PRESTOP_DRAIN_SECONDS, RUNTIME_PROBE_PATHS, RUNTIME_STARTUP_BUDGET_SECONDS, RawHtml, S3StorageController, SMTPEmailService, StoragePolicyError, TOPOLOGY_ENV_VARS, TransformCache, TusHandler, UPLOAD_COLLECTION_FIELD, UPLOAD_PROPERTY_FIELD, UnknownStorageSourceError, WEBHOOK_DELIVERY_TASK, WebhookDispatcher, _resetRebaseMock, _setRebaseMock, accessModelFromCollections, activeDevEmailSink, applyCollectionDefaults, assertAllowedOutboundUrl, assertCollectionConfigs, assertDistinctSuffixes, assertEmailLinkBases, assertEveryKindBindable, assertFieldOpsValid, assertIfMatch, assertNestedWriteAllowed, assertNoFieldOpsOnCreate, assertNoUserUpsert, assertQueryFieldsReadable, assertUploadWithinPathLimits, assertUploadWithinPropertyLimits, assertUserCreationBodyValid, assertWriteRequestValid, authJwt, authRoles, authUid, backupStorageFromEnv, blockedAddressReason, bootFromBundle, callerScopes, classifySurface, cleanupDevPortFile, clearActiveDevEmailSink, compileStoragePolicies, composeCallbacks, configureAccess, configureJwt, createAppleProvider, createBackupLinkRoutes, createBackupRoutes, createBitbucketProvider, createBuiltinAuthAdapter, createCallContext, createContractRoutes, createCronRoutes, createCronStore, createCustomAuthAdapter, createDdlBootstrapper, createDevEmailSink, createDiscordProvider, createEmailService, createFacebookProvider, createFunctionRoutes, createGitHubProvider, createGitLabProvider, createGoogleProvider, createHistoryRoutes, createJobQueue, createJobStore, createJwksRoutes, createJwtService, createLinkedinProvider, createMetricsMiddleware, createMetricsRoutes, createMicrosoftProvider, createRebaseBackend, createRlsAudit, createSlackProvider, createSourceBundle, createSpotifyProvider, createStorageController, createStorageRoutes, createTwitterProvider, createUnconfiguredEmailService, createUploadConstraintResolver, createUploadPathResolver, createUserThroughAuthCollection, decideImpersonation, declareCrons, declaredErrorAnswer, declaredUniqueTargets, defaultBackoff, defineCron, defineFunction, devEmailSinkFor, drainBackgroundWork, envSuffixForKey, errorHandler, escapeHtml, extractLinks, extractUserFromToken, fileTokenAuth, findCollectionConfigProblems, generateSecurePassword, getAccessModel, getApiKey, getDriver, getEmailChangeNoticeTemplate, getEmailChangeTemplate, getEmailOtpTemplate, getEmailVerificationTemplate, getEnv, getJwks, getMagicLinkTemplate, getPasswordResetTemplate, getRequestId, getRoles, getUser, getUserId, getUserInvitationTemplate, getWelcomeEmailTemplate, hasAsymmetricSigningKey, hasFieldOps, hasRole, hasScope, hashPassword, html, httpMethodToOperation, identityResolved, implicitDeclaration, initializeDataSource, initializeDataSources, initializeRebaseBackend, installShutdownHandlers, installUnhandledRejectionHandler, isAcceptedFile, isAdmin, isApiKeyToken, isAuthAdapter, isAuthenticated, isConcurrentDdlRace, isDataException, isDatabaseAdapter, isDatabaseUnreachable, isDuplicateObjectRace, isLocalhostOrigin, isNodeRuntime, isTopologyEnvVar, isTransformableImage, isUncountedPath, lazyResource, listBackupObjects, listenWithPortRetry, loadBootEnv, loadBundle, loadBundleConfigExports, loadBundleSchema, loadCollectionsFromDirectory, loadCronJobsFromDirectory, loadCronJobsWithDiagnostics, loadCrons, loadEnv, loadFunctions, loadFunctionsFromDirectory, loadFunctionsWithDiagnostics, loadUsersCollection, logger, looksLikeFieldOp, oauthCodeFlowSchema, optionalAuth, overridableSecurityHeaders, parseBackupDestination, parseBackupTimestamp, parseFieldOp, parseTransformOptions, pendingBackgroundWork, pkceTokenParams, providerVerifiedEmail, queryTokenAuth, raw, rawQueryLoggingEnabled, readBackupBytes, readBundleManifest, readUploadPropertyContext, realtimeSocketPath, rebase, refuseUnhonouredImpersonation, registerDevEmailSink, registerResourceResolver, reportSimulatedContext, requireAdmin, requireAuth, requireDriver, requireEnv, requireRole, requireScope, resolveApiKey, resolveAuthHooks, resolveAuthOptions, resolveBatchRefs, resolveConflictTarget, resolveCorsOrigin, resolveDataSources, resolveEmailBranding, resolveEmailLinkBase, resolveEmailOptions, resolveRequireAuth, resolveStorageAccessControl, resolveStorageBackend, resolveStorageSources, resourceResolver, resourceResolvers, rowETag, runFromBundle, runtimeKey, safeCompare, schemaDriftRemedy, serveSPA, setDefaultBackend, setLogOutput, splitFieldOps, summarize as summarizeRlsScan, transformImage, tryVerifyOidcIdToken, unbindableKinds, unknownKeyPolicyFromEnv, validateApiKey, validateCronExpression, validatePasswordStrength, verifyCredential, verifyOidcIdToken, verifyPassword, versionProperty, waitUntil, z };
|
|
35464
|
+
export { ACCOUNT_SCOPED_STORAGE_BASES, ApiError, BATCH_REF_KEY, BlockedUrlError, BundleError, CONCURRENT_DDL_SQLSTATES, CORS_EXPOSED_HEADERS, CollectionConfigError, CronScheduler, DATABASE_UNAVAILABLE_MESSAGE, DEFAULT_DRIVER_ID, DEFAULT_MAX_FILE_SIZE, DEFAULT_REFERRER_POLICY, DEFAULT_STORAGE_ID, DOCUMENT_MIME_TYPES, DefaultDriverRegistry, DefaultStorageRegistry, ETAG_HEADER, FIELD_OPERATORS, GCSStorageController, IF_MATCH_HEADER, IMAGE_MIME_TYPES, LocalStorageController, MetricsRegistry, ObjectTooLargeError, PermanentJobError, RUNTIME_BUNDLE_MOUNT, RUNTIME_DEFAULT_MAX_BODY_SIZE, RUNTIME_HEALTH_PATH, RUNTIME_LIVENESS_PATH, RUNTIME_MIN_TERMINATION_GRACE_SECONDS, RUNTIME_PRESTOP_DRAIN_SECONDS, RUNTIME_PROBE_PATHS, RUNTIME_STARTUP_BUDGET_SECONDS, RawHtml, S3StorageController, SMTPEmailService, StoragePolicyError, TOPOLOGY_ENV_VARS, TransformCache, TusHandler, UPLOAD_COLLECTION_FIELD, UPLOAD_PROPERTY_FIELD, UnknownStorageSourceError, WEBHOOK_DELIVERY_TASK, WebhookDispatcher, _resetRebaseMock, _setRebaseMock, accessModelFromCollections, activeDevEmailSink, applyCollectionDefaults, assertAllowedOutboundUrl, assertCollectionConfigs, assertDistinctSuffixes, assertEmailLinkBases, assertEveryKindBindable, assertFieldOpsValid, assertIfMatch, assertNestedWriteAllowed, assertNoFieldOpsOnCreate, assertNoUserUpsert, assertQueryFieldsReadable, assertUploadWithinPathLimits, assertUploadWithinPropertyLimits, assertUserCreationBodyValid, assertWriteRequestValid, authJwt, authRoles, authUid, backupStorageFromEnv, blockedAddressReason, bootFromBundle, callerScopes, classifySurface, cleanupDevPortFile, clearActiveDevEmailSink, compileStoragePolicies, composeCallbacks, configureAccess, configureJwt, createAppleProvider, createBackupLinkRoutes, createBackupRoutes, createBitbucketProvider, createBuiltinAuthAdapter, createCallContext, createContractRoutes, createCronRoutes, createCronStore, createCustomAuthAdapter, createDdlBootstrapper, createDevEmailSink, createDiscordProvider, createEmailService, createFacebookProvider, createFunctionRoutes, createGitHubProvider, createGitLabProvider, createGoogleProvider, createHistoryRoutes, createJobQueue, createJobStore, createJwksRoutes, createJwtService, createLinkedinProvider, createMetricsMiddleware, createMetricsRoutes, createMicrosoftProvider, createRebaseBackend, createRlsAudit, createSlackProvider, createSourceBundle, createSpotifyProvider, createStorageController, createStorageRoutes, createTwitterProvider, createUnconfiguredEmailService, createUploadConstraintResolver, createUploadPathResolver, createUserThroughAuthCollection, decideImpersonation, declareCrons, declaredErrorAnswer, declaredUniqueTargets, defaultBackoff, defineCron, defineFunction, devEmailSinkFor, drainBackgroundWork, envSuffixForKey, errorHandler, escapeHtml, extractLinks, extractUserFromToken, fileTokenAuth, findCollectionConfigProblems, generateSecurePassword, getAccessModel, getApiKey, getDriver, getEmailChangeNoticeTemplate, getEmailChangeTemplate, getEmailOtpTemplate, getEmailVerificationTemplate, getEnv, getJwks, getMagicLinkTemplate, getPasswordResetTemplate, getRequestId, getRoles, getUser, getUserId, getUserInvitationTemplate, getWelcomeEmailTemplate, hasAsymmetricSigningKey, hasFieldOps, hasRole, hasScope, hashPassword, html, httpMethodToOperation, identityResolved, implicitDeclaration, initializeDataSource, initializeDataSources, initializeRebaseBackend, installShutdownHandlers, installUnhandledRejectionHandler, isAcceptedFile, isAdmin, isApiKeyToken, isAuthAdapter, isAuthenticated, isConcurrentDdlRace, isDataException, isDatabaseAdapter, isDatabaseUnreachable, isDuplicateObjectRace, isLocalhostOrigin, isNodeRuntime, isTopologyEnvVar, isTransformableImage, isUncountedPath, lazyResource, listBackupObjects, listenWithPortRetry, loadBootEnv, loadBundle, loadBundleConfigExports, loadBundleSchema, loadCollectionsFromDirectory, loadCronJobsFromDirectory, loadCronJobsWithDiagnostics, loadCrons, loadEnv, loadFunctions, loadFunctionsFromDirectory, loadFunctionsWithDiagnostics, loadUsersCollection, logger, looksLikeFieldOp, oauthCodeFlowSchema, optionalAuth, overridableSecurityHeaders, parseBackupDestination, parseBackupTimestamp, parseFieldOp, parseTransformOptions, pendingBackgroundWork, pkceTokenParams, providerVerifiedEmail, queryTokenAuth, raw, rawQueryLoggingEnabled, readBackupBytes, readBundleManifest, readUploadPropertyContext, realtimeSocketPath, rebase, refuseUnhonouredImpersonation, registerDevEmailSink, registerResourceResolver, reportSimulatedContext, requireAdmin, requireAuth, requireDriver, requireEnv, requireRole, requireScope, resolveApiKey, resolveAuthHooks, resolveAuthOptions, resolveBatchRefs, resolveConflictTarget, resolveCorsOrigin, resolveDataSources, resolveEmailBranding, resolveEmailLinkBase, resolveEmailOptions, resolveRequireAuth, resolveStorageAccessControl, resolveStorageBackend, resolveStorageSources, resourceResolver, resourceResolvers, rowETag, runFromBundle, runtimeKey, safeCompare, schemaDriftRemedy, serveSPA, setDefaultBackend, setLogOutput, splitFieldOps, summarize as summarizeRlsScan, transformImage, tryVerifyOidcIdToken, unbindableKinds, unknownKeyPolicyFromEnv, validateApiKey, validateCronExpression, validatePasswordStrength, verifyCredential, verifyOidcIdToken, verifyPassword, versionProperty, waitUntil, z };
|
|
34956
35465
|
|
|
34957
35466
|
//# sourceMappingURL=index.es.js.map
|