@powerhousedao/reactor-api 6.2.3-dev.77 → 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 (29) hide show
  1. package/dist/{base-document-models-Dh70m9Bh.mjs → base-document-models-ux7TZ9X3.mjs} +5 -5
  2. package/dist/{base-document-models-Dh70m9Bh.mjs.map → base-document-models-ux7TZ9X3.mjs.map} +1 -1
  3. package/dist/{error-info-CCQcLAcW.mjs → error-info-BaEL50f5.mjs} +68 -6
  4. package/dist/error-info-BaEL50f5.mjs.map +1 -0
  5. package/dist/index.d.mts +1025 -763
  6. package/dist/index.d.mts.map +1 -1
  7. package/dist/index.mjs +1720 -1497
  8. package/dist/index.mjs.map +1 -1
  9. package/dist/{package-subgraph-check-DhCWO3YR.mjs → package-subgraph-check-BGfeyfnc.mjs} +4 -4
  10. package/dist/{package-subgraph-check-DhCWO3YR.mjs.map → package-subgraph-check-BGfeyfnc.mjs.map} +1 -1
  11. package/dist/{pglite-node-BMux5A2Y.mjs → pglite-node-DGms6Ssa.mjs} +19 -6
  12. package/dist/pglite-node-DGms6Ssa.mjs.map +1 -0
  13. package/dist/src/graphql/subgraph-types.mjs +1 -1
  14. package/dist/src/packages/vite-loader.d.mts +2 -2
  15. package/dist/src/packages/vite-loader.d.mts.map +1 -1
  16. package/dist/src/packages/vite-loader.mjs +29 -10
  17. package/dist/src/packages/vite-loader.mjs.map +1 -1
  18. package/dist/src/pglite/pglite-node.d.mts +43 -5
  19. package/dist/src/pglite/pglite-node.d.mts.map +1 -1
  20. package/dist/src/pglite/pglite-node.mjs +5 -5
  21. package/dist/src/pglite/worker/entry.mjs +1 -1
  22. package/dist/{subgraph-extraction-zUDn2zX_.mjs → subgraph-extraction-BYKOycxo.mjs} +18 -4
  23. package/dist/subgraph-extraction-BYKOycxo.mjs.map +1 -0
  24. package/dist/{types-CCI5IDgT.d.mts → types-BEpxtyKW.d.mts} +2 -2
  25. package/dist/{types-CCI5IDgT.d.mts.map → types-BEpxtyKW.d.mts.map} +1 -1
  26. package/package.json +13 -13
  27. package/dist/error-info-CCQcLAcW.mjs.map +0 -1
  28. package/dist/pglite-node-BMux5A2Y.mjs.map +0 -1
  29. package/dist/subgraph-extraction-zUDn2zX_.mjs.map +0 -1
package/dist/index.mjs CHANGED
@@ -1,28 +1,29 @@
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]="560dd033-eac1-581d-a504-0117f3526f86")}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-Dh70m9Bh.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 { d as PGLITE_UTC_PARSERS, i as resolvePgliteFsync, r as createDurableNodeFs } from "./error-info-CCQcLAcW.mjs";
8
- import { f as openCurrentPgliteForVerify, p as preparePgliteDataDir } from "./pglite-node-BMux5A2Y.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";
22
23
  import { Readable } from "node:stream";
23
- import nodeFs, { existsSync, readFileSync, watchFile } from "node:fs";
24
24
  import { pipeline } from "node:stream/promises";
25
25
  import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
26
+ import nodeFs, { existsSync, readFileSync, watchFile } from "node:fs";
26
27
  import { monitorEventLoopDelay } from "node:perf_hooks";
27
28
  import { pathToFileURL } from "node:url";
28
29
  import { camelCase } from "change-case";
@@ -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,156 +57,456 @@ 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";
61
- //#region src/graphql/analytics-subgraph.ts
62
- const analyticsResolvers = AnalyticsResolvers;
63
- var AnalyticsSubgraph = class extends BaseSubgraph {
64
- analyticsStore;
65
- analyticsModel;
66
- name = "analytics";
67
- typeDefs = gql`
68
- ${typedefs}
69
- `;
70
- /**
71
- * Every analytics field hangs off `Query.analytics`, so gating it gates them
72
- * all. Series are aggregates a processor built from many documents and carry
73
- * no document to decide on, so only a caller with policy-wide read (anyone
74
- * under OPEN, an admin otherwise) may read them.
75
- */
76
- resolvers = {
77
- ...analyticsResolvers,
78
- Query: {
79
- ...analyticsResolvers.Query,
80
- analytics: (parent, args, ctx) => {
81
- this.#assertCanReadAnalytics(ctx);
82
- return analyticsResolvers.Query.analytics(parent, args, ctx);
83
- }
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?.();
84
117
  }
85
- };
86
- constructor(args) {
87
- super(args);
88
- this.analyticsStore = args.analyticsStore;
89
- this.analyticsModel = new AnalyticsModel(new AnalyticsQueryEngine(this.analyticsStore));
90
- args.graphqlManager.setAdditionalContextFields({ dataSources: { db: { Analytics: this.analyticsModel } } });
91
118
  }
92
- #assertCanReadAnalytics(ctx) {
93
- if (this.authorizationService.isSupremeAdmin(ctx.user?.address)) return;
94
- if (ctx.user?.address) throw new ForbiddenError("to read analytics");
95
- throw new AuthenticationRequiredError("to read analytics");
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();
96
125
  }
97
- };
98
- //#endregion
99
- //#region src/graphql/argument-aliases.ts
100
- /** A renamed argument given under both names, or a required one under neither. */
101
- var ArgumentAliasError = class extends GraphQLError {
102
- constructor(message) {
103
- super(message, { extensions: { code: "BAD_USER_INPUT" } });
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;
104
159
  }
105
160
  };
106
- /** The value of a required argument that may still arrive under its old name. */
107
- function requireOneOf(args, name, deprecatedName) {
108
- const current = args[name] ?? void 0;
109
- const deprecated = args[deprecatedName] ?? void 0;
110
- if (current !== void 0 && deprecated !== void 0) throw new ArgumentAliasError(`Pass ${name} or ${deprecatedName}, not both.`);
111
- if (current === void 0 && deprecated === void 0) throw new ArgumentAliasError(`${name} is required.`);
112
- return current ?? deprecated;
113
- }
114
- /** The value of an optional argument that may still arrive under its old name. */
115
- function optionalOneOf(args, name, deprecatedName) {
116
- const current = args[name] ?? void 0;
117
- const deprecated = args[deprecatedName] ?? void 0;
118
- if (current !== void 0 && deprecated !== void 0) throw new ArgumentAliasError(`Pass ${name} or ${deprecatedName}, not both.`);
119
- return current ?? deprecated;
120
- }
121
- //#endregion
122
- //#region src/graphql/auth/resolvers.ts
123
- async function documentAccess(service, authorizationService, args, userAddress) {
124
- if (!userAddress) throw new GraphQLError("Authentication required");
125
- if (!await authorizationService.canManage(args.documentId, userAddress)) throw new GraphQLError("Forbidden: You must be an admin of this document to view its permissions");
126
- const permissions = await service.getDocumentPermissions(args.documentId);
127
- return {
128
- documentId: args.documentId,
129
- permissions
130
- };
131
- }
132
- async function userDocumentPermissions(service, userAddress) {
133
- return service.getUserDocuments(userAddress);
134
- }
135
- async function grantDocumentPermission(service, authorizationService, args, grantedByAddress) {
136
- if (!grantedByAddress) throw new GraphQLError("Authentication required");
137
- if (!await authorizationService.canManage(args.documentId, grantedByAddress)) throw new GraphQLError("Forbidden: You must be an admin of this document to grant permissions");
138
- return service.grantPermission(args.documentId, args.userAddress, args.permission, grantedByAddress);
139
- }
140
- async function revokeDocumentPermission(service, authorizationService, args, revokedByAddress) {
141
- if (!revokedByAddress) throw new GraphQLError("Authentication required");
142
- if (!await authorizationService.canManage(args.documentId, revokedByAddress)) throw new GraphQLError("Forbidden: You must be an admin of this document to revoke permissions");
143
- await service.revokePermission(args.documentId, args.userAddress);
144
- return true;
145
- }
146
- async function operationPermissions(service, authorizationService, args, userAddress) {
147
- if (!userAddress) throw new GraphQLError("Authentication required");
148
- if (!await authorizationService.canManage(args.documentId, userAddress)) throw new GraphQLError("Forbidden: You must be an admin of this document to view its operation permissions");
149
- const userPermissions = await service.getOperationUserPermissions(args.documentId, args.operationType);
150
- return {
151
- documentId: args.documentId,
152
- operationType: args.operationType,
153
- userPermissions
154
- };
155
- }
156
- async function canExecuteOperation(authorizationService, args, userAddress) {
157
- return authorizationService.canMutate(args.documentId, args.operationType, userAddress);
158
- }
159
- async function grantOperationPermission(service, authorizationService, args, grantedByAddress) {
160
- if (!grantedByAddress) throw new GraphQLError("Authentication required");
161
- if (!await authorizationService.canManage(args.documentId, grantedByAddress)) throw new GraphQLError("Forbidden: You must be an admin of this document to grant operation permissions");
162
- return service.grantOperationPermission(args.documentId, args.operationType, args.userAddress, grantedByAddress);
163
- }
164
- async function revokeOperationPermission(service, authorizationService, args, revokedByAddress) {
165
- if (!revokedByAddress) throw new GraphQLError("Authentication required");
166
- if (!await authorizationService.canManage(args.documentId, revokedByAddress)) throw new GraphQLError("Forbidden: You must be an admin of this document to revoke operation permissions");
167
- await service.revokeOperationPermission(args.documentId, args.operationType, args.userAddress);
168
- return true;
169
- }
170
- async function documentProtection(service, authorizationService, args, userAddress) {
171
- if (!userAddress) throw new GraphQLError("Authentication required");
172
- if (!await authorizationService.canManage(args.documentId, userAddress)) throw new GraphQLError("Forbidden: You must be an admin of this document to view its protection info");
173
- return service.getDocumentProtection(args.documentId);
174
- }
175
- async function setDocumentProtection(service, authorizationService, args, userAddress) {
176
- if (!userAddress) throw new GraphQLError("Authentication required");
177
- if (!await authorizationService.canManage(args.documentId, userAddress)) throw new GraphQLError("Forbidden: You must be an admin of this document to change protection");
178
- await service.setDocumentProtection(args.documentId, args.protected);
179
- return service.getDocumentProtection(args.documentId);
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);
180
163
  }
181
- async function transferDocumentOwnership(service, authorizationService, args, userAddress) {
182
- if (!userAddress) throw new GraphQLError("Authentication required");
183
- if (!await authorizationService.canManage(args.documentId, userAddress)) throw new GraphQLError("Forbidden: You must be an admin of this document to transfer ownership");
184
- const previousOwner = await service.getDocumentOwner(args.documentId);
185
- if (previousOwner) await service.revokePermission(args.documentId, previousOwner);
186
- await service.setDocumentOwner(args.documentId, args.newOwnerAddress);
187
- await service.grantPermission(args.documentId, args.newOwnerAddress, "ADMIN", userAddress);
188
- return service.getDocumentProtection(args.documentId);
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;
189
171
  }
190
172
  //#endregion
191
- //#region src/graphql/auth/subgraph.ts
173
+ //#region src/services/permission-cache.ts
192
174
  /**
193
- * Auth Subgraph - handles all document permission and authorization operations
194
- *
195
- * This subgraph is conditionally registered based on the DOCUMENT_PERMISSIONS_ENABLED
196
- * feature flag. When enabled, it provides GraphQL operations for:
197
- * - Document permissions (grant/revoke user access)
198
- * - Document protection and ownership
199
- * - Operation-level permissions (fine-grained operation control)
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.
200
179
  */
