@powerhousedao/reactor-api 6.2.3-dev.78 → 6.2.3-dev.79

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. package/dist/{base-document-models-By4P20-z.mjs → base-document-models-ux7TZ9X3.mjs} +5 -5
  2. package/dist/{base-document-models-By4P20-z.mjs.map → base-document-models-ux7TZ9X3.mjs.map} +1 -1
  3. package/dist/index.d.mts +843 -780
  4. package/dist/index.d.mts.map +1 -1
  5. package/dist/index.mjs +417 -359
  6. package/dist/index.mjs.map +1 -1
  7. package/dist/{package-subgraph-check-6tK9LMg1.mjs → package-subgraph-check-BGfeyfnc.mjs} +4 -4
  8. package/dist/{package-subgraph-check-6tK9LMg1.mjs.map → package-subgraph-check-BGfeyfnc.mjs.map} +1 -1
  9. package/dist/{pglite-node-DOFZDYCK.mjs → pglite-node-DGms6Ssa.mjs} +18 -5
  10. package/dist/pglite-node-DGms6Ssa.mjs.map +1 -0
  11. package/dist/src/graphql/subgraph-types.mjs +1 -1
  12. package/dist/src/packages/vite-loader.d.mts +2 -2
  13. package/dist/src/packages/vite-loader.d.mts.map +1 -1
  14. package/dist/src/packages/vite-loader.mjs +29 -10
  15. package/dist/src/packages/vite-loader.mjs.map +1 -1
  16. package/dist/src/pglite/pglite-node.d.mts +5 -0
  17. package/dist/src/pglite/pglite-node.d.mts.map +1 -1
  18. package/dist/src/pglite/pglite-node.mjs +4 -4
  19. package/dist/{subgraph-extraction-zUDn2zX_.mjs → subgraph-extraction-BYKOycxo.mjs} +18 -4
  20. package/dist/subgraph-extraction-BYKOycxo.mjs.map +1 -0
  21. package/dist/{types-CCI5IDgT.d.mts → types-BEpxtyKW.d.mts} +2 -2
  22. package/dist/{types-CCI5IDgT.d.mts.map → types-BEpxtyKW.d.mts.map} +1 -1
  23. package/package.json +13 -13
  24. package/dist/pglite-node-DOFZDYCK.mjs.map +0 -1
  25. package/dist/subgraph-extraction-zUDn2zX_.mjs.map +0 -1
package/dist/index.mjs CHANGED
@@ -1,21 +1,22 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="d978d340-82ad-56d2-8827-0daf9ed3bf67")}catch(e){}}();
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="ef156955-2531-5a13-8ece-12e68bf6d841")}catch(e){}}();
3
3
  import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.mjs";
4
- import { A as CanonicalDocumentIdResolutionError, C as loadSubgraphs, D as RequestClientBinder, E as callerSubject, F as AuthEvaluationUnsupportedError, I as AuthenticationRequiredError, L as ForbiddenError, M as AuthorizationPolicy, N as AuthorizedDocumentHandle, O as AuthService, P as createAuthorizationService, R as MalformedStoredOperationError, S as loadProcessors, T as BaseSubgraph, _ as PACKAGE_MODULE_FAILED, c as piecesFromListModule, d as buildGraphQlDriveDocument, f as buildGraphqlOperation, g as runDetached, h as reportFailure, i as PIECE_SOURCE_LIST, j as createCanonicalDocumentIdResolver, k as createCredentialInvalidator, l as extractDocumentModels, m as isSubgraphClass, o as pieceListLocation, p as buildGraphqlOperations, s as piecesFromCdnList, t as extractSubgraphs, u as buildGraphQlDocument, v as debounce, w as manifestDeclaredSubgraphs, x as loadDocumentModels, y as extractUpgradeManifests, z as RefusalNotRecordedError } from "./subgraph-extraction-zUDn2zX_.mjs";
5
- import { A as getDocumentModelSubgraphName, C as createMergedSchema, D as generateDocumentModelSchema, E as findSubgraphTypeCollisions, F as reservedTypeNamesTaken, I as typeDefinitionNames, L as schema_default$1, M as getGeneratedDocumentModelTypes, N as hasOperationSchemas, O as generatedTypesOf, P as reservedTypeNames, S as buildSubgraphSchemaModule, T as documentModelSubgraphTypes, _ as describeOwnershipConflicts, a as inspectionAdminTypeDefs, b as assembleSubgraphTypeDefs, c as HOST_ORIGIN, d as byClaimPriority, f as decideAdmission, g as collectSubgraphClaims, h as supergraphClaimLosers, i as inspectionTypeDefs, j as getDocumentModelTypeDefs, k as getDocumentModelSchemaName, l as RegistrationOrder, m as documentModelSubgraphSources, n as systemTypeDefs, o as CORE_ORIGIN, p as describeOrigin, r as schema_default$2, s as DOCUMENT_MODEL_ORIGIN, t as baseDocumentModels, u as admitDocumentModels, v as DocumentModelSchemaCache, w as createSchema, x as buildDocumentModelSchema, y as SubgraphTypeCollisionError } from "./base-document-models-By4P20-z.mjs";
4
+ import { A as CanonicalDocumentIdResolutionError, C as loadSubgraphs, D as RequestClientBinder, E as callerSubject, F as AuthEvaluationUnsupportedError, I as AuthenticationRequiredError, L as ForbiddenError, M as AuthorizationPolicy, N as AuthorizedDocumentHandle, O as AuthService, P as createAuthorizationService, R as MalformedStoredOperationError, S as loadProcessors, T as BaseSubgraph, _ as PACKAGE_MODULE_FAILED, c as piecesFromListModule, d as buildGraphQlDriveDocument, f as buildGraphqlOperation, g as runDetached, h as reportFailure, i as PIECE_SOURCE_LIST, j as createCanonicalDocumentIdResolver, k as createCredentialInvalidator, l as extractDocumentModels, m as isSubgraphClass, o as pieceListLocation, p as buildGraphqlOperations, s as piecesFromCdnList, t as extractSubgraphs, u as buildGraphQlDocument, v as debounce, w as manifestDeclaredSubgraphs, x as loadDocumentModels, y as extractUpgradeManifests, z as RefusalNotRecordedError } from "./subgraph-extraction-BYKOycxo.mjs";
5
+ import { A as getDocumentModelSubgraphName, C as createMergedSchema, D as generateDocumentModelSchema, E as findSubgraphTypeCollisions, F as reservedTypeNamesTaken, I as typeDefinitionNames, L as schema_default$1, M as getGeneratedDocumentModelTypes, N as hasOperationSchemas, O as generatedTypesOf, P as reservedTypeNames, S as buildSubgraphSchemaModule, T as documentModelSubgraphTypes, _ as describeOwnershipConflicts, a as inspectionAdminTypeDefs, b as assembleSubgraphTypeDefs, c as HOST_ORIGIN, d as byClaimPriority, f as decideAdmission, g as collectSubgraphClaims, h as supergraphClaimLosers, i as inspectionTypeDefs, j as getDocumentModelTypeDefs, k as getDocumentModelSchemaName, l as RegistrationOrder, m as documentModelSubgraphSources, n as systemTypeDefs, o as CORE_ORIGIN, p as describeOrigin, r as schema_default$2, s as DOCUMENT_MODEL_ORIGIN, t as baseDocumentModels, u as admitDocumentModels, v as DocumentModelSchemaCache, w as createSchema, x as buildDocumentModelSchema, y as SubgraphTypeCollisionError } from "./base-document-models-ux7TZ9X3.mjs";
6
6
  import { n as createApolloFetchHandler } from "./adapter-gateway-apollo-D-EdZ4e-.mjs";
7
- import { a as resolvePgliteMaintenance, i as resolvePgliteFsync, m as PGLITE_UTC_PARSERS, r as createDurableNodeFs } from "./error-info-BaEL50f5.mjs";
8
- import { f as openCurrentPgliteForVerify, p as preparePgliteDataDir } from "./pglite-node-DOFZDYCK.mjs";
7
+ import { a as resolvePgliteMaintenance, m as PGLITE_UTC_PARSERS, r as createDurableNodeFs } from "./error-info-BaEL50f5.mjs";
8
+ import { h as preparePgliteDataDir, m as openCurrentPgliteForVerify } from "./pglite-node-DGms6Ssa.mjs";
9
9
  import { findPackageJSON, isBuiltin } from "node:module";
10
+ import { AttachmentBuilder, AttachmentNotFound, AttachmentReferenceIndexBuilder, createRef, createS3AttachmentBackend, parseAttachmentStorageConfig, parseRef, validateReserveMetadata } from "@powerhousedao/reactor-attachments";
11
+ import { ConsoleLogger, childLogger } from "document-model";
10
12
  import { AnalyticsQueryEngine } from "@powerhousedao/analytics-engine-core";
11
13
  import { AnalyticsModel, AnalyticsResolvers, typedefs } from "@powerhousedao/analytics-engine-graphql";
12
14
  import { gql } from "graphql-tag";
13
15
  import { GraphQLError, Kind, OperationTypeNode, buildASTSchema, getOperationAST, isTypeDefinitionNode, isTypeExtensionNode, parse, print, validateSchema, valueFromASTUntyped, visit } from "graphql";
14
16
  import { AuthEnforcementDisabledError, BareReadGate, BatchJobFailedError, CATCH_UP_LOAD_WINDOW_MS, ChannelError, ChannelErrorSource, DEFAULT_DRIVE_CONTAINER_TYPES, DriveCollectionId, DriveInspection, FacadeWriteClient, InvalidDeadLetterCursorError, JOB_NOT_FOUND_ERROR_NAME, JobStatus, ModelReadGate, PropagationMode as PropagationMode$1, READ_ONLY_ACCESS, SyncOperation, SyncScopeGate, consolidateSyncOperations, createReactorHostModuleBase, createReactorInspector, driveIdFromUrl, envelopesToSyncOperations, isCatchUpLevel, parseDriveUrl, readDecisionModel, supportsPurgeRefusals, syncOperationErrorType, toWireCatchUpPriority, toWireDeadLetter, toWireQueueState, warnOnce } from "@powerhousedao/reactor";
15
- import { deserializeSignature, readPeerManifest, serializeSignature, setName, withSignaturePolicy } from "@powerhousedao/shared/document-model";
17
+ import { deserializeSignature, readPeerManifest, serializeSignature, setName } from "@powerhousedao/shared/document-model";
16
18
  import { fetchDelegationCredential, resolveSwitchboardEndpoint } from "@renown/sdk";
17
19
  import { AsyncLocalStorage } from "node:async_hooks";
18
- import { ConsoleLogger, childLogger } from "document-model";
19
20
  import path, { isAbsolute, join } from "node:path";
20
21
  import { match } from "path-to-regexp";
21
22
  import posix from "node:path/posix";
@@ -37,20 +38,18 @@ import { useServer } from "graphql-ws/use/ws";
37
38
  import { createHandler } from "graphql-sse/lib/use/fetch";
38
39
  import lzString from "lz-string";
39
40
  import { PubSub, withFilter } from "graphql-subscriptions";
40
- import dotenv from "dotenv";
41
41
  import { buildTreeUrl } from "@powerhousedao/shared";
42
42
  import { resolvePhDir } from "@powerhousedao/shared/clis/ph-dir";
43
43
  import { init, parse as parse$1 } from "es-module-lexer";
44
44
  import { chmod, lstat, mkdir, readFile, readdir, readlink, realpath, rename, rm, stat, symlink, writeFile } from "node:fs/promises";
45
45
  import { getConfig } from "@powerhousedao/config/node";
46
+ import { createRelationalDb, getCodegenStatusRegistry } from "@powerhousedao/shared/processors";
46
47
  import EventEmitter from "node:events";
47
48
  import { PostgresAnalyticsStore } from "@powerhousedao/analytics-engine-pg";
48
- import { AttachmentBuilder, AttachmentNotFound, AttachmentReferenceIndexBuilder, createRef, createS3AttachmentBackend, parseAttachmentStorageConfig, parseRef, validateReserveMetadata } from "@powerhousedao/reactor-attachments";
49
49
  import { createAttachmentClient } from "@powerhousedao/reactor-attachments/client";
50
50
  import { setupMcpServer } from "@powerhousedao/reactor-mcp";
51
51
  import { tmpdir } from "node:os";
52
52
  import { WebSocketServer } from "ws";
53
- import { createRelationalDb } from "@powerhousedao/shared/processors";
54
53
  import { isAttachmentHash, readGateAllowsAttachmentRead, scopeGateAllowsAttachmentRead } from "@powerhousedao/reactor-attachments/replication";
55
54
  import { Kysely, Migrator, sql } from "kysely";
56
55
  import { PGlite } from "@electric-sql/pglite";
@@ -58,6 +57,306 @@ import { NodeFS } from "@electric-sql/pglite/nodefs";
58
57
  import knex from "knex";
59
58
  import ClientPgLite from "knex-pglite";
60
59
  import { KyselyKnexDialect, PGColdDialect } from "kysely-knex";
60
+ //#region src/graphql/gateway/types.ts
61
+ /** No authenticated caller resolved, and REQUIRE_AUTHENTICATED_CALLER wants one. */
62
+ const WS_CLOSE_REASON_AUTHENTICATION_REQUIRED = "authentication-required";
63
+ /** A bearer was sent and could not be verified. */
64
+ const WS_CLOSE_REASON_BEARER_REJECTED = "bearer-rejected";
65
+ /** An admitted connection's credential was revoked or no longer verifies. */
66
+ const WS_CLOSE_REASON_CREDENTIAL_REVOKED = "credential-revoked";
67
+ /** Every reason a refusal closes with, for a client matching on the set. */
68
+ const WS_AUTH_CLOSE_REASONS = [
69
+ WS_CLOSE_REASON_AUTHENTICATION_REQUIRED,
70
+ WS_CLOSE_REASON_BEARER_REJECTED,
71
+ WS_CLOSE_REASON_CREDENTIAL_REVOKED
72
+ ];
73
+ //#endregion
74
+ //#region src/graphql/ws-credential-monitor.ts
75
+ /** Default interval between credential re-checks of open WebSockets. */
76
+ const DEFAULT_WS_CREDENTIAL_RECHECK_INTERVAL_MS = 6e4;
77
+ /**
78
+ * Re-verifies the credentials of authenticated WebSocket connections.
79
+ *
80
+ * A WebSocket is authenticated once, at `ConnectionInit`, so a credential
81
+ * revoked afterwards would otherwise keep every subscription it opened alive
82
+ * for as long as the socket stays up. The monitor re-checks each tracked
83
+ * connection on an interval and, at once, the connections of an identity whose
84
+ * credential a package invalidated; a connection whose credential no longer
85
+ * verifies is closed 4403 with {@link WS_CLOSE_REASON_CREDENTIAL_REVOKED}.
86
+ *
87
+ * A check that throws (a verifier outage) leaves the connection open: admission
88
+ * fails closed on the next connect, but an outage should not drop every live
89
+ * subscription at once.
90
+ */
91
+ var WsCredentialMonitor = class {
92
+ #connections = /* @__PURE__ */ new Map();
93
+ #options;
94
+ #timer;
95
+ #unsubscribe;
96
+ #sweeping = false;
97
+ constructor(options) {
98
+ this.#options = options;
99
+ }
100
+ get size() {
101
+ return this.#connections.size;
102
+ }
103
+ /** Begin the periodic sweep and listen for invalidations. Idempotent. */
104
+ start() {
105
+ this.#unsubscribe ??= this.#options.authService.onCredentialInvalidated((invalidation) => {
106
+ this.recheck(invalidation);
107
+ });
108
+ if (this.#options.intervalMs > 0 && !this.#timer) {
109
+ this.#timer = setInterval(() => {
110
+ if (this.#sweeping) return;
111
+ this.#sweeping = true;
112
+ this.recheck().finally(() => {
113
+ this.#sweeping = false;
114
+ });
115
+ }, this.#options.intervalMs);
116
+ this.#timer.unref?.();
117
+ }
118
+ }
119
+ dispose() {
120
+ if (this.#timer) clearInterval(this.#timer);
121
+ this.#timer = void 0;
122
+ this.#unsubscribe?.();
123
+ this.#unsubscribe = void 0;
124
+ this.#connections.clear();
125
+ }
126
+ /** Track an admitted, authenticated connection until its socket closes. */
127
+ track(connection, user) {
128
+ const { socket } = connection;
129
+ this.#connections.set(connection, {
130
+ user,
131
+ socket
132
+ });
133
+ socket?.once?.("close", () => {
134
+ this.#connections.delete(connection);
135
+ });
136
+ }
137
+ /**
138
+ * Re-verify tracked connections (those matching `filter`, or all) and close
139
+ * the ones whose credential no longer holds. Resolves to the number closed.
140
+ */
141
+ async recheck(filter) {
142
+ const targets = [...this.#connections].filter(([, tracked]) => !filter || matches(tracked.user, filter));
143
+ let closed = 0;
144
+ await Promise.all(targets.map(async ([connection, tracked]) => {
145
+ let valid;
146
+ try {
147
+ valid = await this.#options.authService.isCredentialValid(tracked.user);
148
+ } catch (error) {
149
+ this.#options.logger.warn("Could not re-verify the credential of a WebSocket connection; keeping it open: @error", error instanceof Error ? error.message : error);
150
+ return;
151
+ }
152
+ if (valid || !this.#connections.has(connection)) return;
153
+ this.#connections.delete(connection);
154
+ this.#options.logger.info("Closing WebSocket connection of @address: credential no longer valid", tracked.user.address);
155
+ tracked.socket?.close?.(4403, WS_CLOSE_REASON_CREDENTIAL_REVOKED);
156
+ closed++;
157
+ }));
158
+ return closed;
159
+ }
160
+ };
161
+ function matches(user, filter) {
162
+ return user.address.toLowerCase() === filter.address && (filter.chainId === void 0 || user.chainId === filter.chainId) && (filter.appDid === void 0 || user.appKey === filter.appDid);
163
+ }
164
+ /** Parse `WS_CREDENTIAL_RECHECK_INTERVAL_MS`; invalid values warn and fall back to the default. */
165
+ function resolveWsCredentialRecheckIntervalMs(raw, logger) {
166
+ if (raw === void 0) return DEFAULT_WS_CREDENTIAL_RECHECK_INTERVAL_MS;
167
+ const parsed = Number(raw);
168
+ if (raw.trim() !== "" && Number.isFinite(parsed) && parsed >= 0) return parsed;
169
+ logger.warn(`Ignoring invalid WS_CREDENTIAL_RECHECK_INTERVAL_MS="${raw}" (expected a non-negative number of milliseconds; 0 disables the periodic re-check) — using ${DEFAULT_WS_CREDENTIAL_RECHECK_INTERVAL_MS}`);
170
+ return DEFAULT_WS_CREDENTIAL_RECHECK_INTERVAL_MS;
171
+ }
172
+ //#endregion
173
+ //#region src/services/permission-cache.ts
174
+ /**
175
+ * Everything an authorization decision reads about one document: its
176
+ * protection flag (the configured default when it has no protection row), its
177
+ * owner, the users' grant levels and the users granted each operation.
178
+ * Addresses are stored lowercase, as the permission service writes them.
179
+ */
180
+ var DocumentPermissionSnapshot = class {
181
+ documentId;
182
+ isProtected;
183
+ ownerAddress;
184
+ grants;
185
+ operationGrants;
186
+ constructor(documentId, isProtected, ownerAddress, grants, operationGrants) {
187
+ this.documentId = documentId;
188
+ this.isProtected = isProtected;
189
+ this.ownerAddress = ownerAddress;
190
+ this.grants = grants;
191
+ this.operationGrants = operationGrants;
192
+ }
193
+ grantLevel(userAddress) {
194
+ return this.grants.get(userAddress.toLowerCase()) ?? null;
195
+ }
196
+ isOperationRestricted(operationType) {
197
+ return (this.operationGrants.get(operationType)?.size ?? 0) > 0;
198
+ }
199
+ hasOperationGrant(operationType, userAddress) {
200
+ return this.operationGrants.get(operationType)?.has(userAddress.toLowerCase()) ?? false;
201
+ }
202
+ };
203
+ const DEFAULT_PERMISSION_CACHE_TTL_MS = 3e4;
204
+ const DEFAULT_PERMISSION_CACHE_OPTIONS = {
205
+ ttlMs: DEFAULT_PERMISSION_CACHE_TTL_MS,
206
+ maxEntries: 1e4,
207
+ now: () => Date.now()
208
+ };
209
+ var PermissionCacheEntry = class {
210
+ snapshot;
211
+ expiresAt;
212
+ constructor(snapshot, expiresAt) {
213
+ this.snapshot = snapshot;
214
+ this.expiresAt = expiresAt;
215
+ }
216
+ };
217
+ /**
218
+ * Per-process cache of document permission snapshots, keyed by document id.
219
+ *
220
+ * Filled on miss from the store, invalidated by the permission service after
221
+ * each of its own writes, and expired after `ttlMs` as the safety net for
222
+ * writes made by another process (another switchboard instance on the same
223
+ * database) until cross-instance invalidation exists.
224
+ *
225
+ * A load that overlaps an invalidation still answers its caller but is not
226
+ * stored, so a read that started before a write commits cannot repopulate
227
+ * the cache with the pre-write rows.
228
+ */
229
+ var PermissionCache = class {
230
+ #load;
231
+ #options;
232
+ #entries = /* @__PURE__ */ new Map();
233
+ #epoch = 0;
234
+ constructor(load, options = DEFAULT_PERMISSION_CACHE_OPTIONS) {
235
+ this.#load = load;
236
+ this.#options = options;
237
+ }
238
+ get size() {
239
+ return this.#entries.size;
240
+ }
241
+ async get(documentId) {
242
+ return (await this.getMany([documentId])).get(documentId);
243
+ }
244
+ /** Snapshots for every id, loading the missing and expired ones in one batch. */
245
+ async getMany(documentIds) {
246
+ const now = this.#options.now();
247
+ const result = /* @__PURE__ */ new Map();
248
+ const missing = [];
249
+ for (const documentId of new Set(documentIds)) {
250
+ const entry = this.#entries.get(documentId);
251
+ if (entry && entry.expiresAt > now) {
252
+ this.#entries.delete(documentId);
253
+ this.#entries.set(documentId, entry);
254
+ result.set(documentId, entry.snapshot);
255
+ } else missing.push(documentId);
256
+ }
257
+ if (missing.length === 0) return result;
258
+ const epoch = this.#epoch;
259
+ const loaded = await this.#load(missing);
260
+ const storable = this.#options.ttlMs > 0 && epoch === this.#epoch;
261
+ const expiresAt = this.#options.now() + this.#options.ttlMs;
262
+ for (const documentId of missing) {
263
+ const snapshot = loaded.get(documentId);
264
+ if (!snapshot) throw new Error(`Permission snapshot loader returned no snapshot for ${documentId}`);
265
+ result.set(documentId, snapshot);
266
+ if (storable) this.#store(documentId, new PermissionCacheEntry(snapshot, expiresAt));
267
+ }
268
+ return result;
269
+ }
270
+ invalidate(documentId) {
271
+ this.#epoch++;
272
+ this.#entries.delete(documentId);
273
+ }
274
+ clear() {
275
+ this.#epoch++;
276
+ this.#entries.clear();
277
+ }
278
+ #store(documentId, entry) {
279
+ this.#entries.delete(documentId);
280
+ while (this.#entries.size >= this.#options.maxEntries) {
281
+ const oldest = this.#entries.keys().next();
282
+ if (oldest.done) break;
283
+ this.#entries.delete(oldest.value);
284
+ }
285
+ this.#entries.set(documentId, entry);
286
+ }
287
+ };
288
+ //#endregion
289
+ //#region src/api-config.ts
290
+ const defaultLogger$1 = childLogger(["reactor-api", "config"]);
291
+ /** The reactor-api settings `env` names; keys it does not set stay undefined. */
292
+ function reactorApiConfigFromEnv(env, logger = defaultLogger$1) {
293
+ return pruned({
294
+ server: pruned({
295
+ basePath: env.BASE_PATH || void 0,
296
+ gatewayAdapter: parseGatewayAdapter(env.GATEWAY_ADAPTER, logger),
297
+ publicUrl: (env.PUBLIC_URL ?? env.RENDER_EXTERNAL_URL) || env.HEROKU_APP_DEFAULT_DOMAIN_NAME || void 0
298
+ }),
299
+ auth: pruned({
300
+ enabled: exactlyTrue(env.AUTH_ENABLED),
301
+ admins: env.ADMINS?.split(",").map((a) => a.toLowerCase()),
302
+ resolveIdentity: exactlyTrue(env.RESOLVE_CALLER_IDENTITY),
303
+ requireAuthenticatedCaller: exactlyTrue(env.REQUIRE_AUTHENTICATED_CALLER),
304
+ requireAuthenticatedCallerExemptPaths: env.REQUIRE_AUTHENTICATED_CALLER_EXEMPT_PATHS?.split(",").map((path) => path.trim()).filter((path) => path.length > 0),
305
+ attachmentReadsFollowDocumentPolicy: exactlyTrue(env.ATTACHMENT_READS_FOLLOW_DOCUMENT_POLICY),
306
+ defaultProtection: env.DEFAULT_PROTECTION === void 0 ? void 0 : env.DEFAULT_PROTECTION.toLowerCase() === "true",
307
+ documentPermissions: pruned({
308
+ enabled: exactlyTrue(env.DOCUMENT_PERMISSIONS_ENABLED),
309
+ cacheTtlMs: env.DOCUMENT_PERMISSION_CACHE_TTL_MS?.trim() ? validOrUnset(env.DOCUMENT_PERMISSION_CACHE_TTL_MS, (raw) => resolvePermissionCacheTtlMs(raw, logger), isPermissionCacheTtlMs) : void 0
310
+ }),
311
+ skipCredentialVerification: exactlyTrue(env.SKIP_CREDENTIAL_VERIFICATION),
312
+ credentialCacheTtlMs: parseCredentialCacheTtlMs(env.CREDENTIAL_VERIFICATION_CACHE_TTL_MS, logger),
313
+ wsRecheckMs: env.WS_CREDENTIAL_RECHECK_INTERVAL_MS === void 0 ? void 0 : validOrUnset(env.WS_CREDENTIAL_RECHECK_INTERVAL_MS, (raw) => resolveWsCredentialRecheckIntervalMs(raw, logger), isWsRecheckMs)
314
+ }),
315
+ inspection: pruned({ admin: exactlyTrue(env.INSPECTION_ADMIN_ENABLED) }),
316
+ attachments: pruned({ storage: env.PH_ATTACHMENT_STORAGE === void 0 ? void 0 : parseAttachmentStorageConfig(env) })
317
+ }) ?? {};
318
+ }
319
+ function pruned(value) {
320
+ const entries = Object.entries(value).filter(([, v]) => v !== void 0);
321
+ return entries.length > 0 ? Object.fromEntries(entries) : void 0;
322
+ }
323
+ function validOrUnset(raw, resolve, isValid) {
324
+ const resolved = resolve(raw);
325
+ return isValid(raw) ? resolved : void 0;
326
+ }
327
+ function isPermissionCacheTtlMs(raw) {
328
+ const parsed = Number(raw);
329
+ return Number.isInteger(parsed) && parsed >= 0;
330
+ }
331
+ function isWsRecheckMs(raw) {
332
+ const parsed = Number(raw);
333
+ return raw.trim() !== "" && Number.isFinite(parsed) && parsed >= 0;
334
+ }
335
+ function exactlyTrue(value) {
336
+ return value === void 0 ? void 0 : value === "true";
337
+ }
338
+ function parseGatewayAdapter(value, logger) {
339
+ if (value === void 0) return void 0;
340
+ if (value === "apollo" || value === "mercurius" || value === "stitching") return value;
341
+ logger.warn(`Unknown GATEWAY_ADAPTER="${value}"; falling back to "apollo"`);
342
+ }
343
+ function parseCredentialCacheTtlMs(raw, logger) {
344
+ if (raw === void 0) return void 0;
345
+ const parsed = Number(raw);
346
+ if (raw.trim() !== "" && Number.isFinite(parsed) && parsed >= 0) return parsed;
347
+ logger.warn(`Ignoring invalid CREDENTIAL_VERIFICATION_CACHE_TTL_MS="${raw}" (expected a non-negative number of milliseconds; 0 disables caching) — using the renown source's default`);
348
+ }
349
+ /** `DOCUMENT_PERMISSION_CACHE_TTL_MS` in ms (0 disables); invalid warns and uses the default. */
350
+ function resolvePermissionCacheTtlMs(raw, logger) {
351
+ if (raw === void 0 || raw.trim() === "") return DEFAULT_PERMISSION_CACHE_TTL_MS;
352
+ const parsed = Number(raw);
353
+ if (!Number.isInteger(parsed) || parsed < 0) {
354
+ logger.warn(`Ignoring DOCUMENT_PERMISSION_CACHE_TTL_MS=${raw}: expected a non-negative integer; using ${DEFAULT_PERMISSION_CACHE_TTL_MS} ms`);
355
+ return DEFAULT_PERMISSION_CACHE_TTL_MS;
356
+ }
357
+ return parsed;
358
+ }
359
+ //#endregion
61
360
  //#region src/graphql/analytics-subgraph.ts