201
- var AuthSubgraph = class extends BaseSubgraph {
202
- logger = new ConsoleLogger(["AuthSubgraph"]);
203
- constructor(args) {
204
- super(args);
205
- this.logger.verbose(`constructor()`);
206
- }
207
- name = "auth";
208
- hasSubscriptions = false;
209
- typeDefs = gql(schema_default$1);
210
- resolvers = {
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
360
+ //#region src/graphql/analytics-subgraph.ts
361
+ const analyticsResolvers = AnalyticsResolvers;
362
+ var AnalyticsSubgraph = class extends BaseSubgraph {
363
+ analyticsStore;
364
+ analyticsModel;
365
+ name = "analytics";
366
+ typeDefs = gql`
367
+ ${typedefs}
368
+ `;
369
+ /**
370
+ * Every analytics field hangs off `Query.analytics`, so gating it gates them
371
+ * all. Series are aggregates a processor built from many documents and carry
372
+ * no document to decide on, so only a caller with policy-wide read (anyone
373
+ * under OPEN, an admin otherwise) may read them.
374
+ */
375
+ resolvers = {
376
+ ...analyticsResolvers,
377
+ Query: {
378
+ ...analyticsResolvers.Query,
379
+ analytics: (parent, args, ctx) => {
380
+ this.#assertCanReadAnalytics(ctx);
381
+ return analyticsResolvers.Query.analytics(parent, args, ctx);
382
+ }
383
+ }
384
+ };
385
+ constructor(args) {
386
+ super(args);
387
+ this.analyticsStore = args.analyticsStore;
388
+ this.analyticsModel = new AnalyticsModel(new AnalyticsQueryEngine(this.analyticsStore));
389
+ args.graphqlManager.setAdditionalContextFields({ dataSources: { db: { Analytics: this.analyticsModel } } });
390
+ }
391
+ #assertCanReadAnalytics(ctx) {
392
+ if (this.authorizationService.isSupremeAdmin(ctx.user?.address)) return;
393
+ if (ctx.user?.address) throw new ForbiddenError("to read analytics");
394
+ throw new AuthenticationRequiredError("to read analytics");
395
+ }
396
+ };
397
+ //#endregion
398
+ //#region src/graphql/argument-aliases.ts
399
+ /** A renamed argument given under both names, or a required one under neither. */
400
+ var ArgumentAliasError = class extends GraphQLError {
401
+ constructor(message) {
402
+ super(message, { extensions: { code: "BAD_USER_INPUT" } });
403
+ }
404
+ };
405
+ /** The value of a required argument that may still arrive under its old name. */
406
+ function requireOneOf(args, name, deprecatedName) {
407
+ const current = args[name] ?? void 0;
408
+ const deprecated = args[deprecatedName] ?? void 0;
409
+ if (current !== void 0 && deprecated !== void 0) throw new ArgumentAliasError(`Pass ${name} or ${deprecatedName}, not both.`);
410
+ if (current === void 0 && deprecated === void 0) throw new ArgumentAliasError(`${name} is required.`);
411
+ return current ?? deprecated;
412
+ }
413
+ /** The value of an optional argument that may still arrive under its old name. */
414
+ function optionalOneOf(args, name, deprecatedName) {
415
+ const current = args[name] ?? void 0;
416
+ const deprecated = args[deprecatedName] ?? void 0;
417
+ if (current !== void 0 && deprecated !== void 0) throw new ArgumentAliasError(`Pass ${name} or ${deprecatedName}, not both.`);
418
+ return current ?? deprecated;
419
+ }
420
+ //#endregion
421
+ //#region src/graphql/auth/resolvers.ts
422
+ async function documentAccess(service, authorizationService, args, userAddress) {
423
+ if (!userAddress) throw new GraphQLError("Authentication required");
424
+ if (!await authorizationService.canManage(args.documentId, userAddress)) throw new GraphQLError("Forbidden: You must be an admin of this document to view its permissions");
425
+ const permissions = await service.getDocumentPermissions(args.documentId);
426
+ return {
427
+ documentId: args.documentId,
428
+ permissions
429
+ };
430
+ }
431
+ async function userDocumentPermissions(service, userAddress) {
432
+ return service.getUserDocuments(userAddress);
433
+ }
434
+ async function grantDocumentPermission(service, authorizationService, args, grantedByAddress) {
435
+ if (!grantedByAddress) throw new GraphQLError("Authentication required");
436
+ if (!await authorizationService.canManage(args.documentId, grantedByAddress)) throw new GraphQLError("Forbidden: You must be an admin of this document to grant permissions");
437
+ return service.grantPermission(args.documentId, args.userAddress, args.permission, grantedByAddress);
438
+ }
439
+ async function revokeDocumentPermission(service, authorizationService, args, revokedByAddress) {
440
+ if (!revokedByAddress) throw new GraphQLError("Authentication required");
441
+ if (!await authorizationService.canManage(args.documentId, revokedByAddress)) throw new GraphQLError("Forbidden: You must be an admin of this document to revoke permissions");
442
+ await service.revokePermission(args.documentId, args.userAddress);
443
+ return true;
444
+ }
445
+ async function operationPermissions(service, authorizationService, args, userAddress) {
446
+ if (!userAddress) throw new GraphQLError("Authentication required");
447
+ if (!await authorizationService.canManage(args.documentId, userAddress)) throw new GraphQLError("Forbidden: You must be an admin of this document to view its operation permissions");
448
+ const userPermissions = await service.getOperationUserPermissions(args.documentId, args.operationType);
449
+ return {
450
+ documentId: args.documentId,
451
+ operationType: args.operationType,
452
+ userPermissions
453
+ };
454
+ }
455
+ async function canExecuteOperation(authorizationService, args, userAddress) {
456
+ return authorizationService.canMutate(args.documentId, args.operationType, userAddress);
457
+ }
458
+ async function grantOperationPermission(service, authorizationService, args, grantedByAddress) {
459
+ if (!grantedByAddress) throw new GraphQLError("Authentication required");
460
+ if (!await authorizationService.canManage(args.documentId, grantedByAddress)) throw new GraphQLError("Forbidden: You must be an admin of this document to grant operation permissions");
461
+ return service.grantOperationPermission(args.documentId, args.operationType, args.userAddress, grantedByAddress);
462
+ }
463
+ async function revokeOperationPermission(service, authorizationService, args, revokedByAddress) {
464
+ if (!revokedByAddress) throw new GraphQLError("Authentication required");
465
+ if (!await authorizationService.canManage(args.documentId, revokedByAddress)) throw new GraphQLError("Forbidden: You must be an admin of this document to revoke operation permissions");
466
+ await service.revokeOperationPermission(args.documentId, args.operationType, args.userAddress);
467
+ return true;
468
+ }
469
+ async function documentProtection(service, authorizationService, args, userAddress) {
470
+ if (!userAddress) throw new GraphQLError("Authentication required");
471
+ if (!await authorizationService.canManage(args.documentId, userAddress)) throw new GraphQLError("Forbidden: You must be an admin of this document to view its protection info");
472
+ return service.getDocumentProtection(args.documentId);
473
+ }
474
+ async function setDocumentProtection(service, authorizationService, args, userAddress) {
475
+ if (!userAddress) throw new GraphQLError("Authentication required");
476
+ if (!await authorizationService.canManage(args.documentId, userAddress)) throw new GraphQLError("Forbidden: You must be an admin of this document to change protection");
477
+ await service.setDocumentProtection(args.documentId, args.protected);
478
+ return service.getDocumentProtection(args.documentId);
479
+ }
480
+ async function transferDocumentOwnership(service, authorizationService, args, userAddress) {
481
+ if (!userAddress) throw new GraphQLError("Authentication required");
482
+ if (!await authorizationService.canManage(args.documentId, userAddress)) throw new GraphQLError("Forbidden: You must be an admin of this document to transfer ownership");
483
+ const previousOwner = await service.getDocumentOwner(args.documentId);
484
+ if (previousOwner) await service.revokePermission(args.documentId, previousOwner);
485
+ await service.setDocumentOwner(args.documentId, args.newOwnerAddress);
486
+ await service.grantPermission(args.documentId, args.newOwnerAddress, "ADMIN", userAddress);
487
+ return service.getDocumentProtection(args.documentId);
488
+ }
489
+ //#endregion
490
+ //#region src/graphql/auth/subgraph.ts
491
+ /**
492
+ * Auth Subgraph - handles all document permission and authorization operations
493
+ *
494
+ * This subgraph is conditionally registered based on the DOCUMENT_PERMISSIONS_ENABLED
495
+ * feature flag. When enabled, it provides GraphQL operations for:
496
+ * - Document permissions (grant/revoke user access)
497
+ * - Document protection and ownership
498
+ * - Operation-level permissions (fine-grained operation control)
499
+ */
500
+ var AuthSubgraph = class extends BaseSubgraph {
501
+ logger = new ConsoleLogger(["AuthSubgraph"]);
502
+ constructor(args) {
503
+ super(args);
504
+ this.logger.verbose(`constructor()`);
505
+ }
506
+ name = "auth";
507
+ hasSubscriptions = false;
508
+ typeDefs = gql(schema_default$1);
509
+ resolvers = {
211
510
  Query: {
212
511
  documentAccess: async (_parent, args, ctx) => {
213
512
  this.logger.debug("documentAccess(@args)", args);
@@ -297,236 +596,95 @@ var AuthSubgraph = class extends BaseSubgraph {
297
596
  },
298
597
  revokeDocumentPermission: async (_parent, args, ctx) => {
299
598
  this.logger.debug("revokeDocumentPermission(@args)", args);
300
- if (!this.documentPermissionService) throw new GraphQLError("DocumentPermissionService not available");
301
- try {
302
- return await revokeDocumentPermission(this.documentPermissionService, this.authorizationService, await this.#withCanonicalDocumentArgs(args, ctx), ctx.user?.address);
303
- } catch (error) {
304
- this.logger.error("Error in revokeDocumentPermission: @error", error);
305
- throw error;
306
- }
307
- },
308
- grantOperationPermission: async (_parent, args, ctx) => {
309
- this.logger.debug("grantOperationPermission(@args)", args);
310
- if (!this.documentPermissionService) throw new GraphQLError("DocumentPermissionService not available");
311
- try {
312
- return await grantOperationPermission(this.documentPermissionService, this.authorizationService, await this.#withCanonicalDocumentArgs(args, ctx), ctx.user?.address);
313
- } catch (error) {
314
- this.logger.error("Error in grantOperationPermission: @error", error);
315
- throw error;
316
- }
317
- },
318
- revokeOperationPermission: async (_parent, args, ctx) => {
319
- this.logger.debug("revokeOperationPermission(@args)", args);
320
- if (!this.documentPermissionService) throw new GraphQLError("DocumentPermissionService not available");
321
- try {
322
- return await revokeOperationPermission(this.documentPermissionService, this.authorizationService, await this.#withCanonicalDocumentArgs(args, ctx), ctx.user?.address);
323
- } catch (error) {
324
- this.logger.error("Error in revokeOperationPermission: @error", error);
325
- throw error;
326
- }
327
- }
328
- }
329
- };
330
- #withCanonicalDocumentArgs(args, ctx) {
331
- const { documentIdOrSlug, documentId, ...rest } = args;
332
- return this.withCanonicalDocumentId({
333
- ...rest,
334
- documentId: requireOneOf({
335
- documentIdOrSlug,
336
- documentId
337
- }, "documentIdOrSlug", "documentId")
338
- }, ctx);
339
- }
340
- onSetup() {
341
- this.logger.debug("Setting up AuthSubgraph");
342
- return Promise.resolve();
343
- }
344
- };
345
- //#endregion
346
- //#region src/graphql/gateway/auth-middleware.ts
347
- const authContextMap = /* @__PURE__ */ new WeakMap();
348
- /** Internal — only `graphql-manager.ts` should call this. */
349
- function getAuthContext(request) {
350
- return authContextMap.get(request);
351
- }
352
- function createAuthFetchMiddleware(authService) {
353
- return (next) => async (request) => {
354
- const result = await authService.authenticateRequest(request);
355
- if (result instanceof globalThis.Response) return result;
356
- authContextMap.set(request, result);
357
- return next(request);
358
- };
359
- }
360
- //#endregion
361
- //#region src/graphql/gateway/factory.ts
362
- async function createGatewayAdapter(type, logger) {
363
- switch (type) {
364
- case "apollo": {
365
- const { ApolloGatewayAdapter } = await import("./adapter-gateway-apollo-D-EdZ4e-.mjs").then((n) => n.t);
366
- return new ApolloGatewayAdapter(logger);
367
- }
368
- case "mercurius": {
369
- const { MercuriusGatewayAdapter } = await import("./adapter-gateway-mercurius-CdxLge5p.mjs");
370
- return new MercuriusGatewayAdapter(logger);
371
- }
372
- case "stitching": {
373
- const { StitchingGatewayAdapter } = await Promise.resolve().then(() => adapter_gateway_stitching_exports);
374
- return new StitchingGatewayAdapter(logger);
375
- }
376
- }
377
- }
378
- async function createHttpAdapter(type) {
379
- 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
- ];
404
- //#endregion
405
- //#region src/http/namespace.ts
406
- /**
407
- * A package's namespace is its npm name, used verbatim as one or two path
408
- * segments. Nothing is slugged: dropping the scope, folding `.`/`_` to `-` or
409
- * lower-casing would all map distinct package names onto one namespace, and a
410
- * lossy mapping means two packages can silently claim the same URL space.
411
- * Verbatim is injective, so there is no collision left to detect.
412
- */
413
- /**
414
- * npm's package-name grammar, per segment. Deliberately the same shape the HTTP
415
- * package loader validates with, so a name that can be installed can be routed.
416
- */
417
- const SEGMENT = /^[a-z0-9][-a-z0-9._]*$/i;
418
- /** Segments that would read as path traversal rather than as a name. */
419
- const TRAVERSAL = /* @__PURE__ */ new Set([".", ".."]);
420
- var InvalidNamespaceError = class extends Error {};
421
- /**
422
- * Turns a package name into the path segments it occupies.
423
- * `@powerhousedao/workflow` → ["@powerhousedao", "workflow"]
424
- * `document-model` → ["document-model"]
425
- */
426
- function namespaceSegments(packageName) {
427
- if (!packageName) throw new InvalidNamespaceError("Package name is empty");
428
- const scoped = packageName.startsWith("@");
429
- const parts = (scoped ? packageName.slice(1) : packageName).split("/");
430
- if (parts.length !== (scoped ? 2 : 1)) throw new InvalidNamespaceError(`"${packageName}" is not a package name: expected ${scoped ? "@scope/name" : "name"}`);
431
- for (const part of parts) if (TRAVERSAL.has(part) || !SEGMENT.test(part)) throw new InvalidNamespaceError(`"${packageName}" contains a segment that is not a valid npm name part: "${part}"`);
432
- return scoped ? [`@${parts[0]}`, parts[1]] : parts;
433
- }
434
- /**
435
- * The path a package's routes hang off, relative to the package prefix.
436
- * Scoped names occupy two segments — the addressing unpkg and jsdelivr use.
437
- */
438
- function namespacePath(packageName) {
439
- return namespaceSegments(packageName).join("/");
440
- }
441
- /**
442
- * The same path with the leading `@` percent-encoded. Both routers match the
443
- * raw pathname, so a client that percent-encodes each segment would otherwise
444
- * 404. Registering both spellings avoids decoding the pathname before matching,
445
- * which would turn `%2f` into `/` and let a crafted URL cross segment
446
- * boundaries. `%40` cannot introduce a boundary, which is what makes this safe.
447
- */
448
- function encodedNamespacePath(packageName) {
449
- const path = namespacePath(packageName);
450
- return path.startsWith("@") ? `%40${path.slice(1)}` : void 0;
451
- }
452
- /**
453
- * A route path a package supplied. Must be relative and must not climb out of
454
- * the scope.
455
- */
456
- function assertRelativeRoutePath(path) {
457
- if (path.startsWith("/")) throw new InvalidNamespaceError(`Route path "${path}" must be relative to the scope, not absolute`);
458
- if (/^[a-z][a-z0-9+.-]*:/i.test(path)) throw new InvalidNamespaceError(`Route path "${path}" must be a path, not a URL`);
459
- if (path.split("/").some((segment) => TRAVERSAL.has(segment))) throw new InvalidNamespaceError(`Route path "${path}" must not contain "." or ".." segments`);
460
- return path.replace(/^\/+|\/+$/g, "");
461
- }
462
- /**
463
- * Resolves the npm name a package is routed under from the key the package
464
- * manager holds it by. That key is the specifier as configured, which is not
465
- * always a name:
466
- * - `@scope/pkg` — already a name.
467
- * - `@scope/pkg@1.3.9` — a registry spec; only the loader strips the tag.
468
- * - `/Users/me/project` — the local project, which switchboard registers by
469
- * `process.cwd()`. Its real name lives in its package.json.
470
- *
471
- * Deriving a URL segment straight from the key would give a developer's home
472
- * directory a route namespace, so the path form is resolved rather than slugged.
473
- */
474
- function resolvePackageName(key, readPackageJsonName = defaultReadName) {
475
- const withoutVersion = stripVersionSpec(key);
476
- if (isPackageName(withoutVersion)) return withoutVersion;
477
- if (key.startsWith("/") || key.startsWith(".")) {
478
- const name = readPackageJsonName(key);
479
- if (name && isPackageName(name)) return name;
480
- throw new InvalidNamespaceError(`Package at "${key}" has no usable name in its package.json, so it cannot host routes`);
599
+ if (!this.documentPermissionService) throw new GraphQLError("DocumentPermissionService not available");
600
+ try {
601
+ return await revokeDocumentPermission(this.documentPermissionService, this.authorizationService, await this.#withCanonicalDocumentArgs(args, ctx), ctx.user?.address);
602
+ } catch (error) {
603
+ this.logger.error("Error in revokeDocumentPermission: @error", error);
604
+ throw error;
605
+ }
606
+ },
607
+ grantOperationPermission: async (_parent, args, ctx) => {
608
+ this.logger.debug("grantOperationPermission(@args)", args);
609
+ if (!this.documentPermissionService) throw new GraphQLError("DocumentPermissionService not available");
610
+ try {
611
+ return await grantOperationPermission(this.documentPermissionService, this.authorizationService, await this.#withCanonicalDocumentArgs(args, ctx), ctx.user?.address);
612
+ } catch (error) {
613
+ this.logger.error("Error in grantOperationPermission: @error", error);
614
+ throw error;
615
+ }
616
+ },
617
+ revokeOperationPermission: async (_parent, args, ctx) => {
618
+ this.logger.debug("revokeOperationPermission(@args)", args);
619
+ if (!this.documentPermissionService) throw new GraphQLError("DocumentPermissionService not available");
620
+ try {
621
+ return await revokeOperationPermission(this.documentPermissionService, this.authorizationService, await this.#withCanonicalDocumentArgs(args, ctx), ctx.user?.address);
622
+ } catch (error) {
623
+ this.logger.error("Error in revokeOperationPermission: @error", error);
624
+ throw error;
625
+ }
626
+ }
627
+ }
628
+ };
629
+ #withCanonicalDocumentArgs(args, ctx) {
630
+ const { documentIdOrSlug, documentId, ...rest } = args;
631
+ return this.withCanonicalDocumentId({
632
+ ...rest,
633
+ documentId: requireOneOf({
634
+ documentIdOrSlug,
635
+ documentId
636
+ }, "documentIdOrSlug", "documentId")
637
+ }, ctx);
481
638
  }
482
- throw new InvalidNamespaceError(`"${key}" is not a package name and not a path, so it cannot host routes`);
483
- }
484
- function isPackageName(value) {
485
- try {
486
- namespaceSegments(value);
487
- return true;
488
- } catch {
489
- return false;
639
+ onSetup() {
640
+ this.logger.debug("Setting up AuthSubgraph");
641
+ return Promise.resolve();
490
642
  }
643
+ };
644
+ //#endregion
645
+ //#region src/graphql/gateway/auth-middleware.ts
646
+ const authContextMap = /* @__PURE__ */ new WeakMap();
647
+ /** Internal — only `graphql-manager.ts` should call this. */
648
+ function getAuthContext(request) {
649
+ return authContextMap.get(request);
491
650
  }
492
- /** `@scope/pkg@1.3.9` → `@scope/pkg`; `pkg@1.0.0` → `pkg`. */
493
- function stripVersionSpec(key) {
494
- const at = key.lastIndexOf("@");
495
- if (at <= 0) return key;
496
- return key.slice(0, at);
651
+ function createAuthFetchMiddleware(authService) {
652
+ return (next) => async (request) => {
653
+ const result = await authService.authenticateRequest(request);
654
+ if (result instanceof globalThis.Response) return result;
655
+ authContextMap.set(request, result);
656
+ return next(request);
657
+ };
497
658
  }
498
- function defaultReadName(dir) {
499
- try {
500
- const raw = readFileSync(join(dir, "package.json"), "utf8");
501
- const parsed = JSON.parse(raw);
502
- return typeof parsed.name === "string" ? parsed.name : void 0;
503
- } catch {
504
- return;
659
+ //#endregion
660
+ //#region src/graphql/gateway/factory.ts
661
+ async function createGatewayAdapter(type, logger) {
662
+ switch (type) {
663
+ case "apollo": {
664
+ const { ApolloGatewayAdapter } = await import("./adapter-gateway-apollo-D-EdZ4e-.mjs").then((n) => n.t);
665
+ return new ApolloGatewayAdapter(logger);
666
+ }
667
+ case "mercurius": {
668
+ const { MercuriusGatewayAdapter } = await import("./adapter-gateway-mercurius-CdxLge5p.mjs");
669
+ return new MercuriusGatewayAdapter(logger);
670
+ }
671
+ case "stitching": {
672
+ const { StitchingGatewayAdapter } = await Promise.resolve().then(() => adapter_gateway_stitching_exports);
673
+ return new StitchingGatewayAdapter(logger);
674
+ }
505
675
  }
506
676
  }
507
- /**
508
- * A mount path the host named for one of its own route groups.
509
- *
510
- * The host owns the whole URL space — it holds the adapter — so unlike a
511
- * package it may name an absolute path. That is the difference between hosting
512
- * and being hosted, and it is why this lives on the service rather than on a
513
- * scope: a package is only ever handed a scope, and a scope has no way to
514
- * express a path outside itself.
515
- *
516
- * What the host still may not name is anything that is not one stable literal
517
- * prefix. A traversal segment, or a pattern segment, would make the group's own
518
- * routes unpredictable relative to each other. Returns the normalized path,
519
- * with a leading and no trailing slash.
520
- */
521
- function assertHostMountPath(path) {
522
- if (!path.startsWith("/")) throw new InvalidNamespaceError(`Host mount path "${path}" must be absolute, e.g. "/webhooks"`);
523
- const segments = path.split("/").filter((segment) => segment.length > 0);
524
- if (segments.length === 0) throw new InvalidNamespaceError(`Host mount path "${path}" is the whole URL space, which is the adapter rather than a scope of it`);
525
- for (const segment of segments) {
526
- if (TRAVERSAL.has(segment)) throw new InvalidNamespaceError(`Host mount path "${path}" must not contain "." or ".." segments`);
527
- if (segment.startsWith(":") || segment.includes("*")) throw new InvalidNamespaceError(`Host mount path "${path}" must be a literal prefix, not a pattern: "${segment}"`);
677
+ async function createHttpAdapter(type) {
678
+ switch (type) {
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
+ }
528
687
  }
529
- return `/${segments.join("/")}`;
530
688
  }
531
689
  //#endregion
532
690
  //#region src/http/node-response.ts
@@ -582,793 +740,926 @@ function readBody(req, maxBytes) {
582
740
  req.off("data", onData);
583
741
  req.off("end", onEnd);
584
742
  req.off("error", onError);
585
- req.pause();
586
- if (error) reject(error);
587
- else resolve(Buffer.concat(chunks));
588
- };
589
- const onData = (chunk) => {
590
- size += chunk.length;
591
- if (size > maxBytes) {
592
- settle(new BodyTooLargeError(`Body exceeds ${maxBytes} bytes`));
593
- return;
594
- }
595
- chunks.push(chunk);
596
- };
597
- const onEnd = () => settle();
598
- const onError = (error) => settle(error);
599
- req.on("data", onData);
600
- req.once("end", onEnd);
601
- req.once("error", onError);
602
- });
603
- }
604
- /**
605
- * Copies a Fetch Response onto a Node response, streaming the body. A HEAD
606
- * response carries headers only, however the handler filled the body.
607
- */
608
- async function writeResponse(res, response, method) {
609
- if (res.writableEnded || res.headersSent) return;
610
- res.statusCode = response.status;
611
- response.headers.forEach((value, key) => {
612
- res.setHeader(key, value);
613
- });
614
- if (!response.body || method.toUpperCase() === "HEAD") {
615
- res.end();
616
- return;
617
- }
618
- const source = Readable.fromWeb(response.body);
619
- res.on("close", () => source.destroy());
620
- await pipeline(source, res);
621
- }
622
- /** Answers with a JSON error, unless the response is already underway. */
623
- function writeError(res, status, message) {
624
- if (res.writableEnded || res.headersSent) {
625
- res.destroy();
626
- return;
627
- }
628
- const body = JSON.stringify({ error: message });
629
- res.statusCode = status;
630
- res.setHeader("content-type", "application/json");
631
- res.setHeader("content-length", Buffer.byteLength(body));
632
- res.end(body);
633
- }
634
- //#endregion
635
- //#region src/http/route-service.ts
636
- const logger$2 = childLogger(["reactor-api", "http-routes"]);
637
- /** The segment package routes live under, inside the host's base path. */
638
- const PACKAGE_ROUTE_SEGMENT = "api";
639
- /** The namespace core's own subgraphs and services register under. */
640
- const CORE_PACKAGE_NAME = "@powerhousedao/reactor-api";
641
- /** Generous enough for any request a route should be buffering at all. */
642
- const DEFAULT_MAX_BODY_BYTES$1 = 1048576;
643
- const ANONYMOUS = {
644
- user: void 0,
645
- authEnabled: false
646
- };
647
- /** Owns the URL space packages serve from, handing each a scope bound to its own namespace. The prefix nests inside
648
- * the host's base path (`<basePath>/api`), so core collisions are prevented by URL shape, not a reserved-name list. */
649
- var HttpRouteService = class {
650
- #adapter;
651
- #authService;
652
- #prefix;
653
- #publicUrl;
654
- #trustProxy;
655
- #scopes = /* @__PURE__ */ new Map();
656
- #webhooks;
657
- constructor({ httpAdapter, basePath = "/", authService, webhooks, publicUrl = "", trustProxy = false }) {
658
- this.#adapter = httpAdapter;
659
- this.#authService = authService;
660
- this.#webhooks = webhooks;
661
- this.#publicUrl = publicUrl.replace(/\/+$/, "");
662
- this.#trustProxy = trustProxy;
663
- this.#prefix = posix.join("/", basePath, "api");
664
- }
665
- /** The absolute path packages are mounted under. */
666
- get prefix() {
667
- return this.#prefix;
668
- }
669
- /** The scope for a package; idempotent per name, so a reload cannot accumulate namespaces. Throws when two packages
670
- * resolve to one namespace — with verbatim names that means one package configured twice, a genuine ambiguity. */
671
- scopeFor(packageKey) {
672
- const packageName = resolvePackageName(packageKey);
673
- const namespace = namespacePath(packageName);
674
- const encoded = encodedNamespacePath(packageName);
675
- return this.#scope({
676
- owner: packageName,
677
- base: posix.join(this.#prefix, namespace),
678
- encodedBase: encoded ? posix.join(this.#prefix, encoded) : void 0,
679
- claim: `the route namespace "${namespace}"`,
680
- webhooks: this.#webhooks?.scopeFor(packageName),
681
- onDispose: () => this.#webhooks?.disposeScope(packageName)
682
- });
683
- }
684
- /** A scope at a host-named path; on the service, not `IHttpScope`, so a package can never name one. Namespacing is package
685
- * policy: the host owns its URL space and third parties hold its URLs, so the path is verbatim and outside the package prefix. */
686
- hostScope(name, mountPath) {
687
- const base = assertHostMountPath(mountPath);
688
- if (base === this.#prefix || base.startsWith(`${this.#prefix}/`)) throw new InvalidNamespaceError(`Host scope "${name}" cannot mount at "${base}": that is the package route prefix, which packages own`);
689
- return this.#scope({
690
- owner: name,
691
- base,
692
- encodedBase: void 0,
693
- claim: `the mount path "${base}"`,
694
- webhooks: void 0,
695
- onDispose: () => void 0
696
- });
697
- }
698
- /** Idempotent per base path, so a package reload cannot accumulate namespaces. Two owners wanting one path is an error —
699
- * with verbatim names that needs one package configured twice at different versions, a genuine ambiguity, not a clash. */
700
- #scope(options) {
701
- const { owner, base } = options;
702
- const existing = this.#scopes.get(base);
703
- if (existing) {
704
- if (existing.owner !== owner) throw new Error(`"${owner}" wants ${options.claim}, which "${existing.owner}" already holds`);
705
- return existing;
706
- }
707
- const scope = new HttpScope({
708
- owner,
709
- base,
710
- encodedBase: options.encodedBase,
711
- publicUrl: this.#publicUrl,
712
- trustProxy: this.#trustProxy,
713
- adapter: this.#adapter,
714
- authService: this.#authService,
715
- webhooks: options.webhooks,
716
- onDispose: () => {
717
- this.#scopes.delete(base);
718
- options.onDispose();
743
+ req.pause();
744
+ if (error) reject(error);
745
+ else resolve(Buffer.concat(chunks));
746
+ };
747
+ const onData = (chunk) => {
748
+ size += chunk.length;
749
+ if (size > maxBytes) {
750
+ settle(new BodyTooLargeError(`Body exceeds ${maxBytes} bytes`));
751
+ return;
719
752
  }
720
- });
721
- this.#scopes.set(base, scope);
722
- return scope;
723
- }
724
- /** Like {@link scopeFor}, but never throws: a key resolving to no usable npm name gets a scope that refuses
725
- * registrations, so one unroutable package cannot stop the host booting — it fails only if it serves a route. */
726
- scopeForOrNull(packageKey) {
727
- try {
728
- return this.scopeFor(packageKey);
729
- } catch (error) {
730
- if (!(error instanceof InvalidNamespaceError)) throw error;
731
- logger$2.warn("Package \"@package\" cannot host HTTP routes: @reason", packageKey, error.message);
732
- return new UnroutableScope(packageKey, error.message);
733
- }
734
- }
735
- /** Releases a package's routes, e.g. when it is replaced or removed. */
736
- disposeScope(packageKey) {
737
- try {
738
- const namespace = namespacePath(resolvePackageName(packageKey));
739
- this.#scopes.get(posix.join(this.#prefix, namespace))?.dispose();
740
- } catch (error) {
741
- if (!(error instanceof InvalidNamespaceError)) throw error;
742
- }
753
+ chunks.push(chunk);
754
+ };
755
+ const onEnd = () => settle();
756
+ const onError = (error) => settle(error);
757
+ req.on("data", onData);
758
+ req.once("end", onEnd);
759
+ req.once("error", onError);
760
+ });
761
+ }
762
+ /**
763
+ * Copies a Fetch Response onto a Node response, streaming the body. A HEAD
764
+ * response carries headers only, however the handler filled the body.
765
+ */
766
+ async function writeResponse(res, response, method) {
767
+ if (res.writableEnded || res.headersSent) return;
768
+ res.statusCode = response.status;
769
+ response.headers.forEach((value, key) => {
770
+ res.setHeader(key, value);
771
+ });
772
+ if (!response.body || method.toUpperCase() === "HEAD") {
773
+ res.end();
774
+ return;
743
775
  }
744
- disposeAll() {
745
- for (const scope of [...this.#scopes.values()]) scope.dispose();
776
+ const source = Readable.fromWeb(response.body);
777
+ res.on("close", () => source.destroy());
778
+ await pipeline(source, res);
779
+ }
780
+ /** Answers with a JSON error, unless the response is already underway. */
781
+ function writeError(res, status, message) {
782
+ if (res.writableEnded || res.headersSent) {
783
+ res.destroy();
784
+ return;
746
785
  }
786
+ const body = JSON.stringify({ error: message });
787
+ res.statusCode = status;
788
+ res.setHeader("content-type", "application/json");
789
+ res.setHeader("content-length", Buffer.byteLength(body));
790
+ res.end(body);
791
+ }
792
+ /** Header each scheme reads when the caller does not name one: the name the format is
793
+ * most often carried in, not a property of it, so `WebhookVerification.header` overrides any of them. */
794
+ const DEFAULT_SCHEME_HEADER = {
795
+ none: "",
796
+ token: "x-webhook-token",
797
+ hmac: "x-signature",
798
+ "hmac-prefixed": "x-hub-signature-256",
799
+ "hmac-timestamped": "stripe-signature"
747
800
  };
748
- var HttpScope = class {
749
- owner;
750
- #base;
751
- #publicUrl;
752
- #trustProxy;
753
- #encodedBase;
754
- #adapter;
755
- #authService;
756
- #onDispose;
757
- #registrations = /* @__PURE__ */ new Map();
758
- #webhooks;
759
- constructor(options) {
760
- this.owner = options.owner;
761
- this.#base = options.base;
762
- this.#publicUrl = options.publicUrl;
763
- this.#trustProxy = options.trustProxy;
764
- this.#encodedBase = options.encodedBase;
765
- this.#adapter = options.adapter;
766
- this.#authService = options.authService;
767
- this.#onDispose = options.onDispose;
768
- this.#webhooks = options.webhooks ?? unavailableWebhooks(options.owner);
769
- }
770
- get baseUrl() {
771
- return `${this.#publicUrl}${this.#base}`;
772
- }
773
- get webhooks() {
774
- return this.#webhooks;
775
- }
776
- get(path, a, b) {
777
- return this.#shorthand("GET", path, a, b);
778
- }
779
- post(path, a, b) {
780
- return this.#shorthand("POST", path, a, b);
781
- }
782
- put(path, a, b) {
783
- return this.#shorthand("PUT", path, a, b);
784
- }
785
- patch(path, a, b) {
786
- return this.#shorthand("PATCH", path, a, b);
801
+ const OK = { ok: true };
802
+ /** Constant-time over equal-length inputs; a length mismatch is already a rejection, so
803
+ * the early return leaks nothing a caller could not measure. */
804
+ function secureEquals(a, b) {
805
+ const left = Buffer.from(a, "utf8");
806
+ const right = Buffer.from(b, "utf8");
807
+ if (left.length !== right.length) return false;
808
+ return timingSafeEqual(left, right);
809
+ }
810
+ function hmacDigest(secret, payload, verification) {
811
+ return createHmac(verification.algorithm ?? "sha256", secret).update(payload).digest(verification.encoding ?? "hex");
812
+ }
813
+ /** Hex folds case, so an uppercased digest still verifies. Base64 must not: two distinct
814
+ * digests can differ only in case, so folding there would accept a signature that is not the one computed. */
815
+ function digestEquals(presented, expected, verification) {
816
+ const candidate = presented.trim();
817
+ if ((verification.encoding ?? "hex") === "base64") return secureEquals(candidate, expected);
818
+ return secureEquals(candidate.toLowerCase(), expected.toLowerCase());
819
+ }
820
+ /** The label `hmac-prefixed` expects before the digest. */
821
+ function signaturePrefix(verification) {
822
+ return verification.prefix ?? `${verification.algorithm ?? "sha256"}=`;
823
+ }
824
+ /** `t=<unix>,v1=<hex>[,v1=<hex>…]`. Several `v1` values appear while a secret is being
825
+ * rotated, and any one of them matching is a pass. */
826
+ function parseTimestampedHeader(value) {
827
+ const signatures = [];
828
+ let timestamp;
829
+ for (const part of value.split(",")) {
830
+ const separator = part.indexOf("=");
831
+ if (separator < 0) continue;
832
+ const key = part.slice(0, separator).trim();
833
+ const item = part.slice(separator + 1).trim();
834
+ if (key === "t") timestamp = Number(item);
835
+ else if (key === "v1") signatures.push(item);
787
836
  }
788
- delete(path, a, b) {
789
- return this.#shorthand("DELETE", path, a, b);
837
+ return {
838
+ timestamp,
839
+ signatures
840
+ };
841
+ }
842
+ function schemeHeader(verification) {
843
+ return (verification.header ?? DEFAULT_SCHEME_HEADER[verification.scheme]).toLowerCase();
844
+ }
845
+ /** Verifies a delivery against the configured scheme; `raw` must be the exact bytes
846
+ * received. The reason is for the log only: callers answer a fixed 401, so a probing sender learns nothing from the body. */
847
+ function verifyWebhook(options) {
848
+ const { verification, headers, raw } = options;
849
+ if (verification.scheme === "none") return OK;
850
+ if (!verification.secret) return {
851
+ ok: false,
852
+ reason: "signing secret missing"
853
+ };
854
+ const header = schemeHeader(verification);
855
+ const presented = headers[header];
856
+ if (!presented) return {
857
+ ok: false,
858
+ reason: `header "${header}" absent`
859
+ };
860
+ const secret = verification.secret;
861
+ const tolerance = verification.toleranceSeconds ?? 300;
862
+ switch (verification.scheme) {
863
+ case "token": return secureEquals(presented, secret) ? OK : {
864
+ ok: false,
865
+ reason: "token mismatch"
866
+ };
867
+ case "hmac": return digestEquals(presented, hmacDigest(secret, raw, verification), verification) ? OK : {
868
+ ok: false,
869
+ reason: "hmac mismatch"
870
+ };
871
+ case "hmac-prefixed": return digestEquals(presented, `${signaturePrefix(verification)}${hmacDigest(secret, raw, verification)}`, verification) ? OK : {
872
+ ok: false,
873
+ reason: "hmac mismatch"
874
+ };
875
+ case "hmac-timestamped": {
876
+ const { timestamp, signatures } = parseTimestampedHeader(presented);
877
+ if (timestamp === void 0 || !Number.isFinite(timestamp)) return {
878
+ ok: false,
879
+ reason: "no timestamp in the signature header"
880
+ };
881
+ if (signatures.length === 0) return {
882
+ ok: false,
883
+ reason: "no v1 signature in the header"
884
+ };
885
+ const nowMs = (options.now ?? /* @__PURE__ */ new Date()).getTime();
886
+ if (Math.abs(nowMs / 1e3 - timestamp) > tolerance) return {
887
+ ok: false,
888
+ reason: "timestamp outside the replay window"
889
+ };
890
+ const expected = hmacDigest(secret, Buffer.concat([Buffer.from(`${timestamp}.`, "utf8"), raw]), verification);
891
+ let matched = false;
892
+ for (const signature of signatures) if (digestEquals(signature, expected, verification)) matched = true;
893
+ return matched ? OK : {
894
+ ok: false,
895
+ reason: "hmac mismatch"
896
+ };
897
+ }
790
898
  }
791
- head(path, a, b) {
792
- return this.#shorthand("HEAD", path, a, b);
899
+ }
900
+ /** Headers that would put a credential in a log or run journal. The configured signature
901
+ * header joins them: it is an HMAC of the body under a live secret. */
902
+ const REDACTED_HEADERS = /* @__PURE__ */ new Set([
903
+ "authorization",
904
+ "proxy-authorization",
905
+ "cookie",
906
+ "set-cookie",
907
+ "x-api-key",
908
+ "x-webhook-token",
909
+ "x-signature",
910
+ "x-hub-signature",
911
+ "x-hub-signature-256",
912
+ "stripe-signature"
913
+ ]);
914
+ const REDACTED = "[redacted]";
915
+ function redactHeaders(headers, extra) {
916
+ const redacted = {};
917
+ for (const [name, value] of Object.entries(headers)) {
918
+ const key = name.toLowerCase();
919
+ redacted[key] = REDACTED_HEADERS.has(key) || extra && key === extra.toLowerCase() ? REDACTED : value;
793
920
  }
794
- #shorthand(method, path, a, b) {
795
- const options = typeof a === "function" ? {} : a;
796
- const handler = typeof a === "function" ? a : b;
797
- if (!handler) throw new Error(`Route ${method} ${path} was registered with no handler`);
798
- return this.route({
799
- ...options,
800
- method,
801
- path,
802
- handler
803
- });
921
+ return redacted;
922
+ }
923
+ /** JSON and form bodies become objects; anything else stays decoded text, so a verified
924
+ * XML or CSV payload is still reachable downstream. */
925
+ function parseWebhookBody(raw, contentType) {
926
+ if (raw.length === 0) return void 0;
927
+ const type = (contentType ?? "").split(";")[0].trim().toLowerCase();
928
+ const text = raw.toString("utf8");
929
+ if (type === "application/json" || type.endsWith("+json")) try {
930
+ return JSON.parse(text);
931
+ } catch {
932
+ return text;
804
933
  }
805
- route(spec) {
806
- const body = spec.body ?? "parsed";
807
- return this.#register(spec, (req, res, ctx) => this.#serve(spec, body, req, res, ctx));
934
+ if (type === "application/x-www-form-urlencoded") return Object.fromEntries(new URLSearchParams(text));
935
+ return text;
936
+ }
937
+ //#endregion
938
+ //#region src/http/webhook-service.ts
939
+ const logger$2 = childLogger(["reactor-api", "webhooks"]);
940
+ /** The flat, token-addressed path family. */
941
+ const WEBHOOK_SEGMENT = "webhooks";
942
+ const DEFAULT_MAX_BODY_BYTES$1 = 1048576;
943
+ const DEFAULT_DEDUPE_TTL_SECONDS = 300;
944
+ function readPublicOrigin(origin) {
945
+ return (typeof origin === "function" ? origin() : origin).replace(/\/+$/, "");
946
+ }
947
+ /** One host route for `/webhooks/:token`, dispatching by token. The flat path leaks
948
+ * neither package nor document; the namespace lives in the token record, which is also what stops one package's token reaching another's handler. */
949
+ var WebhookService = class {
950
+ #store;
951
+ #path;
952
+ #publicUrl;
953
+ #scope;
954
+ #registrations = /* @__PURE__ */ new Map();
955
+ #routes = [];
956
+ constructor({ store, basePath = "/", publicUrl }) {
957
+ this.#store = store;
958
+ this.#path = posix.join("/", basePath, WEBHOOK_SEGMENT);
959
+ this.#publicUrl = publicUrl;
808
960
  }
809
- nodeRoute(spec) {
810
- return this.#register(spec, (req, res, ctx) => spec.handler(req, res, ctx));
961
+ /** The scope the endpoint family serves from, handed over once the route service exists;
962
+ * separate from the constructor only because that service takes this one as an option. */
963
+ attach(scope) {
964
+ this.#scope = scope;
965
+ }
966
+ async init() {
967
+ await this.#store.init();
968
+ if (this.#routes.length) return;
969
+ if (!this.#scope) throw new Error("The webhook service has no HTTP scope; the host must call attach() before a package registers");
970
+ this.#routes = [this.#scope.nodeRoute({
971
+ method: [
972
+ "DELETE",
973
+ "GET",
974
+ "HEAD",
975
+ "PATCH",
976
+ "POST",
977
+ "PUT"
978
+ ],
979
+ path: ":token",
980
+ auth: "public",
981
+ handler: (req, res, ctx) => void this.#deliver(req, res, ctx.params)
982
+ })];
811
983
  }
812
984
  dispose() {
813
- for (const registration of this.#registrations.values()) for (const handle of registration.handles) handle.dispose();
985
+ for (const handle of this.#routes) handle.dispose();
986
+ this.#routes = [];
814
987
  this.#registrations.clear();
815
- this.#onDispose();
816
988
  }
817
- /** Mounts one route under this scope's namespace, in both the verbatim and the
818
- * percent-encoded spelling of a scoped name. */
819
- #register(spec, run) {
820
- const relative = assertRelativeRoutePath(spec.path);
821
- const methods = Array.isArray(spec.method) ? spec.method : [spec.method];
822
- const routePath = relative ? posix.join(this.#base, relative) : this.#base;
823
- const key = `${methods.join(",")} ${routePath}`;
824
- if (this.#registrations.has(key)) throw new Error(`Route ${key} is already registered by "${this.owner}"`);
825
- const handles = [];
826
- const paths = [routePath];
827
- if (this.#encodedBase) paths.push(relative ? posix.join(this.#encodedBase, relative) : this.#encodedBase);
828
- for (const path of paths) for (const method of methods) handles.push(this.#adapter.mountNodeRoute(method, path, (req, res) => {
829
- this.#guard(spec, req, res, run);
830
- }, {
831
- rawBody: true,
832
- prefix: spec.prefix
833
- }));
834
- this.#registrations.set(key, {
835
- path: routePath,
836
- handles
837
- });
838
- logger$2.debug("Registered @route for @package", key, this.owner);
989
+ /** The facade a package's HTTP scope exposes as `scope.webhooks`. */
990
+ scopeFor(namespace) {
839
991
  return {
840
- url: `${this.#publicUrl}${routePath}`,
841
- dispose: () => {
842
- const registration = this.#registrations.get(key);
843
- if (!registration) return;
844
- for (const handle of registration.handles) handle.dispose();
845
- this.#registrations.delete(key);
992
+ hasPublicOrigin: this.hasPublicOrigin,
993
+ register: async (spec) => {
994
+ await this.init();
995
+ const key = `${namespace}|${spec.name}`;
996
+ this.#registrations.set(key, {
997
+ namespace,
998
+ spec
999
+ });
1000
+ return {
1001
+ endpointFor: async (ownerKey) => {
1002
+ const row = await this.#store.ensure(namespace, spec.name, ownerKey);
1003
+ return {
1004
+ token: row.token,
1005
+ url: this.urlFor(row.token),
1006
+ createdAt: row.createdAt
1007
+ };
1008
+ },
1009
+ revoke: (ownerKey) => this.#store.revoke(namespace, spec.name, ownerKey),
1010
+ list: async () => (await this.#store.list(namespace, spec.name)).map((row) => ({
1011
+ key: row.ownerKey,
1012
+ token: row.token,
1013
+ url: this.urlFor(row.token),
1014
+ createdAt: row.createdAt
1015
+ }))
1016
+ };
846
1017
  }
847
1018
  };
848
1019
  }
849
- /** Authenticate, then run. */
850
- async #guard(spec, req, res, run) {
851
- try {
852
- const actor = await this.#authenticate(spec.auth ?? "renown", req, res);
853
- if (actor === REJECTED) return;
854
- await run(req, res, {
855
- params: routeParams(req),
856
- user: actor?.user,
857
- authEnabled: actor?.authEnabled ?? false,
858
- transport: resolveTransport(req, this.#trustProxy)
859
- });
860
- } catch (error) {
861
- logger$2.error("Route handler failed for @package", this.owner, error);
862
- writeError(res, 500, "Internal server error");
863
- }
1020
+ /** Releases every registration a package made. */
1021
+ disposeScope(namespace) {
1022
+ for (const [key, registration] of this.#registrations) if (registration.namespace === namespace) this.#registrations.delete(key);
864
1023
  }
865
- /** Resolves the caller, answering the request itself when the route refuses it;
866
- * returns REJECTED in that case so the caller stops. */
867
- async #authenticate(auth, req, res) {
868
- if (auth === "public") return void 0;
869
- if (typeof auth === "function") {
870
- const result = await auth(req);
871
- if (!result.authorized) {
872
- if ("response" in result) await writeResponse(res, result.response, req.method ?? "GET");
873
- else writeError(res, result.status, result.message);
874
- return REJECTED;
875
- }
1024
+ /** The URL to hand a provider. Absolute whenever the host knows its own origin: a
1025
+ * relative path is useless to the third party that has to call it. */
1026
+ urlFor(token) {
1027
+ const path = posix.join(this.#path, token);
1028
+ return this.#publicUrl === void 0 ? path : `${readPublicOrigin(this.#publicUrl)}${path}`;
1029
+ }
1030
+ /** Whether `urlFor` can produce something a provider could call. */
1031
+ get hasPublicOrigin() {
1032
+ return this.#publicUrl !== void 0;
1033
+ }
1034
+ async #deliver(req, res, params) {
1035
+ const token = params.token;
1036
+ if (!token) {
1037
+ writeError(res, 404, "Unknown endpoint");
876
1038
  return;
877
1039
  }
878
- if (!this.#authService) return ANONYMOUS;
879
- const result = await this.#authService.verifyBearer(req.headers.authorization);
880
- if (result instanceof Response) {
881
- await writeResponse(res, result, req.method ?? "GET");
882
- return REJECTED;
883
- }
884
- if (result.auth_enabled && !result.user && auth === "renown") {
885
- writeError(res, 401, "Authentication required");
886
- return REJECTED;
887
- }
888
- return {
889
- user: result.user,
890
- authEnabled: result.auth_enabled
891
- };
892
- }
893
- /** Builds the Fetch Request from the raw stream and runs the handler. */
894
- async #serve(spec, body, req, res, ctx) {
895
- const method = req.method ?? "GET";
896
- const url = `${ctx.transport.baseUrl}${req.url ?? "/"}`;
897
- const controller = new AbortController();
898
- req.once("close", () => controller.abort());
899
- let raw;
900
- let init = {
901
- method,
902
- headers: fetchHeaders(req),
903
- signal: controller.signal
904
- };
905
- if (method !== "GET" && method !== "HEAD" && body !== "none") {
906
- if (body === "stream") init = {
907
- ...init,
908
- body: Readable.toWeb(req),
909
- duplex: "half"
1040
+ try {
1041
+ const row = await this.#store.find(token);
1042
+ if (!row) {
1043
+ writeError(res, 404, "Unknown endpoint");
1044
+ return;
1045
+ }
1046
+ const registrationKey = `${row.namespace}|${row.endpoint}`;
1047
+ const registration = this.#registrations.get(registrationKey);
1048
+ if (!registration) {
1049
+ writeError(res, 503, "Endpoint temporarily unavailable");
1050
+ return;
1051
+ }
1052
+ const { spec } = registration;
1053
+ const method = (req.method ?? "POST").toUpperCase();
1054
+ const perEndpoint = spec.policyFor ? await spec.policyFor(row.ownerKey) : {};
1055
+ if (!perEndpoint) {
1056
+ writeError(res, 404, "Unknown endpoint");
1057
+ return;
1058
+ }
1059
+ const policy = {
1060
+ ...spec.defaults,
1061
+ ...perEndpoint
910
1062
  };
911
- else {
912
- try {
913
- raw = await readBody(req, spec.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES$1);
914
- } catch (error) {
915
- if (error instanceof BodyTooLargeError) {
916
- res.setHeader("connection", "close");
917
- res.once("finish", () => req.destroy());
918
- writeError(res, 413, "Payload too large");
919
- return;
920
- }
921
- throw error;
1063
+ if (policy.methods && !policy.methods.includes(method)) {
1064
+ writeError(res, 405, "Method not allowed");
1065
+ return;
1066
+ }
1067
+ let raw;
1068
+ try {
1069
+ raw = await readBody(req, policy.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES$1);
1070
+ } catch (error) {
1071
+ if (error instanceof BodyTooLargeError) {
1072
+ res.setHeader("connection", "close");
1073
+ res.once("finish", () => req.destroy());
1074
+ writeError(res, 413, "Payload too large");
1075
+ return;
1076
+ }
1077
+ throw error;
1078
+ }
1079
+ const verification = policy.verify;
1080
+ if (verification) {
1081
+ const result = verifyWebhook({
1082
+ verification,
1083
+ headers: headerRecord(req),
1084
+ raw
1085
+ });
1086
+ if (!result.ok) {
1087
+ logger$2.warn("Rejected webhook delivery for @package/@endpoint: @reason", row.namespace, row.endpoint, result.reason);
1088
+ writeError(res, 401, "Signature verification failed");
1089
+ return;
1090
+ }
1091
+ }
1092
+ const url = new URL(req.url ?? "/", "http://localhost");
1093
+ const queryParams = Object.fromEntries(url.searchParams);
1094
+ const signatureHeader = verification ? schemeHeader(verification) : void 0;
1095
+ const headers = headerRecord(req);
1096
+ const body = parseWebhookBody(raw, headers["content-type"]);
1097
+ const challenge = challengeValue(policy.challengeField, queryParams, headers, body);
1098
+ if (challenge !== void 0) {
1099
+ res.statusCode = 200;
1100
+ res.setHeader("content-type", "text/plain");
1101
+ res.end(challenge);
1102
+ return;
1103
+ }
1104
+ let recordedKey;
1105
+ if (policy.dedupe) {
1106
+ const key = dedupeKey(policy.dedupe.field, queryParams, headers, body);
1107
+ recordedKey = key;
1108
+ if (key !== void 0 && await this.#store.seen(token, key, policy.dedupe.ttlSeconds ?? DEFAULT_DEDUPE_TTL_SECONDS)) {
1109
+ res.statusCode = 200;
1110
+ res.end();
1111
+ return;
922
1112
  }
923
- if (raw.length) init = {
924
- ...init,
925
- body: new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength)
926
- };
927
1113
  }
1114
+ const reply = await spec.onRequest({
1115
+ key: row.ownerKey,
1116
+ method,
1117
+ path: url.pathname,
1118
+ queryParams,
1119
+ headers: redactHeaders(headers, signatureHeader),
1120
+ raw,
1121
+ body
1122
+ });
1123
+ if (reply.unprocessed === true && recordedKey !== void 0) try {
1124
+ await this.#store.forget(token, recordedKey);
1125
+ } catch (error) {
1126
+ logger$2.warn("Could not forget an unprocessed webhook delivery: @error", error);
1127
+ }
1128
+ res.statusCode = reply.status;
1129
+ if (reply.body !== void 0 && method !== "HEAD") {
1130
+ res.setHeader("content-type", reply.contentType ?? "text/plain");
1131
+ res.end(reply.body);
1132
+ } else res.end();
1133
+ } catch (error) {
1134
+ logger$2.error("Webhook delivery failed for @method", req.method, error);
1135
+ writeError(res, 500, "Internal server error");
928
1136
  }
929
- await writeResponse(res, await spec.handler(new Request(url, init), {
930
- ...ctx,
931
- rawBody: body === "raw" ? raw ?? Buffer.alloc(0) : void 0,
932
- signal: controller.signal
933
- }), method);
934
1137
  }
935
1138
  };
936
- const REJECTED = Symbol("rejected");
937
- function routeParams(req) {
938
- const params = req.params;
939
- if (!params || typeof params !== "object") return {};
940
- const out = {};
941
- for (const [key, value] of Object.entries(params)) if (typeof value === "string") out[key] = value;
942
- else if (Array.isArray(value)) out[key] = value.join("/");
943
- return out;
1139
+ function headerRecord(req) {
1140
+ const headers = {};
1141
+ for (const [name, value] of Object.entries(req.headers)) {
1142
+ if (value === void 0) continue;
1143
+ headers[name.toLowerCase()] = Array.isArray(value) ? value.join(", ") : value;
1144
+ }
1145
+ return headers;
944
1146
  }
945
- /** Stands in for a package that cannot be routed — its key resolves to no npm name. Registering a route throws with
946
- * the reason; nothing else does, so the package still loads and its non-HTTP behaviour is unaffected. */
947
- var UnroutableScope = class {
948
- owner;
949
- baseUrl = "";
950
- #reason;
951
- constructor(packageKey, reason) {
952
- this.owner = packageKey;
953
- this.#reason = reason;
1147
+ function scalar(value) {
1148
+ if (typeof value === "string" && value !== "") return value;
1149
+ if (typeof value === "number") return String(value);
1150
+ }
1151
+ /** Walks a dot-separated path into the parsed body. */
1152
+ function bodyPath(path, body) {
1153
+ let current = body;
1154
+ for (const segment of path.split(".")) {
1155
+ if (!current || typeof current !== "object") return void 0;
1156
+ current = current[segment];
954
1157
  }
955
- #refuse() {
956
- throw new Error(`Package "${this.owner}" cannot host HTTP routes: ${this.#reason}`);
1158
+ return scalar(current);
1159
+ }
1160
+ /** Resolves where a provider put a value. A bare string means query first, then a
1161
+ * top-level body field; `{ header }` and `{ body }` reach what that cannot — GitHub's delivery id is a header, Stripe's event id is nested. */
1162
+ function fieldValue(field, queryParams, headers, body) {
1163
+ if (typeof field === "object") return "header" in field ? scalar(headers[field.header.toLowerCase()]) : bodyPath(field.body, body);
1164
+ const fromQuery = scalar(queryParams[field]);
1165
+ if (fromQuery !== void 0) return fromQuery;
1166
+ return body && typeof body === "object" ? scalar(body[field]) : void 0;
1167
+ }
1168
+ function challengeValue(field, queryParams, headers, body) {
1169
+ return field === void 0 ? void 0 : fieldValue(field, queryParams, headers, body);
1170
+ }
1171
+ function dedupeKey(field, queryParams, headers, body) {
1172
+ return fieldValue(field, queryParams, headers, body);
1173
+ }
1174
+ //#endregion
1175
+ //#region src/http/namespace.ts
1176
+ /**
1177
+ * A package's namespace is its npm name, used verbatim as one or two path
1178
+ * segments. Nothing is slugged: dropping the scope, folding `.`/`_` to `-` or
1179
+ * lower-casing would all map distinct package names onto one namespace, and a
1180
+ * lossy mapping means two packages can silently claim the same URL space.
1181
+ * Verbatim is injective, so there is no collision left to detect.
1182
+ */
1183
+ /**
1184
+ * npm's package-name grammar, per segment. Deliberately the same shape the HTTP
1185
+ * package loader validates with, so a name that can be installed can be routed.
1186
+ */
1187
+ const SEGMENT = /^[a-z0-9][-a-z0-9._]*$/i;
1188
+ /** Segments that would read as path traversal rather than as a name. */
1189
+ const TRAVERSAL = /* @__PURE__ */ new Set([".", ".."]);
1190
+ var InvalidNamespaceError = class extends Error {};
1191
+ /**
1192
+ * Turns a package name into the path segments it occupies.
1193
+ * `@powerhousedao/workflow` → ["@powerhousedao", "workflow"]
1194
+ * `document-model` → ["document-model"]
1195
+ */
1196
+ function namespaceSegments(packageName) {
1197
+ if (!packageName) throw new InvalidNamespaceError("Package name is empty");
1198
+ const scoped = packageName.startsWith("@");
1199
+ const parts = (scoped ? packageName.slice(1) : packageName).split("/");
1200
+ if (parts.length !== (scoped ? 2 : 1)) throw new InvalidNamespaceError(`"${packageName}" is not a package name: expected ${scoped ? "@scope/name" : "name"}`);
1201
+ for (const part of parts) if (TRAVERSAL.has(part) || !SEGMENT.test(part)) throw new InvalidNamespaceError(`"${packageName}" contains a segment that is not a valid npm name part: "${part}"`);
1202
+ return scoped ? [`@${parts[0]}`, parts[1]] : parts;
1203
+ }
1204
+ /**
1205
+ * The path a package's routes hang off, relative to the package prefix.
1206
+ * Scoped names occupy two segments — the addressing unpkg and jsdelivr use.
1207
+ */
1208
+ function namespacePath(packageName) {
1209
+ return namespaceSegments(packageName).join("/");
1210
+ }
1211
+ /**
1212
+ * The same path with the leading `@` percent-encoded. Both routers match the
1213
+ * raw pathname, so a client that percent-encodes each segment would otherwise
1214
+ * 404. Registering both spellings avoids decoding the pathname before matching,
1215
+ * which would turn `%2f` into `/` and let a crafted URL cross segment
1216
+ * boundaries. `%40` cannot introduce a boundary, which is what makes this safe.
1217
+ */
1218
+ function encodedNamespacePath(packageName) {
1219
+ const path = namespacePath(packageName);
1220
+ return path.startsWith("@") ? `%40${path.slice(1)}` : void 0;
1221
+ }
1222
+ /**
1223
+ * A route path a package supplied. Must be relative and must not climb out of
1224
+ * the scope.
1225
+ */
1226
+ function assertRelativeRoutePath(path) {
1227
+ if (path.startsWith("/")) throw new InvalidNamespaceError(`Route path "${path}" must be relative to the scope, not absolute`);
1228
+ if (/^[a-z][a-z0-9+.-]*:/i.test(path)) throw new InvalidNamespaceError(`Route path "${path}" must be a path, not a URL`);
1229
+ if (path.split("/").some((segment) => TRAVERSAL.has(segment))) throw new InvalidNamespaceError(`Route path "${path}" must not contain "." or ".." segments`);
1230
+ return path.replace(/^\/+|\/+$/g, "");
1231
+ }
1232
+ /**
1233
+ * Resolves the npm name a package is routed under from the key the package
1234
+ * manager holds it by. That key is the specifier as configured, which is not
1235
+ * always a name:
1236
+ * - `@scope/pkg` — already a name.
1237
+ * - `@scope/pkg@1.3.9` — a registry spec; only the loader strips the tag.
1238
+ * - `/Users/me/project` — the local project, which switchboard registers by
1239
+ * `process.cwd()`. Its real name lives in its package.json.
1240
+ *
1241
+ * Deriving a URL segment straight from the key would give a developer's home
1242
+ * directory a route namespace, so the path form is resolved rather than slugged.
1243
+ */
1244
+ function resolvePackageName(key, readPackageJsonName = defaultReadName) {
1245
+ const withoutVersion = stripVersionSpec(key);
1246
+ if (isPackageName(withoutVersion)) return withoutVersion;
1247
+ if (key.startsWith("/") || key.startsWith(".")) {
1248
+ const name = readPackageJsonName(key);
1249
+ if (name && isPackageName(name)) return name;
1250
+ throw new InvalidNamespaceError(`Package at "${key}" has no usable name in its package.json, so it cannot host routes`);
957
1251
  }
958
- get() {
959
- this.#refuse();
1252
+ throw new InvalidNamespaceError(`"${key}" is not a package name and not a path, so it cannot host routes`);
1253
+ }
1254
+ function isPackageName(value) {
1255
+ try {
1256
+ namespaceSegments(value);
1257
+ return true;
1258
+ } catch {
1259
+ return false;
1260
+ }
1261
+ }
1262
+ /** `@scope/pkg@1.3.9` → `@scope/pkg`; `pkg@1.0.0` → `pkg`. */
1263
+ function stripVersionSpec(key) {
1264
+ const at = key.lastIndexOf("@");
1265
+ if (at <= 0) return key;
1266
+ return key.slice(0, at);
1267
+ }
1268
+ function defaultReadName(dir) {
1269
+ try {
1270
+ const raw = readFileSync(join(dir, "package.json"), "utf8");
1271
+ const parsed = JSON.parse(raw);
1272
+ return typeof parsed.name === "string" ? parsed.name : void 0;
1273
+ } catch {
1274
+ return;
1275
+ }
1276
+ }
1277
+ /**
1278
+ * A mount path the host named for one of its own route groups.
1279
+ *
1280
+ * The host owns the whole URL space — it holds the adapter — so unlike a
1281
+ * package it may name an absolute path. That is the difference between hosting
1282
+ * and being hosted, and it is why this lives on the service rather than on a
1283
+ * scope: a package is only ever handed a scope, and a scope has no way to
1284
+ * express a path outside itself.
1285
+ *
1286
+ * What the host still may not name is anything that is not one stable literal
1287
+ * prefix. A traversal segment, or a pattern segment, would make the group's own
1288
+ * routes unpredictable relative to each other. Returns the normalized path,
1289
+ * with a leading and no trailing slash.
1290
+ */
1291
+ function assertHostMountPath(path) {
1292
+ if (!path.startsWith("/")) throw new InvalidNamespaceError(`Host mount path "${path}" must be absolute, e.g. "/webhooks"`);
1293
+ const segments = path.split("/").filter((segment) => segment.length > 0);
1294
+ if (segments.length === 0) throw new InvalidNamespaceError(`Host mount path "${path}" is the whole URL space, which is the adapter rather than a scope of it`);
1295
+ for (const segment of segments) {
1296
+ if (TRAVERSAL.has(segment)) throw new InvalidNamespaceError(`Host mount path "${path}" must not contain "." or ".." segments`);
1297
+ if (segment.startsWith(":") || segment.includes("*")) throw new InvalidNamespaceError(`Host mount path "${path}" must be a literal prefix, not a pattern: "${segment}"`);
1298
+ }
1299
+ return `/${segments.join("/")}`;
1300
+ }
1301
+ //#endregion
1302
+ //#region src/http/route-service.ts
1303
+ const logger$1 = childLogger(["reactor-api", "http-routes"]);
1304
+ /** The segment package routes live under, inside the host's base path. */
1305
+ const PACKAGE_ROUTE_SEGMENT = "api";
1306
+ /** The namespace core's own subgraphs and services register under. */
1307
+ const CORE_PACKAGE_NAME = "@powerhousedao/reactor-api";
1308
+ /** Generous enough for any request a route should be buffering at all. */
1309
+ const DEFAULT_MAX_BODY_BYTES = 1048576;
1310
+ const ANONYMOUS = {
1311
+ user: void 0,
1312
+ authEnabled: false
1313
+ };
1314
+ /** Owns the URL space packages serve from, handing each a scope bound to its own namespace. The prefix nests inside
1315
+ * the host's base path (`<basePath>/api`), so core collisions are prevented by URL shape, not a reserved-name list. */
1316
+ var HttpRouteService = class {
1317
+ #adapter;
1318
+ #authService;
1319
+ #prefix;
1320
+ #publicUrl;
1321
+ #trustProxy;
1322
+ #scopes = /* @__PURE__ */ new Map();
1323
+ #webhooks;
1324
+ constructor({ httpAdapter, basePath = "/", authService, webhooks, publicUrl = "", trustProxy = false }) {
1325
+ this.#adapter = httpAdapter;
1326
+ this.#authService = authService;
1327
+ this.#webhooks = webhooks;
1328
+ this.#publicUrl = publicUrl;
1329
+ this.#trustProxy = trustProxy;
1330
+ this.#prefix = posix.join("/", basePath, "api");
1331
+ }
1332
+ /** The absolute path packages are mounted under. */
1333
+ get prefix() {
1334
+ return this.#prefix;
1335
+ }
1336
+ /** The scope for a package; idempotent per name, so a reload cannot accumulate namespaces. Throws when two packages
1337
+ * resolve to one namespace — with verbatim names that means one package configured twice, a genuine ambiguity. */
1338
+ scopeFor(packageKey) {
1339
+ const packageName = resolvePackageName(packageKey);
1340
+ const namespace = namespacePath(packageName);
1341
+ const encoded = encodedNamespacePath(packageName);
1342
+ return this.#scope({
1343
+ owner: packageName,
1344
+ base: posix.join(this.#prefix, namespace),
1345
+ encodedBase: encoded ? posix.join(this.#prefix, encoded) : void 0,
1346
+ claim: `the route namespace "${namespace}"`,
1347
+ webhooks: this.#webhooks?.scopeFor(packageName),
1348
+ onDispose: () => this.#webhooks?.disposeScope(packageName)
1349
+ });
960
1350
  }
961
- post() {
962
- this.#refuse();
1351
+ /** A scope at a host-named path; on the service, not `IHttpScope`, so a package can never name one. Namespacing is package
1352
+ * policy: the host owns its URL space and third parties hold its URLs, so the path is verbatim and outside the package prefix. */
1353
+ hostScope(name, mountPath) {
1354
+ const base = assertHostMountPath(mountPath);
1355
+ if (base === this.#prefix || base.startsWith(`${this.#prefix}/`)) throw new InvalidNamespaceError(`Host scope "${name}" cannot mount at "${base}": that is the package route prefix, which packages own`);
1356
+ return this.#scope({
1357
+ owner: name,
1358
+ base,
1359
+ encodedBase: void 0,
1360
+ claim: `the mount path "${base}"`,
1361
+ webhooks: void 0,
1362
+ onDispose: () => void 0
1363
+ });
963
1364
  }
964
- put() {
965
- this.#refuse();
1365
+ /** Idempotent per base path, so a package reload cannot accumulate namespaces. Two owners wanting one path is an error —
1366
+ * with verbatim names that needs one package configured twice at different versions, a genuine ambiguity, not a clash. */
1367
+ #scope(options) {
1368
+ const { owner, base } = options;
1369
+ const existing = this.#scopes.get(base);
1370
+ if (existing) {
1371
+ if (existing.owner !== owner) throw new Error(`"${owner}" wants ${options.claim}, which "${existing.owner}" already holds`);
1372
+ return existing;
1373
+ }
1374
+ const scope = new HttpScope({
1375
+ owner,
1376
+ base,
1377
+ encodedBase: options.encodedBase,
1378
+ publicUrl: this.#publicUrl,
1379
+ trustProxy: this.#trustProxy,
1380
+ adapter: this.#adapter,
1381
+ authService: this.#authService,
1382
+ webhooks: options.webhooks,
1383
+ onDispose: () => {
1384
+ this.#scopes.delete(base);
1385
+ options.onDispose();
1386
+ }
1387
+ });
1388
+ this.#scopes.set(base, scope);
1389
+ return scope;
966
1390
  }
967
- patch() {
968
- this.#refuse();
1391
+ /** Like {@link scopeFor}, but never throws: a key resolving to no usable npm name gets a scope that refuses
1392
+ * registrations, so one unroutable package cannot stop the host booting — it fails only if it serves a route. */
1393
+ scopeForOrNull(packageKey) {
1394
+ try {
1395
+ return this.scopeFor(packageKey);
1396
+ } catch (error) {
1397
+ if (!(error instanceof InvalidNamespaceError)) throw error;
1398
+ logger$1.warn("Package \"@package\" cannot host HTTP routes: @reason", packageKey, error.message);
1399
+ return new UnroutableScope(packageKey, error.message);
1400
+ }
969
1401
  }
970
- delete() {
971
- this.#refuse();
1402
+ /** Releases a package's routes, e.g. when it is replaced or removed. */
1403
+ disposeScope(packageKey) {
1404
+ try {
1405
+ const namespace = namespacePath(resolvePackageName(packageKey));
1406
+ this.#scopes.get(posix.join(this.#prefix, namespace))?.dispose();
1407
+ } catch (error) {
1408
+ if (!(error instanceof InvalidNamespaceError)) throw error;
1409
+ }
972
1410
  }
973
- head() {
974
- this.#refuse();
1411
+ disposeAll() {
1412
+ for (const scope of [...this.#scopes.values()]) scope.dispose();
975
1413
  }
976
- route() {
977
- this.#refuse();
1414
+ };
1415
+ var HttpScope = class {
1416
+ owner;
1417
+ #base;
1418
+ #publicUrl;
1419
+ #trustProxy;
1420
+ #encodedBase;
1421
+ #adapter;
1422
+ #authService;
1423
+ #onDispose;
1424
+ #registrations = /* @__PURE__ */ new Map();
1425
+ #webhooks;
1426
+ constructor(options) {
1427
+ this.owner = options.owner;
1428
+ this.#base = options.base;
1429
+ this.#publicUrl = options.publicUrl;
1430
+ this.#trustProxy = options.trustProxy;
1431
+ this.#encodedBase = options.encodedBase;
1432
+ this.#adapter = options.adapter;
1433
+ this.#authService = options.authService;
1434
+ this.#onDispose = options.onDispose;
1435
+ this.#webhooks = options.webhooks ?? unavailableWebhooks(options.owner);
978
1436
  }
979
- nodeRoute() {
980
- this.#refuse();
1437
+ get baseUrl() {
1438
+ return `${readPublicOrigin(this.#publicUrl)}${this.#base}`;
981
1439
  }
982
1440
  get webhooks() {
983
- return unavailableWebhooks(this.owner);
1441
+ return this.#webhooks;
984
1442
  }
985
- dispose() {}
986
- };
987
- /** Stands in when the host has no webhook store configured. */
988
- function unavailableWebhooks(packageName) {
989
- return {
990
- hasPublicOrigin: false,
991
- register: () => Promise.reject(/* @__PURE__ */ new Error(`Webhooks are not available on this host, so "${packageName}" cannot register one`))
992
- };
993
- }
994
- /** Header each scheme reads when the caller does not name one: the name the format is
995
- * most often carried in, not a property of it, so `WebhookVerification.header` overrides any of them. */
996
- const DEFAULT_SCHEME_HEADER = {
997
- none: "",
998
- token: "x-webhook-token",
999
- hmac: "x-signature",
1000
- "hmac-prefixed": "x-hub-signature-256",
1001
- "hmac-timestamped": "stripe-signature"
1002
- };
1003
- const OK = { ok: true };
1004
- /** Constant-time over equal-length inputs; a length mismatch is already a rejection, so
1005
- * the early return leaks nothing a caller could not measure. */
1006
- function secureEquals(a, b) {
1007
- const left = Buffer.from(a, "utf8");
1008
- const right = Buffer.from(b, "utf8");
1009
- if (left.length !== right.length) return false;
1010
- return timingSafeEqual(left, right);
1011
- }
1012
- function hmacDigest(secret, payload, verification) {
1013
- return createHmac(verification.algorithm ?? "sha256", secret).update(payload).digest(verification.encoding ?? "hex");
1014
- }
1015
- /** Hex folds case, so an uppercased digest still verifies. Base64 must not: two distinct
1016
- * digests can differ only in case, so folding there would accept a signature that is not the one computed. */
1017
- function digestEquals(presented, expected, verification) {
1018
- const candidate = presented.trim();
1019
- if ((verification.encoding ?? "hex") === "base64") return secureEquals(candidate, expected);
1020
- return secureEquals(candidate.toLowerCase(), expected.toLowerCase());
1021
- }
1022
- /** The label `hmac-prefixed` expects before the digest. */
1023
- function signaturePrefix(verification) {
1024
- return verification.prefix ?? `${verification.algorithm ?? "sha256"}=`;
1025
- }
1026
- /** `t=<unix>,v1=<hex>[,v1=<hex>…]`. Several `v1` values appear while a secret is being
1027
- * rotated, and any one of them matching is a pass. */
1028
- function parseTimestampedHeader(value) {
1029
- const signatures = [];
1030
- let timestamp;
1031
- for (const part of value.split(",")) {
1032
- const separator = part.indexOf("=");
1033
- if (separator < 0) continue;
1034
- const key = part.slice(0, separator).trim();
1035
- const item = part.slice(separator + 1).trim();
1036
- if (key === "t") timestamp = Number(item);
1037
- else if (key === "v1") signatures.push(item);
1443
+ get(path, a, b) {
1444
+ return this.#shorthand("GET", path, a, b);
1038
1445
  }
1039
- return {
1040
- timestamp,
1041
- signatures
1042
- };
1043
- }
1044
- function schemeHeader(verification) {
1045
- return (verification.header ?? DEFAULT_SCHEME_HEADER[verification.scheme]).toLowerCase();
1046
- }
1047
- /** Verifies a delivery against the configured scheme; `raw` must be the exact bytes
1048
- * received. The reason is for the log only: callers answer a fixed 401, so a probing sender learns nothing from the body. */
1049
- function verifyWebhook(options) {
1050
- const { verification, headers, raw } = options;
1051
- if (verification.scheme === "none") return OK;
1052
- if (!verification.secret) return {
1053
- ok: false,
1054
- reason: "signing secret missing"
1055
- };
1056
- const header = schemeHeader(verification);
1057
- const presented = headers[header];
1058
- if (!presented) return {
1059
- ok: false,
1060
- reason: `header "${header}" absent`
1061
- };
1062
- const secret = verification.secret;
1063
- const tolerance = verification.toleranceSeconds ?? 300;
1064
- switch (verification.scheme) {
1065
- case "token": return secureEquals(presented, secret) ? OK : {
1066
- ok: false,
1067
- reason: "token mismatch"
1068
- };
1069
- case "hmac": return digestEquals(presented, hmacDigest(secret, raw, verification), verification) ? OK : {
1070
- ok: false,
1071
- reason: "hmac mismatch"
1072
- };
1073
- case "hmac-prefixed": return digestEquals(presented, `${signaturePrefix(verification)}${hmacDigest(secret, raw, verification)}`, verification) ? OK : {
1074
- ok: false,
1075
- reason: "hmac mismatch"
1076
- };
1077
- case "hmac-timestamped": {
1078
- const { timestamp, signatures } = parseTimestampedHeader(presented);
1079
- if (timestamp === void 0 || !Number.isFinite(timestamp)) return {
1080
- ok: false,
1081
- reason: "no timestamp in the signature header"
1082
- };
1083
- if (signatures.length === 0) return {
1084
- ok: false,
1085
- reason: "no v1 signature in the header"
1086
- };
1087
- const nowMs = (options.now ?? /* @__PURE__ */ new Date()).getTime();
1088
- if (Math.abs(nowMs / 1e3 - timestamp) > tolerance) return {
1089
- ok: false,
1090
- reason: "timestamp outside the replay window"
1091
- };
1092
- const expected = hmacDigest(secret, Buffer.concat([Buffer.from(`${timestamp}.`, "utf8"), raw]), verification);
1093
- let matched = false;
1094
- for (const signature of signatures) if (digestEquals(signature, expected, verification)) matched = true;
1095
- return matched ? OK : {
1096
- ok: false,
1097
- reason: "hmac mismatch"
1098
- };
1099
- }
1446
+ post(path, a, b) {
1447
+ return this.#shorthand("POST", path, a, b);
1100
1448
  }
1101
- }
1102
- /** Headers that would put a credential in a log or run journal. The configured signature
1103
- * header joins them: it is an HMAC of the body under a live secret. */
1104
- const REDACTED_HEADERS = /* @__PURE__ */ new Set([
1105
- "authorization",
1106
- "proxy-authorization",
1107
- "cookie",
1108
- "set-cookie",
1109
- "x-api-key",
1110
- "x-webhook-token",
1111
- "x-signature",
1112
- "x-hub-signature",
1113
- "x-hub-signature-256",
1114
- "stripe-signature"
1115
- ]);
1116
- const REDACTED = "[redacted]";
1117
- function redactHeaders(headers, extra) {
1118
- const redacted = {};
1119
- for (const [name, value] of Object.entries(headers)) {
1120
- const key = name.toLowerCase();
1121
- redacted[key] = REDACTED_HEADERS.has(key) || extra && key === extra.toLowerCase() ? REDACTED : value;
1449
+ put(path, a, b) {
1450
+ return this.#shorthand("PUT", path, a, b);
1122
1451
  }
1123
- return redacted;
1124
- }
1125
- /** JSON and form bodies become objects; anything else stays decoded text, so a verified
1126
- * XML or CSV payload is still reachable downstream. */
1127
- function parseWebhookBody(raw, contentType) {
1128
- if (raw.length === 0) return void 0;
1129
- const type = (contentType ?? "").split(";")[0].trim().toLowerCase();
1130
- const text = raw.toString("utf8");
1131
- if (type === "application/json" || type.endsWith("+json")) try {
1132
- return JSON.parse(text);
1133
- } catch {
1134
- return text;
1452
+ patch(path, a, b) {
1453
+ return this.#shorthand("PATCH", path, a, b);
1135
1454
  }
1136
- if (type === "application/x-www-form-urlencoded") return Object.fromEntries(new URLSearchParams(text));
1137
- return text;
1138
- }
1139
- //#endregion
1140
- //#region src/http/webhook-service.ts
1141
- const logger$1 = childLogger(["reactor-api", "webhooks"]);
1142
- /** The flat, token-addressed path family. */
1143
- const WEBHOOK_SEGMENT = "webhooks";
1144
- const DEFAULT_MAX_BODY_BYTES = 1048576;
1145
- const DEFAULT_DEDUPE_TTL_SECONDS = 300;
1146
- /** One host route for `/webhooks/:token`, dispatching by token. The flat path leaks
1147
- * neither package nor document; the namespace lives in the token record, which is also what stops one package's token reaching another's handler. */
1148
- var WebhookService = class {
1149
- #store;
1150
- #path;
1151
- #publicUrl;
1152
- #scope;
1153
- #registrations = /* @__PURE__ */ new Map();
1154
- #routes = [];
1155
- constructor({ store, basePath = "/", publicUrl }) {
1156
- this.#store = store;
1157
- this.#path = posix.join("/", basePath, WEBHOOK_SEGMENT);
1158
- this.#publicUrl = publicUrl?.replace(/\/+$/, "");
1455
+ delete(path, a, b) {
1456
+ return this.#shorthand("DELETE", path, a, b);
1159
1457
  }
1160
- /** The scope the endpoint family serves from, handed over once the route service exists;
1161
- * separate from the constructor only because that service takes this one as an option. */
1162
- attach(scope) {
1163
- this.#scope = scope;
1458
+ head(path, a, b) {
1459
+ return this.#shorthand("HEAD", path, a, b);
1164
1460
  }
1165
- async init() {
1166
- await this.#store.init();
1167
- if (this.#routes.length) return;
1168
- if (!this.#scope) throw new Error("The webhook service has no HTTP scope; the host must call attach() before a package registers");
1169
- this.#routes = [this.#scope.nodeRoute({
1170
- method: [
1171
- "DELETE",
1172
- "GET",
1173
- "HEAD",
1174
- "PATCH",
1175
- "POST",
1176
- "PUT"
1177
- ],
1178
- path: ":token",
1179
- auth: "public",
1180
- handler: (req, res, ctx) => void this.#deliver(req, res, ctx.params)
1181
- })];
1461
+ #shorthand(method, path, a, b) {
1462
+ const options = typeof a === "function" ? {} : a;
1463
+ const handler = typeof a === "function" ? a : b;
1464
+ if (!handler) throw new Error(`Route ${method} ${path} was registered with no handler`);
1465
+ return this.route({
1466
+ ...options,
1467
+ method,
1468
+ path,
1469
+ handler
1470
+ });
1471
+ }
1472
+ route(spec) {
1473
+ const body = spec.body ?? "parsed";
1474
+ return this.#register(spec, (req, res, ctx) => this.#serve(spec, body, req, res, ctx));
1475
+ }
1476
+ nodeRoute(spec) {
1477
+ return this.#register(spec, (req, res, ctx) => spec.handler(req, res, ctx));
1182
1478
  }
1183
1479
  dispose() {
1184
- for (const handle of this.#routes) handle.dispose();
1185
- this.#routes = [];
1480
+ for (const registration of this.#registrations.values()) for (const handle of registration.handles) handle.dispose();
1186
1481
  this.#registrations.clear();
1482
+ this.#onDispose();
1187
1483
  }
1188
- /** The facade a package's HTTP scope exposes as `scope.webhooks`. */
1189
- scopeFor(namespace) {
1484
+ /** Mounts one route under this scope's namespace, in both the verbatim and the
1485
+ * percent-encoded spelling of a scoped name. */
1486
+ #register(spec, run) {
1487
+ const relative = assertRelativeRoutePath(spec.path);
1488
+ const methods = Array.isArray(spec.method) ? spec.method : [spec.method];
1489
+ const routePath = relative ? posix.join(this.#base, relative) : this.#base;
1490
+ const key = `${methods.join(",")} ${routePath}`;
1491
+ if (this.#registrations.has(key)) throw new Error(`Route ${key} is already registered by "${this.owner}"`);
1492
+ const handles = [];
1493
+ const paths = [routePath];
1494
+ if (this.#encodedBase) paths.push(relative ? posix.join(this.#encodedBase, relative) : this.#encodedBase);
1495
+ for (const path of paths) for (const method of methods) handles.push(this.#adapter.mountNodeRoute(method, path, (req, res) => {
1496
+ this.#guard(spec, req, res, run);
1497
+ }, {
1498
+ rawBody: true,
1499
+ prefix: spec.prefix
1500
+ }));
1501
+ this.#registrations.set(key, {
1502
+ path: routePath,
1503
+ handles
1504
+ });
1505
+ logger$1.debug("Registered @route for @package", key, this.owner);
1506
+ const publicUrl = this.#publicUrl;
1190
1507
  return {
1191
- hasPublicOrigin: this.hasPublicOrigin,
1192
- register: async (spec) => {
1193
- await this.init();
1194
- const key = `${namespace}|${spec.name}`;
1195
- this.#registrations.set(key, {
1196
- namespace,
1197
- spec
1198
- });
1199
- return {
1200
- endpointFor: async (ownerKey) => {
1201
- const row = await this.#store.ensure(namespace, spec.name, ownerKey);
1202
- return {
1203
- token: row.token,
1204
- url: this.urlFor(row.token),
1205
- createdAt: row.createdAt
1206
- };
1207
- },
1208
- revoke: (ownerKey) => this.#store.revoke(namespace, spec.name, ownerKey),
1209
- list: async () => (await this.#store.list(namespace, spec.name)).map((row) => ({
1210
- key: row.ownerKey,
1211
- token: row.token,
1212
- url: this.urlFor(row.token),
1213
- createdAt: row.createdAt
1214
- }))
1215
- };
1508
+ get url() {
1509
+ return `${readPublicOrigin(publicUrl)}${routePath}`;
1510
+ },
1511
+ dispose: () => {
1512
+ const registration = this.#registrations.get(key);
1513
+ if (!registration) return;
1514
+ for (const handle of registration.handles) handle.dispose();
1515
+ this.#registrations.delete(key);
1216
1516
  }
1217
1517
  };
1218
1518
  }
1219
- /** Releases every registration a package made. */
1220
- disposeScope(namespace) {
1221
- for (const [key, registration] of this.#registrations) if (registration.namespace === namespace) this.#registrations.delete(key);
1222
- }
1223
- /** The URL to hand a provider. Absolute whenever the host knows its own origin: a
1224
- * relative path is useless to the third party that has to call it. */
1225
- urlFor(token) {
1226
- const path = posix.join(this.#path, token);
1227
- return this.#publicUrl ? `${this.#publicUrl}${path}` : path;
1228
- }
1229
- /** Whether `urlFor` can produce something a provider could call. */
1230
- get hasPublicOrigin() {
1231
- return this.#publicUrl !== void 0;
1519
+ /** Authenticate, then run. */
1520
+ async #guard(spec, req, res, run) {
1521
+ try {
1522
+ const actor = await this.#authenticate(spec.auth ?? "renown", req, res);
1523
+ if (actor === REJECTED) return;
1524
+ await run(req, res, {
1525
+ params: routeParams(req),
1526
+ user: actor?.user,
1527
+ authEnabled: actor?.authEnabled ?? false,
1528
+ transport: resolveTransport(req, this.#trustProxy)
1529
+ });
1530
+ } catch (error) {
1531
+ logger$1.error("Route handler failed for @package", this.owner, error);
1532
+ writeError(res, 500, "Internal server error");
1533
+ }
1232
1534
  }
1233
- async #deliver(req, res, params) {
1234
- const token = params.token;
1235
- if (!token) {
1236
- writeError(res, 404, "Unknown endpoint");
1535
+ /** Resolves the caller, answering the request itself when the route refuses it;
1536
+ * returns REJECTED in that case so the caller stops. */
1537
+ async #authenticate(auth, req, res) {
1538
+ if (auth === "public") return void 0;
1539
+ if (typeof auth === "function") {
1540
+ const result = await auth(req);
1541
+ if (!result.authorized) {
1542
+ if ("response" in result) await writeResponse(res, result.response, req.method ?? "GET");
1543
+ else writeError(res, result.status, result.message);
1544
+ return REJECTED;
1545
+ }
1237
1546
  return;
1238
1547
  }
1239
- try {
1240
- const row = await this.#store.find(token);
1241
- if (!row) {
1242
- writeError(res, 404, "Unknown endpoint");
1243
- return;
1244
- }
1245
- const registrationKey = `${row.namespace}|${row.endpoint}`;
1246
- const registration = this.#registrations.get(registrationKey);
1247
- if (!registration) {
1248
- writeError(res, 503, "Endpoint temporarily unavailable");
1249
- return;
1250
- }
1251
- const { spec } = registration;
1252
- const method = (req.method ?? "POST").toUpperCase();
1253
- const perEndpoint = spec.policyFor ? await spec.policyFor(row.ownerKey) : {};
1254
- if (!perEndpoint) {
1255
- writeError(res, 404, "Unknown endpoint");
1256
- return;
1257
- }
1258
- const policy = {
1259
- ...spec.defaults,
1260
- ...perEndpoint
1261
- };
1262
- if (policy.methods && !policy.methods.includes(method)) {
1263
- writeError(res, 405, "Method not allowed");
1264
- return;
1265
- }
1266
- let raw;
1267
- try {
1268
- raw = await readBody(req, policy.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES);
1269
- } catch (error) {
1270
- if (error instanceof BodyTooLargeError) {
1271
- res.setHeader("connection", "close");
1272
- res.once("finish", () => req.destroy());
1273
- writeError(res, 413, "Payload too large");
1274
- return;
1275
- }
1276
- throw error;
1277
- }
1278
- const verification = policy.verify;
1279
- if (verification) {
1280
- const result = verifyWebhook({
1281
- verification,
1282
- headers: headerRecord(req),
1283
- raw
1284
- });
1285
- if (!result.ok) {
1286
- logger$1.warn("Rejected webhook delivery for @package/@endpoint: @reason", row.namespace, row.endpoint, result.reason);
1287
- writeError(res, 401, "Signature verification failed");
1288
- return;
1289
- }
1290
- }
1291
- const url = new URL(req.url ?? "/", "http://localhost");
1292
- const queryParams = Object.fromEntries(url.searchParams);
1293
- const signatureHeader = verification ? schemeHeader(verification) : void 0;
1294
- const headers = headerRecord(req);
1295
- const body = parseWebhookBody(raw, headers["content-type"]);
1296
- const challenge = challengeValue(policy.challengeField, queryParams, headers, body);
1297
- if (challenge !== void 0) {
1298
- res.statusCode = 200;
1299
- res.setHeader("content-type", "text/plain");
1300
- res.end(challenge);
1301
- return;
1302
- }
1303
- let recordedKey;
1304
- if (policy.dedupe) {
1305
- const key = dedupeKey(policy.dedupe.field, queryParams, headers, body);
1306
- recordedKey = key;
1307
- if (key !== void 0 && await this.#store.seen(token, key, policy.dedupe.ttlSeconds ?? DEFAULT_DEDUPE_TTL_SECONDS)) {
1308
- res.statusCode = 200;
1309
- res.end();
1310
- return;
1548
+ if (!this.#authService) return ANONYMOUS;
1549
+ const result = await this.#authService.verifyBearer(req.headers.authorization);
1550
+ if (result instanceof Response) {
1551
+ await writeResponse(res, result, req.method ?? "GET");
1552
+ return REJECTED;
1553
+ }
1554
+ if (result.auth_enabled && !result.user && auth === "renown") {
1555
+ writeError(res, 401, "Authentication required");
1556
+ return REJECTED;
1557
+ }
1558
+ return {
1559
+ user: result.user,
1560
+ authEnabled: result.auth_enabled
1561
+ };
1562
+ }
1563
+ /** Builds the Fetch Request from the raw stream and runs the handler. */
1564
+ async #serve(spec, body, req, res, ctx) {
1565
+ const method = req.method ?? "GET";
1566
+ const url = `${ctx.transport.baseUrl}${req.url ?? "/"}`;
1567
+ const controller = new AbortController();
1568
+ req.once("close", () => controller.abort());
1569
+ let raw;
1570
+ let init = {
1571
+ method,
1572
+ headers: fetchHeaders(req),
1573
+ signal: controller.signal
1574
+ };
1575
+ if (method !== "GET" && method !== "HEAD" && body !== "none") {
1576
+ if (body === "stream") init = {
1577
+ ...init,
1578
+ body: Readable.toWeb(req),
1579
+ duplex: "half"
1580
+ };
1581
+ else {
1582
+ try {
1583
+ raw = await readBody(req, spec.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES);
1584
+ } catch (error) {
1585
+ if (error instanceof BodyTooLargeError) {
1586
+ res.setHeader("connection", "close");
1587
+ res.once("finish", () => req.destroy());
1588
+ writeError(res, 413, "Payload too large");
1589
+ return;
1590
+ }
1591
+ throw error;
1311
1592
  }
1593
+ if (raw.length) init = {
1594
+ ...init,
1595
+ body: new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength)
1596
+ };
1312
1597
  }
1313
- const reply = await spec.onRequest({
1314
- key: row.ownerKey,
1315
- method,
1316
- path: url.pathname,
1317
- queryParams,
1318
- headers: redactHeaders(headers, signatureHeader),
1319
- raw,
1320
- body
1321
- });
1322
- if (reply.unprocessed === true && recordedKey !== void 0) try {
1323
- await this.#store.forget(token, recordedKey);
1324
- } catch (error) {
1325
- logger$1.warn("Could not forget an unprocessed webhook delivery: @error", error);
1326
- }
1327
- res.statusCode = reply.status;
1328
- if (reply.body !== void 0 && method !== "HEAD") {
1329
- res.setHeader("content-type", reply.contentType ?? "text/plain");
1330
- res.end(reply.body);
1331
- } else res.end();
1332
- } catch (error) {
1333
- logger$1.error("Webhook delivery failed for @method", req.method, error);
1334
- writeError(res, 500, "Internal server error");
1335
1598
  }
1599
+ await writeResponse(res, await spec.handler(new Request(url, init), {
1600
+ ...ctx,
1601
+ rawBody: body === "raw" ? raw ?? Buffer.alloc(0) : void 0,
1602
+ signal: controller.signal
1603
+ }), method);
1336
1604
  }
1337
1605
  };
1338
- function headerRecord(req) {
1339
- const headers = {};
1340
- for (const [name, value] of Object.entries(req.headers)) {
1341
- if (value === void 0) continue;
1342
- headers[name.toLowerCase()] = Array.isArray(value) ? value.join(", ") : value;
1343
- }
1344
- return headers;
1345
- }
1346
- function scalar(value) {
1347
- if (typeof value === "string" && value !== "") return value;
1348
- if (typeof value === "number") return String(value);
1606
+ const REJECTED = Symbol("rejected");
1607
+ function routeParams(req) {
1608
+ const params = req.params;
1609
+ if (!params || typeof params !== "object") return {};
1610
+ const out = {};
1611
+ for (const [key, value] of Object.entries(params)) if (typeof value === "string") out[key] = value;
1612
+ else if (Array.isArray(value)) out[key] = value.join("/");
1613
+ return out;
1349
1614
  }
1350
- /** Walks a dot-separated path into the parsed body. */
1351
- function bodyPath(path, body) {
1352
- let current = body;
1353
- for (const segment of path.split(".")) {
1354
- if (!current || typeof current !== "object") return void 0;
1355
- current = current[segment];
1615
+ /** Stands in for a package that cannot be routed — its key resolves to no npm name. Registering a route throws with
1616
+ * the reason; nothing else does, so the package still loads and its non-HTTP behaviour is unaffected. */
1617
+ var UnroutableScope = class {
1618
+ owner;
1619
+ baseUrl = "";
1620
+ #reason;
1621
+ constructor(packageKey, reason) {
1622
+ this.owner = packageKey;
1623
+ this.#reason = reason;
1356
1624
  }
1357
- return scalar(current);
1358
- }
1359
- /** Resolves where a provider put a value. A bare string means query first, then a
1360
- * top-level body field; `{ header }` and `{ body }` reach what that cannot — GitHub's delivery id is a header, Stripe's event id is nested. */
1361
- function fieldValue(field, queryParams, headers, body) {
1362
- if (typeof field === "object") return "header" in field ? scalar(headers[field.header.toLowerCase()]) : bodyPath(field.body, body);
1363
- const fromQuery = scalar(queryParams[field]);
1364
- if (fromQuery !== void 0) return fromQuery;
1365
- return body && typeof body === "object" ? scalar(body[field]) : void 0;
1366
- }
1367
- function challengeValue(field, queryParams, headers, body) {
1368
- return field === void 0 ? void 0 : fieldValue(field, queryParams, headers, body);
1369
- }
1370
- function dedupeKey(field, queryParams, headers, body) {
1371
- return fieldValue(field, queryParams, headers, body);
1625
+ #refuse() {
1626
+ throw new Error(`Package "${this.owner}" cannot host HTTP routes: ${this.#reason}`);
1627
+ }
1628
+ get() {
1629
+ this.#refuse();
1630
+ }
1631
+ post() {
1632
+ this.#refuse();
1633
+ }
1634
+ put() {
1635
+ this.#refuse();
1636
+ }
1637
+ patch() {
1638
+ this.#refuse();
1639
+ }
1640
+ delete() {
1641
+ this.#refuse();
1642
+ }
1643
+ head() {
1644
+ this.#refuse();
1645
+ }
1646
+ route() {
1647
+ this.#refuse();
1648
+ }
1649
+ nodeRoute() {
1650
+ this.#refuse();
1651
+ }
1652
+ get webhooks() {
1653
+ return unavailableWebhooks(this.owner);
1654
+ }
1655
+ dispose() {}
1656
+ };
1657
+ /** Stands in when the host has no webhook store configured. */
1658
+ function unavailableWebhooks(packageName) {
1659
+ return {
1660
+ hasPublicOrigin: false,
1661
+ register: () => Promise.reject(/* @__PURE__ */ new Error(`Webhooks are not available on this host, so "${packageName}" cannot register one`))
1662
+ };
1372
1663
  }
1373
1664
  //#endregion
1374
1665
  //#region src/http/webhook-store.ts
@@ -1639,6 +1930,11 @@ let DocumentChangeType = /* @__PURE__ */ function(DocumentChangeType) {
1639
1930
  DocumentChangeType["Updated"] = "UPDATED";
1640
1931
  return DocumentChangeType;
1641
1932
  }({});
1933
+ let DriveNodeKind = /* @__PURE__ */ function(DriveNodeKind) {
1934
+ DriveNodeKind["File"] = "FILE";
1935
+ DriveNodeKind["Folder"] = "FOLDER";
1936
+ return DriveNodeKind;
1937
+ }({});
1642
1938
  let PropagationMode = /* @__PURE__ */ function(PropagationMode) {
1643
1939
  PropagationMode["Cascade"] = "CASCADE";
1644
1940
  PropagationMode["Orphan"] = "ORPHAN";
@@ -1653,6 +1949,7 @@ const isDefinedNonNullAny = (v) => v !== void 0 && v !== null;
1653
1949
  const definedNonNullAnySchema = z$1.any().refine((v) => isDefinedNonNullAny(v));
1654
1950
  const AuthDecisionSchema = z$1.enum(AuthDecision);
1655
1951
  const DocumentChangeTypeSchema = z$1.enum(DocumentChangeType);
1952
+ const DriveNodeKindSchema = z$1.enum(DriveNodeKind);
1656
1953
  const PropagationModeSchema = z$1.enum(PropagationMode);
1657
1954
  const SyncEnvelopeTypeSchema = z$1.enum(SyncEnvelopeType);
1658
1955
  function ActionCandidateInputSchema() {
@@ -1891,6 +2188,23 @@ const JobInfoFieldsFragmentDoc = gql`
1891
2188
  }
1892
2189
  }
1893
2190
  `;
2191
+ const DriveNodeFieldsFragmentDoc = gql`
2192
+ fragment DriveNodeFields on DriveNode {
2193
+ ... on DriveFileNode {
2194
+ id
2195
+ driveId
2196
+ name
2197
+ parentFolder
2198
+ documentType
2199
+ }
2200
+ ... on DriveFolderNode {
2201
+ id
2202
+ driveId
2203
+ name
2204
+ parentFolder
2205
+ }
2206
+ }
2207
+ `;
1894
2208
  const GetDocumentModelsDocument = gql`
1895
2209
  query GetDocumentModels($namespace: String, $paging: PagingInput) {
1896
2210
  documentModels(namespace: $namespace, paging: $paging) {
@@ -2141,6 +2455,57 @@ const GetCreateDefaultsDocument = gql`
2141
2455
  }
2142
2456
  }
2143
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
+ `;
2471
+ const GetDriveNodesDocument = gql`
2472
+ query GetDriveNodes(
2473
+ $driveId: ID!
2474
+ $parentFolder: ID
2475
+ $paging: PagingInput
2476
+ $kind: DriveNodeKind
2477
+ ) {
2478
+ driveNodes(
2479
+ driveId: $driveId
2480
+ parentFolder: $parentFolder
2481
+ paging: $paging
2482
+ kind: $kind
2483
+ ) {
2484
+ results {
2485
+ ...DriveNodeFields
2486
+ }
2487
+ nextCursor
2488
+ hasMore
2489
+ }
2490
+ }
2491
+ ${DriveNodeFieldsFragmentDoc}
2492
+ `;
2493
+ const GetDriveNodeDocument = gql`
2494
+ query GetDriveNode($driveId: ID!, $id: ID!) {
2495
+ driveNode(driveId: $driveId, id: $id) {
2496
+ ...DriveNodeFields
2497
+ }
2498
+ }
2499
+ ${DriveNodeFieldsFragmentDoc}
2500
+ `;
2501
+ const GetDriveDescendantsDocument = gql`
2502
+ query GetDriveDescendants($driveId: ID!, $root: ID!) {
2503
+ driveDescendants(driveId: $driveId, root: $root) {
2504
+ ...DriveNodeFields
2505
+ }
2506
+ }
2507
+ ${DriveNodeFieldsFragmentDoc}
2508
+ `;
2144
2509
  const EvaluateActionsDocument = gql`
2145
2510
  query EvaluateActions(
2146
2511
  $documentIdentifier: String!
@@ -2522,6 +2887,18 @@ function getSdk(requester) {
2522
2887
  GetCreateDefaults(variables, options) {
2523
2888
  return requester(GetCreateDefaultsDocument, variables, options);
2524
2889
  },
2890
+ GetCreateProtocolVersions(variables, options) {
2891
+ return requester(GetCreateProtocolVersionsDocument, variables, options);
2892
+ },
2893
+ GetDriveNodes(variables, options) {
2894
+ return requester(GetDriveNodesDocument, variables, options);
2895
+ },
2896
+ GetDriveNode(variables, options) {
2897
+ return requester(GetDriveNodeDocument, variables, options);
2898
+ },
2899
+ GetDriveDescendants(variables, options) {
2900
+ return requester(GetDriveDescendantsDocument, variables, options);
2901
+ },
2525
2902
  EvaluateActions(variables, options) {
2526
2903
  return requester(EvaluateActionsDocument, variables, options);
2527
2904
  },
@@ -2995,7 +3372,6 @@ function isDriveContainerType(documentType) {
2995
3372
  }
2996
3373
  //#endregion
2997
3374
  //#region src/graphql/reactor/resolvers.ts
2998
- const REACTOR_DRIVE_DOCUMENT_TYPE = "powerhouse/reactor-drive";
2999
3375
  /** The branch a mutation applies to when the caller names none. */
3000
3376
  const DEFAULT_BRANCH = "main";
3001
3377
  /** The `Query.<field>` coordinates handed the write client outside a mutation. */
@@ -3006,32 +3382,15 @@ const WRITE_CLIENT_QUERIES = Object.entries({
3006
3382
  peerAgreement: "syncManager",
3007
3383
  jobStatus: "read"
3008
3384
  }).filter(([, binding]) => binding === "write").map(([field]) => field);
3009
- /** The reactor-drive client a reactor-drive parent needs, or the refusal. */
3010
- function requireReactorDriveClient(reactorDriveClient) {
3011
- if (!reactorDriveClient) throw new GraphQLError("Reactor-drive parent encountered but no reactorDriveClient is configured on this switchboard");
3012
- return reactorDriveClient;
3013
- }
3014
3385
  /**
3015
3386
  * Adds a document to a drive parent and returns what to read back once the
3016
- * write is readable. Reactor-drive parents go through the reactor-drive
3017
- * client, which still has the facade's waiting shape.
3387
+ * write is readable. `write.drives` picks the drive type's strategy.
3018
3388
  */
3019
- async function addFileToDrive(clients, driveType, driveId, document, reactorDriveClient) {
3020
- if (driveType === REACTOR_DRIVE_DOCUMENT_TYPE) {
3021
- const added = await requireReactorDriveClient(reactorDriveClient).addFile(driveId, document);
3022
- return {
3023
- documentId: added.header.id,
3024
- branch: added.header.branch || DEFAULT_BRANCH
3025
- };
3026
- }
3389
+ async function addFileToDrive(clients, driveId, document) {
3027
3390
  return (await clients.write.drives.addFile(driveId, document)).readable;
3028
3391
  }
3029
3392
  /** Removes a drive parent's node, waiting until the removal is readable. */
3030
- async function removeNodeFromDrive(clients, driveType, driveId, nodeId, reactorDriveClient) {
3031
- if (driveType === REACTOR_DRIVE_DOCUMENT_TYPE) {
3032
- await requireReactorDriveClient(reactorDriveClient).removeNode(driveId, nodeId);
3033
- return;
3034
- }
3393
+ async function removeNodeFromDrive(clients, driveId, nodeId) {
3035
3394
  await (await clients.write.drives.removeNode(driveId, nodeId)).readable;
3036
3395
  }
3037
3396
  /**
@@ -3065,9 +3424,16 @@ function toConsistencyToken(input) {
3065
3424
  }))
3066
3425
  };
3067
3426
  }
3068
- /** The defaults `create` gives a new document; the parent must already be gated. */
3069
- async function createDefaults(read, parentIdOrSlug) {
3070
- 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
+ })]);
3071
3437
  return {
3072
3438
  signaturePolicy,
3073
3439
  protocolVersions
@@ -3403,7 +3769,7 @@ async function assertSlugAvailable(read, slug, documentId) {
3403
3769
  }
3404
3770
  throw new GraphQLError(`The slug "${slug}" is taken by ${holder}; choose another.`);
3405
3771
  }
3406
- async function createDocument(clients, args, reactorDriveClient, subject) {
3772
+ async function createDocument(clients, args, _reactorDriveClient, subject) {
3407
3773
  if (!args.document || typeof args.document !== "object") throw new GraphQLError("Invalid document: must be an object");
3408
3774
  const document = args.document;
3409
3775
  if (!document.header || typeof document.header !== "object") throw new GraphQLError("Invalid document: missing or invalid header");
@@ -3413,7 +3779,7 @@ async function createDocument(clients, args, reactorDriveClient, subject) {
3413
3779
  try {
3414
3780
  if (parentIdOrSlug) {
3415
3781
  const parent = await clients.read.get(parentIdOrSlug, subject && { subject });
3416
- if (isDriveContainerType(parent.header.documentType)) receipt = await addFileToDrive(clients, parent.header.documentType, parent.header.id, document, reactorDriveClient);
3782
+ if (isDriveContainerType(parent.header.documentType)) receipt = await addFileToDrive(clients, parent.header.id, document);
3417
3783
  else receipt = await (await clients.write.create(document, parentIdOrSlug)).readable;
3418
3784
  } else receipt = await (await clients.write.create(document)).readable;
3419
3785
  } catch (error) {
@@ -3426,7 +3792,7 @@ async function createDocument(clients, args, reactorDriveClient, subject) {
3426
3792
  throw new GraphQLError(`Failed to convert created document to GraphQL: ${error instanceof Error ? error.message : "Unknown error"}`);
3427
3793
  }
3428
3794
  }
3429
- async function createEmptyDocument(clients, args, reactorDriveClient, subject) {
3795
+ async function createEmptyDocument(clients, args, _reactorDriveClient, subject) {
3430
3796
  const parentIdOrSlug = fromInputMaybe(args.parentIdOrSlug);
3431
3797
  const name = fromInputMaybe(args.name);
3432
3798
  let receipt;
@@ -3434,10 +3800,11 @@ async function createEmptyDocument(clients, args, reactorDriveClient, subject) {
3434
3800
  if (parentIdOrSlug) {
3435
3801
  const parent = await clients.read.get(parentIdOrSlug, subject && { subject });
3436
3802
  if (isDriveContainerType(parent.header.documentType)) {
3437
- const module = await clients.read.getDocumentModelModule(args.documentType);
3438
- const document = withSignaturePolicy(module.utils.createDocument(), await clients.read.getCreateSignaturePolicy());
3439
- if (name) document.header.name = name;
3440
- receipt = await addFileToDrive(clients, parent.header.documentType, parent.header.id, document, reactorDriveClient);
3803
+ const document = await clients.read.newDocument(args.documentType, {
3804
+ parentIdentifier: parent.header.id,
3805
+ name: name || void 0
3806
+ });
3807
+ receipt = await addFileToDrive(clients, parent.header.id, document);
3441
3808
  } else receipt = await (await clients.write.createEmpty(args.documentType, { parentIdentifier: parentIdOrSlug })).readable;
3442
3809
  } else receipt = await (await clients.write.createEmpty(args.documentType, {})).readable;
3443
3810
  } catch (error) {
@@ -3450,7 +3817,7 @@ async function createEmptyDocument(clients, args, reactorDriveClient, subject) {
3450
3817
  throw new GraphQLError(`Failed to convert created document to GraphQL: ${error instanceof Error ? error.message : "Unknown error"}`);
3451
3818
  }
3452
3819
  }
3453
- async function createDocumentWithInitialState(clients, args, reactorDriveClient, subject) {
3820
+ async function createDocumentWithInitialState(clients, args, _reactorDriveClient, subject) {
3454
3821
  const parentIdOrSlug = fromInputMaybe(args.parentIdOrSlug);
3455
3822
  const name = fromInputMaybe(args.name);
3456
3823
  const slug = fromInputMaybe(args.slug);
@@ -3461,7 +3828,7 @@ async function createDocumentWithInitialState(clients, args, reactorDriveClient,
3461
3828
  } catch (error) {
3462
3829
  throw new GraphQLError(`Document model not found for type ${args.documentType}: ${error instanceof Error ? error.message : "Unknown error"}`);
3463
3830
  }
3464
- const document = withSignaturePolicy(module.utils.createDocument(), await clients.read.getCreateSignaturePolicy());
3831
+ const document = await clients.read.newDocument(args.documentType, { parentIdentifier: parentIdOrSlug ?? void 0 });
3465
3832
  const allowedScopes = new Set(Object.keys(module.documentModel.global.specifications.at(-1)?.state ?? {}));
3466
3833
  const state = document.state;
3467
3834
  for (const [scope, scopeState] of Object.entries(args.initialState)) if (allowedScopes.has(scope) && scope in state) state[scope] = {
@@ -3486,7 +3853,7 @@ async function createDocumentWithInitialState(clients, args, reactorDriveClient,
3486
3853
  throw new GraphQLError(`Parent document not found: ${error instanceof Error ? error.message : "Unknown error"}`);
3487
3854
  }
3488
3855
  if (isDriveContainerType(parent.header.documentType)) try {
3489
- receipt = await addFileToDrive(clients, parent.header.documentType, parent.header.id, document, reactorDriveClient);
3856
+ receipt = await addFileToDrive(clients, parent.header.id, document);
3490
3857
  } catch (error) {
3491
3858
  throw new GraphQLError(`Failed to create document in drive: ${error instanceof Error ? error.message : "Unknown error"}`);
3492
3859
  }
@@ -3784,13 +4151,13 @@ async function moveRelationship(clients, args, subject) {
3784
4151
  throw new GraphQLError(`Failed to convert documents to GraphQL: ${error instanceof Error ? error.message : "Unknown error"}`);
3785
4152
  }
3786
4153
  }
3787
- async function deleteDocument(clients, args, reactorDriveClient) {
4154
+ async function deleteDocument(clients, args, _reactorDriveClient) {
3788
4155
  const propagate = toReactorPropagationMode(args.propagate);
3789
4156
  try {
3790
4157
  const driveParent = (await clients.read.getIncomingRelationships(args.idOrSlug, "child")).results.find((p) => isDriveContainerType(p.header.documentType));
3791
4158
  if (driveParent) {
3792
4159
  const documentId = await clients.read.resolveIdOrSlug(args.idOrSlug);
3793
- await removeNodeFromDrive(clients, driveParent.header.documentType, driveParent.header.id, documentId, reactorDriveClient);
4160
+ await removeNodeFromDrive(clients, driveParent.header.id, documentId);
3794
4161
  } else await (await clients.write.deleteDocument(args.idOrSlug, propagate)).readable;
3795
4162
  return true;
3796
4163
  } catch (error) {
@@ -4945,155 +5312,56 @@ var SubgraphWsRouter = class {
4945
5312
  routes.sort((a, b) => owners.indexOf(a.owner) - owners.indexOf(b.owner));
4946
5313
  const operation = getOperationAST(document, operationName);
4947
5314
  if (!operation) return routes[0];
4948
- const fields = rootFields(document, operation);
4949
- return routes.find((route) => {
4950
- const root = route.schema.getRootType(operation.operation);
4951
- if (!root) return false;
4952
- const available = root.getFields();
4953
- return fields.every((field) => field in available);
4954
- }) ?? routes[0];
4955
- }
4956
- #operationsOf(ctx) {
4957
- let operations = this.#operations.get(ctx);
4958
- if (!operations) {
4959
- operations = /* @__PURE__ */ new Map();
4960
- this.#operations.set(ctx, operations);
4961
- }
4962
- return operations;
4963
- }
4964
- #endRoute(route) {
4965
- route.ended = true;
4966
- this.#end(route.running);
4967
- }
4968
- async #end(results) {
4969
- await Promise.all(Array.from(results, async (result) => {
4970
- try {
4971
- await result.return(void 0);
4972
- } catch (error) {
4973
- this.#logger.error("Error ending a WebSocket subscription: @error", error);
4974
- }
4975
- }));
4976
- }
4977
- };
4978
- function isAsyncGenerator$1(value) {
4979
- return typeof value === "object" && value !== null && Symbol.asyncIterator in value && typeof value.return === "function";
4980
- }
4981
- /** An operation's root field names, through fragments, without `__` fields. */
4982
- function rootFields(document, operation) {
4983
- const fragments = new Map(document.definitions.flatMap((definition) => definition.kind === Kind.FRAGMENT_DEFINITION ? [[definition.name.value, definition.selectionSet]] : []));
4984
- const fields = /* @__PURE__ */ new Set();
4985
- const visited = /* @__PURE__ */ new Set();
4986
- const collect = (selectionSet) => {
4987
- for (const selection of selectionSet.selections) if (selection.kind === Kind.FIELD) {
4988
- if (!selection.name.value.startsWith("__")) fields.add(selection.name.value);
4989
- } else if (selection.kind === Kind.INLINE_FRAGMENT) collect(selection.selectionSet);
4990
- else if (!visited.has(selection.name.value)) {
4991
- visited.add(selection.name.value);
4992
- const fragment = fragments.get(selection.name.value);
4993
- if (fragment) collect(fragment);
4994
- }
4995
- };
4996
- collect(operation.selectionSet);
4997
- return [...fields];
4998
- }
4999
- //#endregion
5000
- //#region src/graphql/ws-credential-monitor.ts
5001
- /** Default interval between credential re-checks of open WebSockets. */
5002
- const DEFAULT_WS_CREDENTIAL_RECHECK_INTERVAL_MS = 6e4;
5003
- /**
5004
- * Re-verifies the credentials of authenticated WebSocket connections.
5005
- *
5006
- * A WebSocket is authenticated once, at `ConnectionInit`, so a credential
5007
- * revoked afterwards would otherwise keep every subscription it opened alive
5008
- * for as long as the socket stays up. The monitor re-checks each tracked
5009
- * connection on an interval and, at once, the connections of an identity whose
5010
- * credential a package invalidated; a connection whose credential no longer
5011
- * verifies is closed 4403 with {@link WS_CLOSE_REASON_CREDENTIAL_REVOKED}.
5012
- *
5013
- * A check that throws (a verifier outage) leaves the connection open: admission
5014
- * fails closed on the next connect, but an outage should not drop every live
5015
- * subscription at once.
5016
- */
5017
- var WsCredentialMonitor = class {
5018
- #connections = /* @__PURE__ */ new Map();
5019
- #options;
5020
- #timer;
5021
- #unsubscribe;
5022
- #sweeping = false;
5023
- constructor(options) {
5024
- this.#options = options;
5025
- }
5026
- get size() {
5027
- return this.#connections.size;
5315
+ const fields = rootFields(document, operation);
5316
+ return routes.find((route) => {
5317
+ const root = route.schema.getRootType(operation.operation);
5318
+ if (!root) return false;
5319
+ const available = root.getFields();
5320
+ return fields.every((field) => field in available);
5321
+ }) ?? routes[0];
5028
5322
  }
5029
- /** Begin the periodic sweep and listen for invalidations. Idempotent. */
5030
- start() {
5031
- this.#unsubscribe ??= this.#options.authService.onCredentialInvalidated((invalidation) => {
5032
- this.recheck(invalidation);
5033
- });
5034
- if (this.#options.intervalMs > 0 && !this.#timer) {
5035
- this.#timer = setInterval(() => {
5036
- if (this.#sweeping) return;
5037
- this.#sweeping = true;
5038
- this.recheck().finally(() => {
5039
- this.#sweeping = false;
5040
- });
5041
- }, this.#options.intervalMs);
5042
- this.#timer.unref?.();
5323
+ #operationsOf(ctx) {
5324
+ let operations = this.#operations.get(ctx);
5325
+ if (!operations) {
5326
+ operations = /* @__PURE__ */ new Map();
5327
+ this.#operations.set(ctx, operations);
5043
5328
  }
5329
+ return operations;
5044
5330
  }
5045
- dispose() {
5046
- if (this.#timer) clearInterval(this.#timer);
5047
- this.#timer = void 0;
5048
- this.#unsubscribe?.();
5049
- this.#unsubscribe = void 0;
5050
- this.#connections.clear();
5051
- }
5052
- /** Track an admitted, authenticated connection until its socket closes. */
5053
- track(connection, user) {
5054
- const { socket } = connection;
5055
- this.#connections.set(connection, {
5056
- user,
5057
- socket
5058
- });
5059
- socket?.once?.("close", () => {
5060
- this.#connections.delete(connection);
5061
- });
5331
+ #endRoute(route) {
5332
+ route.ended = true;
5333
+ this.#end(route.running);
5062
5334
  }
5063
- /**
5064
- * Re-verify tracked connections (those matching `filter`, or all) and close
5065
- * the ones whose credential no longer holds. Resolves to the number closed.
5066
- */
5067
- async recheck(filter) {
5068
- const targets = [...this.#connections].filter(([, tracked]) => !filter || matches(tracked.user, filter));
5069
- let closed = 0;
5070
- await Promise.all(targets.map(async ([connection, tracked]) => {
5071
- let valid;
5335
+ async #end(results) {
5336
+ await Promise.all(Array.from(results, async (result) => {
5072
5337
  try {
5073
- valid = await this.#options.authService.isCredentialValid(tracked.user);
5338
+ await result.return(void 0);
5074
5339
  } catch (error) {
5075
- this.#options.logger.warn("Could not re-verify the credential of a WebSocket connection; keeping it open: @error", error instanceof Error ? error.message : error);
5076
- return;
5340
+ this.#logger.error("Error ending a WebSocket subscription: @error", error);
5077
5341
  }
5078
- if (valid || !this.#connections.has(connection)) return;
5079
- this.#connections.delete(connection);
5080
- this.#options.logger.info("Closing WebSocket connection of @address: credential no longer valid", tracked.user.address);
5081
- tracked.socket?.close?.(4403, WS_CLOSE_REASON_CREDENTIAL_REVOKED);
5082
- closed++;
5083
5342
  }));
5084
- return closed;
5085
5343
  }
5086
5344
  };
5087
- function matches(user, filter) {
5088
- return user.address.toLowerCase() === filter.address && (filter.chainId === void 0 || user.chainId === filter.chainId) && (filter.appDid === void 0 || user.appKey === filter.appDid);
5345
+ function isAsyncGenerator$1(value) {
5346
+ return typeof value === "object" && value !== null && Symbol.asyncIterator in value && typeof value.return === "function";
5089
5347
  }
5090
- /** Parse `WS_CREDENTIAL_RECHECK_INTERVAL_MS`; invalid values warn and fall back to the default. */
5091
- function resolveWsCredentialRecheckIntervalMs(raw, logger) {
5092
- if (raw === void 0) return DEFAULT_WS_CREDENTIAL_RECHECK_INTERVAL_MS;
5093
- const parsed = Number(raw);
5094
- if (raw.trim() !== "" && Number.isFinite(parsed) && parsed >= 0) return parsed;
5095
- 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}`);
5096
- return DEFAULT_WS_CREDENTIAL_RECHECK_INTERVAL_MS;
5348
+ /** An operation's root field names, through fragments, without `__` fields. */
5349
+ function rootFields(document, operation) {
5350
+ const fragments = new Map(document.definitions.flatMap((definition) => definition.kind === Kind.FRAGMENT_DEFINITION ? [[definition.name.value, definition.selectionSet]] : []));
5351
+ const fields = /* @__PURE__ */ new Set();
5352
+ const visited = /* @__PURE__ */ new Set();
5353
+ const collect = (selectionSet) => {
5354
+ for (const selection of selectionSet.selections) if (selection.kind === Kind.FIELD) {
5355
+ if (!selection.name.value.startsWith("__")) fields.add(selection.name.value);
5356
+ } else if (selection.kind === Kind.INLINE_FRAGMENT) collect(selection.selectionSet);
5357
+ else if (!visited.has(selection.name.value)) {
5358
+ visited.add(selection.name.value);
5359
+ const fragment = fragments.get(selection.name.value);
5360
+ if (fragment) collect(fragment);
5361
+ }
5362
+ };
5363
+ collect(operation.selectionSet);
5364
+ return [...fields];
5097
5365
  }
5098
5366
  //#endregion
5099
5367
  //#region src/graphql/sse.ts
@@ -5391,6 +5659,8 @@ var GraphQLManager = class {
5391
5659
  * it for reactor-drive parents.
5392
5660
  */
5393
5661
  reactorDriveClient;
5662
+ /** See {@link GraphQLManagerOptions.driveNodes}. */
5663
+ driveNodes;
5394
5664
  authorizationService;
5395
5665
  /** Route service in use: the injected one, or one built on first need. */
5396
5666
  #fallbackRoutes;
@@ -5449,6 +5719,7 @@ var GraphQLManager = class {
5449
5719
  this.port = options.port ?? 4001;
5450
5720
  this.authorizationService = options.authorizationService;
5451
5721
  this.reactorDriveClient = options.reactorDriveClient;
5722
+ this.driveNodes = options.driveNodes;
5452
5723
  this.syncServingGate = options.syncServingGate;
5453
5724
  this.httpRoutes = options.httpRoutes;
5454
5725
  this.attachments = options.attachments;
@@ -7225,6 +7496,19 @@ const CreateDefaultsDTO = z.object({
7225
7496
  signaturePolicy: z.string(),
7226
7497
  protocolVersions: JSONObjectDTO
7227
7498
  }).strip();
7499
+ const DriveNodeDTO = z.object({
7500
+ id: z.string(),
7501
+ driveId: z.string(),
7502
+ name: z.string(),
7503
+ parentFolder: z.string().nullable().optional(),
7504
+ documentType: z.string().optional()
7505
+ }).strip();
7506
+ const DriveNodeListDTO = z.array(DriveNodeDTO);
7507
+ const DriveNodePageDTO = z.object({
7508
+ results: z.array(DriveNodeDTO),
7509
+ nextCursor: z.string().nullable().optional(),
7510
+ hasMore: z.boolean()
7511
+ }).strip();
7228
7512
  const ActionEvaluationDTO = z.object({
7229
7513
  decision: z.enum(["ALLOW", "DENY"]),
7230
7514
  reason: z.string().nullable().optional()
@@ -7279,6 +7563,18 @@ const operationValidators = {
7279
7563
  GetCreateDefaults: (data) => {
7280
7564
  if (data.createDefaults) CreateDefaultsDTO.parse(data.createDefaults);
7281
7565
  },
7566
+ GetCreateProtocolVersions: (data) => {
7567
+ if (data.createDefaults) CreateDefaultsDTO.pick({ protocolVersions: true }).parse(data.createDefaults);
7568
+ },
7569
+ GetDriveNodes: (data) => {
7570
+ if (data.driveNodes) DriveNodePageDTO.parse(data.driveNodes);
7571
+ },
7572
+ GetDriveNode: (data) => {
7573
+ if (data.driveNode) DriveNodeDTO.parse(data.driveNode);
7574
+ },
7575
+ GetDriveDescendants: (data) => {
7576
+ if (data.driveDescendants) DriveNodeListDTO.parse(data.driveDescendants);
7577
+ },
7282
7578
  EvaluateActions: (data) => {
7283
7579
  if (data.evaluateActions) ActionEvaluationsDTO.parse(data.evaluateActions);
7284
7580
  },
@@ -7349,6 +7645,49 @@ function createReactorGraphQLClient(url, fetchImpl = fetch, headers) {
7349
7645
  return getSdk(createValidatingRequester(url, fetchImpl, headers));
7350
7646
  }
7351
7647
  //#endregion
7648
+ //#region src/graphql/reactor/drive-nodes.ts
7649
+ const DEFAULT_LIMIT = 100;
7650
+ /** The node source, or the refusal a host without one answers with. */
7651
+ function requireDriveNodeSource(source) {
7652
+ if (!source) throw new GraphQLError("Drive node queries are unavailable: no drive node source is configured on this server", { extensions: { code: "DRIVE_NODE_SOURCE_NOT_CONFIGURED" } });
7653
+ return source;
7654
+ }
7655
+ /** The GraphQL type of a node record, for the `DriveNode` union. */
7656
+ function driveNodeTypeName(node) {
7657
+ const kind = node.kind;
7658
+ if (kind === "file" || kind === "folder") return kind === "file" ? "DriveFileNode" : "DriveFolderNode";
7659
+ return "documentType" in node ? "DriveFileNode" : "DriveFolderNode";
7660
+ }
7661
+ /** One node; undefined when absent or when the drive is withheld. */
7662
+ async function getServedNode(source, gate, driveId, nodeId) {
7663
+ if (!await gate.servesDrive(driveId)) return;
7664
+ return source.getNode(driveId, nodeId);
7665
+ }
7666
+ /** The descendants of `root`; empty when the drive is withheld. */
7667
+ async function getServedDescendants(source, gate, driveId, root) {
7668
+ if (!await gate.servesDrive(driveId)) return [];
7669
+ return source.getDescendants(driveId, root);
7670
+ }
7671
+ /** One page of nodes; empty when the drive is withheld. */
7672
+ async function listServedNodes(source, gate, driveId, parentFolder, paging, kind) {
7673
+ if (!await gate.servesDrive(driveId)) return {
7674
+ results: [],
7675
+ nextCursor: void 0,
7676
+ hasMore: false
7677
+ };
7678
+ const limit = paging?.limit ?? DEFAULT_LIMIT;
7679
+ const wanted = !kind ? void 0 : kind === "FILE" ? "file" : "folder";
7680
+ const page = await source.listChildren(driveId, parentFolder, {
7681
+ cursor: paging?.cursor ?? "",
7682
+ limit
7683
+ }, void 0, wanted);
7684
+ return {
7685
+ results: page.results,
7686
+ nextCursor: page.nextCursor,
7687
+ hasMore: page.nextCursor !== void 0
7688
+ };
7689
+ }
7690
+ //#endregion
7352
7691
  //#region src/graphql/reactor/pubsub.ts
7353
7692
  const pubSub = new PubSub();
7354
7693
  function getPubSub() {
@@ -7517,6 +7856,20 @@ var ReactorSubgraph = class extends BaseSubgraph {
7517
7856
  return handle;
7518
7857
  }
7519
7858
  /**
7859
+ * The read gate a drive node read passes, as the reactor-drive subgraph
7860
+ * applies it: the drive is listed to the caller (reactor read gate, then the
7861
+ * host's ACL); its nodes are then served as the legacy node list was.
7862
+ */
7863
+ #driveNodeGate(ctx) {
7864
+ return { servesDrive: async (driveId) => {
7865
+ try {
7866
+ return await this.listsDocument(driveId, ctx);
7867
+ } catch {
7868
+ return false;
7869
+ }
7870
+ } };
7871
+ }
7872
+ /**
7520
7873
  * Returns the drive id when the given identifier (id or slug) refers
7521
7874
  * to a drive document, otherwise undefined. Used by deleteDocument to
7522
7875
  * decide whether to invalidate the drive-ownership cache after a
@@ -7623,6 +7976,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
7623
7976
  }
7624
7977
  typeDefs = gql(schema_default$2);
7625
7978
  resolvers = {
7979
+ DriveNode: { __resolveType: (node) => driveNodeTypeName(node) },
7626
7980
  PHDocument: { operations: async (parent, args, ctx) => {
7627
7981
  this.logger.debug("PHDocument.operations(@parent.id, @args)", parent.id, args);
7628
7982
  await this.assertCanReadCanonical(parent.id, ctx);
@@ -7791,12 +8145,24 @@ var ReactorSubgraph = class extends BaseSubgraph {
7791
8145
  throw error;
7792
8146
  }
7793
8147
  },
8148
+ driveNodes: async (_parent, args, ctx) => {
8149
+ this.logger.debug("driveNodes(@args)", args);
8150
+ return listServedNodes(requireDriveNodeSource(this.graphqlManager.driveNodes), this.#driveNodeGate(ctx), args.driveId, "parentFolder" in args ? args.parentFolder ?? null : void 0, args.paging, args.kind);
8151
+ },
8152
+ driveNode: async (_parent, args, ctx) => {
8153
+ this.logger.debug("driveNode(@args)", args);
8154
+ return await getServedNode(requireDriveNodeSource(this.graphqlManager.driveNodes), this.#driveNodeGate(ctx), args.driveId, args.id) ?? null;
8155
+ },
8156
+ driveDescendants: async (_parent, args, ctx) => {
8157
+ this.logger.debug("driveDescendants(@args)", args);
8158
+ return getServedDescendants(requireDriveNodeSource(this.graphqlManager.driveNodes), this.#driveNodeGate(ctx), args.driveId, args.root);
8159
+ },
7794
8160
  createDefaults: async (_parent, args, ctx) => {
7795
8161
  this.logger.debug("createDefaults(@args)", args);
7796
8162
  try {
7797
8163
  const parentIdOrSlug = args.parentIdOrSlug ?? void 0;
7798
8164
  if (parentIdOrSlug !== void 0 && !await this.listsDocument(parentIdOrSlug, ctx)) throw new ForbiddenError("to read this document");
7799
- return await createDefaults(this.clientsOf(ctx).read, parentIdOrSlug);
8165
+ return await createDefaults(this.clientsOf(ctx).read, parentIdOrSlug, args.documentType ?? void 0);
7800
8166
  } catch (error) {
7801
8167
  this.logger.error("Error in createDefaults: @Error", error);
7802
8168
  throw error;
@@ -8276,15 +8642,20 @@ const getAdminUsers = () => {
8276
8642
  };
8277
8643
  //#endregion
8278
8644
  //#region src/graphql/system/env/index.ts
8279
- if (typeof process !== "undefined" && typeof process.cwd === "function" && !["1", "true"].includes(process.env.PH_NO_DOTENV?.trim().toLowerCase() ?? "")) dotenv.config();
8280
- 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
+ });
8281
8652
  //#endregion
8282
8653
  //#region src/graphql/system/version.ts
8283
8654
  function getVersion() {
8284
- return "6.2.3-dev.77";
8655
+ return "6.2.3-dev.79";
8285
8656
  }
8286
8657
  function getGitHash() {
8287
- return "52245e43cb7435650abfe72241eaa787ce5757b7";
8658
+ return "e1e361faacfb9bf18a46dcb7a0c5af6033b6b453";
8288
8659
  }
8289
8660
  function getGitUrl() {
8290
8661
  return buildTreeUrl(getGitHash());
@@ -9294,7 +9665,9 @@ var PackageManager = class {
9294
9665
  this.logger.debug("[@loader] Failed to load @kind from package @package: @error", loader.name, kind, pkg, error);
9295
9666
  }
9296
9667
  this.maybeWarnAllLoadersFailed(kind, pkg, loaded !== void 0, failures);
9297
- 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);
9298
9671
  }
9299
9672
  return loads;
9300
9673
  }
@@ -9539,9 +9912,11 @@ var PackageManager = class {
9539
9912
  });
9540
9913
  }
9541
9914
  };
9915
+ function errorText(error) {
9916
+ return error instanceof Error ? error.message : String(error);
9917
+ }
9542
9918
  //#endregion
9543
9919
  //#region src/config.ts
9544
- const config = { basePath: process.env.BASE_PATH || "/" };
9545
9920
  const DefaultCoreSubgraphs = [AnalyticsSubgraph, SystemSubgraph];
9546
9921
  /** The core subgraphs a server registers, given its optional services. */
9547
9922
  function coreSubgraphClasses(options) {
@@ -9556,8 +9931,7 @@ function coreSubgraphClasses(options) {
9556
9931
  //#endregion
9557
9932
  //#region src/attachment-backend.ts
9558
9933
  /** Filesystem is the default; explicit S3 is readiness-gated without fallback. */
9559
- async function createStartupAttachmentBackend({ db, env = process.env, s3Dependencies }) {
9560
- const storage = parseAttachmentStorageConfig(env);
9934
+ async function createStartupAttachmentBackend({ db, storage = { kind: "filesystem" }, s3Dependencies }) {
9561
9935
  if (storage.kind === "filesystem") return void 0;
9562
9936
  const backend = createS3AttachmentBackend(db.withSchema("attachments"), storage.s3, s3Dependencies);
9563
9937
  if (!(await backend.health()).ready) throw new Error("S3 attachment backend readiness check failed");
@@ -10183,122 +10557,6 @@ async function createRenownCredentialVerifier(config = {}) {
10183
10557
  };
10184
10558
  }
10185
10559
  //#endregion
10186
- //#region src/services/permission-cache.ts
10187
- /**
10188
- * Everything an authorization decision reads about one document: its
10189
- * protection flag (the configured default when it has no protection row), its
10190
- * owner, the users' grant levels and the users granted each operation.
10191
- * Addresses are stored lowercase, as the permission service writes them.
10192
- */
10193
- var DocumentPermissionSnapshot = class {
10194
- documentId;
10195
- isProtected;
10196
- ownerAddress;
10197
- grants;
10198
- operationGrants;
10199
- constructor(documentId, isProtected, ownerAddress, grants, operationGrants) {
10200
- this.documentId = documentId;
10201
- this.isProtected = isProtected;
10202
- this.ownerAddress = ownerAddress;
10203
- this.grants = grants;
10204
- this.operationGrants = operationGrants;
10205
- }
10206
- grantLevel(userAddress) {
10207
- return this.grants.get(userAddress.toLowerCase()) ?? null;
10208
- }
10209
- isOperationRestricted(operationType) {
10210
- return (this.operationGrants.get(operationType)?.size ?? 0) > 0;
10211
- }
10212
- hasOperationGrant(operationType, userAddress) {
10213
- return this.operationGrants.get(operationType)?.has(userAddress.toLowerCase()) ?? false;
10214
- }
10215
- };
10216
- const DEFAULT_PERMISSION_CACHE_TTL_MS = 3e4;
10217
- const DEFAULT_PERMISSION_CACHE_OPTIONS = {
10218
- ttlMs: DEFAULT_PERMISSION_CACHE_TTL_MS,
10219
- maxEntries: 1e4,
10220
- now: () => Date.now()
10221
- };
10222
- var PermissionCacheEntry = class {
10223
- snapshot;
10224
- expiresAt;
10225
- constructor(snapshot, expiresAt) {
10226
- this.snapshot = snapshot;
10227
- this.expiresAt = expiresAt;
10228
- }
10229
- };
10230
- /**
10231
- * Per-process cache of document permission snapshots, keyed by document id.
10232
- *
10233
- * Filled on miss from the store, invalidated by the permission service after
10234
- * each of its own writes, and expired after `ttlMs` as the safety net for
10235
- * writes made by another process (another switchboard instance on the same
10236
- * database) until cross-instance invalidation exists.
10237
- *
10238
- * A load that overlaps an invalidation still answers its caller but is not
10239
- * stored, so a read that started before a write commits cannot repopulate
10240
- * the cache with the pre-write rows.
10241
- */
10242
- var PermissionCache = class {
10243
- #load;
10244
- #options;
10245
- #entries = /* @__PURE__ */ new Map();
10246
- #epoch = 0;
10247
- constructor(load, options = DEFAULT_PERMISSION_CACHE_OPTIONS) {
10248
- this.#load = load;
10249
- this.#options = options;
10250
- }
10251
- get size() {
10252
- return this.#entries.size;
10253
- }
10254
- async get(documentId) {
10255
- return (await this.getMany([documentId])).get(documentId);
10256
- }
10257
- /** Snapshots for every id, loading the missing and expired ones in one batch. */
10258
- async getMany(documentIds) {
10259
- const now = this.#options.now();
10260
- const result = /* @__PURE__ */ new Map();
10261
- const missing = [];
10262
- for (const documentId of new Set(documentIds)) {
10263
- const entry = this.#entries.get(documentId);
10264
- if (entry && entry.expiresAt > now) {
10265
- this.#entries.delete(documentId);
10266
- this.#entries.set(documentId, entry);
10267
- result.set(documentId, entry.snapshot);
10268
- } else missing.push(documentId);
10269
- }
10270
- if (missing.length === 0) return result;
10271
- const epoch = this.#epoch;
10272
- const loaded = await this.#load(missing);
10273
- const storable = this.#options.ttlMs > 0 && epoch === this.#epoch;
10274
- const expiresAt = this.#options.now() + this.#options.ttlMs;
10275
- for (const documentId of missing) {
10276
- const snapshot = loaded.get(documentId);
10277
- if (!snapshot) throw new Error(`Permission snapshot loader returned no snapshot for ${documentId}`);
10278
- result.set(documentId, snapshot);
10279
- if (storable) this.#store(documentId, new PermissionCacheEntry(snapshot, expiresAt));
10280
- }
10281
- return result;
10282
- }
10283
- invalidate(documentId) {
10284
- this.#epoch++;
10285
- this.#entries.delete(documentId);
10286
- }
10287
- clear() {
10288
- this.#epoch++;
10289
- this.#entries.clear();
10290
- }
10291
- #store(documentId, entry) {
10292
- this.#entries.delete(documentId);
10293
- while (this.#entries.size >= this.#options.maxEntries) {
10294
- const oldest = this.#entries.keys().next();
10295
- if (oldest.done) break;
10296
- this.#entries.delete(oldest.value);
10297
- }
10298
- this.#entries.set(documentId, entry);
10299
- }
10300
- };
10301
- //#endregion
10302
10560
  //#region src/services/document-permission.service.ts
10303
10561
  /**
10304
10562
  * Service for managing document-level permissions.
@@ -10791,7 +11049,7 @@ function getDbClient(connectionString = void 0, pgliteFactory) {
10791
11049
  const client = isPg ? "pg" : ClientPgLite;
10792
11050
  const pgliteInstance = isPg ? void 0 : pgliteFactory ? pgliteFactory(connectionString) : connectionString ? new PGlite({
10793
11051
  fs: createDurableNodeFs(NodeFS, connectionString, {
10794
- fsync: resolvePgliteFsync(process.env),
11052
+ ...resolvePgliteMaintenance({}),
10795
11053
  logger
10796
11054
  }),
10797
11055
  parsers: PGLITE_UTC_PARSERS
@@ -11026,25 +11284,12 @@ function makeDbClosers(knexInstance, pglite, logger) {
11026
11284
  return closers;
11027
11285
  }
11028
11286
  /**
11029
- * Resolves the gateway adapter type from the `GATEWAY_ADAPTER` env var.
11030
- * Defaults to "apollo" (the federation gateway, production behavior).
11031
- * "stitching" selects the in-process graphql-tools merge gateway (#1565
11032
- * prototype); "mercurius" the Fastify federation gateway.
11033
- */
11034
- function resolveGatewayAdapterType(logger) {
11035
- const configured = process.env.GATEWAY_ADAPTER;
11036
- if (configured === void 0) return "apollo";
11037
- if (configured === "apollo" || configured === "mercurius" || configured === "stitching") return configured;
11038
- logger.warn(`Unknown GATEWAY_ADAPTER="${configured}"; falling back to "apollo"`);
11039
- return "apollo";
11040
- }
11041
- /**
11042
11287
  * Sets up the subgraph manager and registers subgraphs
11043
11288
  */
11044
- async function setupGraphQLManager({ httpAdapter, authFetchMiddleware, requireAuthFetchMiddleware, httpServer, wsServer, clients, relationalDb, analyticsStore, syncManager, subgraphs, logger, authorizationService, authService, documentPermissionService, enableDocumentModelSubgraphs, port, reactorDriveClient, 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 }) {
11045
11290
  const graphqlManager = new GraphQLManager({
11046
- wsCredentialRecheckIntervalMs: resolveWsCredentialRecheckIntervalMs(process.env.WS_CREDENTIAL_RECHECK_INTERVAL_MS, logger),
11047
- path: config.basePath,
11291
+ wsCredentialRecheckIntervalMs: settings.wsCredentialRecheckIntervalMs,
11292
+ path: settings.basePath,
11048
11293
  httpServer,
11049
11294
  wsServer,
11050
11295
  readClient: clients.read,
@@ -11055,13 +11300,14 @@ async function setupGraphQLManager({ httpAdapter, authFetchMiddleware, requireAu
11055
11300
  syncManager,
11056
11301
  logger,
11057
11302
  httpAdapter,
11058
- gatewayAdapter: await createGatewayAdapter(resolveGatewayAdapterType(logger), logger),
11303
+ gatewayAdapter: await createGatewayAdapter(settings.gatewayAdapter, logger),
11059
11304
  authService,
11060
11305
  documentPermissionService,
11061
11306
  featureFlags: { enableDocumentModelSubgraphs },
11062
11307
  port,
11063
11308
  authorizationService,
11064
11309
  reactorDriveClient,
11310
+ driveNodes,
11065
11311
  syncServingGate,
11066
11312
  httpRoutes,
11067
11313
  attachments,
@@ -11093,6 +11339,11 @@ async function startServer(httpAdapter, port, httpsOptions, logger) {
11093
11339
  wsServer
11094
11340
  };
11095
11341
  }
11342
+ function boundPortOf(httpServer) {
11343
+ const address = httpServer.address();
11344
+ if (address === null || typeof address === "string") throw new Error(`The HTTP server is not bound to a TCP port: ${String(address)}`);
11345
+ return address.port;
11346
+ }
11096
11347
  /**
11097
11348
  * Private helper function that sets up common infrastructure before API initialization.
11098
11349
  * This includes auth configuration, database setup, and package manager initialization.
@@ -11101,28 +11352,16 @@ async function _setupCommonInfrastructure(options) {
11101
11352
  const port = options.port ?? DEFAULT_PORT;
11102
11353
  const { adapter: httpAdapter } = await createHttpAdapter("express");
11103
11354
  const logger = options.logger ?? defaultLogger;
11104
- let admins = [];
11105
- let authEnabled = false;
11106
- let configuredResolveIdentity;
11107
- let configuredRequireAuth;
11108
- let configuredExemptPaths;
11109
- let configuredAttachmentPolicyReads;
11110
- let configuredRenown;
11111
- if (options.configFile) {
11112
- const config = getConfig(options.configFile);
11113
- admins = config.auth?.admins.map((a) => a.toLowerCase()) ?? [];
11114
- authEnabled = config.auth?.enabled ?? false;
11115
- configuredRenown = config.auth?.renown;
11116
- } else if (options.auth) {
11117
- admins = options.auth.admins.map((a) => a.toLowerCase());
11118
- authEnabled = options.auth.enabled;
11119
- configuredResolveIdentity = options.auth.resolveIdentity;
11120
- configuredRequireAuth = options.auth.requireAuthenticatedCaller;
11121
- configuredExemptPaths = options.auth.requireAuthenticatedCallerExemptPaths;
11122
- configuredAttachmentPolicyReads = options.auth.attachmentReadsFollowDocumentPolicy;
11123
- }
11124
- 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;
11125
- 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;
11126
11365
  /**
11127
11366
  * Whether the auth middleware reads the bearer and populates `ctx.user`,
11128
11367
  * independently of the authorization policy.
@@ -11134,8 +11373,7 @@ async function _setupCommonInfrastructure(options) {
11134
11373
  * stays `OPEN`, which is the combination custom subgraphs need and the one
11135
11374
  * `AUTH_ENABLED` alone cannot express.
11136
11375
  */
11137
- let resolveCallerIdentity = configuredResolveIdentity ?? authEnabled;
11138
- if (RESOLVE_CALLER_IDENTITY !== void 0) resolveCallerIdentity = RESOLVE_CALLER_IDENTITY === "true";
11376
+ const resolveCallerIdentity = optionAuth.resolveIdentity ?? authEnabled;
11139
11377
  /**
11140
11378
  * Whether the require-authenticated-caller middleware is active: anonymous
11141
11379
  * callers are rejected with a 401 before any subgraph sees the request.
@@ -11150,8 +11388,7 @@ async function _setupCommonInfrastructure(options) {
11150
11388
  * out every non-admin; this expresses "authenticated callers allowed,
11151
11389
  * anonymous not".
11152
11390
  */
11153
- let requireAuthenticatedCaller = configuredRequireAuth ?? false;
11154
- if (REQUIRE_AUTHENTICATED_CALLER !== void 0) requireAuthenticatedCaller = REQUIRE_AUTHENTICATED_CALLER === "true";
11391
+ const requireAuthenticatedCaller = optionAuth.requireAuthenticatedCaller ?? false;
11155
11392
  /**
11156
11393
  * The paths the floor above does not apply to. Comma-separated, like
11157
11394
  * `ADMINS`, because a deployment configures this the same way it configures
@@ -11162,8 +11399,7 @@ async function _setupCommonInfrastructure(options) {
11162
11399
  * cannot ever match is refused, in
11163
11400
  * {@link assertRequireAuthenticatedCallerAllowed}.
11164
11401
  */
11165
- let requireAuthenticatedCallerExemptPaths = configuredExemptPaths ?? [];
11166
- 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 ?? [];
11167
11403
  /**
11168
11404
  * Whether an attachment read is decided by the referencing document's own
11169
11405
  * policy rather than by the host's permission tables.
@@ -11174,22 +11410,18 @@ async function _setupCommonInfrastructure(options) {
11174
11410
  * nothing keeps exactly the behaviour it has, and one that wants the change
11175
11411
  * asks for it and can take it back without disturbing anything else.
11176
11412
  */
11177
- let attachmentReadsFollowDocumentPolicy = configuredAttachmentPolicyReads ?? false;
11178
- if (ATTACHMENT_READS_FOLLOW_DOCUMENT_POLICY !== void 0) attachmentReadsFollowDocumentPolicy = ATTACHMENT_READS_FOLLOW_DOCUMENT_POLICY === "true";
11179
- if (ADMINS !== void 0) admins = ADMINS.split(",").map((a) => a.toLowerCase());
11180
- let defaultProtection = false;
11181
- if (DEFAULT_PROTECTION !== void 0) defaultProtection = DEFAULT_PROTECTION.toLowerCase() === "true";
11182
- let skipCredentialVerification = false;
11183
- if (SKIP_CREDENTIAL_VERIFICATION !== void 0) skipCredentialVerification = SKIP_CREDENTIAL_VERIFICATION === "true";
11184
- const documentPermissionsRequested = options.documentPermissionService !== void 0 || DOCUMENT_PERMISSIONS_ENABLED === "true";
11185
- 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);
11186
11418
  assertSkipCredentialVerificationAllowed(resolveCallerIdentity, skipCredentialVerification, process.env);
11187
11419
  assertRequireAuthenticatedCallerAllowed(requireAuthenticatedCaller, resolveCallerIdentity, requireAuthenticatedCallerExemptPaths);
11188
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.");
11189
11421
  httpAdapter.getRoute("/health", () => new Response("OK", { status: 200 }));
11190
11422
  const readiness = createReadinessGate();
11191
11423
  httpAdapter.getRoute("/ready", () => readiness.isReady() ? new Response("OK", { status: 200 }) : new Response("starting", { status: 503 }));
11192
- const explorerPrefix = getExplorerPrefix(config.basePath);
11424
+ const explorerPrefix = getExplorerPrefix(settings.basePath);
11193
11425
  httpAdapter.getRoute(`${explorerPrefix}/:endpoint?`, (request) => {
11194
11426
  const url = new URL(request.url);
11195
11427
  const suffix = url.pathname.slice(explorerPrefix.length).replace(/^\//, "");
@@ -11203,7 +11435,7 @@ async function _setupCommonInfrastructure(options) {
11203
11435
  let authService;
11204
11436
  if (resolveCallerIdentity || authEnabled) {
11205
11437
  logger.info("Setting up Auth middleware (policy enforcement: @enabled, caller identity: @resolve)", authEnabled, resolveCallerIdentity);
11206
- const renown = options.renown ?? resolveRenownConfig(configuredRenown, process.env, logger);
11438
+ const renown = options.renown ?? resolveRenownConfig(configuredRenown, {}, logger);
11207
11439
  assertCredentialVerifierForSource(renown.source, options.verifyCredential !== void 0);
11208
11440
  if (options.verifyCredential) logger.info("Renown credentials will be verified by the host's verifier");
11209
11441
  else logger.info("Renown credentials will be verified against @url", renown.switchboardUrl ?? renown.url ?? "the default Renown instance");
@@ -11212,7 +11444,7 @@ async function _setupCommonInfrastructure(options) {
11212
11444
  resolveIdentity: resolveCallerIdentity,
11213
11445
  admins,
11214
11446
  skipCredentialVerification,
11215
- credentialVerificationCacheTtlMs: resolveCredentialCacheTtlMs(CREDENTIAL_VERIFICATION_CACHE_TTL_MS, renown.source, logger),
11447
+ credentialVerificationCacheTtlMs: optionAuth.credentialCacheTtlMs ?? (renown.source === "self" ? 0 : void 0),
11216
11448
  verifyCredential: options.verifyCredential ?? await createRenownCredentialVerifier({
11217
11449
  renownUrl: renown.url,
11218
11450
  switchboardUrl: renown.switchboardUrl
@@ -11228,22 +11460,24 @@ async function _setupCommonInfrastructure(options) {
11228
11460
  const { relationalDb, analyticsStore, closers: analyticsClosers } = await initializeDatabaseAndAnalytics(options.dbPath, options.pgliteFactory, logger);
11229
11461
  dbClosers.push(...analyticsClosers);
11230
11462
  const documentPermissionService = options.documentPermissionService;
11231
- const ownDocumentPermissions = !documentPermissionService && DOCUMENT_PERMISSIONS_ENABLED === "true" ? {
11463
+ const ownDocumentPermissions = !documentPermissionService && documentPermissionsEnabled ? {
11232
11464
  defaultProtection,
11233
- cacheTtlMs: resolvePermissionCacheTtlMs(process.env.DOCUMENT_PERMISSION_CACHE_TTL_MS, logger)
11465
+ cacheTtlMs: optionAuth.documentPermissions?.cacheTtlMs ?? 3e4
11234
11466
  } : null;
11235
- const policy = documentPermissionService || ownDocumentPermissions ? AuthorizationPolicy.DOCUMENT_PERMISSIONS : authEnabled ? AuthorizationPolicy.ADMIN_ONLY : AuthorizationPolicy.OPEN;
11236
11467
  const authorizationConfig = {
11237
11468
  admins,
11238
11469
  defaultProtection,
11239
- policy
11470
+ policy: documentPermissionService || ownDocumentPermissions ? AuthorizationPolicy.DOCUMENT_PERMISSIONS : authEnabled ? AuthorizationPolicy.ADMIN_ONLY : AuthorizationPolicy.OPEN
11240
11471
  };
11241
11472
  const attachmentStoragePath = resolveAttachmentStoragePath(options);
11242
11473
  await mkdir(attachmentStoragePath, { recursive: true });
11243
11474
  const { db: attachmentDb, knex: attachmentKnex, pglite: attachmentPglite } = getDbClient(options.dbPath, options.pgliteFactory);
11244
11475
  dbClosers.push(...makeDbClosers(attachmentKnex, attachmentPglite, logger));
11245
11476
  const ATTACHMENT_SWEEP_INTERVAL_MS = 36e5;
11246
- const attachmentBackend = await createStartupAttachmentBackend({ db: attachmentDb });
11477
+ const attachmentBackend = await createStartupAttachmentBackend({
11478
+ db: attachmentDb,
11479
+ storage: options.attachments?.storage ?? { kind: "filesystem" }
11480
+ });
11247
11481
  const attachmentBuilder = new AttachmentBuilder(attachmentDb, attachmentStoragePath).withReservationSweepMs(ATTACHMENT_SWEEP_INTERVAL_MS);
11248
11482
  if (attachmentBackend) attachmentBuilder.withBackend(attachmentBackend);
11249
11483
  const attachments = await attachmentBuilder.build();
@@ -11258,23 +11492,24 @@ async function _setupCommonInfrastructure(options) {
11258
11492
  packages: options.packages ?? [],
11259
11493
  reportError: options.reportError
11260
11494
  });
11261
- const publicUrl = resolvePublicOrigin(port);
11495
+ const listenPort = { current: port };
11496
+ const publicUrl = resolvePublicOrigin(options.server?.publicUrl, listenPort);
11262
11497
  const webhooks = new WebhookService({
11263
11498
  store: new RelationalWebhookStore(relationalDb),
11264
- basePath: config.basePath,
11499
+ basePath: settings.basePath,
11265
11500
  publicUrl
11266
11501
  });
11267
11502
  const httpRoutes = new HttpRouteService({
11268
11503
  httpAdapter,
11269
- basePath: config.basePath,
11504
+ basePath: settings.basePath,
11270
11505
  authService,
11271
11506
  webhooks,
11272
11507
  publicUrl,
11273
11508
  trustProxy: true
11274
11509
  });
11275
- 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)));
11276
11511
  return {
11277
- port,
11512
+ listenPort,
11278
11513
  httpAdapter,
11279
11514
  httpRoutes,
11280
11515
  authFetchMiddleware,
@@ -11291,13 +11526,14 @@ async function _setupCommonInfrastructure(options) {
11291
11526
  packages,
11292
11527
  dbClosers,
11293
11528
  readiness,
11294
- attachmentReadsFollowDocumentPolicy
11529
+ attachmentReadsFollowDocumentPolicy,
11530
+ settings
11295
11531
  };
11296
11532
  }
11297
11533
  /**
11298
11534
  * Private helper function containing common setup logic for API initialization
11299
11535
  */
11300
- async function _setupAPI(clients, syncManager, reactorProcessorManager, httpAdapter, authFetchMiddleware, requireAuthFetchMiddleware, authEnabled, authService, port, packages, relationalDb, analyticsStore, documentPermissionService, processors, subgraphs, options, processorApp, readModels, attachments, attachmentReferenceIndex, attachmentReferenceProjection, authorizationConfig, documentModelRegistry, dbClosers = [], reactorDriveClient, syncServingGate, httpRoutes, attachmentReadsFollowDocumentPolicy = false, inspection, driveStore) {
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) {
11301
11537
  const hostModuleBase = {
11302
11538
  ...createReactorHostModuleBase({
11303
11539
  client: clients.client,
@@ -11338,7 +11574,9 @@ async function _setupAPI(clients, syncManager, reactorProcessorManager, httpAdap
11338
11574
  }
11339
11575
  }))).flat());
11340
11576
  }
11341
- const { httpServer, wsServer } = await startServer(httpAdapter, port, options.https, logger);
11577
+ const { httpServer, wsServer } = await startServer(httpAdapter, listenPort.current, options.https, logger);
11578
+ const boundPort = boundPortOf(httpServer);
11579
+ listenPort.current = boundPort;
11342
11580
  const authorizationService = createAuthorizationService(authorizationConfig, documentPermissionService, createGetParentIdsFn(clients.read));
11343
11581
  logger.info(`Authorization service initialized (policy: ${authorizationConfig.policy})`);
11344
11582
  assertAttachmentPolicyReadsAllowed(attachmentReadsFollowDocumentPolicy, syncServingGate !== void 0);
@@ -11355,6 +11593,7 @@ async function _setupAPI(clients, syncManager, reactorProcessorManager, httpAdap
11355
11593
  });
11356
11594
  if (documentPermissionService) logger.info("Auth subgraph registered (document permissions enabled)");
11357
11595
  const graphqlManager = await setupGraphQLManager({
11596
+ settings,
11358
11597
  httpAdapter,
11359
11598
  authFetchMiddleware,
11360
11599
  requireAuthFetchMiddleware,
@@ -11373,8 +11612,9 @@ async function _setupAPI(clients, syncManager, reactorProcessorManager, httpAdap
11373
11612
  authService,
11374
11613
  documentPermissionService,
11375
11614
  enableDocumentModelSubgraphs: options.enableDocumentModelSubgraphs,
11376
- port,
11615
+ port: boundPort,
11377
11616
  reactorDriveClient,
11617
+ driveNodes,
11378
11618
  syncServingGate,
11379
11619
  httpRoutes,
11380
11620
  attachments: attachmentClientProvider,
@@ -11392,7 +11632,7 @@ async function _setupAPI(clients, syncManager, reactorProcessorManager, httpAdap
11392
11632
  syncManager,
11393
11633
  authorizeRequest: createMcpRequestAuthorizer(authService, authorizationService)
11394
11634
  }, httpAdapter);
11395
- logger.info(`MCP server available at http://localhost:${port}/mcp`);
11635
+ logger.info(`MCP server available at http://localhost:${boundPort}/mcp`);
11396
11636
  }
11397
11637
  const dispose = buildApiDispose({
11398
11638
  graphqlManager,
@@ -11404,6 +11644,7 @@ async function _setupAPI(clients, syncManager, reactorProcessorManager, httpAdap
11404
11644
  });
11405
11645
  return {
11406
11646
  httpAdapter,
11647
+ port: boundPort,
11407
11648
  httpServer,
11408
11649
  httpRoutes: httpRoutes ?? new HttpRouteService({ httpAdapter }),
11409
11650
  graphqlManager,
@@ -11484,24 +11725,10 @@ async function createOwnDocumentPermissionService(settings, permissionsDb, optio
11484
11725
  logger.info(`Document permission service initialized on the read-model store (cache TTL ${settings.cacheTtlMs} ms)`);
11485
11726
  return new DocumentPermissionService(db, config, cacheOptions);
11486
11727
  }
11487
- /**
11488
- * The permission cache TTL from `DOCUMENT_PERMISSION_CACHE_TTL_MS`: a
11489
- * non-negative integer of milliseconds, 0 disabling the cache. Anything else
11490
- * falls back to the default with a warning.
11491
- */
11492
- function resolvePermissionCacheTtlMs(raw, logger) {
11493
- if (raw === void 0 || raw.trim() === "") return DEFAULT_PERMISSION_CACHE_TTL_MS;
11494
- const parsed = Number(raw);
11495
- if (!Number.isInteger(parsed) || parsed < 0) {
11496
- logger.warn(`Ignoring DOCUMENT_PERMISSION_CACHE_TTL_MS=${raw}: expected a non-negative integer; using ${DEFAULT_PERMISSION_CACHE_TTL_MS} ms`);
11497
- return DEFAULT_PERMISSION_CACHE_TTL_MS;
11498
- }
11499
- return parsed;
11500
- }
11501
11728
  async function initializeAndStartAPI(clientInitializer, options, processorApp) {
11502
- const { port, 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);
11503
11730
  const { documentModels, upgradeManifests, processors, subgraphs } = await packages.init();
11504
- const { module: reactorClientModule, reactorDriveClient, attachmentReferenceProjection = {
11731
+ const { module: reactorClientModule, reactorDriveClient, driveNodes, attachmentReferenceProjection = {
11505
11732
  status: "unavailable",
11506
11733
  reason: "initializer-did-not-report"
11507
11734
  }, permissionsDb } = await clientInitializer(documentModels, {
@@ -11523,11 +11750,10 @@ async function initializeAndStartAPI(clientInitializer, options, processorApp) {
11523
11750
  read: reactorClientModule.read,
11524
11751
  write: reactorClientModule.write,
11525
11752
  client: reactorClient
11526
- }, syncManager, reactorProcessorManager, httpAdapter, authFetchMiddleware, requireAuthFetchMiddleware, authEnabled, authService, port, 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, {
11527
- 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, {
11528
11754
  ...options.inspection,
11529
11755
  attachmentStore: attachmentInspectionStore(attachments)
11530
- }) : void 0, reactorClientModule.reactorModule?.reactor),
11756
+ }) : void 0, reactorClientModule.reactorModule?.reactor, driveNodes),
11531
11757
  client: reactorClient,
11532
11758
  read: reactorClientModule.read,
11533
11759
  write: reactorClientModule.write,
@@ -11548,12 +11774,9 @@ async function initializeAndStartAPI(clientInitializer, options, processorApp) {
11548
11774
  * dev` behind a tunnel and, at worst, obviously wrong rather than silently
11549
11775
  * unusable.
11550
11776
  */
11551
- function resolvePublicOrigin(port) {
11552
- const explicit = process.env.PUBLIC_URL ?? process.env.RENDER_EXTERNAL_URL;
11553
- if (explicit) return withScheme(explicit);
11554
- const domain = process.env.HEROKU_APP_DEFAULT_DOMAIN_NAME;
11555
- if (domain) return withScheme(domain);
11556
- return `http://localhost:${port}`;
11777
+ function resolvePublicOrigin(configured, listenPort) {
11778
+ if (configured) return withScheme(configured);
11779
+ return () => `http://localhost:${listenPort.current}`;
11557
11780
  }
11558
11781
  function withScheme(origin) {
11559
11782
  const trimmed = origin.replace(/\/+$/, "");
@@ -11718,7 +11941,7 @@ var PackageManagementService = class {
11718
11941
  }
11719
11942
  };
11720
11943
  //#endregion
11721
- 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, EvaluateActionsDocument, ExecuteBatchDocument, ExecutionJobInputSchema, FindDocumentsDocument, ForbiddenError, GetCreateDefaultsDocument, GetDocumentDocument, GetDocumentIncomingRelationshipEdgesDocument, GetDocumentIncomingRelationshipsDocument, GetDocumentModelsDocument, GetDocumentOperationsDocument, GetDocumentOutgoingRelationshipEdgesDocument, GetDocumentOutgoingRelationshipsDocument, GetDocumentServedDocument, GetDocumentWithOperationsDocument, 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 };
11722
11945
 
11723
11946
  //# sourceMappingURL=index.mjs.map
11724
- //# debugId=560dd033-eac1-581d-a504-0117f3526f86
11947
+ //# debugId=ef156955-2531-5a13-8ece-12e68bf6d841