62
361
  const analyticsResolvers = AnalyticsResolvers;
63
362
  var AnalyticsSubgraph = class extends BaseSubgraph {
@@ -377,30 +676,16 @@ async function createGatewayAdapter(type, logger) {
377
676
  }
378
677
  async function createHttpAdapter(type) {
379
678
  switch (type) {
380
- case "express": {
381
- const { createExpressHttpAdapter } = await import("./adapter-http-express-P0t-mdMV.mjs");
382
- return createExpressHttpAdapter();
383
- }
384
- case "fastify": {
385
- const { createFastifyHttpAdapter } = await import("./adapter-http-fastify-D0OP5q9K.mjs");
386
- return createFastifyHttpAdapter();
387
- }
388
- }
389
- }
390
- //#endregion
391
- //#region src/graphql/gateway/types.ts
392
- /** No authenticated caller resolved, and REQUIRE_AUTHENTICATED_CALLER wants one. */
393
- const WS_CLOSE_REASON_AUTHENTICATION_REQUIRED = "authentication-required";
394
- /** A bearer was sent and could not be verified. */
395
- const WS_CLOSE_REASON_BEARER_REJECTED = "bearer-rejected";
396
- /** An admitted connection's credential was revoked or no longer verifies. */
397
- const WS_CLOSE_REASON_CREDENTIAL_REVOKED = "credential-revoked";
398
- /** Every reason a refusal closes with, for a client matching on the set. */
399
- const WS_AUTH_CLOSE_REASONS = [
400
- WS_CLOSE_REASON_AUTHENTICATION_REQUIRED,
401
- WS_CLOSE_REASON_BEARER_REJECTED,
402
- WS_CLOSE_REASON_CREDENTIAL_REVOKED
403
- ];
679
+ case "express": {
680
+ const { createExpressHttpAdapter } = await import("./adapter-http-express-P0t-mdMV.mjs");
681
+ return createExpressHttpAdapter();
682
+ }
683
+ case "fastify": {
684
+ const { createFastifyHttpAdapter } = await import("./adapter-http-fastify-D0OP5q9K.mjs");
685
+ return createFastifyHttpAdapter();
686
+ }
687
+ }
688
+ }
404
689
  //#endregion
405
690
  //#region src/http/node-response.ts
406
691
  /** Converts Node incoming headers to Fetch Headers. */
@@ -2170,6 +2455,19 @@ const GetCreateDefaultsDocument = gql`
2170
2455
  }
2171
2456
  }
2172
2457
  `;
2458
+ const GetCreateProtocolVersionsDocument = gql`
2459
+ query GetCreateProtocolVersions(
2460
+ $parentIdOrSlug: String
2461
+ $documentType: String!
2462
+ ) {
2463
+ createDefaults(
2464
+ parentIdOrSlug: $parentIdOrSlug
2465
+ documentType: $documentType
2466
+ ) {
2467
+ protocolVersions
2468
+ }
2469
+ }
2470
+ `;
2173
2471
  const GetDriveNodesDocument = gql`
2174
2472
  query GetDriveNodes(
2175
2473
  $driveId: ID!
@@ -2589,6 +2887,9 @@ function getSdk(requester) {
2589
2887
  GetCreateDefaults(variables, options) {
2590
2888
  return requester(GetCreateDefaultsDocument, variables, options);
2591
2889
  },
2890
+ GetCreateProtocolVersions(variables, options) {
2891
+ return requester(GetCreateProtocolVersionsDocument, variables, options);
2892
+ },
2592
2893
  GetDriveNodes(variables, options) {
2593
2894
  return requester(GetDriveNodesDocument, variables, options);
2594
2895
  },
@@ -3123,9 +3424,16 @@ function toConsistencyToken(input) {
3123
3424
  }))
3124
3425
  };
3125
3426
  }
3126
- /** The defaults `create` gives a new document; the parent must already be gated. */
3127
- async function createDefaults(read, parentIdOrSlug) {
3128
- const [signaturePolicy, protocolVersions] = await Promise.all([read.getCreateSignaturePolicy(), read.getCreateProtocolVersions(parentIdOrSlug)]);
3427
+ /**
3428
+ * The defaults `create` gives a new document; the parent must already be
3429
+ * gated. A request without `documentType` predates it and gets the host's
3430
+ * selection unfitted.
3431
+ */
3432
+ async function createDefaults(read, parentIdOrSlug, documentType) {
3433
+ const [signaturePolicy, protocolVersions] = await Promise.all([read.getCreateSignaturePolicy(), read.getCreateProtocolVersions({
3434
+ documentType,
3435
+ parentIdentifier: parentIdOrSlug
3436
+ })]);
3129
3437
  return {
3130
3438
  signaturePolicy,
3131
3439
  protocolVersions
@@ -3492,9 +3800,10 @@ async function createEmptyDocument(clients, args, _reactorDriveClient, subject)
3492
3800
  if (parentIdOrSlug) {
3493
3801
  const parent = await clients.read.get(parentIdOrSlug, subject && { subject });
3494
3802
  if (isDriveContainerType(parent.header.documentType)) {
3495
- const module = await clients.read.getDocumentModelModule(args.documentType);
3496
- const document = withSignaturePolicy(module.utils.createDocument(), await clients.read.getCreateSignaturePolicy());
3497
- if (name) document.header.name = name;
3803
+ const document = await clients.read.newDocument(args.documentType, {
3804
+ parentIdentifier: parent.header.id,
3805
+ name: name || void 0
3806
+ });
3498
3807
  receipt = await addFileToDrive(clients, parent.header.id, document);
3499
3808
  } else receipt = await (await clients.write.createEmpty(args.documentType, { parentIdentifier: parentIdOrSlug })).readable;
3500
3809
  } else receipt = await (await clients.write.createEmpty(args.documentType, {})).readable;
@@ -3519,7 +3828,7 @@ async function createDocumentWithInitialState(clients, args, _reactorDriveClient
3519
3828
  } catch (error) {
3520
3829
  throw new GraphQLError(`Document model not found for type ${args.documentType}: ${error instanceof Error ? error.message : "Unknown error"}`);
3521
3830
  }
3522
- const document = withSignaturePolicy(module.utils.createDocument(), await clients.read.getCreateSignaturePolicy());
3831
+ const document = await clients.read.newDocument(args.documentType, { parentIdentifier: parentIdOrSlug ?? void 0 });
3523
3832
  const allowedScopes = new Set(Object.keys(module.documentModel.global.specifications.at(-1)?.state ?? {}));
3524
3833
  const state = document.state;
3525
3834
  for (const [scope, scopeState] of Object.entries(args.initialState)) if (allowedScopes.has(scope) && scope in state) state[scope] = {
@@ -5055,105 +5364,6 @@ function rootFields(document, operation) {
5055
5364
  return [...fields];
5056
5365
  }
5057
5366
  //#endregion
5058
- //#region src/graphql/ws-credential-monitor.ts
5059
- /** Default interval between credential re-checks of open WebSockets. */
5060
- const DEFAULT_WS_CREDENTIAL_RECHECK_INTERVAL_MS = 6e4;
5061
- /**
5062
- * Re-verifies the credentials of authenticated WebSocket connections.
5063
- *
5064
- * A WebSocket is authenticated once, at `ConnectionInit`, so a credential
5065
- * revoked afterwards would otherwise keep every subscription it opened alive
5066
- * for as long as the socket stays up. The monitor re-checks each tracked
5067
- * connection on an interval and, at once, the connections of an identity whose
5068
- * credential a package invalidated; a connection whose credential no longer
5069
- * verifies is closed 4403 with {@link WS_CLOSE_REASON_CREDENTIAL_REVOKED}.
5070
- *
5071
- * A check that throws (a verifier outage) leaves the connection open: admission
5072
- * fails closed on the next connect, but an outage should not drop every live
5073
- * subscription at once.
5074
- */
5075
- var WsCredentialMonitor = class {
5076
- #connections = /* @__PURE__ */ new Map();
5077
- #options;
5078
- #timer;
5079
- #unsubscribe;
5080
- #sweeping = false;
5081
- constructor(options) {
5082
- this.#options = options;
5083
- }
5084
- get size() {
5085
- return this.#connections.size;
5086
- }
5087
- /** Begin the periodic sweep and listen for invalidations. Idempotent. */
5088
- start() {
5089
- this.#unsubscribe ??= this.#options.authService.onCredentialInvalidated((invalidation) => {
5090
- this.recheck(invalidation);
5091
- });
5092
- if (this.#options.intervalMs > 0 && !this.#timer) {
5093
- this.#timer = setInterval(() => {
5094
- if (this.#sweeping) return;
5095
- this.#sweeping = true;
5096
- this.recheck().finally(() => {
5097
- this.#sweeping = false;
5098
- });
5099
- }, this.#options.intervalMs);
5100
- this.#timer.unref?.();
5101
- }
5102
- }
5103
- dispose() {
5104
- if (this.#timer) clearInterval(this.#timer);
5105
- this.#timer = void 0;
5106
- this.#unsubscribe?.();
5107
- this.#unsubscribe = void 0;
5108
- this.#connections.clear();
5109
- }
5110
- /** Track an admitted, authenticated connection until its socket closes. */
5111
- track(connection, user) {
5112
- const { socket } = connection;
5113
- this.#connections.set(connection, {
5114
- user,
5115
- socket
5116
- });
5117
- socket?.once?.("close", () => {
5118
- this.#connections.delete(connection);
5119
- });
5120
- }
5121
- /**
5122
- * Re-verify tracked connections (those matching `filter`, or all) and close
5123
- * the ones whose credential no longer holds. Resolves to the number closed.
5124
- */
5125
- async recheck(filter) {
5126
- const targets = [...this.#connections].filter(([, tracked]) => !filter || matches(tracked.user, filter));
5127
- let closed = 0;
5128
- await Promise.all(targets.map(async ([connection, tracked]) => {
5129
- let valid;
5130
- try {
5131
- valid = await this.#options.authService.isCredentialValid(tracked.user);
5132
- } catch (error) {
5133
- this.#options.logger.warn("Could not re-verify the credential of a WebSocket connection; keeping it open: @error", error instanceof Error ? error.message : error);
5134
- return;
5135
- }
5136
- if (valid || !this.#connections.has(connection)) return;
5137
- this.#connections.delete(connection);
5138
- this.#options.logger.info("Closing WebSocket connection of @address: credential no longer valid", tracked.user.address);
5139
- tracked.socket?.close?.(4403, WS_CLOSE_REASON_CREDENTIAL_REVOKED);
5140
- closed++;
5141
- }));
5142
- return closed;
5143
- }
5144
- };
5145
- function matches(user, filter) {
5146
- return user.address.toLowerCase() === filter.address && (filter.chainId === void 0 || user.chainId === filter.chainId) && (filter.appDid === void 0 || user.appKey === filter.appDid);
5147
- }
5148
- /** Parse `WS_CREDENTIAL_RECHECK_INTERVAL_MS`; invalid values warn and fall back to the default. */
5149
- function resolveWsCredentialRecheckIntervalMs(raw, logger) {
5150
- if (raw === void 0) return DEFAULT_WS_CREDENTIAL_RECHECK_INTERVAL_MS;
5151
- const parsed = Number(raw);
5152
- if (raw.trim() !== "" && Number.isFinite(parsed) && parsed >= 0) return parsed;
5153
- logger.warn(`Ignoring invalid WS_CREDENTIAL_RECHECK_INTERVAL_MS="${raw}" (expected a non-negative number of milliseconds; 0 disables the periodic re-check) — using ${DEFAULT_WS_CREDENTIAL_RECHECK_INTERVAL_MS}`);
5154
- return DEFAULT_WS_CREDENTIAL_RECHECK_INTERVAL_MS;
5155
- }
5156
- //#endregion
5157
5367
  //#region src/graphql/sse.ts
5158
5368
  /** Open SSE operations; `end()` completes them, and any that start later. */
5159
5369
  var SSEStreams = class {
@@ -7353,6 +7563,9 @@ const operationValidators = {
7353
7563
  GetCreateDefaults: (data) => {
7354
7564
  if (data.createDefaults) CreateDefaultsDTO.parse(data.createDefaults);
7355
7565
  },
7566
+ GetCreateProtocolVersions: (data) => {
7567
+ if (data.createDefaults) CreateDefaultsDTO.pick({ protocolVersions: true }).parse(data.createDefaults);
7568
+ },
7356
7569
  GetDriveNodes: (data) => {
7357
7570
  if (data.driveNodes) DriveNodePageDTO.parse(data.driveNodes);
7358
7571
  },
@@ -7949,7 +8162,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
7949
8162
  try {
7950
8163
  const parentIdOrSlug = args.parentIdOrSlug ?? void 0;
7951
8164
  if (parentIdOrSlug !== void 0 && !await this.listsDocument(parentIdOrSlug, ctx)) throw new ForbiddenError("to read this document");
7952
- return await createDefaults(this.clientsOf(ctx).read, parentIdOrSlug);
8165
+ return await createDefaults(this.clientsOf(ctx).read, parentIdOrSlug, args.documentType ?? void 0);
7953
8166
  } catch (error) {
7954
8167
  this.logger.error("Error in createDefaults: @Error", error);
7955
8168
  throw error;
@@ -8429,15 +8642,20 @@ const getAdminUsers = () => {
8429
8642
  };
8430
8643
  //#endregion
8431
8644
  //#region src/graphql/system/env/index.ts
8432
- if (typeof process !== "undefined" && typeof process.cwd === "function" && !["1", "true"].includes(process.env.PH_NO_DOTENV?.trim().toLowerCase() ?? "")) dotenv.config();
8433
- const ADMIN_USERS = getAdminUsers();
8645
+ /** @deprecated Nothing reads it; read `ADMIN_USERS` at your own edge. Reads env on each access. */
8646
+ const ADMIN_USERS = new Proxy([], {
8647
+ get: (_target, key) => Reflect.get(getAdminUsers(), key),
8648
+ has: (_target, key) => Reflect.has(getAdminUsers(), key),
8649
+ ownKeys: () => Reflect.ownKeys(getAdminUsers()),
8650
+ getOwnPropertyDescriptor: (_target, key) => Reflect.getOwnPropertyDescriptor(getAdminUsers(), key)
8651
+ });
8434
8652
  //#endregion
8435
8653
  //#region src/graphql/system/version.ts
8436
8654
  function getVersion() {
8437
- return "6.2.3-dev.78";
8655
+ return "6.2.3-dev.79";
8438
8656
  }
8439
8657
  function getGitHash() {
8440
- return "1c899a137d71c6be7e24a23bbe2163e07f2cc5a1";
8658
+ return "e1e361faacfb9bf18a46dcb7a0c5af6033b6b453";
8441
8659
  }
8442
8660
  function getGitUrl() {
8443
8661
  return buildTreeUrl(getGitHash());
@@ -9447,7 +9665,9 @@ var PackageManager = class {
9447
9665
  this.logger.debug("[@loader] Failed to load @kind from package @package: @error", loader.name, kind, pkg, error);
9448
9666
  }
9449
9667
  this.maybeWarnAllLoadersFailed(kind, pkg, loaded !== void 0, failures);
9450
- loads.set(pkg, loaded ?? (failures.every(({ error }) => isExpectedLoaderMiss(error, pkg, subPath)) ? { status: "absent" } : { status: "failed" }));
9668
+ const outcome = loaded ?? (failures.every(({ error }) => isExpectedLoaderMiss(error, pkg, subPath)) ? { status: "absent" } : { status: "failed" });
9669
+ loads.set(pkg, outcome);
9670
+ getCodegenStatusRegistry().reportLoad(pkg, kind, outcome.status === "failed" ? failures.filter(({ error }) => !isExpectedLoaderMiss(error, pkg, subPath)).map(({ loader, error }) => `[${loader}] ${errorText(error)}`).join("\n") : void 0);
9451
9671
  }
9452
9672
  return loads;
9453
9673
  }
@@ -9692,9 +9912,11 @@ var PackageManager = class {
9692
9912
  });
9693
9913
  }
9694
9914
  };
9915
+ function errorText(error) {
9916
+ return error instanceof Error ? error.message : String(error);
9917
+ }
9695
9918
  //#endregion
9696
9919
  //#region src/config.ts
9697
- const config = { basePath: process.env.BASE_PATH || "/" };
9698
9920
  const DefaultCoreSubgraphs = [AnalyticsSubgraph, SystemSubgraph];
9699
9921
  /** The core subgraphs a server registers, given its optional services. */
9700
9922
  function coreSubgraphClasses(options) {
@@ -9709,8 +9931,7 @@ function coreSubgraphClasses(options) {
9709
9931
  //#endregion
9710
9932
  //#region src/attachment-backend.ts
9711
9933
  /** Filesystem is the default; explicit S3 is readiness-gated without fallback. */
9712
- async function createStartupAttachmentBackend({ db, env = process.env, s3Dependencies }) {
9713
- const storage = parseAttachmentStorageConfig(env);
9934
+ async function createStartupAttachmentBackend({ db, storage = { kind: "filesystem" }, s3Dependencies }) {
9714
9935
  if (storage.kind === "filesystem") return void 0;
9715
9936
  const backend = createS3AttachmentBackend(db.withSchema("attachments"), storage.s3, s3Dependencies);
9716
9937
  if (!(await backend.health()).ready) throw new Error("S3 attachment backend readiness check failed");
@@ -10336,122 +10557,6 @@ async function createRenownCredentialVerifier(config = {}) {
10336
10557
  };
10337
10558
  }
10338
10559
  //#endregion
10339
- //#region src/services/permission-cache.ts
10340
- /**
10341
- * Everything an authorization decision reads about one document: its
10342
- * protection flag (the configured default when it has no protection row), its
10343
- * owner, the users' grant levels and the users granted each operation.
10344
- * Addresses are stored lowercase, as the permission service writes them.
10345
- */
10346
- var DocumentPermissionSnapshot = class {
10347
- documentId;
10348
- isProtected;
10349
- ownerAddress;
10350
- grants;
10351
- operationGrants;
10352
- constructor(documentId, isProtected, ownerAddress, grants, operationGrants) {
10353
- this.documentId = documentId;
10354
- this.isProtected = isProtected;
10355
- this.ownerAddress = ownerAddress;
10356
- this.grants = grants;
10357
- this.operationGrants = operationGrants;
10358
- }
10359
- grantLevel(userAddress) {
10360
- return this.grants.get(userAddress.toLowerCase()) ?? null;
10361
- }
10362
- isOperationRestricted(operationType) {
10363
- return (this.operationGrants.get(operationType)?.size ?? 0) > 0;
10364
- }
10365
- hasOperationGrant(operationType, userAddress) {
10366
- return this.operationGrants.get(operationType)?.has(userAddress.toLowerCase()) ?? false;
10367
- }
10368
- };
10369
- const DEFAULT_PERMISSION_CACHE_TTL_MS = 3e4;
10370
- const DEFAULT_PERMISSION_CACHE_OPTIONS = {
10371
- ttlMs: DEFAULT_PERMISSION_CACHE_TTL_MS,
10372
- maxEntries: 1e4,
10373
- now: () => Date.now()
10374
- };
10375
- var PermissionCacheEntry = class {
10376
- snapshot;
10377
- expiresAt;
10378
- constructor(snapshot, expiresAt) {
10379
- this.snapshot = snapshot;
10380
- this.expiresAt = expiresAt;
10381
- }
10382
- };
10383
- /**
10384
- * Per-process cache of document permission snapshots, keyed by document id.
10385
- *
10386
- * Filled on miss from the store, invalidated by the permission service after
10387
- * each of its own writes, and expired after `ttlMs` as the safety net for
10388
- * writes made by another process (another switchboard instance on the same
10389
- * database) until cross-instance invalidation exists.
10390
- *
10391
- * A load that overlaps an invalidation still answers its caller but is not
10392
- * stored, so a read that started before a write commits cannot repopulate
10393
- * the cache with the pre-write rows.
10394
- */
10395
- var PermissionCache = class {
10396
- #load;
10397
- #options;
10398
- #entries = /* @__PURE__ */ new Map();
10399
- #epoch = 0;
10400
- constructor(load, options = DEFAULT_PERMISSION_CACHE_OPTIONS) {
10401
- this.#load = load;
10402
- this.#options = options;
10403
- }
10404
- get size() {
10405
- return this.#entries.size;
10406
- }
10407
- async get(documentId) {
10408
- return (await this.getMany([documentId])).get(documentId);
10409
- }
10410
- /** Snapshots for every id, loading the missing and expired ones in one batch. */
10411
- async getMany(documentIds) {
10412
- const now = this.#options.now();
10413
- const result = /* @__PURE__ */ new Map();
10414
- const missing = [];
10415
- for (const documentId of new Set(documentIds)) {
10416
- const entry = this.#entries.get(documentId);
10417
- if (entry && entry.expiresAt > now) {
10418
- this.#entries.delete(documentId);
10419
- this.#entries.set(documentId, entry);
10420
- result.set(documentId, entry.snapshot);
10421
- } else missing.push(documentId);
10422
- }
10423
- if (missing.length === 0) return result;
10424
- const epoch = this.#epoch;
10425
- const loaded = await this.#load(missing);
10426
- const storable = this.#options.ttlMs > 0 && epoch === this.#epoch;
10427
- const expiresAt = this.#options.now() + this.#options.ttlMs;
10428
- for (const documentId of missing) {
10429
- const snapshot = loaded.get(documentId);
10430
- if (!snapshot) throw new Error(`Permission snapshot loader returned no snapshot for ${documentId}`);
10431
- result.set(documentId, snapshot);
10432
- if (storable) this.#store(documentId, new PermissionCacheEntry(snapshot, expiresAt));
10433
- }
10434
- return result;
10435
- }
10436
- invalidate(documentId) {
10437
- this.#epoch++;
10438
- this.#entries.delete(documentId);
10439
- }
10440
- clear() {
10441
- this.#epoch++;
10442
- this.#entries.clear();
10443
- }
10444
- #store(documentId, entry) {
10445
- this.#entries.delete(documentId);
10446
- while (this.#entries.size >= this.#options.maxEntries) {
10447
- const oldest = this.#entries.keys().next();
10448
- if (oldest.done) break;
10449
- this.#entries.delete(oldest.value);
10450
- }
10451
- this.#entries.set(documentId, entry);
10452
- }
10453
- };
10454
- //#endregion
10455
10560
  //#region src/services/document-permission.service.ts
10456
10561
  /**
10457
10562
  * Service for managing document-level permissions.
@@ -10944,8 +11049,7 @@ function getDbClient(connectionString = void 0, pgliteFactory) {
10944
11049
  const client = isPg ? "pg" : ClientPgLite;
10945
11050
  const pgliteInstance = isPg ? void 0 : pgliteFactory ? pgliteFactory(connectionString) : connectionString ? new PGlite({
10946
11051
  fs: createDurableNodeFs(NodeFS, connectionString, {
10947
- fsync: resolvePgliteFsync(process.env),
10948
- ...resolvePgliteMaintenance(process.env),
11052
+ ...resolvePgliteMaintenance({}),
10949
11053
  logger
10950
11054
  }),
10951
11055
  parsers: PGLITE_UTC_PARSERS
@@ -11180,25 +11284,12 @@ function makeDbClosers(knexInstance, pglite, logger) {
11180
11284
  return closers;
11181
11285
  }
11182
11286
  /**
11183
- * Resolves the gateway adapter type from the `GATEWAY_ADAPTER` env var.
11184
- * Defaults to "apollo" (the federation gateway, production behavior).
11185
- * "stitching" selects the in-process graphql-tools merge gateway (#1565
11186
- * prototype); "mercurius" the Fastify federation gateway.
11187
- */
11188
- function resolveGatewayAdapterType(logger) {
11189
- const configured = process.env.GATEWAY_ADAPTER;
11190
- if (configured === void 0) return "apollo";
11191
- if (configured === "apollo" || configured === "mercurius" || configured === "stitching") return configured;
11192
- logger.warn(`Unknown GATEWAY_ADAPTER="${configured}"; falling back to "apollo"`);
11193
- return "apollo";
11194
- }
11195
- /**
11196
11287
  * Sets up the subgraph manager and registers subgraphs
11197
11288
  */
11198
- async function setupGraphQLManager({ httpAdapter, authFetchMiddleware, requireAuthFetchMiddleware, httpServer, wsServer, clients, relationalDb, analyticsStore, syncManager, subgraphs, logger, authorizationService, authService, documentPermissionService, enableDocumentModelSubgraphs, port, reactorDriveClient, driveNodes, syncServingGate, httpRoutes, attachments, inspection, driveStore, reportError }) {
11289
+ async function setupGraphQLManager({ settings, httpAdapter, authFetchMiddleware, requireAuthFetchMiddleware, httpServer, wsServer, clients, relationalDb, analyticsStore, syncManager, subgraphs, logger, authorizationService, authService, documentPermissionService, enableDocumentModelSubgraphs, port, reactorDriveClient, driveNodes, syncServingGate, httpRoutes, attachments, inspection, driveStore, reportError }) {
11199
11290
  const graphqlManager = new GraphQLManager({
11200
- wsCredentialRecheckIntervalMs: resolveWsCredentialRecheckIntervalMs(process.env.WS_CREDENTIAL_RECHECK_INTERVAL_MS, logger),
11201
- path: config.basePath,
11291
+ wsCredentialRecheckIntervalMs: settings.wsCredentialRecheckIntervalMs,
11292
+ path: settings.basePath,
11202
11293
  httpServer,
11203
11294
  wsServer,
11204
11295
  readClient: clients.read,
@@ -11209,7 +11300,7 @@ async function setupGraphQLManager({ httpAdapter, authFetchMiddleware, requireAu
11209
11300
  syncManager,
11210
11301
  logger,
11211
11302
  httpAdapter,
11212
- gatewayAdapter: await createGatewayAdapter(resolveGatewayAdapterType(logger), logger),
11303
+ gatewayAdapter: await createGatewayAdapter(settings.gatewayAdapter, logger),
11213
11304
  authService,
11214
11305
  documentPermissionService,
11215
11306
  featureFlags: { enableDocumentModelSubgraphs },
@@ -11261,28 +11352,16 @@ async function _setupCommonInfrastructure(options) {
11261
11352
  const port = options.port ?? DEFAULT_PORT;
11262
11353
  const { adapter: httpAdapter } = await createHttpAdapter("express");
11263
11354
  const logger = options.logger ?? defaultLogger;
11264
- let admins = [];
11265
- let authEnabled = false;
11266
- let configuredResolveIdentity;
11267
- let configuredRequireAuth;
11268
- let configuredExemptPaths;
11269
- let configuredAttachmentPolicyReads;
11270
- let configuredRenown;
11271
- if (options.configFile) {
11272
- const config = getConfig(options.configFile);
11273
- admins = config.auth?.admins.map((a) => a.toLowerCase()) ?? [];
11274
- authEnabled = config.auth?.enabled ?? false;
11275
- configuredRenown = config.auth?.renown;
11276
- } else if (options.auth) {
11277
- admins = options.auth.admins.map((a) => a.toLowerCase());
11278
- authEnabled = options.auth.enabled;
11279
- configuredResolveIdentity = options.auth.resolveIdentity;
11280
- configuredRequireAuth = options.auth.requireAuthenticatedCaller;
11281
- configuredExemptPaths = options.auth.requireAuthenticatedCallerExemptPaths;
11282
- configuredAttachmentPolicyReads = options.auth.attachmentReadsFollowDocumentPolicy;
11283
- }
11284
- const { AUTH_ENABLED, RESOLVE_CALLER_IDENTITY, REQUIRE_AUTHENTICATED_CALLER, REQUIRE_AUTHENTICATED_CALLER_EXEMPT_PATHS, ATTACHMENT_READS_FOLLOW_DOCUMENT_POLICY, ADMINS, DEFAULT_PROTECTION, DOCUMENT_PERMISSIONS_ENABLED, SKIP_CREDENTIAL_VERIFICATION, CREDENTIAL_VERIFICATION_CACHE_TTL_MS } = process.env;
11285
- if (AUTH_ENABLED !== void 0) authEnabled = AUTH_ENABLED === "true";
11355
+ const optionAuth = options.auth ?? {};
11356
+ const settings = {
11357
+ basePath: options.server?.basePath ?? "/",
11358
+ gatewayAdapter: options.server?.gatewayAdapter ?? "apollo",
11359
+ wsCredentialRecheckIntervalMs: optionAuth.wsRecheckMs
11360
+ };
11361
+ const fileAuth = options.configFile ? getConfig(options.configFile).auth : void 0;
11362
+ const admins = (optionAuth.admins ?? fileAuth?.admins ?? []).map((a) => a.toLowerCase());
11363
+ const authEnabled = optionAuth.enabled ?? fileAuth?.enabled ?? false;
11364
+ const configuredRenown = fileAuth?.renown;
11286
11365
  /**
11287
11366
  * Whether the auth middleware reads the bearer and populates `ctx.user`,
11288
11367
  * independently of the authorization policy.
@@ -11294,8 +11373,7 @@ async function _setupCommonInfrastructure(options) {
11294
11373
  * stays `OPEN`, which is the combination custom subgraphs need and the one
11295
11374
  * `AUTH_ENABLED` alone cannot express.
11296
11375
  */
11297
- let resolveCallerIdentity = configuredResolveIdentity ?? authEnabled;
11298
- if (RESOLVE_CALLER_IDENTITY !== void 0) resolveCallerIdentity = RESOLVE_CALLER_IDENTITY === "true";
11376
+ const resolveCallerIdentity = optionAuth.resolveIdentity ?? authEnabled;
11299
11377
  /**
11300
11378
  * Whether the require-authenticated-caller middleware is active: anonymous
11301
11379
  * callers are rejected with a 401 before any subgraph sees the request.
@@ -11310,8 +11388,7 @@ async function _setupCommonInfrastructure(options) {
11310
11388
  * out every non-admin; this expresses "authenticated callers allowed,
11311
11389
  * anonymous not".
11312
11390
  */
11313
- let requireAuthenticatedCaller = configuredRequireAuth ?? false;
11314
- if (REQUIRE_AUTHENTICATED_CALLER !== void 0) requireAuthenticatedCaller = REQUIRE_AUTHENTICATED_CALLER === "true";
11391
+ const requireAuthenticatedCaller = optionAuth.requireAuthenticatedCaller ?? false;
11315
11392
  /**
11316
11393
  * The paths the floor above does not apply to. Comma-separated, like
11317
11394
  * `ADMINS`, because a deployment configures this the same way it configures
@@ -11322,8 +11399,7 @@ async function _setupCommonInfrastructure(options) {
11322
11399
  * cannot ever match is refused, in
11323
11400
  * {@link assertRequireAuthenticatedCallerAllowed}.
11324
11401
  */
11325
- let requireAuthenticatedCallerExemptPaths = configuredExemptPaths ?? [];
11326
- if (REQUIRE_AUTHENTICATED_CALLER_EXEMPT_PATHS !== void 0) requireAuthenticatedCallerExemptPaths = REQUIRE_AUTHENTICATED_CALLER_EXEMPT_PATHS.split(",").map((path) => path.trim()).filter((path) => path.length > 0);
11402
+ const requireAuthenticatedCallerExemptPaths = optionAuth.requireAuthenticatedCallerExemptPaths ?? [];
11327
11403
  /**
11328
11404
  * Whether an attachment read is decided by the referencing document's own
11329
11405
  * policy rather than by the host's permission tables.
@@ -11334,22 +11410,18 @@ async function _setupCommonInfrastructure(options) {
11334
11410
  * nothing keeps exactly the behaviour it has, and one that wants the change
11335
11411
  * asks for it and can take it back without disturbing anything else.
11336
11412
  */
11337
- let attachmentReadsFollowDocumentPolicy = configuredAttachmentPolicyReads ?? false;
11338
- if (ATTACHMENT_READS_FOLLOW_DOCUMENT_POLICY !== void 0) attachmentReadsFollowDocumentPolicy = ATTACHMENT_READS_FOLLOW_DOCUMENT_POLICY === "true";
11339
- if (ADMINS !== void 0) admins = ADMINS.split(",").map((a) => a.toLowerCase());
11340
- let defaultProtection = false;
11341
- if (DEFAULT_PROTECTION !== void 0) defaultProtection = DEFAULT_PROTECTION.toLowerCase() === "true";
11342
- let skipCredentialVerification = false;
11343
- if (SKIP_CREDENTIAL_VERIFICATION !== void 0) skipCredentialVerification = SKIP_CREDENTIAL_VERIFICATION === "true";
11344
- const documentPermissionsRequested = options.documentPermissionService !== void 0 || DOCUMENT_PERMISSIONS_ENABLED === "true";
11345
- assertAuthRequiredForDocumentPermissions(authEnabled, documentPermissionsRequested);
11413
+ const attachmentReadsFollowDocumentPolicy = optionAuth.attachmentReadsFollowDocumentPolicy ?? false;
11414
+ const defaultProtection = optionAuth.defaultProtection ?? false;
11415
+ const skipCredentialVerification = optionAuth.skipCredentialVerification ?? false;
11416
+ const documentPermissionsEnabled = optionAuth.documentPermissions?.enabled ?? false;
11417
+ assertAuthRequiredForDocumentPermissions(authEnabled, options.documentPermissionService !== void 0 || documentPermissionsEnabled);
11346
11418
  assertSkipCredentialVerificationAllowed(resolveCallerIdentity, skipCredentialVerification, process.env);
11347
11419
  assertRequireAuthenticatedCallerAllowed(requireAuthenticatedCaller, resolveCallerIdentity, requireAuthenticatedCallerExemptPaths);
11348
11420
  if (authEnabled && skipCredentialVerification) logger.warn("SECURITY: SKIP_CREDENTIAL_VERIFICATION is enabled — Renown credential verification is disabled and a bearer token's claimed address is NOT cryptographically bound to its signing key. Identity is unverifiable; use only in development or test.");
11349
11421
  httpAdapter.getRoute("/health", () => new Response("OK", { status: 200 }));
11350
11422
  const readiness = createReadinessGate();
11351
11423
  httpAdapter.getRoute("/ready", () => readiness.isReady() ? new Response("OK", { status: 200 }) : new Response("starting", { status: 503 }));
11352
- const explorerPrefix = getExplorerPrefix(config.basePath);
11424
+ const explorerPrefix = getExplorerPrefix(settings.basePath);
11353
11425
  httpAdapter.getRoute(`${explorerPrefix}/:endpoint?`, (request) => {
11354
11426
  const url = new URL(request.url);
11355
11427
  const suffix = url.pathname.slice(explorerPrefix.length).replace(/^\//, "");
@@ -11363,7 +11435,7 @@ async function _setupCommonInfrastructure(options) {
11363
11435
  let authService;
11364
11436
  if (resolveCallerIdentity || authEnabled) {
11365
11437
  logger.info("Setting up Auth middleware (policy enforcement: @enabled, caller identity: @resolve)", authEnabled, resolveCallerIdentity);
11366
- const renown = options.renown ?? resolveRenownConfig(configuredRenown, process.env, logger);
11438
+ const renown = options.renown ?? resolveRenownConfig(configuredRenown, {}, logger);
11367
11439
  assertCredentialVerifierForSource(renown.source, options.verifyCredential !== void 0);
11368
11440
  if (options.verifyCredential) logger.info("Renown credentials will be verified by the host's verifier");
11369
11441
  else logger.info("Renown credentials will be verified against @url", renown.switchboardUrl ?? renown.url ?? "the default Renown instance");
@@ -11372,7 +11444,7 @@ async function _setupCommonInfrastructure(options) {
11372
11444
  resolveIdentity: resolveCallerIdentity,
11373
11445
  admins,
11374
11446
  skipCredentialVerification,
11375
- credentialVerificationCacheTtlMs: resolveCredentialCacheTtlMs(CREDENTIAL_VERIFICATION_CACHE_TTL_MS, renown.source, logger),
11447
+ credentialVerificationCacheTtlMs: optionAuth.credentialCacheTtlMs ?? (renown.source === "self" ? 0 : void 0),
11376
11448
  verifyCredential: options.verifyCredential ?? await createRenownCredentialVerifier({
11377
11449
  renownUrl: renown.url,
11378
11450
  switchboardUrl: renown.switchboardUrl
@@ -11388,22 +11460,24 @@ async function _setupCommonInfrastructure(options) {
11388
11460
  const { relationalDb, analyticsStore, closers: analyticsClosers } = await initializeDatabaseAndAnalytics(options.dbPath, options.pgliteFactory, logger);
11389
11461
  dbClosers.push(...analyticsClosers);
11390
11462
  const documentPermissionService = options.documentPermissionService;
11391
- const ownDocumentPermissions = !documentPermissionService && DOCUMENT_PERMISSIONS_ENABLED === "true" ? {
11463
+ const ownDocumentPermissions = !documentPermissionService && documentPermissionsEnabled ? {
11392
11464
  defaultProtection,
11393
- cacheTtlMs: resolvePermissionCacheTtlMs(process.env.DOCUMENT_PERMISSION_CACHE_TTL_MS, logger)
11465
+ cacheTtlMs: optionAuth.documentPermissions?.cacheTtlMs ?? 3e4
11394
11466
  } : null;
11395
- const policy = documentPermissionService || ownDocumentPermissions ? AuthorizationPolicy.DOCUMENT_PERMISSIONS : authEnabled ? AuthorizationPolicy.ADMIN_ONLY : AuthorizationPolicy.OPEN;
11396
11467
  const authorizationConfig = {
11397
11468
  admins,
11398
11469
  defaultProtection,
11399
- policy
11470
+ policy: documentPermissionService || ownDocumentPermissions ? AuthorizationPolicy.DOCUMENT_PERMISSIONS : authEnabled ? AuthorizationPolicy.ADMIN_ONLY : AuthorizationPolicy.OPEN
11400
11471
  };
11401
11472
  const attachmentStoragePath = resolveAttachmentStoragePath(options);
11402
11473
  await mkdir(attachmentStoragePath, { recursive: true });
11403
11474
  const { db: attachmentDb, knex: attachmentKnex, pglite: attachmentPglite } = getDbClient(options.dbPath, options.pgliteFactory);
11404
11475
  dbClosers.push(...makeDbClosers(attachmentKnex, attachmentPglite, logger));
11405
11476
  const ATTACHMENT_SWEEP_INTERVAL_MS = 36e5;
11406
- const attachmentBackend = await createStartupAttachmentBackend({ db: attachmentDb });
11477
+ const attachmentBackend = await createStartupAttachmentBackend({
11478
+ db: attachmentDb,
11479
+ storage: options.attachments?.storage ?? { kind: "filesystem" }
11480
+ });
11407
11481
  const attachmentBuilder = new AttachmentBuilder(attachmentDb, attachmentStoragePath).withReservationSweepMs(ATTACHMENT_SWEEP_INTERVAL_MS);
11408
11482
  if (attachmentBackend) attachmentBuilder.withBackend(attachmentBackend);
11409
11483
  const attachments = await attachmentBuilder.build();
@@ -11419,21 +11493,21 @@ async function _setupCommonInfrastructure(options) {
11419
11493
  reportError: options.reportError
11420
11494
  });
11421
11495
  const listenPort = { current: port };
11422
- const publicUrl = resolvePublicOrigin(listenPort);
11496
+ const publicUrl = resolvePublicOrigin(options.server?.publicUrl, listenPort);
11423
11497
  const webhooks = new WebhookService({
11424
11498
  store: new RelationalWebhookStore(relationalDb),
11425
- basePath: config.basePath,
11499
+ basePath: settings.basePath,
11426
11500
  publicUrl
11427
11501
  });
11428
11502
  const httpRoutes = new HttpRouteService({
11429
11503
  httpAdapter,
11430
- basePath: config.basePath,
11504
+ basePath: settings.basePath,
11431
11505
  authService,
11432
11506
  webhooks,
11433
11507
  publicUrl,
11434
11508
  trustProxy: true
11435
11509
  });
11436
- webhooks.attach(httpRoutes.hostScope(CORE_PACKAGE_NAME, path.posix.join("/", config.basePath ?? "/", WEBHOOK_SEGMENT)));
11510
+ webhooks.attach(httpRoutes.hostScope(CORE_PACKAGE_NAME, path.posix.join("/", settings.basePath, WEBHOOK_SEGMENT)));
11437
11511
  return {
11438
11512
  listenPort,
11439
11513
  httpAdapter,
@@ -11452,13 +11526,14 @@ async function _setupCommonInfrastructure(options) {
11452
11526
  packages,
11453
11527
  dbClosers,
11454
11528
  readiness,
11455
- attachmentReadsFollowDocumentPolicy
11529
+ attachmentReadsFollowDocumentPolicy,
11530
+ settings
11456
11531
  };
11457
11532
  }
11458
11533
  /**
11459
11534
  * Private helper function containing common setup logic for API initialization
11460
11535
  */
11461
- async function _setupAPI(clients, syncManager, reactorProcessorManager, httpAdapter, authFetchMiddleware, requireAuthFetchMiddleware, authEnabled, authService, listenPort, packages, relationalDb, analyticsStore, documentPermissionService, processors, subgraphs, options, processorApp, readModels, attachments, attachmentReferenceIndex, attachmentReferenceProjection, authorizationConfig, documentModelRegistry, dbClosers = [], reactorDriveClient, syncServingGate, httpRoutes, attachmentReadsFollowDocumentPolicy = false, inspection, driveStore, driveNodes) {
11536
+ async function _setupAPI(clients, syncManager, reactorProcessorManager, httpAdapter, authFetchMiddleware, requireAuthFetchMiddleware, authEnabled, authService, listenPort, packages, relationalDb, analyticsStore, documentPermissionService, processors, subgraphs, options, settings, processorApp, readModels, attachments, attachmentReferenceIndex, attachmentReferenceProjection, authorizationConfig, documentModelRegistry, dbClosers = [], reactorDriveClient, syncServingGate, httpRoutes, attachmentReadsFollowDocumentPolicy = false, inspection, driveStore, driveNodes) {
11462
11537
  const hostModuleBase = {
11463
11538
  ...createReactorHostModuleBase({
11464
11539
  client: clients.client,
@@ -11518,6 +11593,7 @@ async function _setupAPI(clients, syncManager, reactorProcessorManager, httpAdap
11518
11593
  });
11519
11594
  if (documentPermissionService) logger.info("Auth subgraph registered (document permissions enabled)");
11520
11595
  const graphqlManager = await setupGraphQLManager({
11596
+ settings,
11521
11597
  httpAdapter,
11522
11598
  authFetchMiddleware,
11523
11599
  requireAuthFetchMiddleware,
@@ -11649,22 +11725,8 @@ async function createOwnDocumentPermissionService(settings, permissionsDb, optio
11649
11725
  logger.info(`Document permission service initialized on the read-model store (cache TTL ${settings.cacheTtlMs} ms)`);
11650
11726
  return new DocumentPermissionService(db, config, cacheOptions);
11651
11727
  }
11652
- /**
11653
- * The permission cache TTL from `DOCUMENT_PERMISSION_CACHE_TTL_MS`: a
11654
- * non-negative integer of milliseconds, 0 disabling the cache. Anything else
11655
- * falls back to the default with a warning.
11656
- */
11657
- function resolvePermissionCacheTtlMs(raw, logger) {
11658
- if (raw === void 0 || raw.trim() === "") return DEFAULT_PERMISSION_CACHE_TTL_MS;
11659
- const parsed = Number(raw);
11660
- if (!Number.isInteger(parsed) || parsed < 0) {
11661
- logger.warn(`Ignoring DOCUMENT_PERMISSION_CACHE_TTL_MS=${raw}: expected a non-negative integer; using ${DEFAULT_PERMISSION_CACHE_TTL_MS} ms`);
11662
- return DEFAULT_PERMISSION_CACHE_TTL_MS;
11663
- }
11664
- return parsed;
11665
- }
11666
11728
  async function initializeAndStartAPI(clientInitializer, options, processorApp) {
11667
- const { listenPort, httpAdapter, httpRoutes, authFetchMiddleware, requireAuthFetchMiddleware, authEnabled, authService, relationalDb, analyticsStore, documentPermissionService: providedDocumentPermissionService, ownDocumentPermissions, authorizationConfig, attachments, attachmentReferenceIndex, packages, dbClosers, readiness, attachmentReadsFollowDocumentPolicy } = await _setupCommonInfrastructure(options);
11729
+ const { listenPort, httpAdapter, httpRoutes, authFetchMiddleware, requireAuthFetchMiddleware, authEnabled, authService, relationalDb, analyticsStore, documentPermissionService: providedDocumentPermissionService, ownDocumentPermissions, authorizationConfig, attachments, attachmentReferenceIndex, packages, dbClosers, readiness, attachmentReadsFollowDocumentPolicy, settings } = await _setupCommonInfrastructure(options);
11668
11730
  const { documentModels, upgradeManifests, processors, subgraphs } = await packages.init();
11669
11731
  const { module: reactorClientModule, reactorDriveClient, driveNodes, attachmentReferenceProjection = {
11670
11732
  status: "unavailable",
@@ -11688,8 +11750,7 @@ async function initializeAndStartAPI(clientInitializer, options, processorApp) {
11688
11750
  read: reactorClientModule.read,
11689
11751
  write: reactorClientModule.write,
11690
11752
  client: reactorClient
11691
- }, syncManager, reactorProcessorManager, httpAdapter, authFetchMiddleware, requireAuthFetchMiddleware, authEnabled, authService, listenPort, packages, relationalDb, analyticsStore, documentPermissionService, processors, subgraphs, options, processorApp, readModels, attachments, attachmentReferenceIndex, attachmentReferenceProjection, authorizationConfig, documentModelRegistry, dbClosers, reactorDriveClient, buildSyncServingGate(reactorClientModule.reactorModule, authorizationConfig, options.logger ?? defaultLogger), httpRoutes, attachmentReadsFollowDocumentPolicy, reactorClientModule.reactorModule && options.inspection !== false ? createReactorInspectionSource(reactorClientModule.reactorModule, {
11692
- admin: process.env.INSPECTION_ADMIN_ENABLED === "true",
11753
+ }, syncManager, reactorProcessorManager, httpAdapter, authFetchMiddleware, requireAuthFetchMiddleware, authEnabled, authService, listenPort, packages, relationalDb, analyticsStore, documentPermissionService, processors, subgraphs, options, settings, processorApp, readModels, attachments, attachmentReferenceIndex, attachmentReferenceProjection, authorizationConfig, documentModelRegistry, dbClosers, reactorDriveClient, buildSyncServingGate(reactorClientModule.reactorModule, authorizationConfig, options.logger ?? defaultLogger), httpRoutes, attachmentReadsFollowDocumentPolicy, reactorClientModule.reactorModule && options.inspection !== false ? createReactorInspectionSource(reactorClientModule.reactorModule, {
11693
11754
  ...options.inspection,
11694
11755
  attachmentStore: attachmentInspectionStore(attachments)
11695
11756
  }) : void 0, reactorClientModule.reactorModule?.reactor, driveNodes),
@@ -11713,11 +11774,8 @@ async function initializeAndStartAPI(clientInitializer, options, processorApp) {
11713
11774
  * dev` behind a tunnel and, at worst, obviously wrong rather than silently
11714
11775
  * unusable.
11715
11776
  */
11716
- function resolvePublicOrigin(listenPort) {
11717
- const explicit = process.env.PUBLIC_URL ?? process.env.RENDER_EXTERNAL_URL;
11718
- if (explicit) return withScheme(explicit);
11719
- const domain = process.env.HEROKU_APP_DEFAULT_DOMAIN_NAME;
11720
- if (domain) return withScheme(domain);
11777
+ function resolvePublicOrigin(configured, listenPort) {
11778
+ if (configured) return withScheme(configured);
11721
11779
  return () => `http://localhost:${listenPort.current}`;
11722
11780
  }
11723
11781
  function withScheme(origin) {
@@ -11883,7 +11941,7 @@ var PackageManagementService = class {
11883
11941
  }
11884
11942
  };
11885
11943
  //#endregion
11886
- export { ADMIN_USERS, ActionCandidateInputSchema, ActionContextInputSchema, ActionInputSchema, AddRelationshipDocument, AnalyticsSubgraph, AttachmentAccessFailed, AttachmentAccessService, AttachmentAccessUnavailable, AttachmentClientProvider, AuthDecision, AuthDecisionSchema, AuthEvaluationUnsupportedError, AuthService, AuthSubgraph, AuthenticationRequiredError, AuthorizationPolicy, AuthorizedAttachmentService, AuthorizedDocumentHandle, BaseSubgraph, CORE_PACKAGE_NAME, CanonicalDocumentIdResolutionError, ChannelMetaInputSchema, ConsistencyCoordinateInputSchema, ConsistencyTokenInputSchema, CreateDocumentDocument, CreateEmptyDocumentDocument, DEFAULT_INSPECTION_THROTTLE, DEFAULT_PERMISSION_CACHE_OPTIONS, DEFAULT_PERMISSION_CACHE_TTL_MS, DeleteDocumentDocument, DeleteDocumentsDocument, DocumentChangeType, DocumentChangeTypeSchema, DocumentChangesDocument, DocumentModelSchemaCache, DocumentOperationsFilterInputSchema, DocumentPermissionService, DocumentPermissionSnapshot, DocumentRelationshipFieldsFragmentDoc, DriveNodeFieldsFragmentDoc, DriveNodeKind, DriveNodeKindSchema, EvaluateActionsDocument, ExecuteBatchDocument, ExecutionJobInputSchema, FindDocumentsDocument, ForbiddenError, GetCreateDefaultsDocument, GetDocumentDocument, GetDocumentIncomingRelationshipEdgesDocument, GetDocumentIncomingRelationshipsDocument, GetDocumentModelsDocument, GetDocumentOperationsDocument, GetDocumentOutgoingRelationshipEdgesDocument, GetDocumentOutgoingRelationshipsDocument, GetDocumentServedDocument, GetDocumentWithOperationsDocument, GetDriveDescendantsDocument, GetDriveNodeDocument, GetDriveNodesDocument, GetJobStatusDocument, GraphQLManager, HttpDocumentModelLoader, HttpPackageLoader, HttpRouteService, ImportPackageLoader, InMemoryPackageStorage, InspectionAdminSubgraph, InspectionSubgraph, InspectionThrottle, InspectionThrottledError, InvalidNamespaceError, JobChangesDocument, JobInfoFieldsFragmentDoc, MalformedStoredOperationError, MemoryWebhookStore, MoveRelationshipDocument, MutateDocumentAsyncDocument, MutateDocumentDocument, NodeEventLoopDelay, OperationContextInputSchema, OperationInputSchema, OperationWithContextInputSchema, OperationsFilterInputSchema, PACKAGE_ROUTE_SEGMENT, PGLITE_UTC_PARSERS, PackageManagementService, PackageManager, PackagesSubgraph, PagingInputSchema, PermissionCache, PhDocumentFieldsFragmentDoc, PollSyncEnvelopesDocument, PrivacyPermissionAdapter, PropagationMode, PropagationModeSchema, PushSyncEnvelopesDocument, ReactorSignerAppInputSchema, ReactorSignerInputSchema, ReactorSignerUserInputSchema, ReactorSubgraph, RefusalNotRecordedError, RelationalWebhookStore, RemoteCursorInputSchema, RemoteFilterInputSchema, RemoveRelationshipDocument, RenameDocumentDocument, RequestLoadRecorder, SearchFilterInputSchema, SetPreferredEditorDocument, SubgraphTypeCollisionError, SyncEnvelopeInputSchema, SyncEnvelopeType, SyncEnvelopeTypeSchema, SyncRefusalInputSchema, SystemSubgraph, TouchChannelDocument, TouchChannelInputSchema, UpdateRelationshipDocument, ViewFilterInputSchema, WEBHOOK_SEGMENT, WS_AUTH_CLOSE_REASONS, WS_CLOSE_REASON_AUTHENTICATION_REQUIRED, WS_CLOSE_REASON_BEARER_REJECTED, WS_CLOSE_REASON_CREDENTIAL_REVOKED, WebhookService, assembleSubgraphTypeDefs, assertAttachmentPolicyReadsAllowed, assertAuthRequiredForDocumentPermissions, assertCredentialVerifierForSource, assertHostMountPath, assertRequireAuthenticatedCallerAllowed, assertSkipCredentialVerificationAllowed, baseDocumentModels, buildDocumentModelSchema, buildGraphQlDocument, buildGraphQlDriveDocument, buildGraphqlOperation, buildGraphqlOperations, buildSubgraphSchemaModule, callerSubject, createAuthFetchMiddleware, createCanonicalDocumentIdResolver, createCredentialInvalidator, createGatewayAdapter, createHttpAdapter, createInspectionResolvers, createMergedSchema, createReactorGraphQLClient, createReactorInspectionSource, createRenownCredentialVerifier, createSchema, createWsAuthHandlers, decodeExplorerUrlState, definedNonNullAnySchema, documentModelSubgraphTypes, driveIdFromUrl, extractSubgraphs, extractSubgraphsFromModule, findSubgraphTypeCollisions, generateDocumentModelSchema, generatedTypesOf, getAuthContext, getDbClient, getDocumentModelSchemaName, getDocumentModelSubgraphName, getDocumentModelTypeDefs, getExplorerPrefix, getGeneratedDocumentModelTypes, getGitHash, getGitUrl, getSdk, getUniqueDocumentModels, getUniqueUpgradeManifests, getVersion, hasOperationSchemas, initAnalyticsStoreSql, initializeAndStartAPI, inspectionAdminTypeDefs, inspectionTypeDefs, isCountedRequest, isDefinedNonNullAny, isExpectedLoaderMiss, isListedAdmin, isPostgresConnectionString, isSubgraphClass, namespacePath, namespaceSegments, newWebhookToken, parseDriveUrl, parseWebhookBody, piecesBaseUrl, redactHeaders, renderGraphqlPlayground, reportFailure, reservedTypeNames, reservedTypeNamesTaken, resolveCredentialCacheTtlMs, resolvePackageName, resolvePermissionCacheTtlMs, resolveRenownConfig, runDetached, typeDefinitionNames, verifyWebhook };
11944
+ export { ADMIN_USERS, ActionCandidateInputSchema, ActionContextInputSchema, ActionInputSchema, AddRelationshipDocument, AnalyticsSubgraph, AttachmentAccessFailed, AttachmentAccessService, AttachmentAccessUnavailable, AttachmentClientProvider, AuthDecision, AuthDecisionSchema, AuthEvaluationUnsupportedError, AuthService, AuthSubgraph, AuthenticationRequiredError, AuthorizationPolicy, AuthorizedAttachmentService, AuthorizedDocumentHandle, BaseSubgraph, CORE_PACKAGE_NAME, CanonicalDocumentIdResolutionError, ChannelMetaInputSchema, ConsistencyCoordinateInputSchema, ConsistencyTokenInputSchema, CreateDocumentDocument, CreateEmptyDocumentDocument, DEFAULT_INSPECTION_THROTTLE, DEFAULT_PERMISSION_CACHE_OPTIONS, DEFAULT_PERMISSION_CACHE_TTL_MS, DeleteDocumentDocument, DeleteDocumentsDocument, DocumentChangeType, DocumentChangeTypeSchema, DocumentChangesDocument, DocumentModelSchemaCache, DocumentOperationsFilterInputSchema, DocumentPermissionService, DocumentPermissionSnapshot, DocumentRelationshipFieldsFragmentDoc, DriveNodeFieldsFragmentDoc, DriveNodeKind, DriveNodeKindSchema, EvaluateActionsDocument, ExecuteBatchDocument, ExecutionJobInputSchema, FindDocumentsDocument, ForbiddenError, GetCreateDefaultsDocument, GetCreateProtocolVersionsDocument, GetDocumentDocument, GetDocumentIncomingRelationshipEdgesDocument, GetDocumentIncomingRelationshipsDocument, GetDocumentModelsDocument, GetDocumentOperationsDocument, GetDocumentOutgoingRelationshipEdgesDocument, GetDocumentOutgoingRelationshipsDocument, GetDocumentServedDocument, GetDocumentWithOperationsDocument, GetDriveDescendantsDocument, GetDriveNodeDocument, GetDriveNodesDocument, GetJobStatusDocument, GraphQLManager, HttpDocumentModelLoader, HttpPackageLoader, HttpRouteService, ImportPackageLoader, InMemoryPackageStorage, InspectionAdminSubgraph, InspectionSubgraph, InspectionThrottle, InspectionThrottledError, InvalidNamespaceError, JobChangesDocument, JobInfoFieldsFragmentDoc, MalformedStoredOperationError, MemoryWebhookStore, MoveRelationshipDocument, MutateDocumentAsyncDocument, MutateDocumentDocument, NodeEventLoopDelay, OperationContextInputSchema, OperationInputSchema, OperationWithContextInputSchema, OperationsFilterInputSchema, PACKAGE_ROUTE_SEGMENT, PGLITE_UTC_PARSERS, PackageManagementService, PackageManager, PackagesSubgraph, PagingInputSchema, PermissionCache, PhDocumentFieldsFragmentDoc, PollSyncEnvelopesDocument, PrivacyPermissionAdapter, PropagationMode, PropagationModeSchema, PushSyncEnvelopesDocument, ReactorSignerAppInputSchema, ReactorSignerInputSchema, ReactorSignerUserInputSchema, ReactorSubgraph, RefusalNotRecordedError, RelationalWebhookStore, RemoteCursorInputSchema, RemoteFilterInputSchema, RemoveRelationshipDocument, RenameDocumentDocument, RequestLoadRecorder, SearchFilterInputSchema, SetPreferredEditorDocument, SubgraphTypeCollisionError, SyncEnvelopeInputSchema, SyncEnvelopeType, SyncEnvelopeTypeSchema, SyncRefusalInputSchema, SystemSubgraph, TouchChannelDocument, TouchChannelInputSchema, UpdateRelationshipDocument, ViewFilterInputSchema, WEBHOOK_SEGMENT, WS_AUTH_CLOSE_REASONS, WS_CLOSE_REASON_AUTHENTICATION_REQUIRED, WS_CLOSE_REASON_BEARER_REJECTED, WS_CLOSE_REASON_CREDENTIAL_REVOKED, WebhookService, assembleSubgraphTypeDefs, assertAttachmentPolicyReadsAllowed, assertAuthRequiredForDocumentPermissions, assertCredentialVerifierForSource, assertHostMountPath, assertRequireAuthenticatedCallerAllowed, assertSkipCredentialVerificationAllowed, baseDocumentModels, buildDocumentModelSchema, buildGraphQlDocument, buildGraphQlDriveDocument, buildGraphqlOperation, buildGraphqlOperations, buildSubgraphSchemaModule, callerSubject, createAuthFetchMiddleware, createCanonicalDocumentIdResolver, createCredentialInvalidator, createGatewayAdapter, createHttpAdapter, createInspectionResolvers, createMergedSchema, createReactorGraphQLClient, createReactorInspectionSource, createRenownCredentialVerifier, createSchema, createWsAuthHandlers, decodeExplorerUrlState, definedNonNullAnySchema, documentModelSubgraphTypes, driveIdFromUrl, extractSubgraphs, extractSubgraphsFromModule, findSubgraphTypeCollisions, generateDocumentModelSchema, generatedTypesOf, getAuthContext, getDbClient, getDocumentModelSchemaName, getDocumentModelSubgraphName, getDocumentModelTypeDefs, getExplorerPrefix, getGeneratedDocumentModelTypes, getGitHash, getGitUrl, getSdk, getUniqueDocumentModels, getUniqueUpgradeManifests, getVersion, hasOperationSchemas, initAnalyticsStoreSql, initializeAndStartAPI, inspectionAdminTypeDefs, inspectionTypeDefs, isCountedRequest, isDefinedNonNullAny, isExpectedLoaderMiss, isListedAdmin, isPostgresConnectionString, isSubgraphClass, namespacePath, namespaceSegments, newWebhookToken, parseDriveUrl, parseWebhookBody, piecesBaseUrl, reactorApiConfigFromEnv, redactHeaders, renderGraphqlPlayground, reportFailure, reservedTypeNames, reservedTypeNamesTaken, resolveCredentialCacheTtlMs, resolvePackageName, resolvePermissionCacheTtlMs, resolveRenownConfig, runDetached, typeDefinitionNames, verifyWebhook };
11887
11945
 
11888
11946
  //# sourceMappingURL=index.mjs.map
11889
- //# debugId=d978d340-82ad-56d2-8827-0daf9ed3bf67
11947
+ //# debugId=ef156955-2531-5a13-8ece-12e68bf6d841