@powerhousedao/switchboard 6.2.3-dev.5 → 6.2.3-dev.51

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 (143) hide show
  1. package/.tsbuild/test/attachments/byte-grants.test.d.ts +2 -0
  2. package/.tsbuild/test/attachments/byte-grants.test.d.ts.map +1 -0
  3. package/.tsbuild/test/attachments/byte-routes-read-gate.integration.test.d.ts +2 -0
  4. package/.tsbuild/test/attachments/byte-routes-read-gate.integration.test.d.ts.map +1 -0
  5. package/.tsbuild/test/attachments/reserve-metadata-parity.test.d.ts +2 -0
  6. package/.tsbuild/test/attachments/reserve-metadata-parity.test.d.ts.map +1 -0
  7. package/.tsbuild/test/attachments/url-signer.test.d.ts +2 -0
  8. package/.tsbuild/test/attachments/url-signer.test.d.ts.map +1 -0
  9. package/.tsbuild/test/boot-create-signature-policy.test.d.ts +2 -0
  10. package/.tsbuild/test/boot-create-signature-policy.test.d.ts.map +1 -0
  11. package/.tsbuild/test/boot-mcp-enabled.test.d.ts +2 -0
  12. package/.tsbuild/test/boot-mcp-enabled.test.d.ts.map +1 -0
  13. package/.tsbuild/test/boot-privacy.test.d.ts +2 -0
  14. package/.tsbuild/test/boot-privacy.test.d.ts.map +1 -0
  15. package/.tsbuild/test/boot-unsupported-stored-documents.test.d.ts +2 -0
  16. package/.tsbuild/test/boot-unsupported-stored-documents.test.d.ts.map +1 -0
  17. package/.tsbuild/test/boot-without-renown.test.d.ts +2 -0
  18. package/.tsbuild/test/boot-without-renown.test.d.ts.map +1 -0
  19. package/.tsbuild/test/boot-without-require-signatures.test.d.ts +2 -0
  20. package/.tsbuild/test/boot-without-require-signatures.test.d.ts.map +1 -0
  21. package/.tsbuild/test/boot-worker-trust-policy.test.d.ts +2 -0
  22. package/.tsbuild/test/boot-worker-trust-policy.test.d.ts.map +1 -0
  23. package/.tsbuild/test/boot-workflow-singleton-conflict.test.d.ts +2 -0
  24. package/.tsbuild/test/boot-workflow-singleton-conflict.test.d.ts.map +1 -0
  25. package/.tsbuild/test/boot-workflow-singleton-retry.test.d.ts +2 -0
  26. package/.tsbuild/test/boot-workflow-singleton-retry.test.d.ts.map +1 -0
  27. package/.tsbuild/test/builder-defaults.test.d.ts +2 -0
  28. package/.tsbuild/test/builder-defaults.test.d.ts.map +1 -0
  29. package/.tsbuild/test/create-signature-policy.test.d.ts +2 -0
  30. package/.tsbuild/test/create-signature-policy.test.d.ts.map +1 -0
  31. package/.tsbuild/test/durable-node-fs-pg16.test.d.ts +2 -0
  32. package/.tsbuild/test/durable-node-fs-pg16.test.d.ts.map +1 -0
  33. package/.tsbuild/test/fatal-shutdown.test.d.ts +2 -0
  34. package/.tsbuild/test/fatal-shutdown.test.d.ts.map +1 -0
  35. package/.tsbuild/test/mcp-flag.test.d.ts +2 -0
  36. package/.tsbuild/test/mcp-flag.test.d.ts.map +1 -0
  37. package/.tsbuild/test/observability-signals.test.d.ts +2 -0
  38. package/.tsbuild/test/observability-signals.test.d.ts.map +1 -0
  39. package/.tsbuild/test/pglite-preflight.test.d.ts +2 -0
  40. package/.tsbuild/test/pglite-preflight.test.d.ts.map +1 -0
  41. package/.tsbuild/test/renown-trust-policy.test.d.ts +2 -0
  42. package/.tsbuild/test/renown-trust-policy.test.d.ts.map +1 -0
  43. package/.tsbuild/test/snapshot-writer.d.ts +18 -0
  44. package/.tsbuild/test/snapshot-writer.d.ts.map +1 -0
  45. package/.tsbuild/test/unsupported-stored-documents.test.d.ts +2 -0
  46. package/.tsbuild/test/unsupported-stored-documents.test.d.ts.map +1 -0
  47. package/.tsbuild/test/workflow/harness.d.ts +56 -0
  48. package/.tsbuild/test/workflow/harness.d.ts.map +1 -0
  49. package/.tsbuild/test/workflow/oauth.test.d.ts +2 -0
  50. package/.tsbuild/test/workflow/oauth.test.d.ts.map +1 -0
  51. package/.tsbuild/test/workflow/resolvers.test.d.ts +2 -0
  52. package/.tsbuild/test/workflow/resolvers.test.d.ts.map +1 -0
  53. package/.tsbuild/test/workflow/webhook-dedupe.test.d.ts +2 -0
  54. package/.tsbuild/test/workflow/webhook-dedupe.test.d.ts.map +1 -0
  55. package/.tsbuild/test/workflow/webhook-signed.test.d.ts +2 -0
  56. package/.tsbuild/test/workflow/webhook-signed.test.d.ts.map +1 -0
  57. package/.tsbuild/test/workflow/webhook-trigger-test.test.d.ts +2 -0
  58. package/.tsbuild/test/workflow/webhook-trigger-test.test.d.ts.map +1 -0
  59. package/.tsbuild/test/workflow/webhook-unsigned.test.d.ts +2 -0
  60. package/.tsbuild/test/workflow/webhook-unsigned.test.d.ts.map +1 -0
  61. package/.tsbuild/test/workflow-reactor-access.test.d.ts +2 -0
  62. package/.tsbuild/test/workflow-reactor-access.test.d.ts.map +1 -0
  63. package/.tsbuild/test/workflow-reactor-enforcement.test.d.ts +2 -0
  64. package/.tsbuild/test/workflow-reactor-enforcement.test.d.ts.map +1 -0
  65. package/.tsbuild/test/workflow-read-gate.test.d.ts +2 -0
  66. package/.tsbuild/test/workflow-read-gate.test.d.ts.map +1 -0
  67. package/.tsbuild/test/workflow-runtime.test.d.ts +2 -0
  68. package/.tsbuild/test/workflow-runtime.test.d.ts.map +1 -0
  69. package/.tsbuild/tsconfig.tsbuildinfo +1 -1
  70. package/.tsbuild/tsdown.config.d.ts.map +1 -1
  71. package/.tsbuild/vitest.config.d.ts.map +1 -1
  72. package/Auth.md +94 -0
  73. package/CHANGELOG.md +541 -0
  74. package/README.md +35 -0
  75. package/dist/index.d.mts +2 -1
  76. package/dist/index.mjs +48 -49
  77. package/dist/index.mjs.map +1 -1
  78. package/dist/install-packages.d.mts +2 -1
  79. package/dist/install-packages.mjs +2 -2
  80. package/dist/install-packages.mjs.map +1 -1
  81. package/dist/migrate.d.mts +2 -1
  82. package/dist/migrate.mjs +4 -3
  83. package/dist/migrate.mjs.map +1 -1
  84. package/dist/server-J9fpd42v.mjs +3549 -0
  85. package/dist/server-J9fpd42v.mjs.map +1 -0
  86. package/dist/server.d.mts +155 -30
  87. package/dist/server.d.mts.map +1 -1
  88. package/dist/server.mjs +4 -5
  89. package/dist/{utils-Baw7rThP.mjs → utils-uaBlzyjS.mjs} +15 -9
  90. package/dist/utils-uaBlzyjS.mjs.map +1 -0
  91. package/dist/utils.d.mts +4 -5
  92. package/dist/utils.d.mts.map +1 -1
  93. package/dist/utils.mjs +3 -3
  94. package/package.json +22 -18
  95. package/test/attachment-reference-read-model.test.ts +6 -1
  96. package/test/attachments/auth.test.ts +85 -0
  97. package/test/attachments/byte-grants.test.ts +290 -0
  98. package/test/attachments/byte-routes-read-gate.integration.test.ts +314 -0
  99. package/test/attachments/download-target.test.ts +201 -32
  100. package/test/attachments/index.test.ts +34 -3
  101. package/test/attachments/reserve-metadata-parity.test.ts +96 -0
  102. package/test/attachments/routes-integration.test.ts +60 -4
  103. package/test/attachments/routes.test.ts +166 -23
  104. package/test/attachments/service-config.test.ts +13 -3
  105. package/test/attachments/url-signer.test.ts +105 -0
  106. package/test/boot-create-signature-policy.test.ts +108 -0
  107. package/test/boot-mcp-enabled.test.ts +121 -0
  108. package/test/boot-privacy.test.ts +243 -0
  109. package/test/boot-unsupported-stored-documents.test.ts +213 -0
  110. package/test/boot-without-renown.test.ts +81 -0
  111. package/test/boot-without-require-signatures.test.ts +74 -0
  112. package/test/boot-worker-trust-policy.test.ts +90 -0
  113. package/test/boot-workflow-singleton-conflict.test.ts +107 -0
  114. package/test/boot-workflow-singleton-retry.test.ts +133 -0
  115. package/test/builder-defaults.test.ts +80 -0
  116. package/test/create-signature-policy.test.ts +69 -0
  117. package/test/durable-node-fs-pg16.test.ts +80 -0
  118. package/test/fatal-shutdown.test.ts +165 -0
  119. package/test/mcp-flag.test.ts +56 -0
  120. package/test/observability-signals.test.ts +131 -0
  121. package/test/pglite-dialect.test.ts +217 -2
  122. package/test/pglite-preflight.test.ts +313 -0
  123. package/test/pglite-version.test.ts +9 -1
  124. package/test/renown-trust-policy.test.ts +315 -0
  125. package/test/snapshot-writer.ts +94 -0
  126. package/test/unsupported-stored-documents.test.ts +72 -0
  127. package/test/worker-pool.test.ts +27 -1
  128. package/test/workflow/harness.ts +289 -0
  129. package/test/workflow/oauth.test.ts +214 -0
  130. package/test/workflow/resolvers.test.ts +357 -0
  131. package/test/workflow/webhook-dedupe.test.ts +295 -0
  132. package/test/workflow/webhook-signed.test.ts +509 -0
  133. package/test/workflow/webhook-trigger-test.test.ts +82 -0
  134. package/test/workflow/webhook-unsigned.test.ts +345 -0
  135. package/test/workflow-reactor-access.test.ts +384 -0
  136. package/test/workflow-reactor-enforcement.test.ts +808 -0
  137. package/test/workflow-read-gate.test.ts +213 -0
  138. package/test/workflow-runtime.test.ts +1067 -0
  139. package/tsconfig.json +9 -3
  140. package/tsdown.config.ts +3 -1
  141. package/dist/server-CiKkVE6g.mjs +0 -1555
  142. package/dist/server-CiKkVE6g.mjs.map +0 -1
  143. package/dist/utils-Baw7rThP.mjs.map +0 -1
@@ -0,0 +1,3549 @@
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]="e3d937b6-2957-5fe0-8fc9-bf4fd0c18c93")}catch(e){}}();
3
+ import { n as addDefaultReactorDrive, r as isPostgresUrl, t as addDefaultDrive } from "./utils-uaBlzyjS.mjs";
4
+ import { createRequire, register } from "node:module";
5
+ import { metrics, trace } from "@opentelemetry/api";
6
+ import { ReactorInstrumentation } from "@powerhousedao/opentelemetry-instrumentation-reactor";
7
+ import * as Sentry from "@sentry/node";
8
+ import { childLogger, documentModelDocumentModelModule, setLogLevel } from "document-model";
9
+ import dotenv from "dotenv";
10
+ import { getConfig } from "@powerhousedao/config/node";
11
+ import { existsSync, promises, realpathSync } from "node:fs";
12
+ import path, { resolve } from "node:path";
13
+ import { createDurableNodeFs, preparePgliteDataDir, removeStalePgliteFiles, resolvePgliteFsync, syncTree } from "@powerhousedao/reactor-api/pglite-node";
14
+ import { ChannelScheme, DriveCollectionId, EventBus, HardenedPGliteDialect, IN_MEMORY_PGLITE_STORAGE_FACTS, PGLITE_PATH_STORAGE_FACTS, POSTGRES_STORAGE_FACTS, REACTOR_SCHEMA, ReactorBuilder, ReactorClientBuilder, UnsupportedStoredProtocolError, createHybridProjectionCoordinatorFactory, instrumentPgPool, parseDriveUrl, supportsLiveReadModelRegistration } from "@powerhousedao/reactor";
15
+ import { AuthorizationPolicy, BaseSubgraph, ForbiddenError, HttpPackageLoader, ImportPackageLoader, PGLITE_UTC_PARSERS, PackageManagementService, PackagesSubgraph, PrivacyPermissionAdapter, callerSubject, createCanonicalDocumentIdResolver, getUniqueDocumentModels, initializeAndStartAPI, resolveRenownConfig } from "@powerhousedao/reactor-api";
16
+ import { httpsHooksPath } from "@powerhousedao/reactor-api/https-hooks";
17
+ import { AttachmentAlreadyExists, AttachmentNotFound, AttachmentPending, AttachmentReferenceReadModel, AttachmentSchemaCompiler, HashMismatch, InvalidAttachmentMetadata, InvalidAttachmentRef, ReservationNotFound, SizeMismatch, UploadTooLarge, createRef, createRemoteAttachmentService, parseAttachmentDownloadTarget, parseRef, validateReserveMetadata } from "@powerhousedao/reactor-attachments";
18
+ import { createAttachmentClient } from "@powerhousedao/reactor-attachments/client";
19
+ import { DriveNodeView, NodeProcessor, ReactorDriveClient, createReactorDriveResolvers, reactorDriveDocumentModelModule, reactorDriveSubgraphTypeDefs } from "@powerhousedao/reactor-drive";
20
+ import { DEFAULT_KEYPAIR_PATH, DEFAULT_RENOWN_URL, NodeKeyStorage, RENOWN_READ_MODEL_SUBGRAPH, RenownBuilder, RenownCryptoBuilder, createLocalCredentialVerifier, createRenownTrustPolicy, resolveSwitchboardEndpoint } from "@renown/sdk/node";
21
+ import { Kysely, PostgresDialect } from "kysely";
22
+ import net from "node:net";
23
+ import path$1 from "path";
24
+ import { Pool } from "pg";
25
+ import { Readable } from "node:stream";
26
+ import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
27
+ import { DisclosureService, MIN_DEPLOYMENT_SECRET_BYTES, createModuleErasure, createPrivacySubgraph, registerSubjectDocumentsReadModel } from "@powerhousedao/reactor-privacy";
28
+ import { ReactorGroupV1 } from "@powerhousedao/reactor-group";
29
+ import { driveDocumentModelModule } from "@powerhousedao/shared/document-drive";
30
+ import { DEFAULT_SIGNATURE_POLICY, isSignaturePolicy } from "@powerhousedao/shared/document-model";
31
+ import { readFile } from "node:fs/promises";
32
+ import os from "node:os";
33
+ import { fileURLToPath, pathToFileURL } from "node:url";
34
+ import { EnvVarProvider } from "@openfeature/env-var-provider";
35
+ import { OpenFeature } from "@openfeature/server-sdk";
36
+ import { GraphQLError, Kind } from "graphql";
37
+ import { gql } from "graphql-tag";
38
+ //#region src/pglite-version.ts
39
+ const SUPPORTED_PG_MAJORS = [16, 17];
40
+ async function readPgVersionFile(dataDir) {
41
+ try {
42
+ const raw = await promises.readFile(path.join(dataDir, "PG_VERSION"), "utf8");
43
+ const major = parseInt(raw.trim(), 10);
44
+ return Number.isFinite(major) ? major : null;
45
+ } catch {
46
+ return null;
47
+ }
48
+ }
49
+ function isSupportedMajor(major) {
50
+ return SUPPORTED_PG_MAJORS.includes(major);
51
+ }
52
+ /**
53
+ * Parses the `PH_FORCE_PG_VERSION` env var. Returns the validated major, or
54
+ * `null` when the var is unset/empty. Throws on any value that is not a
55
+ * supported major — invalid configuration must fail before the server starts
56
+ * touching disk.
57
+ */
58
+ function parseForcePgVersion(raw) {
59
+ if (raw === void 0 || raw.trim() === "") return null;
60
+ const parsed = Number(raw);
61
+ if (Number.isInteger(parsed) && isSupportedMajor(parsed)) return parsed;
62
+ throw new Error(`PH_FORCE_PG_VERSION must be one of: ${SUPPORTED_PG_MAJORS.join(", ")} (got: ${raw})`);
63
+ }
64
+ async function loadPGliteModule(major) {
65
+ if (major === 16) return await import("pglite-legacy-02");
66
+ return import("@electric-sql/pglite");
67
+ }
68
+ /** The stock NodeFS class of the PGlite module that opens `major` dirs. */
69
+ async function loadNodeFsClass(major) {
70
+ if (major === 16) return (await import("pglite-legacy-02/nodefs")).NodeFS;
71
+ return (await import("@electric-sql/pglite/nodefs")).NodeFS;
72
+ }
73
+ /** Opens a converted dir over stock NodeFS so the conversion can check it. */
74
+ async function openForVerify(major, dataDir) {
75
+ if (!isSupportedMajor(major)) throw new Error(`Cannot verify PGlite data dir ${dataDir}: PG_VERSION=${major} is not supported (expected one of ${SUPPORTED_PG_MAJORS.join(", ")})`);
76
+ const [{ PGlite }, NodeFS] = await Promise.all([loadPGliteModule(major), loadNodeFsClass(major)]);
77
+ const pg = new PGlite({ fs: new NodeFS(dataDir) });
78
+ await pg.waitReady;
79
+ return pg;
80
+ }
81
+ async function loadPgDump(major) {
82
+ if (major === 16) return (await import("pglite-tools-legacy-02/pg_dump")).pgDump;
83
+ return (await import("@electric-sql/pglite-tools/pg_dump")).pgDump;
84
+ }
85
+ //#endregion
86
+ //#region src/profiler.ts
87
+ let started = false;
88
+ async function initProfilerFromEnv(env) {
89
+ if (started || !env.PYROSCOPE_SERVER_ADDRESS) return;
90
+ started = true;
91
+ const { PYROSCOPE_SERVER_ADDRESS: serverAddress, PYROSCOPE_APPLICATION_NAME: appName, PYROSCOPE_USER: basicAuthUser, PYROSCOPE_PASSWORD: basicAuthPassword, PYROSCOPE_WALL_ENABLED: wallEnabled, PYROSCOPE_HEAP_ENABLED: heapEnabled } = env;
92
+ return initProfiler({
93
+ serverAddress,
94
+ appName,
95
+ basicAuthUser,
96
+ basicAuthPassword,
97
+ wall: {
98
+ samplingDurationMs: 1e4,
99
+ samplingIntervalMicros: 1e4,
100
+ collectCpuTime: true
101
+ },
102
+ heap: {
103
+ samplingIntervalBytes: 524288,
104
+ stackDepth: 64
105
+ }
106
+ }, {
107
+ wallEnabled: wallEnabled !== "false",
108
+ heapEnabled: heapEnabled === "true"
109
+ });
110
+ }
111
+ async function initProfiler(options, flags = {
112
+ wallEnabled: true,
113
+ heapEnabled: false
114
+ }) {
115
+ console.log("Initializing Pyroscope profiler at:", options?.serverAddress);
116
+ console.log(" Wall profiling:", flags.wallEnabled ? "enabled" : "disabled");
117
+ console.log(" Heap profiling:", flags.heapEnabled ? "enabled" : "disabled");
118
+ const { default: Pyroscope } = await import("@pyroscope/nodejs");
119
+ Pyroscope.init(options);
120
+ if (flags.wallEnabled) Pyroscope.startWallProfiling();
121
+ Pyroscope.startCpuProfiling();
122
+ if (flags.heapEnabled) Pyroscope.startHeapProfiling();
123
+ }
124
+ //#endregion
125
+ //#region src/attachments/auth.ts
126
+ const ANONYMOUS_ACTOR = {
127
+ user: void 0,
128
+ authEnabled: false
129
+ };
130
+ /**
131
+ * Wrap a Node-style handler so that, when `authService` is provided and auth is
132
+ * enabled, the request must carry a verifiable Bearer token. The handler always
133
+ * receives an actor context: the verified bearer user when auth is enabled, or
134
+ * the anonymous context when it is disabled. With `allowAnonymous`, a missing
135
+ * bearer yields an anonymous actor with `authEnabled: true` instead of a 401 —
136
+ * unless `requireAuthenticatedCaller` says the deployment refuses anonymous
137
+ * callers outright, which overrides it.
138
+ *
139
+ * With no `authService` there is no bearer to read and every caller is
140
+ * anonymous, so nothing is refused here. That combination cannot carry the
141
+ * floor: `assertRequireAuthenticatedCallerAllowed` refuses to boot with
142
+ * `REQUIRE_AUTHENTICATED_CALLER` set and no identity resolution, and identity
143
+ * resolution is what builds the service.
144
+ */
145
+ function requireAuth(authService, handler, options) {
146
+ if (!authService) return (req, res, body) => handler(req, res, body, ANONYMOUS_ACTOR);
147
+ return async (req, res, body) => {
148
+ let result;
149
+ try {
150
+ result = await authService.verifyBearer(req.headers.authorization);
151
+ } catch {
152
+ res.statusCode = 500;
153
+ res.setHeader("Content-Type", "application/json");
154
+ res.end(JSON.stringify({ error: "Internal authentication error" }));
155
+ return;
156
+ }
157
+ if (result instanceof Response) {
158
+ const body = await result.text();
159
+ res.statusCode = result.status;
160
+ const contentType = result.headers.get("content-type");
161
+ if (contentType) res.setHeader("Content-Type", contentType);
162
+ res.end(body);
163
+ return;
164
+ }
165
+ if (!result.user) {
166
+ if (options?.requireAuthenticatedCaller === true || result.auth_enabled && !options?.allowAnonymous) {
167
+ res.statusCode = 401;
168
+ res.setHeader("Content-Type", "application/json");
169
+ res.end(JSON.stringify({ error: "Authentication required" }));
170
+ return;
171
+ }
172
+ }
173
+ await handler(req, res, body, {
174
+ user: result.user,
175
+ authEnabled: result.auth_enabled
176
+ });
177
+ };
178
+ }
179
+ //#endregion
180
+ //#region src/attachments/mount-auth.ts
181
+ /**
182
+ * Mount a Node-style attachment route with `requireAuth` applied unconditionally.
183
+ * When `api.authService` is undefined (auth disabled), the handler still runs
184
+ * through `requireAuth` and receives the anonymous actor context — that is the
185
+ * only way to opt out of bearer verification. To register a route without auth
186
+ * wrapping you must call `api.httpAdapter.mountNodeRoute` directly.
187
+ *
188
+ * `allowAnonymous` is reserved for routes whose handlers make a per-document
189
+ * authorization decision themselves; identity-only routes must not use it. It
190
+ * is also not the last word: a deployment that refuses anonymous callers
191
+ * (`REQUIRE_AUTHENTICATED_CALLER`) refuses them here too, because these routes
192
+ * are mounted on the HTTP adapter and never reach the fetch chain that carries
193
+ * that floor for GraphQL. The flag is read from the API, so every route
194
+ * mounted through here inherits it without each one remembering to.
195
+ */
196
+ function mountAuthenticatedNodeRoute(api, method, path, handler, options) {
197
+ api.httpAdapter.mountNodeRoute(method, path, requireAuth(api.authService, handler, {
198
+ ...options,
199
+ requireAuthenticatedCaller: api.requireAuthenticatedCaller
200
+ }));
201
+ }
202
+ //#endregion
203
+ //#region src/attachments/routes.ts
204
+ const logger$2 = childLogger(["switchboard", "attachments"]);
205
+ const RETRY_AFTER_SECONDS = 5;
206
+ const HASH_PATTERN = /^[a-f0-9]{64}$/i;
207
+ function sendJson(res, status, body) {
208
+ res.statusCode = status;
209
+ res.setHeader("Content-Type", "application/json");
210
+ res.end(JSON.stringify(body));
211
+ }
212
+ function sendError(res, status, message) {
213
+ sendJson(res, status, { error: message });
214
+ }
215
+ function statusForError(err) {
216
+ if (err instanceof AttachmentNotFound) return 404;
217
+ if (err instanceof ReservationNotFound) return 404;
218
+ if (err instanceof InvalidAttachmentRef) return 400;
219
+ if (err instanceof UploadTooLarge) return 413;
220
+ return 500;
221
+ }
222
+ function sendErrorFromException(res, err) {
223
+ const status = statusForError(err);
224
+ if (status >= 500) {
225
+ logger$2.error("Attachment route error: @error", err);
226
+ sendError(res, status, "Internal error");
227
+ return;
228
+ }
229
+ sendError(res, status, err instanceof Error ? err.message : String(err));
230
+ }
231
+ async function readJsonBody(req, body) {
232
+ if (body !== void 0 && body !== null && typeof body === "object") return body;
233
+ const chunks = [];
234
+ for await (const chunk of req) chunks.push(chunk);
235
+ if (chunks.length === 0) return void 0;
236
+ const text = Buffer.concat(chunks).toString("utf8");
237
+ if (text.length === 0) return void 0;
238
+ return JSON.parse(text);
239
+ }
240
+ function parseReserveOptions(input) {
241
+ if (input === null || typeof input !== "object") return null;
242
+ const obj = input;
243
+ const { mimeType, fileName } = obj;
244
+ const extension = obj.extension ?? null;
245
+ try {
246
+ validateReserveMetadata({
247
+ mimeType,
248
+ fileName,
249
+ extension
250
+ });
251
+ } catch (err) {
252
+ if (err instanceof InvalidAttachmentMetadata) return null;
253
+ throw err;
254
+ }
255
+ if (typeof mimeType !== "string" || typeof fileName !== "string") return null;
256
+ if (extension !== null && typeof extension !== "string") return null;
257
+ if (obj.clientHash !== void 0) {
258
+ if (typeof obj.clientHash !== "string" || !HASH_PATTERN.test(obj.clientHash)) return null;
259
+ if (typeof obj.sizeBytes !== "number" || !Number.isInteger(obj.sizeBytes) || obj.sizeBytes <= 0 || !Number.isSafeInteger(obj.sizeBytes)) return null;
260
+ return {
261
+ mimeType,
262
+ fileName,
263
+ extension,
264
+ clientHash: obj.clientHash.toLowerCase(),
265
+ sizeBytes: obj.sizeBytes
266
+ };
267
+ }
268
+ return {
269
+ mimeType,
270
+ fileName,
271
+ extension
272
+ };
273
+ }
274
+ function quoteFilename(name) {
275
+ return `"${name.replace(/[\\"]/g, "\\$&")}"`;
276
+ }
277
+ function buildContentDisposition(fileName) {
278
+ const ascii = fileName.replace(/[^\x20-\x21\x23-\x5b\x5d-\x7e]/g, "_");
279
+ const encoded = encodeURIComponent(fileName).replace(/['()*!]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
280
+ return `attachment; filename=${quoteFilename(ascii)}; filename*=UTF-8''${encoded}`;
281
+ }
282
+ function makeReserveHandler(attachments) {
283
+ return async (req, res, body) => {
284
+ let parsed;
285
+ try {
286
+ parsed = await readJsonBody(req, body);
287
+ } catch {
288
+ sendError(res, 400, "Invalid JSON body");
289
+ return;
290
+ }
291
+ const opts = parseReserveOptions(parsed);
292
+ if (!opts) {
293
+ sendError(res, 400, "Body must be { mimeType: string (type/subtype), fileName: string (no control characters, max 255 chars), extension?: string|null, clientHash?: string (64 hex chars), sizeBytes?: number (required with clientHash) }");
294
+ return;
295
+ }
296
+ let upload;
297
+ try {
298
+ upload = await attachments.service.reserve(opts);
299
+ } catch (err) {
300
+ if (err instanceof AttachmentAlreadyExists) {
301
+ sendJson(res, 409, {
302
+ error: "already_exists",
303
+ ref: err.ref
304
+ });
305
+ return;
306
+ }
307
+ sendErrorFromException(res, err);
308
+ return;
309
+ }
310
+ sendJson(res, 201, {
311
+ reservationId: upload.reservationId,
312
+ ref: upload.ref,
313
+ expiresAtUtc: upload.expiresAtUtc,
314
+ ...upload.uploadTarget ? { uploadTarget: upload.uploadTarget } : {}
315
+ });
316
+ };
317
+ }
318
+ function makeUploadHandler(attachments) {
319
+ return async (req, res) => {
320
+ const reservationId = extractParam(req, "reservationId");
321
+ if (!reservationId) {
322
+ sendError(res, 400, "Missing reservationId");
323
+ return;
324
+ }
325
+ if (attachments.backend?.kind === "s3") {
326
+ sendError(res, 405, "Use the reservation uploadTarget for S3 uploads");
327
+ return;
328
+ }
329
+ let reservation;
330
+ try {
331
+ reservation = await attachments.reservations.get(reservationId);
332
+ } catch (err) {
333
+ sendErrorFromException(res, err);
334
+ return;
335
+ }
336
+ const upload = attachments.uploadFactory.createUpload(reservation);
337
+ const webStream = Readable.toWeb(req);
338
+ try {
339
+ sendJson(res, 200, await upload.send(webStream));
340
+ } catch (err) {
341
+ if (err instanceof HashMismatch) {
342
+ sendJson(res, 422, {
343
+ error: "hash_mismatch",
344
+ claimed: err.claimed,
345
+ actual: err.actual
346
+ });
347
+ return;
348
+ }
349
+ if (err instanceof SizeMismatch) {
350
+ sendJson(res, 422, {
351
+ error: "size_mismatch",
352
+ declared: err.declared,
353
+ actual: err.actual
354
+ });
355
+ return;
356
+ }
357
+ sendErrorFromException(res, err);
358
+ }
359
+ };
360
+ }
361
+ function makeDownloadHandler(attachments, attachmentAccess, urlSigner) {
362
+ return async (req, res, _body, actor) => {
363
+ const hash = extractParam(req, "hash");
364
+ if (!hash || !HASH_PATTERN.test(hash)) {
365
+ sendError(res, 400, "Invalid attachment hash");
366
+ return;
367
+ }
368
+ const canonicalHash = hash.toLowerCase();
369
+ const grant = await resolveByteGrant(req, canonicalHash, actor, attachmentAccess, urlSigner);
370
+ if (!admitGrant(res, grant)) return;
371
+ const controller = new AbortController();
372
+ req.once("close", () => controller.abort());
373
+ let response;
374
+ try {
375
+ response = await attachments.store.get(canonicalHash, controller.signal, grant.documentId);
376
+ } catch (err) {
377
+ if (err instanceof AttachmentPending) {
378
+ res.statusCode = 202;
379
+ res.setHeader("Cache-Control", "private");
380
+ res.setHeader("Retry-After", String(RETRY_AFTER_SECONDS));
381
+ res.setHeader("Attachment-Pending", buildPendingHeader({
382
+ expiresAtUtc: err.expiresAtUtc,
383
+ ...err.metadata ?? {}
384
+ }));
385
+ res.end();
386
+ return;
387
+ }
388
+ sendErrorFromException(res, err);
389
+ return;
390
+ }
391
+ const { header, body } = response;
392
+ res.statusCode = 200;
393
+ res.setHeader("Cache-Control", "private");
394
+ res.setHeader("Content-Type", header.mimeType);
395
+ res.setHeader("Content-Length", String(header.sizeBytes));
396
+ res.setHeader("Content-Disposition", buildContentDisposition(header.fileName));
397
+ res.setHeader("Attachment-Metadata", buildMetadataHeader(header));
398
+ Readable.fromWeb(body).pipe(res);
399
+ };
400
+ }
401
+ function toAsciiJson(value) {
402
+ return JSON.stringify(value).replace(/[\u007f-\uffff]/g, (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`);
403
+ }
404
+ function buildPendingHeader(pending) {
405
+ return toAsciiJson(pending);
406
+ }
407
+ function buildMetadataHeader(header) {
408
+ return toAsciiJson({
409
+ mimeType: header.mimeType,
410
+ fileName: header.fileName,
411
+ sizeBytes: header.sizeBytes,
412
+ extension: header.extension,
413
+ createdAtUtc: header.createdAtUtc,
414
+ lastAccessedAtUtc: header.lastAccessedAtUtc
415
+ });
416
+ }
417
+ function makeStatHandler(attachments, attachmentAccess, urlSigner) {
418
+ return async (req, res, _body, actor) => {
419
+ const hash = extractParam(req, "hash");
420
+ if (!hash || !HASH_PATTERN.test(hash)) {
421
+ sendError(res, 400, "Invalid attachment hash");
422
+ return;
423
+ }
424
+ const canonicalHash = hash.toLowerCase();
425
+ if (!admitGrant(res, await resolveByteGrant(req, canonicalHash, actor, attachmentAccess, urlSigner))) return;
426
+ let header;
427
+ try {
428
+ header = await attachments.store.stat(canonicalHash);
429
+ } catch (err) {
430
+ sendErrorFromException(res, err);
431
+ return;
432
+ }
433
+ res.setHeader("Cache-Control", "private");
434
+ if (header.status === "pending") {
435
+ res.statusCode = 202;
436
+ res.setHeader("Retry-After", String(RETRY_AFTER_SECONDS));
437
+ res.setHeader("Attachment-Pending", buildPendingHeader({
438
+ expiresAtUtc: header.expiresAtUtc,
439
+ mimeType: header.mimeType,
440
+ fileName: header.fileName,
441
+ sizeBytes: header.sizeBytes
442
+ }));
443
+ res.end();
444
+ return;
445
+ }
446
+ res.statusCode = 200;
447
+ res.setHeader("Content-Type", header.mimeType);
448
+ res.setHeader("Content-Length", String(header.sizeBytes));
449
+ res.setHeader("Content-Disposition", buildContentDisposition(header.fileName));
450
+ res.setHeader("Attachment-Metadata", buildMetadataHeader(header));
451
+ res.end();
452
+ };
453
+ }
454
+ function makeGetReservationHandler(attachments) {
455
+ return async (req, res) => {
456
+ const reservationId = extractParam(req, "reservationId");
457
+ if (!reservationId) {
458
+ sendError(res, 400, "Missing reservationId");
459
+ return;
460
+ }
461
+ try {
462
+ sendJson(res, 200, await attachments.reservations.get(reservationId));
463
+ } catch (err) {
464
+ sendErrorFromException(res, err);
465
+ }
466
+ };
467
+ }
468
+ function makeDeleteReservationHandler(attachments) {
469
+ return async (req, res) => {
470
+ const reservationId = extractParam(req, "reservationId");
471
+ if (!reservationId) {
472
+ sendError(res, 400, "Missing reservationId");
473
+ return;
474
+ }
475
+ try {
476
+ await attachments.reservations.delete(reservationId);
477
+ res.statusCode = 204;
478
+ res.end();
479
+ } catch (err) {
480
+ sendErrorFromException(res, err);
481
+ }
482
+ };
483
+ }
484
+ function extractParam(req, name) {
485
+ return req.params?.[name];
486
+ }
487
+ const MAX_DOCUMENT_ID_LEN = 512;
488
+ const ATTACHMENT_NOT_FOUND_BODY = { error: "Attachment not found" };
489
+ const MAX_DOWNLOAD_TARGET_TTL_SECONDS = 604800;
490
+ /**
491
+ * How long a download target may live, by default.
492
+ *
493
+ * The authorization behind a presigned URL is decided once, when it is issued,
494
+ * and the URL keeps working until it expires however the document's policy
495
+ * changes in between. A week of that is a revocation that does not revoke: an
496
+ * account deactivated, a company reassigned or a group left, and the bytes stay
497
+ * fetchable by anyone holding the link. Minutes are enough to open a file;
498
+ * days are only enough to lose control of it.
499
+ *
500
+ * A deployment that needs longer sets ATTACHMENT_DOWNLOAD_TARGET_MAX_TTL_SECONDS,
501
+ * still bounded by the signing ceiling above.
502
+ */
503
+ const DEFAULT_DOWNLOAD_TARGET_TTL_SECONDS = 300;
504
+ /**
505
+ * The ceiling in force, read per call so a deployment can set it without the
506
+ * value being frozen at import — which is also what lets a test cover it.
507
+ * Anything unparseable falls back to the default rather than to the maximum:
508
+ * a typo must not quietly widen the window it was meant to narrow.
509
+ */
510
+ function downloadTargetTtlCapSeconds() {
511
+ const configured = process.env.ATTACHMENT_DOWNLOAD_TARGET_MAX_TTL_SECONDS;
512
+ if (configured === void 0) return DEFAULT_DOWNLOAD_TARGET_TTL_SECONDS;
513
+ const parsed = Number(configured);
514
+ if (!Number.isInteger(parsed) || parsed <= 0) {
515
+ logger$2.warn(`Ignoring invalid ATTACHMENT_DOWNLOAD_TARGET_MAX_TTL_SECONDS="${configured}" (expected a positive integer number of seconds) — using ${DEFAULT_DOWNLOAD_TARGET_TTL_SECONDS}`);
516
+ return DEFAULT_DOWNLOAD_TARGET_TTL_SECONDS;
517
+ }
518
+ return Math.min(parsed, MAX_DOWNLOAD_TARGET_TTL_SECONDS);
519
+ }
520
+ /**
521
+ * Returns the single `documentId` query value, or null when it is missing,
522
+ * duplicated, blank, or oversized. Validation happens before authorization so
523
+ * malformed requests never reach the access service.
524
+ */
525
+ function extractSingleDocumentId(req) {
526
+ if (!req.url) return null;
527
+ let url;
528
+ try {
529
+ url = new URL(req.url, "http://switchboard.invalid");
530
+ } catch {
531
+ return null;
532
+ }
533
+ const values = url.searchParams.getAll("documentId");
534
+ if (values.length !== 1) return null;
535
+ const value = values[0];
536
+ if (value.trim().length === 0 || value.length > MAX_DOCUMENT_ID_LEN) return null;
537
+ return value;
538
+ }
539
+ /**
540
+ * Returns the target TTL in seconds, or "invalid" when the caller's own value
541
+ * is malformed (duplicated, non-integer, or non-positive).
542
+ *
543
+ * The cap applies whether or not the caller asked for a lifetime: omitting
544
+ * `expiresIn` used to fall through to whatever the storage backend was
545
+ * configured with, which would make the ceiling something a client opts out of
546
+ * by saying nothing.
547
+ */
548
+ function extractExpiresIn(req) {
549
+ const cap = downloadTargetTtlCapSeconds();
550
+ if (!req.url) return cap;
551
+ let url;
552
+ try {
553
+ url = new URL(req.url, "http://switchboard.invalid");
554
+ } catch {
555
+ return cap;
556
+ }
557
+ const values = url.searchParams.getAll("expiresIn");
558
+ if (values.length === 0) return cap;
559
+ if (values.length > 1) return "invalid";
560
+ const parsed = Number(values[0]);
561
+ if (!Number.isInteger(parsed) || parsed <= 0) return "invalid";
562
+ return Math.min(parsed, cap);
563
+ }
564
+ function singleQueryValue(params, name) {
565
+ const values = params.getAll(name);
566
+ return values.length === 1 ? values[0] : null;
567
+ }
568
+ /**
569
+ * Byte routes serve only under a grant: a signed URL minted by the
570
+ * download-target route, or a documentId the caller may read the attachment
571
+ * through. A signed request is judged by its signature alone.
572
+ */
573
+ async function resolveByteGrant(req, hash, actor, attachmentAccess, urlSigner) {
574
+ let params;
575
+ try {
576
+ params = new URL(req.url ?? "", "http://switchboard.invalid").searchParams;
577
+ } catch {
578
+ return { kind: "denied" };
579
+ }
580
+ const documentId = extractSingleDocumentId(req);
581
+ if (documentId === null) return { kind: "denied" };
582
+ if (params.has("signature") || params.has("expires")) {
583
+ const signature = singleQueryValue(params, "signature");
584
+ const expires = singleQueryValue(params, "expires");
585
+ if (!urlSigner || signature === null || expires === null) return { kind: "denied" };
586
+ return urlSigner.verify(hash, documentId, expires, signature) ? {
587
+ kind: "granted",
588
+ documentId
589
+ } : { kind: "denied" };
590
+ }
591
+ let decision;
592
+ try {
593
+ decision = await attachmentAccess.canReadAttachment({
594
+ documentId,
595
+ attachmentRef: createRef(hash),
596
+ userAddress: actor?.user?.address,
597
+ appKey: actor?.user?.appKey
598
+ });
599
+ } catch (err) {
600
+ logger$2.error("Attachment access decision failed: @error", err);
601
+ return { kind: "error" };
602
+ }
603
+ if (decision.kind === "projection-unavailable") return { kind: "unavailable" };
604
+ if (decision.kind === "denied") return { kind: "denied" };
605
+ return {
606
+ kind: "granted",
607
+ documentId: decision.documentId
608
+ };
609
+ }
610
+ /** Answers a refused grant; true when the request may proceed. */
611
+ function admitGrant(res, grant) {
612
+ switch (grant.kind) {
613
+ case "granted": return true;
614
+ case "denied":
615
+ sendJson(res, 404, ATTACHMENT_NOT_FOUND_BODY);
616
+ return false;
617
+ case "unavailable":
618
+ sendError(res, 503, "Attachment downloads are temporarily unavailable");
619
+ return false;
620
+ case "error":
621
+ sendError(res, 500, "Internal error");
622
+ return false;
623
+ }
624
+ }
625
+ /**
626
+ * Base URL of this Switchboard as seen by the caller, used to build
627
+ * filesystem `switchboard` download targets that point back at the signed
628
+ * byte route.
629
+ */
630
+ function requestBaseUrl(req) {
631
+ const forwardedProto = req.headers["x-forwarded-proto"];
632
+ const proto = (Array.isArray(forwardedProto) ? forwardedProto[0] : forwardedProto)?.split(",")[0]?.trim() || (req.socket.encrypted ? "https" : "http");
633
+ const forwardedHost = req.headers["x-forwarded-host"];
634
+ const host = (Array.isArray(forwardedHost) ? forwardedHost[0] : forwardedHost) ?? req.headers.host;
635
+ if (!host) return null;
636
+ return `${proto}://${host}`;
637
+ }
638
+ function makeDownloadTargetHandler(attachments, attachmentAccess, urlSigner) {
639
+ return async (req, res, _body, actor) => {
640
+ res.setHeader("Cache-Control", "no-store");
641
+ const hash = extractParam(req, "hash");
642
+ if (!hash || !HASH_PATTERN.test(hash)) {
643
+ sendError(res, 400, "Invalid attachment hash");
644
+ return;
645
+ }
646
+ const documentId = extractSingleDocumentId(req);
647
+ if (documentId === null) {
648
+ sendError(res, 400, "documentId is required exactly once as a non-empty query parameter");
649
+ return;
650
+ }
651
+ const expiresIn = extractExpiresIn(req);
652
+ if (expiresIn === "invalid") {
653
+ sendError(res, 400, "expiresIn must be a single positive integer number of seconds");
654
+ return;
655
+ }
656
+ const canonicalHash = hash.toLowerCase();
657
+ let decision;
658
+ try {
659
+ decision = await attachmentAccess.canReadAttachment({
660
+ documentId,
661
+ attachmentRef: createRef(canonicalHash),
662
+ userAddress: actor?.user?.address,
663
+ appKey: actor?.user?.appKey
664
+ });
665
+ } catch (err) {
666
+ logger$2.error("Attachment access decision failed: @error", err);
667
+ sendError(res, 500, "Internal error");
668
+ return;
669
+ }
670
+ if (decision.kind === "projection-unavailable") {
671
+ sendError(res, 503, "Attachment downloads are temporarily unavailable");
672
+ return;
673
+ }
674
+ if (decision.kind === "denied") {
675
+ sendJson(res, 404, ATTACHMENT_NOT_FOUND_BODY);
676
+ return;
677
+ }
678
+ let header;
679
+ try {
680
+ header = await attachments.store.stat(canonicalHash);
681
+ } catch (err) {
682
+ if (err instanceof AttachmentNotFound) {
683
+ sendJson(res, 404, ATTACHMENT_NOT_FOUND_BODY);
684
+ return;
685
+ }
686
+ logger$2.error("Attachment metadata lookup failed: @error", err);
687
+ sendError(res, 500, "Internal error");
688
+ return;
689
+ }
690
+ if (header.status !== "available") {
691
+ sendJson(res, 404, ATTACHMENT_NOT_FOUND_BODY);
692
+ return;
693
+ }
694
+ let target;
695
+ if (attachments.backend && attachments.backend.kind !== "filesystem") try {
696
+ target = await attachments.backend.prepareDownloadTarget(canonicalHash, expiresIn);
697
+ } catch {
698
+ sendError(res, 502, "Attachment download target unavailable");
699
+ return;
700
+ }
701
+ else {
702
+ if (!urlSigner) {
703
+ sendError(res, 503, "Attachment download signing is not configured");
704
+ return;
705
+ }
706
+ const base = requestBaseUrl(req);
707
+ if (!base) {
708
+ sendError(res, 500, "Internal error");
709
+ return;
710
+ }
711
+ const signed = urlSigner.sign(canonicalHash, decision.documentId, expiresIn);
712
+ try {
713
+ target = parseAttachmentDownloadTarget({
714
+ kind: "switchboard",
715
+ method: "GET",
716
+ url: `${base}/attachments/${canonicalHash}?${signed.query}`,
717
+ headers: {},
718
+ expiresAtUtc: signed.expiresAtUtc
719
+ });
720
+ } catch {
721
+ sendError(res, 500, "Internal error");
722
+ return;
723
+ }
724
+ }
725
+ sendJson(res, 200, target);
726
+ };
727
+ }
728
+ //#endregion
729
+ //#region src/attachments/url-signer.ts
730
+ const ATTACHMENT_URL_SIGNING_SECRET_ENV = "PH_ATTACHMENT_URL_SIGNING_SECRET";
731
+ const MIN_SECRET_LENGTH = 32;
732
+ const EXPIRES_PATTERN = /^[1-9]\d{0,15}$/;
733
+ const SIGNATURE_PATTERN = /^[A-Za-z0-9_-]{43}$/;
734
+ var AttachmentUrlSigner = class {
735
+ secret;
736
+ now;
737
+ constructor(secret, now = Date.now) {
738
+ this.secret = secret;
739
+ this.now = now;
740
+ }
741
+ sign(hash, documentId, ttlSeconds) {
742
+ const expires = Math.floor(this.now() / 1e3) + ttlSeconds;
743
+ return {
744
+ query: new URLSearchParams({
745
+ documentId,
746
+ expires: String(expires),
747
+ signature: this.mac(hash, documentId, String(expires))
748
+ }).toString(),
749
+ expiresAtUtc: (/* @__PURE__ */ new Date(expires * 1e3)).toISOString()
750
+ };
751
+ }
752
+ verify(hash, documentId, expires, signature) {
753
+ if (!EXPIRES_PATTERN.test(expires) || !SIGNATURE_PATTERN.test(signature)) return false;
754
+ if (Number(expires) * 1e3 <= this.now()) return false;
755
+ const expected = Buffer.from(this.mac(hash, documentId, expires));
756
+ const presented = Buffer.from(signature);
757
+ return expected.length === presented.length && timingSafeEqual(expected, presented);
758
+ }
759
+ mac(hash, documentId, expires) {
760
+ return createHmac("sha256", this.secret).update(JSON.stringify([
761
+ "attachment-download/v1",
762
+ hash,
763
+ documentId,
764
+ expires
765
+ ])).digest("base64url");
766
+ }
767
+ };
768
+ function resolveAttachmentUrlSigning(env = process.env) {
769
+ const secret = env[ATTACHMENT_URL_SIGNING_SECRET_ENV];
770
+ if (secret !== void 0) {
771
+ if (secret.trim() !== secret || secret.length < MIN_SECRET_LENGTH) throw new Error(`${ATTACHMENT_URL_SIGNING_SECRET_ENV} must be at least ${MIN_SECRET_LENGTH} characters with no leading or trailing whitespace`);
772
+ return {
773
+ status: "configured",
774
+ signer: new AttachmentUrlSigner(secret)
775
+ };
776
+ }
777
+ if (env.NODE_ENV === "production") return { status: "unconfigured" };
778
+ return {
779
+ status: "ephemeral",
780
+ signer: new AttachmentUrlSigner(randomBytes(32))
781
+ };
782
+ }
783
+ //#endregion
784
+ //#region src/attachments/index.ts
785
+ const logger$1 = childLogger(["switchboard", "attachments"]);
786
+ function registerAttachmentRoutes(api, options = {}) {
787
+ const { attachments, attachmentAccess } = api;
788
+ const urlSigner = options.urlSigner === void 0 ? signerFromEnvironment(attachments.backend?.kind ?? "filesystem") : options.urlSigner;
789
+ mountAuthenticatedNodeRoute(api, "POST", "/attachments/reservations", makeReserveHandler(attachments));
790
+ mountAuthenticatedNodeRoute(api, "GET", "/attachments/reservations/:reservationId", makeGetReservationHandler(attachments));
791
+ mountAuthenticatedNodeRoute(api, "DELETE", "/attachments/reservations/:reservationId", makeDeleteReservationHandler(attachments));
792
+ mountAuthenticatedNodeRoute(api, "PUT", "/attachments/reservations/:reservationId", makeUploadHandler(attachments));
793
+ mountAuthenticatedNodeRoute(api, "HEAD", "/attachments/:hash", makeStatHandler(attachments, attachmentAccess, urlSigner), { allowAnonymous: true });
794
+ mountAuthenticatedNodeRoute(api, "GET", "/attachments/:hash/download-target", makeDownloadTargetHandler(attachments, attachmentAccess, urlSigner), { allowAnonymous: true });
795
+ mountAuthenticatedNodeRoute(api, "GET", "/attachments/:hash", makeDownloadHandler(attachments, attachmentAccess, urlSigner), { allowAnonymous: true });
796
+ }
797
+ function signerFromEnvironment(backend) {
798
+ const signing = resolveAttachmentUrlSigning();
799
+ if (signing.status === "unconfigured") {
800
+ if (backend === "filesystem") logger$1.error(`${ATTACHMENT_URL_SIGNING_SECRET_ENV} is not set: filesystem attachment download targets are refused until it is`);
801
+ return null;
802
+ }
803
+ if (signing.status === "ephemeral" && backend === "filesystem") logger$1.warn(`${ATTACHMENT_URL_SIGNING_SECRET_ENV} is not set: signing attachment download URLs with a per-process secret`);
804
+ return signing.signer;
805
+ }
806
+ //#endregion
807
+ //#region src/attachment-reference-read-model.mts
808
+ const attachmentSchemaCompiler = new AttachmentSchemaCompiler();
809
+ function createAttachmentReferenceReadModel(baseKysely, dependencies, attachmentReferenceWriter) {
810
+ return new AttachmentReferenceReadModel(baseKysely.withSchema(REACTOR_SCHEMA), dependencies.operationIndex, dependencies.writeCache, dependencies.processorManagerConsistencyTracker, dependencies.documentModelRegistry, attachmentSchemaCompiler, attachmentReferenceWriter);
811
+ }
812
+ function registerAttachmentReferenceReadModel(reactorBuilder, registration) {
813
+ reactorBuilder.withReadModelFactory(async ({ documentModelRegistry, operationIndex, writeCache, processorManagerConsistencyTracker }) => {
814
+ const readModel = createAttachmentReferenceReadModel(registration.baseKysely, {
815
+ operationIndex,
816
+ writeCache,
817
+ processorManagerConsistencyTracker,
818
+ documentModelRegistry
819
+ }, registration.attachmentReferenceWriter);
820
+ await readModel.init();
821
+ return readModel;
822
+ });
823
+ }
824
+ async function registerAttachmentReferenceReadModelOnModule(clientModule, attachmentReferenceWriter) {
825
+ const reactorModule = clientModule.reactorModule;
826
+ if (!reactorModule) return {
827
+ status: "unavailable",
828
+ reason: "in-process-reactor-module-unavailable"
829
+ };
830
+ const coordinator = reactorModule.readModelCoordinator;
831
+ if (!supportsLiveReadModelRegistration(coordinator)) return {
832
+ status: "unavailable",
833
+ reason: "live-read-model-registration-unsupported"
834
+ };
835
+ const readModel = createAttachmentReferenceReadModel(reactorModule.database, {
836
+ operationIndex: reactorModule.operationIndex,
837
+ writeCache: reactorModule.writeCache,
838
+ processorManagerConsistencyTracker: reactorModule.processorManagerConsistencyTracker,
839
+ documentModelRegistry: reactorModule.documentModelRegistry
840
+ }, attachmentReferenceWriter);
841
+ await readModel.init();
842
+ coordinator.addReadModel(readModel, "pre_ready");
843
+ await readModel.init();
844
+ return { status: "available" };
845
+ }
846
+ //#endregion
847
+ //#region src/fatal-shutdown.mts
848
+ const FORCED_EXIT_MS = 15e3;
849
+ const fatalHandlers = /* @__PURE__ */ new WeakMap();
850
+ /**
851
+ * Sends an uncaught exception or unhandled rejection through the SIGTERM
852
+ * shutdown that `withSignalHandlers()` installs, so the reactor and read-model
853
+ * PGlite stores close with a shutdown checkpoint before the process exits
854
+ * with code 1. Node's default is to exit at once, which leaves both stores
855
+ * to WAL recovery on the next open. A store whose wasm runtime aborted
856
+ * (ENOSPC) rejects its close; the builder logs that and still exits. A
857
+ * shutdown that hangs is cut off after FORCED_EXIT_MS.
858
+ *
859
+ * A rejection is fatal only when this is its sole listener: Node exits on an
860
+ * unhandled rejection only when nothing listens for it, and Sentry's
861
+ * listener deliberately keeps the process running.
862
+ */
863
+ function installFatalErrorShutdown(logger, proc = process) {
864
+ if (fatalHandlers.has(proc)) return;
865
+ const realExit = proc.exit.bind(proc);
866
+ let shuttingDown = false;
867
+ /**
868
+ * Logs without ever throwing. onFatal runs inside the uncaughtException
869
+ * handler, so a logger whose transport is gone (EPIPE on a closed stdout)
870
+ * would otherwise throw from the handler that reports throws, killing the
871
+ * process before the shutdown it is supposed to run. A logging failure is
872
+ * swallowed: there is nowhere left to report it.
873
+ */
874
+ const logFatal = (message, err) => {
875
+ try {
876
+ if (err === void 0) logger.error(message);
877
+ else logger.error(message, err);
878
+ } catch {}
879
+ };
880
+ const onFatal = (kind, err) => {
881
+ logFatal(`${kind}: @error`, err);
882
+ if (shuttingDown) return;
883
+ shuttingDown = true;
884
+ proc.exitCode = 1;
885
+ setTimeout(() => {
886
+ logFatal("Shutdown after fatal error timed out; exiting");
887
+ realExit(1);
888
+ }, FORCED_EXIT_MS).unref();
889
+ proc.kill(proc.pid, "SIGTERM");
890
+ };
891
+ fatalHandlers.set(proc, onFatal);
892
+ proc.on("uncaughtException", (err) => onFatal("Uncaught exception", err));
893
+ proc.on("unhandledRejection", (reason) => {
894
+ if (proc.listenerCount("unhandledRejection") > 1) return;
895
+ onFatal("Unhandled rejection", reason);
896
+ });
897
+ }
898
+ /**
899
+ * Routes a fatal condition the caller detected through the same shutdown as an
900
+ * uncaught error. Returns false, and does nothing, when
901
+ * `installFatalErrorShutdown` has not run for `proc`.
902
+ */
903
+ function triggerFatalShutdown(kind, err, proc = process) {
904
+ const onFatal = fatalHandlers.get(proc);
905
+ if (!onFatal) return false;
906
+ onFatal(kind, err);
907
+ return true;
908
+ }
909
+ //#endregion
910
+ //#region src/privacy.mts
911
+ const DAY_MS = 864e5;
912
+ /** Enabling privacy on a switchboard that cannot run it safely. */
913
+ var PrivacyBootError = class extends Error {
914
+ constructor(message) {
915
+ super(message);
916
+ this.name = "PrivacyBootError";
917
+ }
918
+ };
919
+ function positive(env, name, unitMs) {
920
+ const raw = env[name];
921
+ if (raw === void 0 || raw.trim() === "") return void 0;
922
+ const value = Number(raw);
923
+ if (!Number.isFinite(value) || value <= 0) throw new PrivacyBootError(`${name} must be a positive number, got "${raw}"`);
924
+ return value * unitMs;
925
+ }
926
+ function resolvePrivacy(options, env) {
927
+ if (!(options?.enabled ?? env.PH_PRIVACY_ENABLED === "true")) return { enabled: false };
928
+ const deploymentSecret = options?.deploymentSecret ?? env.PH_PRIVACY_DEPLOYMENT_SECRET;
929
+ if (!deploymentSecret || Buffer.byteLength(deploymentSecret, "utf8") < MIN_DEPLOYMENT_SECRET_BYTES) throw new PrivacyBootError(`PH_PRIVACY_ENABLED needs PH_PRIVACY_DEPLOYMENT_SECRET of at least ${MIN_DEPLOYMENT_SECRET_BYTES} bytes`);
930
+ return {
931
+ enabled: true,
932
+ deploymentSecret,
933
+ intervalMs: positive(env, "PH_PRIVACY_INTERVAL_MS", 1),
934
+ deadlineMs: positive(env, "PH_PRIVACY_DEADLINE_DAYS", DAY_MS),
935
+ markerGraceMs: positive(env, "PH_PRIVACY_MARKER_GRACE_DAYS", DAY_MS),
936
+ purgeTimeoutMs: positive(env, "PH_PRIVACY_PURGE_TIMEOUT_MINUTES", 6e4)
937
+ };
938
+ }
939
+ /** Subject index, erasure scheduler and admin subgraph on a built reactor. */
940
+ async function startPrivacy(deps) {
941
+ const { config, reactorModule, authorizationService } = deps;
942
+ if (authorizationService.config.policy === AuthorizationPolicy.OPEN) throw new PrivacyBootError("PH_PRIVACY_ENABLED is refused under the OPEN authorization policy: every caller, anonymous included, would administer erasure. Enable authentication (AUTH_ENABLED=true with ADMINS) first.");
943
+ if (!reactorModule) throw new PrivacyBootError("PH_PRIVACY_ENABLED needs an in-process reactor module");
944
+ if (!deps.signer?.app?.key) throw new PrivacyBootError("PH_PRIVACY_ENABLED needs a reactor signer (a Renown identity): every receiver refuses an unsigned purge marker");
945
+ const permissions = deps.documentPermissionService ? new PrivacyPermissionAdapter(deps.documentPermissionService) : void 0;
946
+ const { service, scheduler } = createModuleErasure(reactorModule, {
947
+ deploymentSecret: config.deploymentSecret,
948
+ signer: deps.signer,
949
+ permissions,
950
+ intervalMs: config.intervalMs,
951
+ deadlineMs: config.deadlineMs,
952
+ markerGraceMs: config.markerGraceMs,
953
+ purgeTimeoutMs: config.purgeTimeoutMs,
954
+ logger: deps.logger
955
+ });
956
+ const disclosure = new DisclosureService(reactorModule.database, config.deploymentSecret, permissions);
957
+ let subgraph;
958
+ try {
959
+ subgraph = createPrivacySubgraph({
960
+ authorizationService,
961
+ erasure: service,
962
+ disclosure
963
+ });
964
+ } catch (error) {
965
+ throw new PrivacyBootError(error instanceof Error ? error.message : String(error));
966
+ }
967
+ await registerSubjectDocumentsReadModel(reactorModule, { deploymentSecret: config.deploymentSecret });
968
+ await deps.graphqlManager.registerSubgraphInstance({
969
+ ...subgraph,
970
+ path: deps.graphqlManager.getBasePath(),
971
+ reactorClient: deps.reactorClient,
972
+ relationalDb: void 0
973
+ }, "graphql", false);
974
+ scheduler.start();
975
+ deps.logger.info("Privacy add-on started: subject index, erasure scheduler");
976
+ return {
977
+ erasure: service,
978
+ scheduler,
979
+ stop: () => scheduler.stop()
980
+ };
981
+ }
982
+ //#endregion
983
+ //#region src/builder-defaults.mts
984
+ /**
985
+ * Apply switchboard's standard configuration to a reactor + client builder
986
+ * pair. Each piece is opt-out via the options object; defaults mirror what
987
+ * `startSwitchboard` does when building a reactor itself. Mutates both
988
+ * builders in place.
989
+ *
990
+ * Does NOT touch kysely or read models — callers wire those themselves
991
+ * (see `withKysely` / `withReadModelFactory` on the reactor builder).
992
+ */
993
+ /** The models switchboard always registers alongside package models. */
994
+ function switchboardBaseDocumentModels() {
995
+ return [
996
+ documentModelDocumentModelModule,
997
+ driveDocumentModelModule,
998
+ reactorDriveDocumentModelModule,
999
+ ReactorGroupV1
1000
+ ];
1001
+ }
1002
+ function applySwitchboardReactorDefaults(reactorBuilder, clientBuilder, options = {}) {
1003
+ const baseModels = options.includeBaseModels !== false ? switchboardBaseDocumentModels() : [];
1004
+ const extra = options.documentModels ?? [];
1005
+ if (baseModels.length || extra.length) reactorBuilder.withDocumentModelSources(getUniqueDocumentModels(baseModels, extra));
1006
+ if (options.upgradeManifests?.length) reactorBuilder.withUpgradeManifests(options.upgradeManifests);
1007
+ const scheme = options.channelScheme === void 0 ? ChannelScheme.SWITCHBOARD : options.channelScheme;
1008
+ if (scheme !== false) reactorBuilder.withChannelScheme(scheme);
1009
+ if (options.signalHandlers !== false) reactorBuilder.withSignalHandlers();
1010
+ if (options.executorConfig?.maxSkipThreshold !== void 0 || options.executorConfig?.featureFlags !== void 0) reactorBuilder.withExecutorConfig({
1011
+ ...options.executorConfig.maxSkipThreshold !== void 0 ? { maxSkipThreshold: options.executorConfig.maxSkipThreshold } : {},
1012
+ ...options.executorConfig.featureFlags !== void 0 ? { featureFlags: options.executorConfig.featureFlags } : {}
1013
+ });
1014
+ if (options.documentModelLoader) reactorBuilder.withDocumentModelLoader(options.documentModelLoader);
1015
+ if (options.logger) reactorBuilder.withLogger(options.logger);
1016
+ if (options.signer) {
1017
+ clientBuilder.withSigner(options.signer);
1018
+ reactorBuilder.withSigner(options.signer.signer, options.signer.workerSigner);
1019
+ }
1020
+ if (options.createSignaturePolicy) clientBuilder.withCreateSignaturePolicy(options.createSignaturePolicy);
1021
+ const trust = options.trustPolicy ?? options.signer;
1022
+ if (trust?.trustPolicy) reactorBuilder.withTrustPolicy(trust.trustPolicy, trust.workerTrustPolicy);
1023
+ }
1024
+ //#endregion
1025
+ //#region src/worker-pool.mts
1026
+ const DEFAULT_DB_POOL_SIZE_PER_WORKER = 2;
1027
+ const DEFAULT_ACQUIRE_TIMEOUT_MS = 5e3;
1028
+ const DEFAULT_DB_POOL_SIZE_HOST = 16;
1029
+ const AUTO_RESERVED_CORES = 2;
1030
+ const AUTO_WORKER_CAP = 8;
1031
+ /** Worker count for "auto": always at least 1 — auto sizes the pool, it does not turn worker mode off. */
1032
+ function autoWorkerCount(availableCores) {
1033
+ return Math.max(1, Math.min(AUTO_WORKER_CAP, availableCores - AUTO_RESERVED_CORES));
1034
+ }
1035
+ /**
1036
+ * Effective worker-pool config from programmatic options (which win) and the
1037
+ * REACTOR_* env vars; null when disabled (numWorkers 0, the default).
1038
+ * `"auto"` sizes the pool from the machine's available cores.
1039
+ */
1040
+ function resolveWorkerPoolOptions(input, env, availableCores = os.availableParallelism()) {
1041
+ const requested = input?.numWorkers ?? parseWorkerCount(env.REACTOR_WORKERS) ?? 0;
1042
+ const mode = requested === "auto" ? "auto" : "explicit";
1043
+ const numWorkers = requested === "auto" ? autoWorkerCount(availableCores) : requested;
1044
+ if (!Number.isInteger(numWorkers) || numWorkers < 0) throw new Error(`workerPool.numWorkers must be "auto" or a non-negative integer, got ${numWorkers}`);
1045
+ if (numWorkers === 0) return null;
1046
+ return {
1047
+ numWorkers,
1048
+ mode,
1049
+ dbPoolSizePerWorker: input?.dbPoolSizePerWorker ?? parseNonNegativeInt(env.REACTOR_DB_POOL_SIZE_WORKER, "REACTOR_DB_POOL_SIZE_WORKER") ?? DEFAULT_DB_POOL_SIZE_PER_WORKER,
1050
+ acquireTimeoutMs: input?.acquireTimeoutMs ?? parseNonNegativeInt(env.REACTOR_DB_ACQUIRE_TIMEOUT_MS, "REACTOR_DB_ACQUIRE_TIMEOUT_MS") ?? DEFAULT_ACQUIRE_TIMEOUT_MS
1051
+ };
1052
+ }
1053
+ /**
1054
+ * Size of the reactor's own (host) Postgres pool. Unlike the worker pool there
1055
+ * is no "disabled" state — the host pool is the only Postgres pool in the
1056
+ * server path, backing both reactor storage and the read models that reach it
1057
+ * via `withSchema` — so 0 is rejected rather than read as "off".
1058
+ *
1059
+ * The acquire timeout is deliberately not configurable here: the host pool
1060
+ * waits indefinitely today, and making it finite converts saturation from a
1061
+ * latency problem into a thrown error on the read-model path. That is a
1062
+ * behavior change worth making separately, once the retry semantics of a
1063
+ * rejected `pool.connect()` inside the read-model coordinator are settled.
1064
+ */
1065
+ function resolveHostPoolSize(env) {
1066
+ const poolSize = parseNonNegativeInt(env.REACTOR_DB_POOL_SIZE_HOST, "REACTOR_DB_POOL_SIZE_HOST") ?? DEFAULT_DB_POOL_SIZE_HOST;
1067
+ if (poolSize < 1) throw new Error("REACTOR_DB_POOL_SIZE_HOST must be at least 1; the host pool cannot be disabled");
1068
+ return poolSize;
1069
+ }
1070
+ /**
1071
+ * DbConfig for each worker's own pool, parsed from a postgres:// URL.
1072
+ * Explicit host, database, and user are required — no pg-side defaults.
1073
+ */
1074
+ function buildWorkerDbConfig(postgresUrl, options) {
1075
+ let parsed;
1076
+ try {
1077
+ parsed = new URL(postgresUrl);
1078
+ } catch {
1079
+ throw new Error(`Worker pool requires a valid postgres:// URL for the reactor database, got "${postgresUrl}"`);
1080
+ }
1081
+ const database = decodeURIComponent(parsed.pathname.replace(/^\//, ""));
1082
+ if (!parsed.hostname || !database) throw new Error(`Worker pool requires a postgres URL with a host and database name, got "${postgresUrl}"`);
1083
+ if (!parsed.username) throw new Error(`Worker pool requires explicit credentials in the postgres URL (workers open their own connections), got "${postgresUrl}"`);
1084
+ const sslmode = parsed.searchParams.get("sslmode");
1085
+ const ssl = parsed.searchParams.get("ssl") === "true" || sslmode !== null && sslmode !== "disable";
1086
+ return {
1087
+ host: parsed.hostname,
1088
+ port: parsed.port ? Number(parsed.port) : 5432,
1089
+ database,
1090
+ user: decodeURIComponent(parsed.username),
1091
+ password: decodeURIComponent(parsed.password),
1092
+ ssl,
1093
+ applicationName: "switchboard-worker",
1094
+ poolSize: options.dbPoolSizePerWorker,
1095
+ connectionTimeoutMillis: options.acquireTimeoutMs
1096
+ };
1097
+ }
1098
+ /** Specifiers of the base models switchboard always registers. */
1099
+ const BASE_MODEL_SPECIFIERS = [
1100
+ "document-model",
1101
+ "@powerhousedao/shared/document-drive",
1102
+ "@powerhousedao/reactor-drive",
1103
+ "@powerhousedao/reactor-group/document-models"
1104
+ ];
1105
+ function isModelModule(value) {
1106
+ const candidate = value;
1107
+ return typeof candidate?.reducer === "function" && typeof candidate.documentModel?.global?.id === "string";
1108
+ }
1109
+ async function keepImportableSources(sources, logger) {
1110
+ const kept = [];
1111
+ for (const source of sources) try {
1112
+ const exports = await import(pathToFileURL(source.filePath).href);
1113
+ if (Object.values(exports).some(isModelModule)) kept.push(source);
1114
+ } catch (error) {
1115
+ logger.warn(`Worker model sources: "${source.filePath}" does not import, so workflow pieces will not see its models: ${String(error)}`);
1116
+ }
1117
+ return kept;
1118
+ }
1119
+ /**
1120
+ * Resolves base models and configured package identifiers to `{ filePath }`
1121
+ * sources for the reactor builder. Resolution to absolute paths happens here
1122
+ * because workers (and the builder) resolve bare specifiers from the reactor
1123
+ * package's own dependency context, which cannot see switchboard or project
1124
+ * packages. Unresolvable identifiers are skipped with a warning; the builder
1125
+ * fails the boot if a registered model ends up without an importable source.
1126
+ */
1127
+ async function resolveWorkerModelSources(packages, logger, options = {}) {
1128
+ const sources = [];
1129
+ for (const identifier of [...BASE_MODEL_SPECIFIERS, ...packages]) {
1130
+ const filePath = await resolveModelModuleFile(identifier) ?? await resolveRemoteSafely(identifier, options.resolveRemote, logger);
1131
+ if (!filePath) {
1132
+ logger.warn(`Worker model sources: no importable document-models entry for "${identifier}", skipping`);
1133
+ continue;
1134
+ }
1135
+ sources.push({ filePath });
1136
+ }
1137
+ return sources;
1138
+ }
1139
+ async function resolveRemoteSafely(identifier, resolveRemote, logger) {
1140
+ if (!resolveRemote) return null;
1141
+ try {
1142
+ return await resolveRemote(identifier);
1143
+ } catch (error) {
1144
+ logger.warn(`Worker model sources: could not cache "${identifier}" from the registry: ${String(error)}`);
1145
+ return null;
1146
+ }
1147
+ }
1148
+ /**
1149
+ * Absolute file path of a source's models barrel. Mirrors reactor-api's
1150
+ * import-resolver: import.meta.resolve, then the project's node_modules via
1151
+ * the package.json exports map / dist layout.
1152
+ */
1153
+ async function resolveModelModuleFile(source) {
1154
+ if (isFsPath(source)) return resolveFromPackageDir(source, "./document-models");
1155
+ const specifier = BASE_MODEL_SPECIFIERS.includes(source) ? source : `${source}/document-models`;
1156
+ try {
1157
+ const resolved = import.meta.resolve(specifier);
1158
+ if (resolved.startsWith("file:")) return fileURLToPath(resolved);
1159
+ } catch {}
1160
+ const { packageName, subpath } = splitSpecifier(specifier);
1161
+ const packageDir = path.join(process.cwd(), "node_modules", packageName);
1162
+ if (!existsSync(packageDir)) return null;
1163
+ let realDir;
1164
+ try {
1165
+ realDir = realpathSync(packageDir);
1166
+ } catch {
1167
+ return null;
1168
+ }
1169
+ return resolveFromPackageDir(realDir, subpath);
1170
+ }
1171
+ function splitSpecifier(specifier) {
1172
+ const parts = specifier.split("/");
1173
+ const packageSegments = specifier.startsWith("@") ? 2 : 1;
1174
+ const packageName = parts.slice(0, packageSegments).join("/");
1175
+ const rest = parts.slice(packageSegments).join("/");
1176
+ return {
1177
+ packageName,
1178
+ subpath: rest ? `./${rest}` : "."
1179
+ };
1180
+ }
1181
+ /** Exports-map lookup (import condition), then conventional dist paths. */
1182
+ async function resolveFromPackageDir(packageDir, subpath) {
1183
+ const fromManifest = await resolveViaManifest(packageDir, subpath);
1184
+ if (fromManifest) return fromManifest;
1185
+ const candidates = subpath === "." ? [path.join(packageDir, "dist", "index.js")] : [
1186
+ path.join(packageDir, "dist", subpath.slice(2), "index.js"),
1187
+ path.join(packageDir, "dist", `${subpath.slice(2)}.js`),
1188
+ path.join(packageDir, subpath.slice(2), "index.js")
1189
+ ];
1190
+ for (const candidate of candidates) if (existsSync(candidate)) return candidate;
1191
+ return null;
1192
+ }
1193
+ async function resolveViaManifest(packageDir, subpath) {
1194
+ let raw;
1195
+ try {
1196
+ raw = await readFile(path.join(packageDir, "package.json"), "utf8");
1197
+ } catch {
1198
+ return null;
1199
+ }
1200
+ let manifest;
1201
+ try {
1202
+ manifest = JSON.parse(raw);
1203
+ } catch {
1204
+ return null;
1205
+ }
1206
+ let entry;
1207
+ const exportsField = manifest.exports;
1208
+ if (exportsField !== null && typeof exportsField === "object" && !Array.isArray(exportsField)) {
1209
+ const map = exportsField;
1210
+ entry = Object.keys(map).some((key) => key.startsWith(".")) ? map[subpath] : subpath === "." ? map : void 0;
1211
+ } else if (typeof exportsField === "string" && subpath === ".") entry = exportsField;
1212
+ let target = pickImportTarget(entry);
1213
+ if (!target && subpath === "." && typeof manifest.main === "string") target = manifest.main;
1214
+ if (!target) return null;
1215
+ const resolved = path.join(packageDir, target);
1216
+ return existsSync(resolved) ? resolved : null;
1217
+ }
1218
+ function pickImportTarget(entry) {
1219
+ if (typeof entry === "string") return entry;
1220
+ if (typeof entry !== "object" || entry === null) return null;
1221
+ const conditions = entry;
1222
+ for (const condition of [
1223
+ "import",
1224
+ "node",
1225
+ "default"
1226
+ ]) {
1227
+ const value = conditions[condition];
1228
+ if (typeof value === "string") return value;
1229
+ }
1230
+ return null;
1231
+ }
1232
+ function isFsPath(identifier) {
1233
+ return path.isAbsolute(identifier) || identifier.startsWith("./") || identifier.startsWith("../");
1234
+ }
1235
+ function parseWorkerCount(raw) {
1236
+ if (raw === void 0 || raw.trim() === "") return;
1237
+ if (raw.trim().toLowerCase() === "auto") return "auto";
1238
+ const value = Number.parseInt(raw, 10);
1239
+ if (!Number.isInteger(value) || value < 0 || String(value) !== raw.trim()) throw new Error(`REACTOR_WORKERS must be "auto" or a non-negative integer, got "${raw}"`);
1240
+ return value;
1241
+ }
1242
+ function parseNonNegativeInt(raw, name) {
1243
+ if (raw === void 0 || raw.trim() === "") return;
1244
+ const value = Number.parseInt(raw, 10);
1245
+ if (!Number.isInteger(value) || value < 0 || String(value) !== raw.trim()) throw new Error(`${name} must be a non-negative integer, got "${raw}"`);
1246
+ return value;
1247
+ }
1248
+ //#endregion
1249
+ //#region src/projection-worker.mts
1250
+ const DEFAULT_DB_POOL_SIZE_PROJECTION = 8;
1251
+ const ON_TOKENS = [
1252
+ "1",
1253
+ "true",
1254
+ "on",
1255
+ "yes"
1256
+ ];
1257
+ const OFF_TOKENS = [
1258
+ "0",
1259
+ "false",
1260
+ "off",
1261
+ "no"
1262
+ ];
1263
+ /**
1264
+ * Enabled by REACTOR_PROJECTION_WORKER (1/true/on/yes, case-insensitive) or
1265
+ * `input.enabled`, which wins when defined; null when off (the default).
1266
+ */
1267
+ function resolveProjectionWorkerOptions(input, env) {
1268
+ if (!(input?.enabled ?? parseOnOff(env.REACTOR_PROJECTION_WORKER) ?? false)) return null;
1269
+ const dbPoolSize = input?.dbPoolSize ?? parseNonNegativeInt(env.REACTOR_DB_POOL_SIZE_PROJECTION, "REACTOR_DB_POOL_SIZE_PROJECTION") ?? DEFAULT_DB_POOL_SIZE_PROJECTION;
1270
+ if (dbPoolSize < 1) throw new Error("REACTOR_DB_POOL_SIZE_PROJECTION must be at least 1; the projection worker cannot run without a pool");
1271
+ return { dbPoolSize };
1272
+ }
1273
+ /** Same preconditions as the executor worker pool; message shape mirrors server.mts. */
1274
+ function assertProjectionWorkerSupported(args) {
1275
+ if (args.dev) throw new Error("The projection worker (REACTOR_PROJECTION_WORKER) is not supported in dev mode: Vite-loaded document models cannot cross a worker-thread boundary");
1276
+ if (!args.reactorDbUrl || !isPostgresUrl(args.reactorDbUrl)) throw new Error("The projection worker (REACTOR_PROJECTION_WORKER) requires a Postgres reactor database — set PH_REACTOR_DATABASE_URL or PH_SWITCHBOARD_DATABASE_URL. PGlite cannot be shared across worker threads.");
1277
+ }
1278
+ function parseOnOff(raw) {
1279
+ if (raw === void 0 || raw.trim() === "") return;
1280
+ const token = raw.trim().toLowerCase();
1281
+ if (ON_TOKENS.includes(token)) return true;
1282
+ if (OFF_TOKENS.includes(token)) return false;
1283
+ throw new Error(`REACTOR_PROJECTION_WORKER must be one of 1, true, on, yes, 0, false, off, no, got "${raw}"`);
1284
+ }
1285
+ //#endregion
1286
+ //#region src/feature-flags.ts
1287
+ async function initFeatureFlags() {
1288
+ const provider = new EnvVarProvider();
1289
+ await OpenFeature.setProviderAndWait(provider);
1290
+ return OpenFeature.getClient();
1291
+ }
1292
+ //#endregion
1293
+ //#region src/mcp-flag.mts
1294
+ /** The env var and OpenFeature flag key that can keep the MCP server unmounted. */
1295
+ const MCP_ENABLED = "MCP_ENABLED";
1296
+ /** Whether to mount the MCP server at `/mcp`. On unless the host passes
1297
+ * `mcp: false` or MCP_ENABLED is "false": the env var can turn a host's MCP
1298
+ * off, never on, so a deployment that serves no MCP client can close the
1299
+ * endpoint without the bin growing a flag of its own. */
1300
+ async function resolveMcpEnabled({ featureFlags, option }) {
1301
+ if (option === false) return false;
1302
+ return featureFlags.getBooleanValue(MCP_ENABLED, true);
1303
+ }
1304
+ //#endregion
1305
+ //#region src/workflow/oauth-callback.ts
1306
+ const OAUTH_CALLBACK_PATH = "oauth/callback";
1307
+ function escapeHtml(text) {
1308
+ return text.replace(/[&<>"']/g, (char) => ({
1309
+ "&": "&amp;",
1310
+ "<": "&lt;",
1311
+ ">": "&gt;",
1312
+ "\"": "&quot;",
1313
+ "'": "&#39;"
1314
+ })[char]);
1315
+ }
1316
+ function resultPage(ok, detail) {
1317
+ const title = ok ? "Connected" : "Sign-in failed";
1318
+ return `<!doctype html>
1319
+ <html><head><meta charset="utf-8"><title>${title}</title>
1320
+ <meta name="viewport" content="width=device-width, initial-scale=1">
1321
+ <style>body{font:15px system-ui,sans-serif;margin:0;display:grid;place-items:center;min-height:100vh;background:#fafafa;color:#222}main{max-width:28rem;padding:1.5rem;text-align:center}h1{font-size:1.1rem}</style>
1322
+ </head><body><main><h1>${title}</h1><p>${ok ? "You can close this window." : escapeHtml(detail ?? "The sign-in did not finish.")}</p></main>
1323
+ ${ok ? "<script>setTimeout(function(){window.close()},600)<\/script>" : ""}
1324
+ </body></html>`;
1325
+ }
1326
+ function registerOAuthCallback(http, runtime) {
1327
+ return http.get(OAUTH_CALLBACK_PATH, { auth: "public" }, async (request) => {
1328
+ const params = new URL(request.url).searchParams;
1329
+ const state = params.get("state");
1330
+ const result = state ? await runtime.completeOAuth({
1331
+ state,
1332
+ code: params.get("code") ?? void 0,
1333
+ error: params.get("error") ?? void 0,
1334
+ errorDescription: params.get("error_description") ?? void 0
1335
+ }) : {
1336
+ ok: false,
1337
+ detail: "The provider sent no state",
1338
+ returnUrl: null
1339
+ };
1340
+ if (result.returnUrl && state) {
1341
+ const back = new URL(result.returnUrl);
1342
+ back.searchParams.set("ph_oauth", state);
1343
+ return new Response(null, {
1344
+ status: 303,
1345
+ headers: {
1346
+ location: back.href,
1347
+ "cache-control": "no-store"
1348
+ }
1349
+ });
1350
+ }
1351
+ return new Response(resultPage(result.ok, result.detail), {
1352
+ status: result.ok ? 200 : 400,
1353
+ headers: {
1354
+ "content-type": "text/html; charset=utf-8",
1355
+ "cache-control": "no-store",
1356
+ "referrer-policy": "no-referrer"
1357
+ }
1358
+ });
1359
+ });
1360
+ }
1361
+ function callbackUrlOf(http) {
1362
+ return `${http.baseUrl.replace(/\/+$/, "")}/${OAUTH_CALLBACK_PATH}`;
1363
+ }
1364
+ //#endregion
1365
+ //#region src/workflow/resolvers.ts
1366
+ const PIECE_SOURCES = [
1367
+ "local",
1368
+ "registry",
1369
+ "activepieces"
1370
+ ];
1371
+ function isPieceSource(value) {
1372
+ return PIECE_SOURCES.includes(value);
1373
+ }
1374
+ function blockRef(input) {
1375
+ if (input.kind !== "action" && input.kind !== "trigger") throw new GraphQLError(`A block's kind is "action" or "trigger", got "${input.kind}"`);
1376
+ return {
1377
+ pieceName: input.pieceName,
1378
+ pieceVersion: input.pieceVersion,
1379
+ name: input.name,
1380
+ kind: input.kind
1381
+ };
1382
+ }
1383
+ async function cursorAware(call) {
1384
+ try {
1385
+ return await call();
1386
+ } catch (error) {
1387
+ if (error instanceof Error && error.name === "InvalidRunCursorError") throw new GraphQLError(error.message, { extensions: { code: "BAD_USER_INPUT" } });
1388
+ throw error;
1389
+ }
1390
+ }
1391
+ function selectsStepData(selections, path) {
1392
+ let level = selections;
1393
+ for (const name of [...path, "steps"]) {
1394
+ const next = [];
1395
+ for (const set of level) for (const selection of set.selections) {
1396
+ if (selection.kind !== Kind.FIELD) return true;
1397
+ if (selection.name.value === name && selection.selectionSet) next.push(selection.selectionSet);
1398
+ }
1399
+ if (next.length === 0) return false;
1400
+ level = next;
1401
+ }
1402
+ return level.some((set) => set.selections.some((selection) => selection.kind !== Kind.FIELD || selection.name.value === "input" || selection.name.value === "output"));
1403
+ }
1404
+ function readsStepData(info, path) {
1405
+ if (!info) return true;
1406
+ return selectsStepData(info.fieldNodes.flatMap((node) => node.selectionSet ? [node.selectionSet] : []), path);
1407
+ }
1408
+ function requireAdmin(authorizationService, ctx) {
1409
+ if (!authorizationService.isSupremeAdmin(ctx.user?.address)) throw new GraphQLError("Admin access required");
1410
+ }
1411
+ async function syncAware(call) {
1412
+ try {
1413
+ return await call();
1414
+ } catch (error) {
1415
+ if (error instanceof Error && error.name === "WorkflowSyncingError") throw new GraphQLError(error.message, { extensions: {
1416
+ code: "WORKFLOW_SYNCING",
1417
+ retryable: true
1418
+ } });
1419
+ throw error;
1420
+ }
1421
+ }
1422
+ function parseJson(value) {
1423
+ if (value === null) return null;
1424
+ try {
1425
+ return JSON.parse(value);
1426
+ } catch {
1427
+ return value;
1428
+ }
1429
+ }
1430
+ function toStepRecord(row) {
1431
+ return {
1432
+ stepId: row.step_id,
1433
+ stepKey: row.step_key,
1434
+ pieceName: row.piece_name,
1435
+ blockName: row.block_name,
1436
+ status: row.status,
1437
+ input: parseJson(row.input),
1438
+ output: parseJson(row.output),
1439
+ port: row.port,
1440
+ error: row.error,
1441
+ errorName: row.error_name,
1442
+ startedAt: row.started_at,
1443
+ endedAt: row.ended_at,
1444
+ pieceVersion: row.piece_version,
1445
+ pieceSource: row.piece_source,
1446
+ versionMatch: row.version_match,
1447
+ versionNote: row.version_note
1448
+ };
1449
+ }
1450
+ function toRunRecord(row, steps) {
1451
+ return {
1452
+ id: row.id,
1453
+ workflowId: row.workflow_id,
1454
+ workflowName: row.workflow_name,
1455
+ workflowVersion: row.workflow_version,
1456
+ triggerKind: row.trigger_kind,
1457
+ triggerPayload: parseJson(row.trigger_payload),
1458
+ status: row.status,
1459
+ error: row.error,
1460
+ errorName: row.error_name,
1461
+ startedAt: row.started_at,
1462
+ endedAt: row.ended_at,
1463
+ rerunOf: row.rerun_of,
1464
+ warnings: row.warnings,
1465
+ warningNotes: parseJson(row.warning_notes) ?? [],
1466
+ steps: steps.map(toStepRecord)
1467
+ };
1468
+ }
1469
+ const UNKNOWN_ACCESS = {
1470
+ authEnforcement: true,
1471
+ authConditions: false,
1472
+ identity: null
1473
+ };
1474
+ function signedIn(ctx) {
1475
+ return Boolean(ctx.user?.address);
1476
+ }
1477
+ function isAbsolute(url) {
1478
+ return /^https?:\/\//i.test(url);
1479
+ }
1480
+ function redirectUriFor(routing, requested) {
1481
+ if (!routing) throw new GraphQLError("This host serves no OAuth2 callback");
1482
+ if (isAbsolute(routing.callbackUrl)) return routing.callbackUrl;
1483
+ if (!requested) throw new GraphQLError("This host does not know its public URL; pass redirectUri");
1484
+ let url;
1485
+ try {
1486
+ url = new URL(requested);
1487
+ } catch {
1488
+ throw new GraphQLError(`"${requested}" is not a URL`);
1489
+ }
1490
+ if (url.protocol !== "https:" && url.protocol !== "http:" || url.pathname !== routing.callbackUrl || url.search !== "" || url.hash !== "") throw new GraphQLError(`redirectUri must be this host's ${routing.callbackUrl}`);
1491
+ return url.href;
1492
+ }
1493
+ function returnUrlFor(requested, ctx) {
1494
+ if (!requested) return void 0;
1495
+ const origin = ctx.headers.origin;
1496
+ let url;
1497
+ try {
1498
+ url = new URL(requested);
1499
+ } catch {
1500
+ url = void 0;
1501
+ }
1502
+ if (!url || !origin || url.origin !== origin) throw new GraphQLError("returnUrl must be on the requesting page's origin");
1503
+ return url.href;
1504
+ }
1505
+ const getResolvers = (runtime, authorizationService, oauth, access = UNKNOWN_ACCESS, assertCanRead) => {
1506
+ return {
1507
+ Query: { workflowRuntime: () => ({}) },
1508
+ WorkflowRuntimeQueries: {
1509
+ health: () => "ok",
1510
+ authEnforcement: () => access.authEnforcement,
1511
+ reactorIdentity: (_parent, _args, ctx) => signedIn(ctx) ? access.identity : null,
1512
+ authConditions: (_parent, _args, ctx) => signedIn(ctx) ? access.authConditions : null,
1513
+ reactorAccessDenial: async (_parent, args, ctx) => {
1514
+ if (!assertCanRead) throw new GraphQLError("No read check configured");
1515
+ await assertCanRead(args.workflowId, ctx);
1516
+ return runtime.reactorAccessDenial(args.workflowId) ?? null;
1517
+ },
1518
+ blockDescriptor: (_parent, args) => runtime.blockDescriptor(blockRef(args.block)),
1519
+ blockOptions: (_parent, args, ctx) => runtime.blockOptions(blockRef(args.block), args.propName, args.input, args.connectionId ?? void 0, ctx, args.searchValue ?? void 0, args.reactorConnectionId ?? void 0),
1520
+ pieceCatalog: () => runtime.pieceCatalog(),
1521
+ pieceActions: (_parent, args) => runtime.pieceActions(args.packageName, args.version ?? void 0),
1522
+ pieceTriggers: (_parent, args) => runtime.pieceTriggers(args.packageName, args.version ?? void 0),
1523
+ blockOutputTree: (_parent, args) => runtime.blockOutputTree(blockRef(args.block), args.config),
1524
+ stepOutputTree: (_parent, args, ctx) => runtime.stepOutputTree(args.workflowId, args.stepId, ctx),
1525
+ blockResolutions: (_parent, args, ctx) => runtime.blockResolutions(args.workflowId, ctx),
1526
+ pieceDetail: (_parent, args) => runtime.pieceDetail(args.packageName, args.version ?? void 0),
1527
+ searchPieces: (_parent, args) => {
1528
+ if (args.kind !== "action" && args.kind !== "trigger") throw new GraphQLError(`A search's kind is "action" or "trigger", got "${args.kind}"`);
1529
+ const unknown = (args.sources ?? []).filter((source) => !isPieceSource(source));
1530
+ if (unknown.length > 0) throw new GraphQLError(`A search's sources are ${PIECE_SOURCES.join(", ")}, got ${unknown.join(", ")}`);
1531
+ return runtime.searchPieces(args.query, {
1532
+ kind: args.kind,
1533
+ sources: (args.sources ?? []).filter(isPieceSource),
1534
+ categories: args.categories ?? void 0,
1535
+ limit: args.limit ?? void 0
1536
+ });
1537
+ },
1538
+ connections: (_parent, _args, ctx) => runtime.connections(ctx),
1539
+ webhookEndpoint: (_parent, args, ctx) => syncAware(() => runtime.webhookEndpoint(args.workflowId, ctx, { driveId: args.driveId ?? void 0 })),
1540
+ secret: async (_parent, args) => {
1541
+ try {
1542
+ return await (await runtime.secrets()).stat(args.ref);
1543
+ } catch {
1544
+ return null;
1545
+ }
1546
+ },
1547
+ secrets: async () => (await runtime.secrets()).list(),
1548
+ oauthRedirectUri: () => oauth?.callbackUrl ?? null,
1549
+ oauthAttempt: (_parent, args, ctx) => runtime.oauthAttempt(args.state, ctx),
1550
+ triggerStates: async (_parent, _args, ctx) => (await runtime.triggerStates(ctx)).map((row) => ({
1551
+ workflowId: row.workflow_id,
1552
+ pieceName: row.piece_name,
1553
+ triggerName: row.trigger_name,
1554
+ status: row.status,
1555
+ intervalMs: row.interval_ms,
1556
+ nextPollAt: row.next_poll_at,
1557
+ lastPollAt: row.last_poll_at,
1558
+ lastError: row.last_error,
1559
+ consecutiveFailures: row.consecutive_failures,
1560
+ nextRenewAt: row.next_renew_at,
1561
+ renewError: row.renew_error,
1562
+ renewFailures: row.renew_failures,
1563
+ pieceVersion: row.piece_version,
1564
+ pieceSource: row.piece_source,
1565
+ versionMatch: row.version_match,
1566
+ versionNote: row.version_note
1567
+ })),
1568
+ runs: async (_parent, args, ctx, info) => (await runtime.runs({
1569
+ ...args,
1570
+ withStepData: readsStepData(info, [])
1571
+ }, ctx)).map((record) => toRunRecord(record.row, record.steps)),
1572
+ runsPage: async (_parent, args, ctx, info) => {
1573
+ const { paging, ...scope } = args;
1574
+ const page = await cursorAware(() => runtime.runsPage({
1575
+ ...scope,
1576
+ limit: paging?.limit ?? void 0,
1577
+ cursor: paging?.cursor ?? null,
1578
+ withStepData: readsStepData(info, ["items"])
1579
+ }, ctx));
1580
+ return {
1581
+ items: page.records.map((record) => toRunRecord(record.row, record.steps)),
1582
+ hasNextPage: page.hasNextPage,
1583
+ hasPreviousPage: Boolean(paging?.cursor),
1584
+ cursor: page.cursor
1585
+ };
1586
+ },
1587
+ run: async (_parent, args, ctx) => {
1588
+ const record = await runtime.run(args.id, ctx);
1589
+ return record ? toRunRecord(record.row, record.steps) : null;
1590
+ }
1591
+ },
1592
+ Mutation: { workflowRuntime: () => ({}) },
1593
+ WorkflowRuntimeMutations: {
1594
+ fire: (_parent, args, ctx) => runtime.fire(args.workflowId, args.payload, "manual", void 0, ctx),
1595
+ testTrigger: (_parent, args, ctx) => syncAware(() => runtime.testTrigger(args.workflowId, ctx, {
1596
+ ...args.payload !== void 0 ? { payload: args.payload } : {},
1597
+ ...typeof args.timeoutSeconds === "number" ? { timeoutMs: args.timeoutSeconds * 1e3 } : {},
1598
+ driveId: args.driveId ?? void 0
1599
+ })),
1600
+ cancelTriggerTest: (_parent, args, ctx) => runtime.cancelTriggerTestFor(args.workflowId, ctx),
1601
+ testStep: (_parent, args, ctx) => syncAware(() => runtime.testStep(args.workflowId, args.stepId, ctx, { driveId: args.driveId ?? void 0 })),
1602
+ rerun: (_parent, args, ctx) => runtime.rerun(args.runId, ctx),
1603
+ createSecret: async (_parent, args, ctx) => {
1604
+ requireAdmin(authorizationService, ctx);
1605
+ return (await runtime.secrets()).create({
1606
+ value: args.value,
1607
+ label: args.label ?? void 0
1608
+ });
1609
+ },
1610
+ rotateSecret: async (_parent, args, ctx) => {
1611
+ requireAdmin(authorizationService, ctx);
1612
+ return (await runtime.secrets()).rotate(args.ref, args.value);
1613
+ },
1614
+ deleteSecret: async (_parent, args, ctx) => {
1615
+ requireAdmin(authorizationService, ctx);
1616
+ await (await runtime.secrets()).delete(args.ref);
1617
+ return true;
1618
+ },
1619
+ checkConnection: (_parent, args, ctx) => runtime.checkConnection(args.connectionId, ctx),
1620
+ startOAuth: (_parent, args, ctx) => {
1621
+ requireAdmin(authorizationService, ctx);
1622
+ const returnUrl = returnUrlFor(args.returnUrl, ctx);
1623
+ return runtime.startOAuth(args.connectionId, ctx, {
1624
+ redirectUri: redirectUriFor(oauth, args.redirectUri),
1625
+ ...returnUrl ? { returnUrl } : {}
1626
+ });
1627
+ }
1628
+ }
1629
+ };
1630
+ };
1631
+ //#endregion
1632
+ //#region src/workflow/schema.ts
1633
+ const schema = gql`
1634
+ """
1635
+ WorkflowRuntime Queries
1636
+ """
1637
+ type WorkflowRuntimeQueries {
1638
+ health: String!
1639
+ """
1640
+ Whether this reactor enforces document auth (REACTOR_AUTH_ENFORCEMENT).
1641
+ On, a workflow needs a signed publish, and the host grants, to reach
1642
+ documents. Answered to any caller.
1643
+ """
1644
+ authEnforcement: Boolean!
1645
+ """
1646
+ Who this host signs as: grant it on each document a step writes. Null for
1647
+ a caller who is not signed in, or a host with no signer.
1648
+ """
1649
+ reactorIdentity: ReactorIdentity
1650
+ """
1651
+ REACTOR_AUTH_CONDITIONS. True: grant the host by key, with
1652
+ { match: subject.key == key }; false: by address. Null for a caller who
1653
+ is not signed in.
1654
+ """
1655
+ authConditions: Boolean
1656
+ """
1657
+ Why the workflow's last publish or enable got no reactor access, naming
1658
+ the publisher and the connection; null when the check passed.
1659
+ """
1660
+ reactorAccessDenial(workflowId: String!): String
1661
+ """
1662
+ Persisted runs, newest first. Scope them to one workflow, or to every
1663
+ workflow a drive holds; workflowId wins when both are given.
1664
+ """
1665
+ runs(
1666
+ workflowId: String
1667
+ driveId: String
1668
+ limit: Int
1669
+ "Trigger kinds to leave out, e.g. test."
1670
+ excludeTriggerKinds: [String!]
1671
+ ): [WorkflowRunRecord!]!
1672
+ """
1673
+ The same listing a page at a time, newest journaled first. Pass a page's
1674
+ cursor back in paging to read the next; a page is short only when
1675
+ hasNextPage is false, or when the caller could read none of a long
1676
+ stretch of runs. A run that starts between pages keeps its place.
1677
+ """
1678
+ runsPage(
1679
+ workflowId: String
1680
+ driveId: String
1681
+ excludeTriggerKinds: [String!]
1682
+ paging: WorkflowRunsPagingInput
1683
+ ): WorkflowRunResultPage!
1684
+ run(id: String!): WorkflowRunRecord
1685
+ """
1686
+ The descriptor (props, auth, ports) of one action or trigger, as the
1687
+ version that runs it describes it; triggers come back under "trigger".
1688
+ """
1689
+ blockDescriptor(block: BlockInput!): Unknown
1690
+ """
1691
+ Resolves a dynamic prop against the current config values: a DROPDOWN
1692
+ yields { options, placeholder, disabled }, a DYNAMIC prop yields the
1693
+ resolved sub-property descriptor list.
1694
+ """
1695
+ blockOptions(
1696
+ block: BlockInput!
1697
+ propName: String!
1698
+ input: Unknown
1699
+ connectionId: String
1700
+ "What the author typed, for a DROPDOWN declared with refreshOnSearch."
1701
+ searchValue: String
1702
+ "The step's reactor connection; its filter narrows what the resolver reads."
1703
+ reactorConnectionId: String
1704
+ ): Unknown
1705
+ """
1706
+ Every piece this reactor offers: the core piece, its package pieces, and
1707
+ the pieces the registry and Activepieces publish.
1708
+ """
1709
+ pieceCatalog: Unknown
1710
+ """
1711
+ A piece's actions at one version; pin a step to that version.
1712
+ """
1713
+ pieceActions(
1714
+ packageName: String!
1715
+ "That version; the installed or latest one when omitted."
1716
+ version: String
1717
+ ): Unknown
1718
+ """
1719
+ A piece's triggers at one version; pin a trigger to that version.
1720
+ """
1721
+ pieceTriggers(
1722
+ packageName: String!
1723
+ "That version; the installed or latest one when omitted."
1724
+ version: String
1725
+ ): Unknown
1726
+ """
1727
+ Full piece detail (PieceMetadataModel-shaped), verbatim from the cloud API.
1728
+ """
1729
+ pieceDetail(
1730
+ packageName: String!
1731
+ "That version; the installed or latest one when omitted."
1732
+ version: String
1733
+ ): Unknown
1734
+ """
1735
+ Piece and block search across the catalog, grouped by piece. The index
1736
+ builds lazily on first use; poll while status is "indexing".
1737
+ """
1738
+ searchPieces(
1739
+ query: String!
1740
+ "action | trigger"
1741
+ kind: String!
1742
+ "local | registry | activepieces; all when omitted."
1743
+ sources: [String!]
1744
+ "Category ids, any of; all when omitted."
1745
+ categories: [String!]
1746
+ "Pieces returned."
1747
+ limit: Int
1748
+ ): PieceSearchResult!
1749
+ """
1750
+ Health of every registered piece trigger (poll schedule, errors).
1751
+ """
1752
+ triggerStates: [TriggerStateRecord!]!
1753
+ """
1754
+ Authored output shape of a block (SDL / outputSchema / sampleData).
1755
+ """
1756
+ blockOutputTree(block: BlockInput!, config: Unknown): Unknown
1757
+ """
1758
+ Output shape of a draft step or trigger: its latest test output
1759
+ (source "test", with sample and testedAt) when tested, else as blockOutputTree.
1760
+ """
1761
+ stepOutputTree(workflowId: String!, stepId: String!): Unknown
1762
+ """
1763
+ Every block of the draft (trigger first) as this reactor resolves it:
1764
+ which piece version runs, from where, and how it matches the pin.
1765
+ """
1766
+ blockResolutions(workflowId: String!): [BlockResolutionRecord!]!
1767
+ """
1768
+ Every powerhouse/connection document, for connection pickers.
1769
+ """
1770
+ connections: [ConnectionRecord!]!
1771
+ """
1772
+ The webhook endpoint for a workflow: the URL to hand the provider. Minted
1773
+ on first ask, whether or not the workflow is armed — an author needs the
1774
+ URL before enabling, and the armed field carries that difference. Null
1775
+ only when the host has no webhook service. With driveId, a workflow not
1776
+ synced here yet is waited for briefly, then fails as WORKFLOW_SYNCING.
1777
+ """
1778
+ webhookEndpoint(workflowId: String!, driveId: String): WebhookEndpointRecord
1779
+ """
1780
+ Secret metadata (label, version, status). Never the value.
1781
+ """
1782
+ secret(ref: String!): SecretRecord
1783
+ secrets: [SecretRecord!]!
1784
+ """
1785
+ The URL an OAuth2 app must register as its redirect. A bare path when
1786
+ this host does not know its public origin; resolve it against the URL
1787
+ this API is reached at. Null when the host serves no HTTP routes.
1788
+ """
1789
+ oauthRedirectUri: String
1790
+ """
1791
+ How an OAuth2 sign-in opened by startOAuth stands; null when unknown.
1792
+ """
1793
+ oauthAttempt(state: String!): OAuthAttempt
1794
+ }
1795
+
1796
+ type OAuthAttempt {
1797
+ connectionId: String!
1798
+ "PENDING | EXCHANGING | OK | ERROR"
1799
+ status: String!
1800
+ error: String
1801
+ }
1802
+
1803
+ type OAuthStart {
1804
+ state: String!
1805
+ "Where to send the user to sign in."
1806
+ authorizationUrl: String!
1807
+ redirectUri: String!
1808
+ expiresAt: String!
1809
+ }
1810
+
1811
+ """
1812
+ One action or trigger of a piece, as a workflow pins it. The engine's own
1813
+ blocks are the piece @powerhousedao/piece-core.
1814
+ """
1815
+ input BlockInput {
1816
+ pieceName: String!
1817
+ "Exact semver."
1818
+ pieceVersion: String!
1819
+ "The action or trigger name."
1820
+ name: String!
1821
+ "action | trigger"
1822
+ kind: String!
1823
+ }
1824
+
1825
+ type BlockSearchHit {
1826
+ pieceName: String!
1827
+ "The version the hit is listed at; pin to it when picking the block."
1828
+ pieceVersion: String!
1829
+ "The action or trigger name."
1830
+ name: String!
1831
+ pieceDisplayName: String!
1832
+ logoUrl: String!
1833
+ displayName: String!
1834
+ description: String!
1835
+ "action | trigger"
1836
+ kind: String!
1837
+ "Triggers only: POLLING | WEBHOOK | APP_WEBHOOK | MANUAL"
1838
+ strategy: String
1839
+ "Why this block cannot run on this reactor; null when it can."
1840
+ unsupported: String
1841
+ }
1842
+
1843
+ type BlockResolutionRecord {
1844
+ "The trigger's or step's id."
1845
+ stepId: String!
1846
+ pieceName: String!
1847
+ "The version the block pins."
1848
+ pieceVersion: String!
1849
+ "The action or trigger name."
1850
+ name: String!
1851
+ "action | trigger"
1852
+ kind: String!
1853
+ "The version that runs; null when nothing resolves."
1854
+ resolvedVersion: String
1855
+ "local | registry | activepieces | npm; null when nothing resolves."
1856
+ source: String
1857
+ "exact | compatible | fallback | installed | missing"
1858
+ match: String!
1859
+ "Why the version that runs differs from the pin, or why nothing resolves."
1860
+ note: String
1861
+ "The newest version any source offers."
1862
+ latestVersion: String
1863
+ }
1864
+
1865
+ type PieceSearchMatch {
1866
+ pieceName: String!
1867
+ pieceVersion: String!
1868
+ displayName: String!
1869
+ description: String!
1870
+ logoUrl: String!
1871
+ categories: [String!]!
1872
+ "local | registry | activepieces"
1873
+ source: String!
1874
+ deprecated: Boolean
1875
+ "Why no block of the piece can run on this reactor."
1876
+ unsupported: String
1877
+ "Every query token matched the piece's own name."
1878
+ namedPiece: Boolean!
1879
+ "Matching blocks of the kind asked for, best first."
1880
+ blocks: [BlockSearchHit!]!
1881
+ }
1882
+
1883
+ type PieceSearchResult {
1884
+ "ready | indexing | error"
1885
+ status: String!
1886
+ pieces: [PieceSearchMatch!]!
1887
+ indexedPieces: Int!
1888
+ error: String
1889
+ }
1890
+
1891
+ type SecretRecord {
1892
+ ref: String!
1893
+ label: String
1894
+ version: Int!
1895
+ status: String!
1896
+ createdAt: String!
1897
+ updatedAt: String!
1898
+ }
1899
+
1900
+ type ConnectionRecord {
1901
+ id: String!
1902
+ name: String!
1903
+ connectorId: String!
1904
+ authType: String!
1905
+ status: String!
1906
+ accountLabel: String
1907
+ }
1908
+
1909
+ type ReactorIdentity {
1910
+ "The address the host signs as; null without a signed-in identity."
1911
+ address: String
1912
+ "The did:key that signs the host's operations."
1913
+ key: String!
1914
+ }
1915
+
1916
+ type ConnectionCheckResult {
1917
+ ok: Boolean!
1918
+ detail: String
1919
+ """
1920
+ From auth.getConnectionIdentifier when the check passes; otherwise the
1921
+ label the connection already holds.
1922
+ """
1923
+ accountLabel: String
1924
+ }
1925
+
1926
+ type WebhookEndpointRecord {
1927
+ workflowId: String!
1928
+ url: String!
1929
+ """
1930
+ False when the host gave the webhook service no public origin, so the url
1931
+ above is a bare path. Switchboard always gives one, falling back to
1932
+ http://localhost:<port> when PUBLIC_URL is unset.
1933
+ """
1934
+ absoluteUrl: Boolean!
1935
+ "True while the workflow is ENABLED with a valid webhook trigger"
1936
+ armed: Boolean!
1937
+ createdAt: String!
1938
+ }
1939
+
1940
+ type TriggerStateRecord {
1941
+ workflowId: String!
1942
+ pieceName: String!
1943
+ triggerName: String!
1944
+ status: String!
1945
+ intervalMs: Int!
1946
+ nextPollAt: String
1947
+ lastPollAt: String
1948
+ lastError: String
1949
+ consecutiveFailures: Int!
1950
+ "When a webhook trigger next renews its subscription; null if it never does."
1951
+ nextRenewAt: String
1952
+ "The last failed renewal, kept apart from lastError, the poll's."
1953
+ renewError: String
1954
+ renewFailures: Int!
1955
+ "The piece version the trigger armed with; null for a host-fed trigger."
1956
+ pieceVersion: String
1957
+ pieceSource: String
1958
+ versionMatch: String
1959
+ versionNote: String
1960
+ }
1961
+
1962
+ type Query {
1963
+ workflowRuntime: WorkflowRuntimeQueries!
1964
+ }
1965
+
1966
+ type WorkflowStepRunRecord {
1967
+ stepId: String!
1968
+ stepKey: String!
1969
+ pieceName: String!
1970
+ "The action the step ran, or the trigger a trigger test sampled."
1971
+ blockName: String!
1972
+ status: String!
1973
+ input: Unknown
1974
+ output: Unknown
1975
+ port: String
1976
+ error: String
1977
+ "The thrown error's name, e.g. ReactorAccessDeniedError."
1978
+ errorName: String
1979
+ startedAt: String
1980
+ endedAt: String
1981
+ "The piece version that ran; null for an unresolved block."
1982
+ pieceVersion: String
1983
+ "local | registry | activepieces | npm"
1984
+ pieceSource: String
1985
+ "exact | compatible | fallback | installed | missing"
1986
+ versionMatch: String
1987
+ "Why the version that ran differs from the pin."
1988
+ versionNote: String
1989
+ }
1990
+
1991
+ type WorkflowRunRecord {
1992
+ id: String!
1993
+ workflowId: String!
1994
+ workflowName: String!
1995
+ workflowVersion: Int!
1996
+ triggerKind: String!
1997
+ triggerPayload: Unknown
1998
+ status: String!
1999
+ error: String
2000
+ errorName: String
2001
+ "When the run began executing; a PENDING run's is when it was journaled."
2002
+ startedAt: String!
2003
+ endedAt: String
2004
+ rerunOf: String
2005
+ "How many warningNotes the run has; a run with any is not a plain success."
2006
+ warnings: Int!
2007
+ "Steps that ran a fallback piece version, edges on ports nothing emits."
2008
+ warningNotes: [String!]!
2009
+ steps: [WorkflowStepRunRecord!]!
2010
+ }
2011
+
2012
+ input WorkflowRunsPagingInput {
2013
+ "Page size; default 25, at most 100."
2014
+ limit: Int
2015
+ "The cursor of the previous page."
2016
+ cursor: String
2017
+ }
2018
+
2019
+ type WorkflowRunResultPage {
2020
+ items: [WorkflowRunRecord!]!
2021
+ hasNextPage: Boolean!
2022
+ "True when the page was read after a cursor."
2023
+ hasPreviousPage: Boolean!
2024
+ "Resumes after this page's last run; null for an empty page."
2025
+ cursor: String
2026
+ }
2027
+
2028
+ type WorkflowStepRun {
2029
+ stepId: String!
2030
+ key: String!
2031
+ pieceName: String!
2032
+ blockName: String!
2033
+ status: String!
2034
+ input: Unknown
2035
+ output: Unknown
2036
+ port: String
2037
+ error: String
2038
+ errorName: String
2039
+ }
2040
+
2041
+ type WorkflowRunPayload {
2042
+ runId: String
2043
+ status: String!
2044
+ error: String
2045
+ errorName: String
2046
+ steps: [WorkflowStepRun!]!
2047
+ }
2048
+
2049
+ type WorkflowStepTestResult {
2050
+ "Null when the test never started, e.g. an upstream block is untested."
2051
+ runId: String
2052
+ """
2053
+ SUCCEEDED | FAILED | INDETERMINATE. INDETERMINATE is neither: a host call
2054
+ the block made timed out, so a write it asked for may well have landed.
2055
+ Show it distinctly - it is not a confirmed pass.
2056
+ """
2057
+ status: String!
2058
+ output: Unknown
2059
+ error: String
2060
+ errorName: String
2061
+ durationMs: Int!
2062
+ }
2063
+
2064
+ """
2065
+ WorkflowRuntime Mutations
2066
+ """
2067
+ type WorkflowRuntimeMutations {
2068
+ """
2069
+ Fires a workflow's manual trigger (the core piece's) and runs it to completion.
2070
+ """
2071
+ fire(workflowId: String!, payload: Unknown): WorkflowRunPayload!
2072
+ """
2073
+ Samples the draft trigger and saves it as the trigger's last test. A piece
2074
+ trigger runs its test hook (no cursor changes). Of the core piece's
2075
+ triggers, manual takes payload, schedule samples a fire now, and webhook
2076
+ waits for the next delivery to the workflow's endpoint, up to
2077
+ timeoutSeconds (default and cap 300), and that delivery runs nothing.
2078
+ """
2079
+ testTrigger(
2080
+ workflowId: String!
2081
+ payload: Unknown
2082
+ timeoutSeconds: Int
2083
+ driveId: String
2084
+ ): Unknown
2085
+ """
2086
+ Stops a webhook trigger test that is waiting; false when none was.
2087
+ """
2088
+ cancelTriggerTest(workflowId: String!): Boolean!
2089
+ """
2090
+ Runs one draft step against the latest test outputs of the blocks it
2091
+ reads, journaled as a "test" run and noted as the step's lastTest.
2092
+ driveId waits for an unsynced workflow, as for webhookEndpoint.
2093
+ """
2094
+ testStep(
2095
+ workflowId: String!
2096
+ stepId: String!
2097
+ driveId: String
2098
+ ): WorkflowStepTestResult!
2099
+ """
2100
+ Resumes a FAILED run: succeeded steps replay from the journal,
2101
+ execution restarts at the failure. Produces a new run.
2102
+ """
2103
+ rerun(runId: String!): WorkflowRunPayload!
2104
+ """
2105
+ Mints a managed secret and returns its ref; the value is stored
2106
+ encrypted and is never readable back over any API.
2107
+ """
2108
+ createSecret(value: String!, label: String): SecretRecord!
2109
+ """
2110
+ Replaces the value behind an existing ref; documents stay untouched.
2111
+ """
2112
+ rotateSecret(ref: String!, value: String!): SecretRecord!
2113
+ """
2114
+ Tombstones a secret; its value becomes unrecoverable.
2115
+ """
2116
+ deleteSecret(ref: String!): Boolean!
2117
+ """
2118
+ Runs the piece's auth.validate against the connection's credentials,
2119
+ then auth.getConnectionIdentifier for the account label, and records the
2120
+ outcome on the connection document.
2121
+ """
2122
+ checkConnection(connectionId: String!): ConnectionCheckResult!
2123
+ """
2124
+ Opens an OAuth2 sign-in with the connection's own app (client_id in its
2125
+ config, client_secret in its secretRefs). redirectUri is needed only when
2126
+ oauthRedirectUri is a bare path. With returnUrl, which must be on the
2127
+ caller's origin, the callback sends the browser back there with
2128
+ ?ph_oauth=<state> instead of closing the window.
2129
+ """
2130
+ startOAuth(
2131
+ connectionId: String!
2132
+ redirectUri: String
2133
+ returnUrl: String
2134
+ ): OAuthStart!
2135
+ }
2136
+
2137
+ type Mutation {
2138
+ workflowRuntime: WorkflowRuntimeMutations!
2139
+ }
2140
+ `;
2141
+ //#endregion
2142
+ //#region src/workflow/subgraph.ts
2143
+ /** The runtime's read/write surface. The runtime itself is composed by the
2144
+ * host, so the subgraph only serves what it is handed. */
2145
+ function createWorkflowRuntimeSubgraph(runtime, oauth, access) {
2146
+ return class WorkflowRuntimeSubgraph extends BaseSubgraph {
2147
+ name = "workflow-runtime";
2148
+ typeDefs = schema;
2149
+ resolvers = getResolvers(runtime, this.authorizationService, oauth, access, (documentId, ctx) => this.assertCanRead(documentId, ctx));
2150
+ additionalContextFields = {};
2151
+ };
2152
+ }
2153
+ //#endregion
2154
+ //#region src/workflow-runtime.mts
2155
+ /** The npm name the workflow package owns: its HTTP namespace and its models. */
2156
+ const WORKFLOW_PACKAGE_NAME = "@powerhousedao/workflow";
2157
+ const WORKFLOW_TELEMETRY_SCOPE = "@powerhousedao/reactor-workflow";
2158
+ /** The env var and OpenFeature flag key that turns workflows on. */
2159
+ const PH_WORKFLOWS_ENABLED = "PH_WORKFLOWS_ENABLED";
2160
+ const SINGLETON_LOST = {
2161
+ status: "unavailable",
2162
+ reason: "workflow-singleton-lost"
2163
+ };
2164
+ /** Precedence, unchanged from the reactor-api resolver this replaces: the
2165
+ * host's option, then PH_WORKFLOWS_ENABLED, then the config file, then off. */
2166
+ async function resolveWorkflowsEnabled({ featureFlags, override, configEnabled = false, env = process.env }) {
2167
+ if (override !== void 0) return override;
2168
+ const raw = env[PH_WORKFLOWS_ENABLED]?.trim();
2169
+ if (raw === "1") return true;
2170
+ if (raw === "0") return false;
2171
+ return featureFlags.getBooleanValue(PH_WORKFLOWS_ENABLED, configEnabled);
2172
+ }
2173
+ async function assertWorkflowPackageLoadable(load = () => import("@powerhousedao/workflow/document-models")) {
2174
+ try {
2175
+ await load();
2176
+ } catch (error) {
2177
+ throw new Error(`Workflows are enabled but ${WORKFLOW_PACKAGE_NAME} could not be loaded`, { cause: error });
2178
+ }
2179
+ }
2180
+ /**
2181
+ * Whether a composition failure was the workflow singleton refusing this
2182
+ * process, rather than something that should take the boot down.
2183
+ *
2184
+ * Matched by NAME: the engine loads lazily, and importing it here for the
2185
+ * constructor would defeat that. The fields the engine's error carries are
2186
+ * typed optional for the same reason.
2187
+ */
2188
+ function isWorkflowSingletonConflict(error) {
2189
+ return error instanceof Error && error.name === "WorkflowSingletonConflictError";
2190
+ }
2191
+ /**
2192
+ * Retries the singleton claim for a host that booted without it, and hands
2193
+ * the runtime over once a claim succeeds.
2194
+ *
2195
+ * Without it a rolling deploy whose slots have different owner names ends
2196
+ * with nobody running workflows: the new pod is refused while the old one
2197
+ * still holds the lease, and nothing retries once the old pod releases it.
2198
+ * Only for a host that never composed; one that lost the lease after
2199
+ * composing stays without workflows until it restarts.
2200
+ */
2201
+ function retryWorkflowSingleton(options) {
2202
+ const intervalMs = options.intervalMs ?? 2e4;
2203
+ let stopped = false;
2204
+ let timer;
2205
+ let attempt;
2206
+ const run = async () => {
2207
+ let workflows;
2208
+ try {
2209
+ workflows = await options.compose();
2210
+ } catch (error) {
2211
+ if (!isWorkflowSingletonConflict(error)) options.logger.error("Composing the workflow runtime after the singleton came free failed: @error", error);
2212
+ schedule();
2213
+ return;
2214
+ }
2215
+ if (stopped) {
2216
+ await workflows.stop();
2217
+ return;
2218
+ }
2219
+ options.logger.info("Claimed the workflow singleton after boot; starting the workflow runtime");
2220
+ await options.onComposed(workflows);
2221
+ };
2222
+ const schedule = () => {
2223
+ if (stopped) return;
2224
+ timer = setTimeout(() => {
2225
+ timer = void 0;
2226
+ attempt = run().finally(() => {
2227
+ attempt = void 0;
2228
+ });
2229
+ }, intervalMs);
2230
+ timer.unref();
2231
+ };
2232
+ schedule();
2233
+ return { async stop() {
2234
+ stopped = true;
2235
+ if (timer) clearTimeout(timer);
2236
+ timer = void 0;
2237
+ await attempt?.catch(() => void 0);
2238
+ } };
2239
+ }
2240
+ /**
2241
+ * What a host does once its composed runtime has shut down for losing the
2242
+ * workflow singleton.
2243
+ *
2244
+ * Taken over by another claim: that process runs workflows now, so this one
2245
+ * stays without them until it restarts. Unrenewable with no takeover seen (a
2246
+ * database blip): nothing else runs them, so the process goes down through
2247
+ * the fatal shutdown and its supervisor restarts it, which re-claims at boot.
2248
+ * A host with no fatal shutdown installed (embedded) stays without workflows
2249
+ * and says a restart is needed.
2250
+ */
2251
+ function workflowSingletonLossHandler(logger, fatal = triggerFatalShutdown) {
2252
+ return (loss) => {
2253
+ if (loss.reason === "taken") {
2254
+ logger.error(`Another process ("${loss.heldBy ?? "unknown"}") took the workflow singleton. This Switchboard has stopped its workflow runtime and runs no workflows until it is restarted; everything else serves normally.`);
2255
+ return;
2256
+ }
2257
+ const error = /* @__PURE__ */ new Error(`The workflow singleton lease could not be renewed for ${Math.round(loss.silentMs)}ms; no other process was seen taking it over`);
2258
+ if (fatal("Workflow singleton lease unrenewable", error)) return;
2259
+ logger.error(`${error.message}. This Switchboard has stopped its workflow runtime and runs no workflows until it is restarted.`);
2260
+ };
2261
+ }
2262
+ function modelManifestSource(builder) {
2263
+ return {
2264
+ modelManifest: () => builder.getResolvedModelManifest() ?? [],
2265
+ modelEntries: (documentType) => builder.getImportableEntries(documentType)
2266
+ };
2267
+ }
2268
+ function readAssertion(authorizationService, reactorClient) {
2269
+ const resolveCanonical = createCanonicalDocumentIdResolver(reactorClient);
2270
+ const hostCanRead = async (identifier, ctx) => {
2271
+ if (authorizationService.isSupremeAdmin(ctx.user?.address)) return;
2272
+ if (authorizationService.config.policy !== AuthorizationPolicy.DOCUMENT_PERMISSIONS) throw new ForbiddenError();
2273
+ let documentId;
2274
+ try {
2275
+ documentId = await resolveCanonical(identifier);
2276
+ } catch {
2277
+ throw new ForbiddenError();
2278
+ }
2279
+ if (!await authorizationService.canRead(documentId, ctx.user?.address)) throw new ForbiddenError("to read this document");
2280
+ };
2281
+ return async (identifier, caller) => {
2282
+ const ctx = caller;
2283
+ await hostCanRead(identifier, ctx);
2284
+ let served;
2285
+ try {
2286
+ served = await reactorClient.isServed(identifier, { subject: callerSubject(ctx.user) });
2287
+ } catch {
2288
+ throw new ForbiddenError();
2289
+ }
2290
+ if (!served) throw new ForbiddenError("to read this document");
2291
+ };
2292
+ }
2293
+ /** The same, for a design-time call that writes what it names. */
2294
+ function writeAssertion(authorizationService, reactorClient) {
2295
+ const resolveCanonical = createCanonicalDocumentIdResolver(reactorClient);
2296
+ return async (identifier, caller) => {
2297
+ const ctx = caller;
2298
+ if (authorizationService.isSupremeAdmin(ctx.user?.address)) return;
2299
+ if (authorizationService.config.policy !== AuthorizationPolicy.DOCUMENT_PERMISSIONS) throw new ForbiddenError();
2300
+ let documentId;
2301
+ try {
2302
+ documentId = await resolveCanonical(identifier);
2303
+ } catch {
2304
+ throw new ForbiddenError();
2305
+ }
2306
+ if (!await authorizationService.canWrite(documentId, ctx.user?.address)) throw new ForbiddenError("to write this document");
2307
+ };
2308
+ }
2309
+ /** What the reactor enforces and who it signs as; unknown counts as enforced. */
2310
+ function reactorAccessOf(clientModule) {
2311
+ const flags = clientModule?.reactorModule?.featureFlags;
2312
+ const signer = clientModule?.signer;
2313
+ const key = signer?.app?.key;
2314
+ const identity = key ? {
2315
+ address: signer.user?.address ?? null,
2316
+ key
2317
+ } : null;
2318
+ return {
2319
+ authEnforcement: flags ? flags.authEnforcement : true,
2320
+ authConditions: flags?.authConditions === true,
2321
+ identity
2322
+ };
2323
+ }
2324
+ /** Whom a run's created documents also grant: the host, as §8 grants it. */
2325
+ function hostPrincipalOf(access) {
2326
+ const identity = access.identity;
2327
+ if (!identity) return void 0;
2328
+ if (access.authConditions) return { match: { eq: [{ attr: "subject.key" }, { lit: identity.key }] } };
2329
+ return identity.address ? { address: identity.address } : void 0;
2330
+ }
2331
+ /** Who the host signs as, so a publish it signs makes no run user. */
2332
+ function hostIdentityOf(access) {
2333
+ const identity = access.identity;
2334
+ if (!identity) return void 0;
2335
+ return identity.address ? {
2336
+ address: identity.address,
2337
+ key: identity.key
2338
+ } : { key: identity.key };
2339
+ }
2340
+ const REFERENCE_INDEX_RETRIES = 8;
2341
+ const REFERENCE_INDEX_RETRY_MS = 250;
2342
+ /** A step reads an attachment the way the download route serves one: when the
2343
+ * run's user may read a document that references it. The candidates are the
2344
+ * documents the run was handed; the reference index can trail the operation
2345
+ * that fired the trigger, so a denial is retried briefly. */
2346
+ function attachmentReadPolicy(access, retryMs = REFERENCE_INDEX_RETRY_MS) {
2347
+ return async (request) => {
2348
+ try {
2349
+ if (parseRef(request.ref).version !== 1) return false;
2350
+ } catch {
2351
+ return false;
2352
+ }
2353
+ if (!access || request.documentIds.length === 0) return false;
2354
+ const subject = request.runUser?.subject;
2355
+ const caller = {
2356
+ ...subject?.address ? { userAddress: subject.address } : {},
2357
+ ...subject?.key ? { appKey: subject.key } : {}
2358
+ };
2359
+ for (let attempt = 0; attempt <= REFERENCE_INDEX_RETRIES; attempt++) {
2360
+ for (const documentId of request.documentIds) if ((await access.canReadAttachment({
2361
+ documentId,
2362
+ attachmentRef: request.ref,
2363
+ ...caller
2364
+ })).kind === "allowed") return true;
2365
+ if (attempt < REFERENCE_INDEX_RETRIES) await new Promise((resolve) => setTimeout(resolve, retryMs));
2366
+ }
2367
+ return false;
2368
+ };
2369
+ }
2370
+ async function registerWorkflowTriggersReadModel(engine, runtime, clientModule, registration) {
2371
+ const reactorModule = clientModule?.reactorModule;
2372
+ if (!reactorModule) return {
2373
+ status: "unavailable",
2374
+ reason: "in-process-reactor-module-unavailable"
2375
+ };
2376
+ const coordinator = reactorModule.readModelCoordinator;
2377
+ if (!supportsLiveReadModelRegistration(coordinator)) return {
2378
+ status: "unavailable",
2379
+ reason: "live-read-model-registration-unsupported"
2380
+ };
2381
+ const readModel = new engine.WorkflowTriggersReadModel(reactorModule.database.withSchema(REACTOR_SCHEMA), reactorModule.operationIndex, reactorModule.writeCache, reactorModule.processorManagerConsistencyTracker, runtime);
2382
+ await readModel.init();
2383
+ if (registration.tornDown) return SINGLETON_LOST;
2384
+ coordinator.addReadModel(readModel, engine.WORKFLOW_TRIGGERS_READ_MODEL_STAGE);
2385
+ registration.detach = () => coordinator.removeReadModel(readModel);
2386
+ return { status: "available" };
2387
+ }
2388
+ function bindPackagePieces(registry, source) {
2389
+ const apply = (byPackage) => {
2390
+ registry.setPieces([...byPackage.entries()].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).flatMap(([, pieces]) => pieces));
2391
+ };
2392
+ apply(source.getPieces());
2393
+ source.onPiecesChange(apply);
2394
+ }
2395
+ async function composeWorkflowRuntime(deps) {
2396
+ const load = deps.load ?? (() => import("@powerhousedao/reactor-workflow"));
2397
+ let engine;
2398
+ try {
2399
+ engine = await load();
2400
+ } catch (error) {
2401
+ throw new Error("Workflows are enabled but @powerhousedao/reactor-workflow could not be loaded", { cause: error });
2402
+ }
2403
+ const loss = { lost: false };
2404
+ const lease = deps.singletonLease === false ? void 0 : await engine.acquireWorkflowSingletonLease({
2405
+ relationalDb: deps.relationalDb,
2406
+ logger: deps.logger,
2407
+ ...deps.storageId ? { storageId: deps.storageId } : {},
2408
+ selfFence: deps.exclusiveJournal !== true,
2409
+ onLost: (lost) => {
2410
+ loss.lost = true;
2411
+ if (lost.reason === "taken") loss.heldBy = lost.heldBy;
2412
+ loss.tearDown?.();
2413
+ if (loss.composed) deps.onSingletonLost?.(lost);
2414
+ }
2415
+ });
2416
+ try {
2417
+ const composed = await composeClaimed(engine, deps, lease, loss);
2418
+ if (loss.lost) throw singletonLostError(engine, loss, lease);
2419
+ loss.composed = true;
2420
+ return composed;
2421
+ } catch (error) {
2422
+ loss.tearDown?.();
2423
+ await lease?.release();
2424
+ throw error;
2425
+ }
2426
+ }
2427
+ function singletonLostError(engine, loss, lease) {
2428
+ return new engine.WorkflowSingletonConflictError(loss.heldBy ?? "unknown", "unknown", lease?.owner ?? "unknown");
2429
+ }
2430
+ async function composeClaimed(engine, deps, lease, loss) {
2431
+ engine.setPieceRegistryUrl(deps.pieceRegistryUrl);
2432
+ if (deps.pieces) bindPackagePieces(engine.packagePieces, deps.pieces);
2433
+ if (loss.lost) throw singletonLostError(engine, loss, lease);
2434
+ const access = reactorAccessOf(deps.clientModule);
2435
+ const models = deps.models;
2436
+ const runtime = engine.createWorkflowRuntime({
2437
+ relationalDb: deps.relationalDb,
2438
+ secretsKeyFile: deps.secretsKeyFile,
2439
+ reactorClient: deps.reactorClient,
2440
+ assertCanRead: readAssertion(deps.authorizationService, deps.reactorClient),
2441
+ subjectOf: (caller) => callerSubject(caller.user),
2442
+ assertCanWrite: writeAssertion(deps.authorizationService, deps.reactorClient),
2443
+ ...deps.clientModule?.reactorModule ? { authEnforcement: access.authEnforcement } : {},
2444
+ hostPrincipal: hostPrincipalOf(access),
2445
+ hostIdentity: hostIdentityOf(access),
2446
+ ...models ? {
2447
+ modelManifest: () => models.modelManifest(),
2448
+ modelEntries: (documentType) => models.modelEntries(documentType)
2449
+ } : {},
2450
+ webhooks: deps.webhooks,
2451
+ attachments: deps.attachments,
2452
+ canReadAttachmentRef: attachmentReadPolicy(deps.attachmentAccess),
2453
+ logger: deps.logger,
2454
+ ...deps.telemetry ? { telemetry: deps.telemetry } : {}
2455
+ });
2456
+ const routes = {};
2457
+ const registration = { tornDown: false };
2458
+ const tearDown = () => {
2459
+ if (registration.tornDown) return;
2460
+ registration.tornDown = true;
2461
+ routes.oauthCallback?.dispose();
2462
+ runtime.shutdown();
2463
+ registration.detach?.();
2464
+ };
2465
+ loss.tearDown = tearDown;
2466
+ const triggers = await registerWorkflowTriggersReadModel(engine, runtime, deps.clientModule, registration);
2467
+ if (registration.tornDown) throw singletonLostError(engine, loss, lease);
2468
+ if (triggers.status === "available") deps.logger.info(`Workflow trigger read model registered (${engine.WORKFLOW_TRIGGERS_READ_MODEL}, ${engine.WORKFLOW_TRIGGERS_READ_MODEL_STAGE})`);
2469
+ else deps.logger.error("Workflow document triggers are NOT armed (@reason): this reactor's read-model coordinator takes no live registration, so no document operation reaches the runtime. Webhook and schedule triggers are unaffected.", triggers.reason);
2470
+ let stopped = false;
2471
+ if (deps.http) routes.oauthCallback = registerOAuthCallback(deps.http, runtime);
2472
+ return {
2473
+ subgraph: createWorkflowRuntimeSubgraph(runtime, deps.http ? { callbackUrl: callbackUrlOf(deps.http) } : void 0, access),
2474
+ get triggers() {
2475
+ return loss.lost ? SINGLETON_LOST : triggers;
2476
+ },
2477
+ ...lease ? { singletonOwner: lease.owner } : {},
2478
+ async start() {
2479
+ if (registration.tornDown) return;
2480
+ await runtime.registerWebhookEndpoint();
2481
+ if (loss.lost || stopped) return;
2482
+ runtime.startTriggerSupervisor();
2483
+ runtime.warmPieceSearch();
2484
+ },
2485
+ async stop() {
2486
+ if (stopped) return;
2487
+ stopped = true;
2488
+ tearDown();
2489
+ await lease?.release();
2490
+ }
2491
+ };
2492
+ }
2493
+ //#endregion
2494
+ //#region src/pglite-dialect.ts
2495
+ /** A poisoned store cannot recover in process, so it takes the fatal shutdown and a supervisor restart. */
2496
+ function reactorPgliteDialectOptions(logger, proc) {
2497
+ return {
2498
+ onDiagnostic: (message, error) => logger.error(`[pglite-dialect] ${message}: @error`, error),
2499
+ onPoisoned: (cause) => {
2500
+ if (!triggerFatalShutdown("PGlite session poisoned", cause, proc)) logger.error("PGlite session poisoned: @error", cause);
2501
+ }
2502
+ };
2503
+ }
2504
+ var ClosablePGliteDialect = class {
2505
+ #inner;
2506
+ #pglite;
2507
+ constructor(pglite, options = {}) {
2508
+ this.#pglite = pglite;
2509
+ this.#inner = new HardenedPGliteDialect(pglite, options);
2510
+ }
2511
+ createAdapter() {
2512
+ return this.#inner.createAdapter();
2513
+ }
2514
+ createDriver() {
2515
+ const driver = this.#inner.createDriver();
2516
+ const pglite = this.#pglite;
2517
+ const innerDestroy = driver.destroy.bind(driver);
2518
+ driver.destroy = async () => {
2519
+ await innerDestroy();
2520
+ if (pglite.closed) return;
2521
+ try {
2522
+ await pglite.close();
2523
+ } catch (err) {
2524
+ if (!/PGlite aborted/.test(String(err))) throw err;
2525
+ }
2526
+ };
2527
+ return driver;
2528
+ }
2529
+ createQueryCompiler() {
2530
+ return this.#inner.createQueryCompiler();
2531
+ }
2532
+ createIntrospector(db) {
2533
+ return this.#inner.createIntrospector(db);
2534
+ }
2535
+ };
2536
+ //#endregion
2537
+ //#region src/pglite-migration.ts
2538
+ function backupPath(dataDir, major) {
2539
+ return `${dataDir}.backup-pg${major}-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}`;
2540
+ }
2541
+ async function pathExists(p) {
2542
+ try {
2543
+ await promises.stat(p);
2544
+ return true;
2545
+ } catch {
2546
+ return false;
2547
+ }
2548
+ }
2549
+ function logRestoreFailure(dataDir, sql, err, logger) {
2550
+ const errObj = err;
2551
+ const position = typeof errObj.position === "string" ? parseInt(errObj.position, 10) : typeof errObj.position === "number" ? errObj.position : NaN;
2552
+ logger.error(`[pglite-migration] Restore failed for ${dataDir}: code=${errObj.code ?? ""} severity=${errObj.severity ?? ""} message=${errObj.message ?? ""} sqlLength=${sql.length}`);
2553
+ if (Number.isFinite(position) && position > 0) {
2554
+ const zeroBased = position - 1;
2555
+ const start = Math.max(0, zeroBased - 200);
2556
+ const end = Math.min(sql.length, zeroBased + 200);
2557
+ const before = sql.slice(start, zeroBased);
2558
+ const at = sql.slice(zeroBased, zeroBased + 1);
2559
+ const after = sql.slice(zeroBased + 1, end);
2560
+ logger.error(`[pglite-migration] SQL context around position ${position}:\n${before}»${at}«${after}`);
2561
+ } else logger.error(`[pglite-migration] No position info. First 2000 chars of dump:\n${sql.slice(0, 2e3)}`);
2562
+ }
2563
+ /**
2564
+ * Migrate a filesystem PGLite data directory from a legacy PG major to the
2565
+ * current one. Renames the existing dir to a timestamped backup, dumps via the
2566
+ * matching legacy `pg_dump`, restores into a fresh current-version PGLite at
2567
+ * the original path. On failure, the original dir is restored from the backup.
2568
+ *
2569
+ * No-op when the dir is missing or already at the current major.
2570
+ */
2571
+ async function migratePgliteDir(dataDir, logger) {
2572
+ const major = await readPgVersionFile(dataDir);
2573
+ if (major === null) {
2574
+ logger.info(`[pglite-migration] No PG_VERSION at ${dataDir}; skipping migration`);
2575
+ return;
2576
+ }
2577
+ if (major === 17) return;
2578
+ if (!isSupportedMajor(major)) throw new Error(`Unsupported legacy PGlite data dir: PG_VERSION=${major} for ${dataDir}`);
2579
+ const backupDir = backupPath(dataDir, major);
2580
+ logger.info(`[pglite-migration] Migrating ${dataDir} from PG${major} to PG17; backup: ${backupDir}`);
2581
+ await promises.rename(dataDir, backupDir);
2582
+ let sql;
2583
+ try {
2584
+ const [legacyMod, pgDump] = await Promise.all([loadPGliteModule(major), loadPgDump(major)]);
2585
+ const LegacyPGlite = legacyMod.PGlite;
2586
+ const onDisk = new LegacyPGlite(backupDir);
2587
+ let tar;
2588
+ try {
2589
+ await onDisk.waitReady;
2590
+ tar = await onDisk.dumpDataDir("none");
2591
+ } finally {
2592
+ await onDisk.close();
2593
+ }
2594
+ const pg = new LegacyPGlite({ loadDataDir: tar });
2595
+ try {
2596
+ await pg.waitReady;
2597
+ sql = await (await pgDump({ pg })).text();
2598
+ } finally {
2599
+ await pg.close();
2600
+ }
2601
+ } catch (err) {
2602
+ await rollback(dataDir, backupDir, err, logger);
2603
+ throw err;
2604
+ }
2605
+ try {
2606
+ const CurrentPGlite = (await loadPGliteModule(17)).PGlite;
2607
+ const pg = new CurrentPGlite(dataDir, { relaxedDurability: false });
2608
+ try {
2609
+ await pg.waitReady;
2610
+ try {
2611
+ await pg.exec("SET standard_conforming_strings = off;");
2612
+ } catch (gucErr) {
2613
+ logger.warn(`[pglite-migration] Could not force standard_conforming_strings=off: ${String(gucErr)}`);
2614
+ }
2615
+ try {
2616
+ await pg.exec(sql);
2617
+ } catch (execErr) {
2618
+ logRestoreFailure(dataDir, sql, execErr, logger);
2619
+ throw execErr;
2620
+ }
2621
+ } finally {
2622
+ await pg.close();
2623
+ }
2624
+ syncTree(dataDir);
2625
+ } catch (err) {
2626
+ await rollback(dataDir, backupDir, err, logger);
2627
+ throw err;
2628
+ }
2629
+ logger.info(`[pglite-migration] Migration of ${dataDir} complete. Backup retained at ${backupDir}; remove it manually once you have verified the upgrade.`);
2630
+ }
2631
+ async function rollback(dataDir, backupDir, originalError, logger) {
2632
+ try {
2633
+ if (await pathExists(dataDir)) await promises.rm(dataDir, {
2634
+ recursive: true,
2635
+ force: true
2636
+ });
2637
+ if (await pathExists(backupDir)) await promises.rename(backupDir, dataDir);
2638
+ } catch (rollbackErr) {
2639
+ logger.error(`[pglite-migration] Migration AND rollback failed for ${dataDir}. Original error: ${String(originalError)}; rollback error: ${String(rollbackErr)}; backup may still exist at ${backupDir}.`);
2640
+ return;
2641
+ }
2642
+ logger.error(`[pglite-migration] Migration failed for ${dataDir}; rolled back from ${backupDir}. Original error: ${String(originalError)}`);
2643
+ }
2644
+ //#endregion
2645
+ //#region src/pglite-preflight.ts
2646
+ const RM_OPTIONS = {
2647
+ recursive: true,
2648
+ force: true,
2649
+ maxRetries: 10,
2650
+ retryDelay: 100
2651
+ };
2652
+ /**
2653
+ * Prepares every local PGlite dir before the first open and returns the
2654
+ * PG major detected on disk per dir. Conversion of an AtomicNodeFs snapshot
2655
+ * runs for every dir, before the major is read, so a pure-snapshot PG16 dir
2656
+ * is converted and then migrated.
2657
+ */
2658
+ async function runPglitePreflight(options) {
2659
+ const { dirs, logger } = options;
2660
+ const detectedMajors = /* @__PURE__ */ new Map();
2661
+ if (options.inMemory || dirs.length === 0) return detectedMajors;
2662
+ if (options.forcePgVersion !== void 0) {
2663
+ if (options.migratePglite) logger.warn("PH_FORCE_PG_VERSION is set; ignoring --migrate-pglite/PH_MIGRATE_PGLITE because the data dirs will be wiped.");
2664
+ logger.warn(`PH_FORCE_PG_VERSION=${options.forcePgVersion} set; wiping PGLite data dirs and re-initializing at PG${options.forcePgVersion}.`);
2665
+ for (const dir of dirs) {
2666
+ for (const p of [
2667
+ dir,
2668
+ `${dir}.converting`,
2669
+ `${dir}.old`
2670
+ ]) await promises.rm(p, RM_OPTIONS);
2671
+ logger.info(`Wiped PGLite data dir ${dir}`);
2672
+ }
2673
+ return detectedMajors;
2674
+ }
2675
+ const deps = {
2676
+ openForVerify: options.openForVerify ?? openForVerify,
2677
+ logger
2678
+ };
2679
+ for (const dir of dirs) {
2680
+ await preparePgliteDataDir(dir, deps);
2681
+ const major = await readPgVersionFile(dir);
2682
+ if (major !== null) detectedMajors.set(dir, major);
2683
+ }
2684
+ if (options.migratePglite) for (const [dir, major] of detectedMajors) {
2685
+ if (major === 17) continue;
2686
+ await migratePgliteDir(dir, logger);
2687
+ await removeStalePgliteFiles(dir, logger);
2688
+ const after = await readPgVersionFile(dir);
2689
+ if (after !== null) detectedMajors.set(dir, after);
2690
+ }
2691
+ else for (const [dir, major] of detectedMajors) {
2692
+ if (major === 17) continue;
2693
+ logger.warn(`PGLite data dir at ${dir} was created with PG${major} but Switchboard ships PG17. Running on legacy PGLite. Re-start with --migrate-pglite (or PH_MIGRATE_PGLITE=true) to upgrade.`);
2694
+ }
2695
+ return detectedMajors;
2696
+ }
2697
+ //#endregion
2698
+ //#region src/reactor-feature-flags.mts
2699
+ /**
2700
+ * Enforcement flags from the REACTOR_* env vars. Each flag requires the ones
2701
+ * before it; the reactor rejects an inconsistent set rather than enforcing less
2702
+ * than the operator asked for, so this reports what was asked without
2703
+ * correcting it.
2704
+ */
2705
+ function resolveReactorFeatureFlags(env) {
2706
+ const flags = {
2707
+ documentDecisions: env.REACTOR_DOCUMENT_DECISIONS === "true",
2708
+ authEnforcement: env.REACTOR_AUTH_ENFORCEMENT === "true",
2709
+ authGroups: env.REACTOR_AUTH_GROUPS === "true",
2710
+ authConditions: env.REACTOR_AUTH_CONDITIONS === "true"
2711
+ };
2712
+ return {
2713
+ flags,
2714
+ enabled: Object.entries(flags).filter(([, isEnabled]) => isEnabled).map(([name]) => name)
2715
+ };
2716
+ }
2717
+ //#endregion
2718
+ //#region src/create-signature-policy.mts
2719
+ /**
2720
+ * What new documents are created as, from CREATE_SIGNATURE_POLICY. Without a
2721
+ * signer this switchboard cannot write to a v2-required document, so it falls
2722
+ * back to legacy and says so.
2723
+ */
2724
+ function resolveCreateSignaturePolicy(env, options) {
2725
+ const raw = env.CREATE_SIGNATURE_POLICY?.trim();
2726
+ let policy = DEFAULT_SIGNATURE_POLICY;
2727
+ if (raw) {
2728
+ if (!isSignaturePolicy(raw)) throw new Error(`CREATE_SIGNATURE_POLICY must be "legacy" or "v2-required", got "${raw}"`);
2729
+ policy = raw;
2730
+ }
2731
+ if (policy === "v2-required" && !options.hasSigner) {
2732
+ options.logger?.warn("No signer is configured, so new documents are created legacy: a v2-required document refuses the unsigned operations this switchboard would write. Set up an identity (ph login) to create v2-required documents.");
2733
+ return "legacy";
2734
+ }
2735
+ return policy;
2736
+ }
2737
+ //#endregion
2738
+ //#region src/renown.ts
2739
+ const logger = childLogger(["switchboard", "renown"]);
2740
+ /**
2741
+ * Initialize Renown for the Switchboard instance.
2742
+ * This allows Switchboard to authenticate with remote services
2743
+ * using the same identity established during `ph login`.
2744
+ */
2745
+ async function initRenown(options = {}) {
2746
+ const { keypairPath, requireExisting = false, baseUrl = DEFAULT_RENOWN_URL } = options;
2747
+ const keyStorage = new NodeKeyStorage(keypairPath, { logger });
2748
+ const existingKeyPair = await keyStorage.loadKeyPair();
2749
+ if (!existingKeyPair && requireExisting) throw new Error("No existing keypair found and requireExisting is true. Run \"ph login\" to create one.");
2750
+ if (!existingKeyPair) logger.info("No existing keypair found. A new one will be generated.");
2751
+ const renownCrypto = await new RenownCryptoBuilder().withKeyPairStorage(keyStorage).build();
2752
+ const renown = await new RenownBuilder("switchboard", {}).withCrypto(renownCrypto).withBaseUrl(baseUrl).build();
2753
+ logger.info("Switchboard identity initialized: @did", renownCrypto.did);
2754
+ return renown;
2755
+ }
2756
+ /**
2757
+ * Get the signer config for the given renown instance.
2758
+ *
2759
+ * @param renown - The renown instance
2760
+ * @param keypairPath - Where `initRenown` loaded the key from
2761
+ */
2762
+ function getRenownSignerConfig(renown, keypairPath) {
2763
+ return {
2764
+ signer: renown.signer,
2765
+ workerSigner: getRenownWorkerSignerSpec(renown, keypairPath)
2766
+ };
2767
+ }
2768
+ /**
2769
+ * What a pooled executor worker imports to sign as this switchboard: it
2770
+ * reloads the key `initRenown` stored, and takes the user known at boot.
2771
+ */
2772
+ function getRenownWorkerSignerSpec(renown, keypairPath) {
2773
+ const { signer } = renown;
2774
+ const user = signer.user;
2775
+ return {
2776
+ module: {
2777
+ filePath: createRequire(import.meta.url).resolve("@renown/sdk/node"),
2778
+ exportName: "createNodeRenownSigner"
2779
+ },
2780
+ initArgs: {
2781
+ appName: signer.app?.name ?? "switchboard",
2782
+ keypairPath: resolve(keypairPath ?? DEFAULT_KEYPAIR_PATH),
2783
+ ...signer.app?.key ? { did: signer.app.key } : {},
2784
+ ...user ? { user: {
2785
+ address: user.address,
2786
+ networkId: user.networkId,
2787
+ chainId: user.chainId
2788
+ } } : {}
2789
+ }
2790
+ };
2791
+ }
2792
+ /**
2793
+ * Admits a key as a signer for an address a Renown credential binds it to; a
2794
+ * `self` source has no worker spec. In process, the switchboard's own key is
2795
+ * matched against its current user; the worker spec carries the user known now.
2796
+ */
2797
+ async function getRenownTrustPolicyConfig(trustSource, renown) {
2798
+ const ownSigner = renown?.signer;
2799
+ if (trustSource.source === "self") return { trustPolicy: createRenownTrustPolicy({
2800
+ switchboard: trustSource.request,
2801
+ ownSigner
2802
+ }) };
2803
+ const switchboardUrl = await resolveSwitchboardEndpoint({
2804
+ switchboardUrl: trustSource.switchboardUrl,
2805
+ baseUrl: trustSource.renownUrl
2806
+ });
2807
+ const options = {
2808
+ ...switchboardUrl ? { switchboard: switchboardUrl } : {},
2809
+ ...trustSource.renownUrl ? { renownUrl: trustSource.renownUrl } : {}
2810
+ };
2811
+ const self = ownIdentity(renown);
2812
+ return {
2813
+ trustPolicy: createRenownTrustPolicy({
2814
+ ...options,
2815
+ ownSigner
2816
+ }),
2817
+ workerTrustPolicy: {
2818
+ module: {
2819
+ filePath: createRequire(import.meta.url).resolve("@renown/sdk/node"),
2820
+ exportName: "createRenownTrustPolicy"
2821
+ },
2822
+ initArgs: {
2823
+ ...options,
2824
+ ...self ? { self } : {}
2825
+ }
2826
+ }
2827
+ };
2828
+ }
2829
+ /**
2830
+ * Fails the boot when pooled workers would refuse every signed write the
2831
+ * in-process executor accepts: a `self` Renown source gives workers no trust
2832
+ * policy spec, so under authEnforcement they apply the default.
2833
+ */
2834
+ function assertWorkerTrustPolicy(config) {
2835
+ if (config.workers > 0 && config.authEnforcement && config.renownSource === "self") throw new Error("The executor worker pool (REACTOR_WORKERS) cannot verify signers when REACTOR_AUTH_ENFORCEMENT is on and Renown credentials are read from this switchboard (\"self\" via auth.renown.source or RENOWN_SOURCE): pooled workers have no trust policy and would refuse every signed write. Set RENOWN_SOURCE=remote, or disable the worker pool (REACTOR_WORKERS=0).");
2836
+ }
2837
+ function ownIdentity(renown) {
2838
+ const key = renown?.signer.app?.key;
2839
+ if (!key) return;
2840
+ const user = renown.signer.user;
2841
+ return {
2842
+ key,
2843
+ user: {
2844
+ address: user?.address ?? "",
2845
+ networkId: user?.networkId ?? "",
2846
+ chainId: user?.chainId ?? 0
2847
+ }
2848
+ };
2849
+ }
2850
+ //#endregion
2851
+ //#region src/unsupported-stored-documents.mts
2852
+ const MODES = ["refuse", "read-only"];
2853
+ /** From REACTOR_UNSUPPORTED_STORED_DOCUMENTS; `input` wins when defined. */
2854
+ function resolveUnsupportedStoredDocuments(input, env) {
2855
+ if (input !== void 0) return input;
2856
+ const raw = env.REACTOR_UNSUPPORTED_STORED_DOCUMENTS?.trim();
2857
+ if (!raw) return "refuse";
2858
+ if (!MODES.includes(raw)) throw new Error(`REACTOR_UNSUPPORTED_STORED_DOCUMENTS must be "refuse" or "read-only", got "${raw}"`);
2859
+ return raw;
2860
+ }
2861
+ /** The reactor refused to start over documents this build does not run. */
2862
+ var StoredDocumentsRefusedError = class extends Error {
2863
+ versions;
2864
+ documents;
2865
+ constructor(cause) {
2866
+ const named = cause.versions.map(({ protocol, version }) => `${protocol} ${version}`).join(", ");
2867
+ super(`Refusing to start: ${cause.documents} stored document(s) require ${named}, which this switchboard does not run. Either start a switchboard build that runs ${named}, or set REACTOR_UNSUPPORTED_STORED_DOCUMENTS=read-only to start with those documents read-only.`, { cause });
2868
+ this.name = "StoredDocumentsRefusedError";
2869
+ this.versions = cause.versions;
2870
+ this.documents = cause.documents;
2871
+ }
2872
+ static isError(error) {
2873
+ return Error.isError(error) && error.name === "StoredDocumentsRefusedError";
2874
+ }
2875
+ };
2876
+ //#endregion
2877
+ //#region src/server.mts
2878
+ const defaultLogger = childLogger(["switchboard"]);
2879
+ const LogLevel = process.env.LOG_LEVEL || "info";
2880
+ setLogLevel(LogLevel);
2881
+ dotenv.config();
2882
+ const DOCUMENT_MODEL_SUBGRAPHS_ENABLED = "DOCUMENT_MODEL_SUBGRAPHS_ENABLED";
2883
+ const DOCUMENT_MODEL_SUBGRAPHS_ENABLED_DEFAULT = true;
2884
+ const DEFAULT_PORT = process.env.PORT ? Number(process.env.PORT) : 4001;
2885
+ const PORT_FALLBACK_ATTEMPTS = 20;
2886
+ let flushIntervalWarned = false;
2887
+ function warnIgnoredFlushInterval(logger) {
2888
+ if (flushIntervalWarned) return;
2889
+ if (process.env.PGLITE_FLUSH_INTERVAL_MS === void 0) return;
2890
+ flushIntervalWarned = true;
2891
+ logger.warn("PGLITE_FLUSH_INTERVAL_MS is set but ignored: PGlite stores no longer snapshot on a timer.");
2892
+ }
2893
+ function onPgliteAbort(logger, what) {
2894
+ if (!triggerFatalShutdown("PGlite aborted", what)) logger.error("PGlite aborted: @error", what);
2895
+ }
2896
+ function pgliteFsyncFor(major, dir, logger) {
2897
+ const wanted = resolvePgliteFsync(process.env);
2898
+ if (wanted && major === 16) logger.warn(`PGlite data dir ${dir} is PG16 on pglite-legacy-02, which does not sync commits to disk; only checkpoints are synced until --migrate-pglite upgrades it.`);
2899
+ return wanted;
2900
+ }
2901
+ /** Preloads the module's NodeFS so the returned factory can be synchronous. */
2902
+ async function loadDurableFsFactory(major, logger) {
2903
+ const NodeFS = await loadNodeFsClass(major);
2904
+ return (dir) => createDurableNodeFs(NodeFS, dir, {
2905
+ fsync: pgliteFsyncFor(major, dir, logger),
2906
+ logger,
2907
+ onAbort: (what) => onPgliteAbort(logger, what)
2908
+ });
2909
+ }
2910
+ const PGLITE_IN_MEMORY = process.env.PH_PGLITE_IN_MEMORY === "1";
2911
+ /**
2912
+ * Attempt to bind a throwaway TCP server to the given port. Resolves true if
2913
+ * the port is free, false if the OS reports it in use. Any other error is
2914
+ * surfaced so we don't silently mask real issues (permissions, bad host, …).
2915
+ */
2916
+ function isPortAvailable(port) {
2917
+ return new Promise((resolve, reject) => {
2918
+ const tester = net.createServer();
2919
+ tester.once("error", (err) => {
2920
+ if (err.code === "EADDRINUSE" || err.code === "EACCES") resolve(false);
2921
+ else reject(err);
2922
+ });
2923
+ tester.once("listening", () => {
2924
+ tester.close(() => resolve(true));
2925
+ });
2926
+ tester.listen({
2927
+ port,
2928
+ host: "::"
2929
+ });
2930
+ });
2931
+ }
2932
+ /** The powerhouse.config.json this run reads, defaulting to the cwd copy. */
2933
+ function resolveConfigPath(configFile) {
2934
+ return configFile ?? path$1.join(process.cwd(), "powerhouse.config.json");
2935
+ }
2936
+ function readConfigWorkflowsEnabled(configPath) {
2937
+ try {
2938
+ return getConfig(configPath).workflows?.enabled ?? false;
2939
+ } catch {
2940
+ return false;
2941
+ }
2942
+ }
2943
+ async function resolveServerPort(requested, strictPort, logger) {
2944
+ if (strictPort) return requested;
2945
+ for (let i = 0; i < PORT_FALLBACK_ATTEMPTS; i++) {
2946
+ const candidate = requested + i;
2947
+ if (await isPortAvailable(candidate)) {
2948
+ if (candidate !== requested) logger.info(`Port ${requested} is in use. Falling back to port ${candidate}.`);
2949
+ return candidate;
2950
+ }
2951
+ }
2952
+ return requested;
2953
+ }
2954
+ async function createReactorKysely(opts) {
2955
+ const { reactorDbUrl, reactorPgliteDir, reactorPgliteMajor, inMemory, hostPoolSize, logger } = opts;
2956
+ if (reactorDbUrl && isPostgresUrl(reactorDbUrl)) {
2957
+ const connectionString = reactorDbUrl.includes("?") ? reactorDbUrl : `${reactorDbUrl}?sslmode=disable`;
2958
+ const poolSize = hostPoolSize();
2959
+ const pool = new Pool({
2960
+ connectionString,
2961
+ max: poolSize
2962
+ });
2963
+ const poolInstrumentation = instrumentPgPool(pool, "reactor-host");
2964
+ logger.info(`Using PostgreSQL for reactor storage (host pool max ${poolSize})`);
2965
+ return {
2966
+ kysely: new Kysely({ dialect: new PostgresDialect({ pool }) }),
2967
+ poolInstrumentation,
2968
+ storageFacts: POSTGRES_STORAGE_FACTS
2969
+ };
2970
+ }
2971
+ if (!reactorPgliteDir || reactorPgliteMajor === null) throw new Error("Reactor PGLite directory not resolved");
2972
+ const { PGlite } = await loadPGliteModule(reactorPgliteMajor);
2973
+ const pglite = inMemory ? new PGlite() : new PGlite({ fs: (await loadDurableFsFactory(reactorPgliteMajor, logger))(reactorPgliteDir) });
2974
+ logger.info(inMemory ? `Using in-memory PGlite (PG${reactorPgliteMajor}) for reactor storage [PH_PGLITE_IN_MEMORY=1]` : `Using PGlite (PG${reactorPgliteMajor}) for reactor storage at ${reactorPgliteDir}`);
2975
+ return {
2976
+ kysely: new Kysely({ dialect: new ClosablePGliteDialect(pglite, reactorPgliteDialectOptions(logger)) }),
2977
+ poolInstrumentation: void 0,
2978
+ storageFacts: inMemory ? IN_MEMORY_PGLITE_STORAGE_FACTS : PGLITE_PATH_STORAGE_FACTS
2979
+ };
2980
+ }
2981
+ /** Derive the remote attachment service config for switchboard's own `/attachments/*` API. */
2982
+ function deriveAttachmentServiceConfig(options, serverPort, renown) {
2983
+ const protocol = options.https ? "https" : "http";
2984
+ return {
2985
+ remoteUrl: options.attachmentServiceUrl ?? process.env.PH_SWITCHBOARD_PUBLIC_URL ?? `${protocol}://localhost:${serverPort}`,
2986
+ jwtHandler: renown ? async (url) => renown.user ? renown.getBearerToken({
2987
+ expiresIn: 10,
2988
+ aud: url
2989
+ }) : void 0 : void 0
2990
+ };
2991
+ }
2992
+ async function initServer(serverPort, options, renown, renownConfig) {
2993
+ const { dev, packages = [], remoteDrives = [], logger = defaultLogger } = options;
2994
+ logger.level = LogLevel;
2995
+ const dbPath = options.dbPath ?? process.env.DATABASE_URL ?? process.env.PH_SWITCHBOARD_DATABASE_URL;
2996
+ const readModelPath = dbPath || ".ph/read-storage";
2997
+ const reactorDbUrl = options.dbPath ?? process.env.PH_REACTOR_DATABASE_URL ?? process.env.PH_SWITCHBOARD_DATABASE_URL;
2998
+ const reactorPath = reactorDbUrl || "./.ph/reactor-storage";
2999
+ const reactorPgliteDir = options.reactor ? null : !reactorDbUrl || !isPostgresUrl(reactorDbUrl) ? reactorPath : null;
3000
+ const readModelPgliteDir = !dbPath || !isPostgresUrl(dbPath) ? readModelPath : null;
3001
+ const pgliteDirs = [reactorPgliteDir, readModelPgliteDir].filter((d) => d !== null);
3002
+ warnIgnoredFlushInterval(logger);
3003
+ const detectedMajors = await runPglitePreflight({
3004
+ dirs: pgliteDirs,
3005
+ forcePgVersion: options.forcePgVersion,
3006
+ migratePglite: options.migratePglite,
3007
+ inMemory: PGLITE_IN_MEMORY,
3008
+ logger
3009
+ });
3010
+ function resolvePgliteMajorForDir(dir) {
3011
+ if (options.forcePgVersion !== void 0) return options.forcePgVersion;
3012
+ const detected = detectedMajors.get(dir);
3013
+ if (detected === void 0) return 17;
3014
+ if (!isSupportedMajor(detected)) throw new Error(`Unsupported PGLite data dir at ${dir}: PG_VERSION=${detected}`);
3015
+ return detected;
3016
+ }
3017
+ const reactorPgliteMajor = reactorPgliteDir ? resolvePgliteMajorForDir(reactorPgliteDir) : null;
3018
+ const readModelPgliteMajor = readModelPgliteDir ? resolvePgliteMajorForDir(readModelPgliteDir) : null;
3019
+ let workerPool = resolveWorkerPoolOptions(options.workerPool, process.env);
3020
+ if (workerPool && options.reactor) {
3021
+ logger.warn("Worker pool configuration ignored: the caller-provided reactor owns its own executor");
3022
+ workerPool = null;
3023
+ }
3024
+ if (workerPool) {
3025
+ if (dev) throw new Error("The executor worker pool (REACTOR_WORKERS) is not supported in dev mode: Vite-loaded document models cannot cross a worker-thread boundary");
3026
+ assertWorkerTrustPolicy({
3027
+ workers: workerPool.numWorkers,
3028
+ authEnforcement: resolveReactorFeatureFlags(process.env).flags.authEnforcement === true,
3029
+ renownSource: renownConfig.source
3030
+ });
3031
+ if (!reactorDbUrl || !isPostgresUrl(reactorDbUrl)) throw new Error("The executor worker pool (REACTOR_WORKERS) requires a Postgres reactor database — set PH_REACTOR_DATABASE_URL or PH_SWITCHBOARD_DATABASE_URL. PGlite cannot be shared across worker threads.");
3032
+ }
3033
+ const unsupportedStoredDocuments = resolveUnsupportedStoredDocuments(options.unsupportedStoredDocuments, process.env);
3034
+ let projectionWorker = resolveProjectionWorkerOptions(options.projectionWorker, process.env);
3035
+ if (projectionWorker && options.reactor) {
3036
+ logger.warn("Projection worker configuration ignored: the caller-provided reactor owns its own read-model coordinator");
3037
+ projectionWorker = null;
3038
+ }
3039
+ if (projectionWorker) assertProjectionWorkerSupported({
3040
+ dev: dev === true,
3041
+ reactorDbUrl
3042
+ });
3043
+ const apiRef = { current: void 0 };
3044
+ let driveNodeView;
3045
+ const configPath = resolveConfigPath(options.configFile);
3046
+ const config = getConfig(configPath);
3047
+ const registryUrl = options.registryUrl ?? process.env.PH_REGISTRY_URL ?? config.packageRegistryUrl;
3048
+ const registryPackages = process.env.PH_REGISTRY_PACKAGES;
3049
+ const dynamicModelLoading = options.dynamicModelLoading ?? process.env.DYNAMIC_MODEL_LOADING === "true";
3050
+ let httpLoader;
3051
+ if (registryUrl) {
3052
+ register(httpsHooksPath, import.meta.url);
3053
+ httpLoader = new HttpPackageLoader({ registryUrl });
3054
+ registryPackages?.split(",").forEach((p) => {
3055
+ const name = p.trim();
3056
+ if (!packages.includes(name)) packages.push(name);
3057
+ });
3058
+ }
3059
+ const registryPackageNames = new Set((registryPackages ?? "").split(",").map((p) => p.trim()).filter(Boolean));
3060
+ const resolveRegistryModels = async (identifier) => httpLoader && registryPackageNames.has(identifier) ? (await httpLoader.cachePackage(identifier)).entries.documentModels ?? null : null;
3061
+ const reactorLogger = logger.child(["reactor"]);
3062
+ let projectionWorkerFatalFired = false;
3063
+ const onProjectionWorkerFatal = (shardId, reason) => {
3064
+ if (projectionWorkerFatalFired) return;
3065
+ projectionWorkerFatalFired = true;
3066
+ reactorLogger.error(`Projection worker ${shardId} died; shutting down so the supervisor restarts a healthy process`, reason);
3067
+ process.kill(process.pid, "SIGTERM");
3068
+ };
3069
+ const workflowsEnabled = options.workflows?.enabled === true;
3070
+ const privacyConfig = resolvePrivacy(options.privacy, process.env);
3071
+ if (workflowsEnabled) {
3072
+ await assertWorkflowPackageLoadable();
3073
+ if (!packages.includes("@powerhousedao/workflow")) packages.push(WORKFLOW_PACKAGE_NAME);
3074
+ }
3075
+ let ownedReactorModule;
3076
+ let workerModels;
3077
+ let localRenownRequest;
3078
+ const initializeClient = async (documentModels, { attachmentReferenceWriter, upgradeManifests }) => {
3079
+ if (options.reactor) {
3080
+ const attachmentReferenceProjection = await registerAttachmentReferenceReadModelOnModule(options.reactor, attachmentReferenceWriter);
3081
+ if (options.reactor.reactorModule) {
3082
+ new ReactorInstrumentation(options.reactor.reactorModule).start();
3083
+ reactorLogger.info("Reactor metrics instrumentation started (using caller-provided reactor)");
3084
+ }
3085
+ return {
3086
+ module: options.reactor,
3087
+ attachmentReferenceProjection
3088
+ };
3089
+ }
3090
+ const { kysely: baseKysely, poolInstrumentation, storageFacts } = await createReactorKysely({
3091
+ reactorDbUrl,
3092
+ reactorPgliteDir,
3093
+ reactorPgliteMajor,
3094
+ inMemory: PGLITE_IN_MEMORY,
3095
+ hostPoolSize: () => resolveHostPoolSize(process.env),
3096
+ logger
3097
+ });
3098
+ const maxSkipThreshold = parseInt(process.env.MAX_SKIP_THRESHOLD ?? "", 10);
3099
+ const hasSkipThreshold = !isNaN(maxSkipThreshold) && maxSkipThreshold > 0;
3100
+ if (hasSkipThreshold) logger.info(`Reactor maxSkipThreshold set to ${maxSkipThreshold}`);
3101
+ const { flags: reactorFeatureFlags, enabled: enabledFeatureFlags } = resolveReactorFeatureFlags(process.env);
3102
+ if (enabledFeatureFlags.length > 0) logger.info(`Reactor feature flags enabled: ${enabledFeatureFlags.join(", ")}`);
3103
+ const reactorBuilder = new ReactorBuilder().withEventBus(new EventBus()).withKysely(baseKysely).withStorageFacts(storageFacts).withFeatures({ legacyProcessorIds: process.env.REACTOR_LEGACY_PROCESSOR_IDS !== "false" }).withUnsupportedStoredDocuments(unsupportedStoredDocuments);
3104
+ if (poolInstrumentation) reactorBuilder.withInstrumentedPool(poolInstrumentation);
3105
+ const clientBuilder = new ReactorClientBuilder().withReactorBuilder(reactorBuilder);
3106
+ const vetraDocumentModels = dev ? Object.values(await import("@powerhousedao/vetra/document-models")).filter((m) => typeof m === "object" && m !== null && "documentModel" in m && "reducer" in m) : [];
3107
+ applySwitchboardReactorDefaults(reactorBuilder, clientBuilder, {
3108
+ documentModels: [...documentModels, ...vetraDocumentModels],
3109
+ upgradeManifests,
3110
+ executorConfig: hasSkipThreshold || enabledFeatureFlags.length > 0 ? {
3111
+ ...hasSkipThreshold ? { maxSkipThreshold } : {},
3112
+ ...enabledFeatureFlags.length > 0 ? { featureFlags: reactorFeatureFlags } : {}
3113
+ } : void 0,
3114
+ documentModelLoader: httpLoader && dynamicModelLoading ? httpLoader.documentModelLoader : void 0,
3115
+ logger: reactorLogger,
3116
+ signer: renown ? getRenownSignerConfig(renown, options.identity?.keypairPath) : void 0,
3117
+ createSignaturePolicy: resolveCreateSignaturePolicy(process.env, {
3118
+ hasSigner: renown !== null,
3119
+ logger
3120
+ }),
3121
+ trustPolicy: reactorFeatureFlags.authEnforcement ? await getRenownTrustPolicyConfig(renownConfig.source === "self" ? {
3122
+ source: "self",
3123
+ request: (query, variables) => localRenownRequest ? localRenownRequest(query, variables) : Promise.reject(/* @__PURE__ */ new Error("The local renown read model is not bound yet"))
3124
+ } : {
3125
+ source: "remote",
3126
+ renownUrl: renownConfig.url,
3127
+ switchboardUrl: renownConfig.switchboardUrl
3128
+ }, renown) : void 0
3129
+ });
3130
+ if (workerPool || projectionWorker || workflowsEnabled) {
3131
+ const sources = await resolveWorkerModelSources(packages, reactorLogger, { resolveRemote: resolveRegistryModels });
3132
+ reactorBuilder.withDocumentModelSources(workerPool || projectionWorker ? sources : await keepImportableSources(sources, reactorLogger));
3133
+ }
3134
+ workerModels = modelManifestSource(reactorBuilder);
3135
+ if (workerPool) {
3136
+ if (!reactorDbUrl) throw new Error("unreachable: worker pool enabled without a reactor database URL");
3137
+ reactorBuilder.withWorkerPool({
3138
+ numWorkers: workerPool.numWorkers,
3139
+ db: buildWorkerDbConfig(reactorDbUrl, workerPool)
3140
+ });
3141
+ reactorLogger.info(`Executor worker pool enabled: ${workerPool.numWorkers} worker threads${workerPool.mode === "auto" ? " (auto-sized from cores)" : ""}`);
3142
+ }
3143
+ reactorBuilder.withReadModelFactory(async ({ operationIndex, writeCache, processorManagerConsistencyTracker }) => {
3144
+ const nodeProcessor = new NodeProcessor(baseKysely, REACTOR_SCHEMA, operationIndex, writeCache, processorManagerConsistencyTracker);
3145
+ await nodeProcessor.init();
3146
+ return nodeProcessor;
3147
+ });
3148
+ registerAttachmentReferenceReadModel(reactorBuilder, {
3149
+ baseKysely,
3150
+ attachmentReferenceWriter
3151
+ });
3152
+ if (projectionWorker) {
3153
+ if (!reactorDbUrl) throw new Error("unreachable: projection worker enabled without a reactor database URL");
3154
+ const db = {
3155
+ ...buildWorkerDbConfig(reactorDbUrl, {
3156
+ dbPoolSizePerWorker: projectionWorker.dbPoolSize,
3157
+ acquireTimeoutMs: workerPool?.acquireTimeoutMs ?? 5e3
3158
+ }),
3159
+ applicationName: "switchboard-projection"
3160
+ };
3161
+ reactorBuilder.withReadModelCoordinatorFactory(createHybridProjectionCoordinatorFactory({
3162
+ shardCount: 1,
3163
+ poolSize: projectionWorker.dbPoolSize,
3164
+ db,
3165
+ onFatal: onProjectionWorkerFatal
3166
+ }));
3167
+ reactorLogger.info(`Projection worker enabled: 1 worker thread, pool size ${projectionWorker.dbPoolSize}`);
3168
+ }
3169
+ reactorBuilder.withShutdownHook(async () => {
3170
+ if (apiRef.current) await apiRef.current.dispose();
3171
+ });
3172
+ let module;
3173
+ try {
3174
+ module = await clientBuilder.buildModule();
3175
+ } catch (error) {
3176
+ try {
3177
+ await baseKysely.destroy();
3178
+ } catch (destroyError) {
3179
+ logger.error("Aborting boot: reactor database destroy failed: @error", destroyError);
3180
+ }
3181
+ if (UnsupportedStoredProtocolError.isError(error)) throw new StoredDocumentsRefusedError(error);
3182
+ throw error;
3183
+ }
3184
+ if (module.reactorModule) {
3185
+ new ReactorInstrumentation(module.reactorModule).start();
3186
+ reactorLogger.info("Reactor metrics instrumentation started");
3187
+ }
3188
+ const reactorDriveSchemaDb = baseKysely.withSchema(REACTOR_SCHEMA);
3189
+ driveNodeView = new DriveNodeView(reactorDriveSchemaDb);
3190
+ const reactorDriveClient = new ReactorDriveClient({
3191
+ reactor: module.client,
3192
+ readModel: driveNodeView
3193
+ });
3194
+ ownedReactorModule = module;
3195
+ if (options.fatalErrorShutdown) installFatalErrorShutdown(logger);
3196
+ return {
3197
+ module,
3198
+ reactorDriveClient,
3199
+ attachmentReferenceProjection: { status: "available" }
3200
+ };
3201
+ };
3202
+ const abortBoot = async (api) => {
3203
+ const owned = ownedReactorModule;
3204
+ if (owned) try {
3205
+ await owned.reactor.kill().completed;
3206
+ } catch (error) {
3207
+ logger.error("Aborting boot: reactor shutdown failed: @error", error);
3208
+ }
3209
+ try {
3210
+ await api.dispose();
3211
+ } catch (error) {
3212
+ logger.error("Aborting boot: api dispose failed: @error", error);
3213
+ }
3214
+ if (owned?.reactorModule) try {
3215
+ await owned.reactorModule.database.destroy();
3216
+ } catch (error) {
3217
+ logger.error("Aborting boot: database destroy failed: @error", error);
3218
+ }
3219
+ };
3220
+ let localCredentialCheck;
3221
+ const verifyCredential = renownConfig.source === "self" ? (params) => localCredentialCheck ? localCredentialCheck(params) : Promise.reject(/* @__PURE__ */ new Error("The local renown read model is not bound yet")) : void 0;
3222
+ let defaultDriveUrl = void 0;
3223
+ const basePath = process.cwd();
3224
+ let vite;
3225
+ let viteLoader;
3226
+ if (dev) {
3227
+ const { VitePackageLoader, createViteLogger, startViteServer } = await import("@powerhousedao/reactor-api/vite");
3228
+ vite = await startViteServer(process.cwd(), createViteLogger(logger));
3229
+ viteLoader = VitePackageLoader.build(vite, { resolveFrom: [import.meta.url] });
3230
+ }
3231
+ const vetraProcessorFactory = dev ? (await import("@powerhousedao/vetra/processors")).processorFactory : void 0;
3232
+ if (!options.disableLocalPackages) packages.push(basePath);
3233
+ const packageLoaders = [];
3234
+ if (viteLoader) packageLoaders.push(viteLoader);
3235
+ else packageLoaders.push(new ImportPackageLoader());
3236
+ if (httpLoader) {
3237
+ packageLoaders.push(httpLoader);
3238
+ registryPackages?.split(",").forEach((p) => {
3239
+ const name = p.trim();
3240
+ if (!packages.includes(name)) packages.push(name);
3241
+ });
3242
+ }
3243
+ const apiLogger = logger.child(["reactor-api"]);
3244
+ let pgliteFactory;
3245
+ if (readModelPgliteDir && readModelPgliteMajor !== null) {
3246
+ const { PGlite: ReadModelPGlite } = await loadPGliteModule(readModelPgliteMajor);
3247
+ const durableFs = await loadDurableFsFactory(readModelPgliteMajor, logger);
3248
+ pgliteFactory = PGLITE_IN_MEMORY ? () => new ReadModelPGlite({ parsers: PGLITE_UTC_PARSERS }) : (connectionString) => new ReadModelPGlite({
3249
+ fs: durableFs(connectionString ?? readModelPgliteDir),
3250
+ parsers: PGLITE_UTC_PARSERS
3251
+ });
3252
+ }
3253
+ const api = await initializeAndStartAPI(initializeClient, {
3254
+ port: serverPort,
3255
+ dbPath: readModelPath,
3256
+ pgliteFactory,
3257
+ https: options.https,
3258
+ packageLoaders: packageLoaders.length > 0 ? packageLoaders : void 0,
3259
+ packages,
3260
+ processorConfig: options.processorConfig,
3261
+ processors: vetraProcessorFactory ? { "@powerhousedao/vetra": [vetraProcessorFactory] } : {},
3262
+ configFile: configPath,
3263
+ mcp: options.mcp ?? true,
3264
+ logger: apiLogger,
3265
+ enableDocumentModelSubgraphs: options.enableDocumentModelSubgraphs,
3266
+ renown: renownConfig,
3267
+ verifyCredential
3268
+ }, "switchboard");
3269
+ apiRef.current = api;
3270
+ if (renownConfig.source === "self") {
3271
+ const { graphqlManager: manager } = api;
3272
+ if (!manager.hasSubgraphHandler(RENOWN_READ_MODEL_SUBGRAPH)) {
3273
+ await abortBoot(api);
3274
+ throw new Error(`Renown credential verification is set to "self" (auth.renown.source or RENOWN_SOURCE) but no loaded package serves the "${RENOWN_READ_MODEL_SUBGRAPH}" subgraph. Install one (@powerhousedao/renown-package) or set RENOWN_SOURCE=remote.`);
3275
+ }
3276
+ localRenownRequest = (query, variables) => manager.executeSubgraphQuery(RENOWN_READ_MODEL_SUBGRAPH, query, variables);
3277
+ localCredentialCheck = createLocalCredentialVerifier(localRenownRequest, { onError: (error) => logger.error("Renown read model query failed: @error", error) });
3278
+ logger.info("Renown credentials will be verified against this switchboard's own renown read model");
3279
+ }
3280
+ registerAttachmentRoutes(api);
3281
+ const attachmentService = createRemoteAttachmentService(deriveAttachmentServiceConfig(options, serverPort, renown));
3282
+ if (process.env.SENTRY_DSN) api.httpAdapter.setupSentryErrorHandler(Sentry);
3283
+ const { client, graphqlManager, documentModelRegistry } = api;
3284
+ const lateSubgraphs = [];
3285
+ let workflows;
3286
+ let workflowsRetry;
3287
+ const composeWorkflows = () => composeWorkflowRuntime({
3288
+ reactorClient: client,
3289
+ clientModule: options.reactor ?? ownedReactorModule,
3290
+ relationalDb: api.relationalDb,
3291
+ secretsKeyFile: readModelPgliteDir === null ? false : void 0,
3292
+ storageId: readModelPgliteDir === null ? readModelPath : path$1.resolve(readModelPath),
3293
+ attachments: createAttachmentClient(api.attachments.service),
3294
+ attachmentAccess: api.attachmentAccess,
3295
+ webhooks: api.httpRoutes.scopeFor(WORKFLOW_PACKAGE_NAME).webhooks,
3296
+ http: api.httpRoutes.scopeFor(WORKFLOW_PACKAGE_NAME),
3297
+ authorizationService: api.authorizationService,
3298
+ pieces: api.packageManager,
3299
+ pieceRegistryUrl: registryUrl,
3300
+ models: workerModels,
3301
+ logger: logger.child(["workflow-runtime"]),
3302
+ exclusiveJournal: readModelPgliteDir !== null,
3303
+ onSingletonLost: workflowSingletonLossHandler(logger),
3304
+ telemetry: {
3305
+ tracer: trace.getTracer(WORKFLOW_TELEMETRY_SCOPE),
3306
+ meter: metrics.getMeter(WORKFLOW_TELEMETRY_SCOPE)
3307
+ }
3308
+ });
3309
+ const registerWorkflowSubgraph = (composed) => {
3310
+ const WorkflowRuntimeSubgraph = composed.subgraph;
3311
+ const workflowSubgraph = new WorkflowRuntimeSubgraph({
3312
+ reactorClient: client,
3313
+ http: graphqlManager.scopeForPackage(WORKFLOW_PACKAGE_NAME),
3314
+ relationalDb: api.relationalDb,
3315
+ analyticsStore: void 0,
3316
+ graphqlManager,
3317
+ syncManager: api.syncManager,
3318
+ authorizationService: graphqlManager.getAuthorizationService(),
3319
+ path: graphqlManager.getBasePath(),
3320
+ attachments: api.attachmentClientProvider
3321
+ });
3322
+ return graphqlManager.registerSubgraphInstance(workflowSubgraph, "graphql", false).catch((error) => {
3323
+ logger.error("Failed to register workflow-runtime subgraph: @error", error);
3324
+ });
3325
+ };
3326
+ if (workflowsEnabled) try {
3327
+ workflows = await composeWorkflows();
3328
+ } catch (error) {
3329
+ if (!isWorkflowSingletonConflict(error)) throw error;
3330
+ logger.warn(`Workflows are enabled but another live process ("${error.owner ?? "unknown"}") holds the workflow singleton until ${error.expiresAt ?? "unknown"}. This Switchboard has booted WITHOUT the workflow runtime: no trigger of any kind fires here, and the workflow GraphQL face is absent. Everything else serves normally. Stop the other owner, or set PH_WORKFLOWS_SINGLETON_OWNER to the same stable name on the slot that owns workflows. This Switchboard retries the claim and starts workflows once the lease comes free.`);
3331
+ workflowsRetry = retryWorkflowSingleton({
3332
+ compose: composeWorkflows,
3333
+ onComposed: async (composed) => {
3334
+ workflows = composed;
3335
+ await registerWorkflowSubgraph(composed);
3336
+ try {
3337
+ await graphqlManager.updateRouter();
3338
+ } catch (error) {
3339
+ logger.error("Mounting the late workflow-runtime subgraph failed: @error", error);
3340
+ }
3341
+ await composed.start();
3342
+ logger.info("Workflow runtime started");
3343
+ },
3344
+ logger
3345
+ });
3346
+ }
3347
+ if (workflows) {
3348
+ lateSubgraphs.push(registerWorkflowSubgraph(workflows));
3349
+ await workflows.start();
3350
+ logger.info("Workflow runtime started");
3351
+ api.inspection?.facts.setWorkflows(true);
3352
+ }
3353
+ let privacy;
3354
+ if (privacyConfig.enabled) {
3355
+ const signer = options.reactor ? options.privacy?.signer : options.privacy?.signer ?? renown?.signer;
3356
+ try {
3357
+ privacy = await startPrivacy({
3358
+ config: privacyConfig,
3359
+ reactorModule: (options.reactor ?? ownedReactorModule)?.reactorModule,
3360
+ signer,
3361
+ authorizationService: api.authorizationService,
3362
+ documentPermissionService: api.documentPermissionService,
3363
+ graphqlManager,
3364
+ reactorClient: client,
3365
+ logger: logger.child(["privacy"])
3366
+ });
3367
+ } catch (error) {
3368
+ await workflowsRetry?.stop();
3369
+ await workflows?.stop();
3370
+ await abortBoot(api);
3371
+ throw error;
3372
+ }
3373
+ }
3374
+ const shutdown = async () => {
3375
+ await privacy?.stop();
3376
+ await workflowsRetry?.stop();
3377
+ await workflows?.stop();
3378
+ await api.dispose();
3379
+ };
3380
+ apiRef.current = { dispose: shutdown };
3381
+ if (httpLoader) {
3382
+ const packageManagementService = new PackageManagementService({
3383
+ defaultRegistryUrl: registryUrl,
3384
+ httpLoader,
3385
+ documentModelRegistry,
3386
+ packageManager: api.packageManager
3387
+ });
3388
+ packageManagementService.setOnModelsChanged(() => {
3389
+ graphqlManager.regenerateDocumentModelSubgraphs().catch((error) => {
3390
+ logger.error("Failed to regenerate document model subgraphs: @error", error);
3391
+ });
3392
+ });
3393
+ const packagesSubgraph = new PackagesSubgraph({
3394
+ relationalDb: void 0,
3395
+ analyticsStore: void 0,
3396
+ reactorClient: client,
3397
+ graphqlManager,
3398
+ syncManager: api.syncManager,
3399
+ path: graphqlManager.getBasePath(),
3400
+ authorizationService: graphqlManager.getAuthorizationService(),
3401
+ packageManagementService,
3402
+ http: graphqlManager.scopeForPackage("@powerhousedao/switchboard"),
3403
+ attachments: api.attachmentClientProvider
3404
+ });
3405
+ lateSubgraphs.push(graphqlManager.registerSubgraphInstance(packagesSubgraph, "graphql", false).catch((error) => {
3406
+ logger.error("Failed to register packages subgraph: @error", error);
3407
+ }));
3408
+ }
3409
+ if (driveNodeView) {
3410
+ graphqlManager.setAdditionalContextFields({ readModel: driveNodeView });
3411
+ const authorizationService = graphqlManager.getAuthorizationService();
3412
+ const reactorDriveSubgraph = {
3413
+ name: "reactor-drive",
3414
+ path: graphqlManager.getBasePath(),
3415
+ resolvers: createReactorDriveResolvers({
3416
+ reactorClient: client,
3417
+ readModel: driveNodeView,
3418
+ hostCanRead: (documentId, address) => authorizationService.canRead(documentId, address)
3419
+ }),
3420
+ typeDefs: reactorDriveSubgraphTypeDefs,
3421
+ reactorClient: client,
3422
+ relationalDb: void 0
3423
+ };
3424
+ lateSubgraphs.push(graphqlManager.registerSubgraphInstance(reactorDriveSubgraph, "graphql", false).catch((error) => {
3425
+ logger.error("Failed to register reactor-drive subgraph: @error", error);
3426
+ }));
3427
+ }
3428
+ (async () => {
3429
+ await Promise.all(lateSubgraphs);
3430
+ try {
3431
+ await graphqlManager.updateRouter(true);
3432
+ } catch (error) {
3433
+ logger.error("Final router update before readiness failed: @error", error);
3434
+ }
3435
+ api.readiness.markReady();
3436
+ })();
3437
+ if (options.drive) {
3438
+ if (!renown) throw new Error("Cannot create default drive without Renown identity");
3439
+ if ((options.drive.documentType ?? "powerhouse/document-drive") === "powerhouse/reactor-drive") defaultDriveUrl = await addDefaultReactorDrive(client, options.drive, serverPort);
3440
+ else defaultDriveUrl = await addDefaultDrive(client, options.drive, serverPort);
3441
+ }
3442
+ if (vite) api.httpAdapter.mountRawMiddleware(vite.middlewares);
3443
+ if (remoteDrives.length > 0) for (const remoteDriveUrl of remoteDrives) {
3444
+ let driveId;
3445
+ try {
3446
+ const { syncManager } = api;
3447
+ const parsed = parseDriveUrl(remoteDriveUrl);
3448
+ driveId = parsed.driveId;
3449
+ const remoteName = `remote-drive-${driveId}-${crypto.randomUUID()}`;
3450
+ await syncManager.add(remoteName, DriveCollectionId.forDrive(driveId), {
3451
+ type: "gql",
3452
+ parameters: { url: parsed.graphqlEndpoint }
3453
+ });
3454
+ logger.debug("Remote drive @remoteDriveUrl synced", remoteDriveUrl);
3455
+ } catch (error) {
3456
+ if (error instanceof Error && error.message.includes("already exists")) {
3457
+ logger.debug("Remote drive already added: @remoteDriveUrl", remoteDriveUrl);
3458
+ driveId = remoteDriveUrl.split("/").pop();
3459
+ } else logger.error("Failed to connect to remote drive @remoteDriveUrl: @error", remoteDriveUrl, error);
3460
+ } finally {
3461
+ if (!defaultDriveUrl && driveId) defaultDriveUrl = `${options.https ? "https" : "http"}://localhost:${serverPort}/d/${driveId}`;
3462
+ }
3463
+ }
3464
+ return {
3465
+ defaultDriveUrl,
3466
+ api,
3467
+ reactor: client,
3468
+ attachmentService,
3469
+ attachmentReferenceProjection: api.attachmentReferenceProjection,
3470
+ get workflowTriggers() {
3471
+ return workflows?.triggers;
3472
+ },
3473
+ workflowsEnabled,
3474
+ modelManifest: () => workerModels?.modelManifest() ?? [],
3475
+ privacy: privacy ? { erasure: privacy.erasure } : void 0,
3476
+ mcpEnabled: options.mcp !== false,
3477
+ renown,
3478
+ port: serverPort,
3479
+ shutdown
3480
+ };
3481
+ }
3482
+ /**
3483
+ * Boot the switchboard HTTP/GraphQL/MCP stack on top of a reactor.
3484
+ *
3485
+ * If `options.reactor` is provided, the switchboard reuses it instead of
3486
+ * building its own — the caller then owns the reactor's lifecycle and is
3487
+ * responsible for invoking `SwitchboardReactor.shutdown()` from their own
3488
+ * teardown / SIGINT path. The switchboard will not reach into the caller's
3489
+ * reactor; killing the reactor alone leaves the api/GraphQL/MCP resources
3490
+ * dangling until the process exits.
3491
+ *
3492
+ * When `options.reactor` is omitted, the switchboard builds and owns the
3493
+ * reactor. `shutdown()` on the returned handle only drains the api (HTTP
3494
+ * server, GraphQL, MCP, attachments); the reactor itself is torn down by
3495
+ * its own signal handlers (`withSignalHandlers`), which call `kill()` and
3496
+ * trigger the `withShutdownHook` chain that disposes the api. Programmatic
3497
+ * full teardown isn't currently exposed — wire it via SIGINT/SIGTERM.
3498
+ */
3499
+ const startSwitchboard = async (options = {}) => {
3500
+ const requestedPort = options.port ?? DEFAULT_PORT;
3501
+ const logger = options.logger ?? defaultLogger;
3502
+ if (process.env.PYROSCOPE_SERVER_ADDRESS) await initProfilerFromEnv(process.env).catch((error) => logger.error("Error starting profiler: @error", error));
3503
+ const serverPort = await resolveServerPort(requestedPort, options.strictPort ?? false, logger);
3504
+ const featureFlags = await initFeatureFlags();
3505
+ const enableDocumentModelSubgraphs = await featureFlags.getBooleanValue(DOCUMENT_MODEL_SUBGRAPHS_ENABLED, options.enableDocumentModelSubgraphs ?? DOCUMENT_MODEL_SUBGRAPHS_ENABLED_DEFAULT);
3506
+ options.enableDocumentModelSubgraphs = enableDocumentModelSubgraphs;
3507
+ options.mcp = await resolveMcpEnabled({
3508
+ featureFlags,
3509
+ option: options.mcp
3510
+ });
3511
+ const configPathForFlags = resolveConfigPath(options.configFile);
3512
+ const workflowsEnabled = await resolveWorkflowsEnabled({
3513
+ featureFlags,
3514
+ override: options.workflows?.enabled,
3515
+ configEnabled: readConfigWorkflowsEnabled(configPathForFlags)
3516
+ });
3517
+ options.workflows = { enabled: workflowsEnabled };
3518
+ const renownConfig = resolveRenownConfig(getConfig(resolveConfigPath(options.configFile)).auth?.renown, process.env, logger);
3519
+ options.identity = {
3520
+ ...options.identity,
3521
+ baseUrl: options.identity?.baseUrl ?? renownConfig.url
3522
+ };
3523
+ logger.info("Feature flags: @flags", JSON.stringify({
3524
+ DOCUMENT_MODEL_SUBGRAPHS_ENABLED: enableDocumentModelSubgraphs,
3525
+ MCP_ENABLED: options.mcp,
3526
+ PH_WORKFLOWS_ENABLED: workflowsEnabled
3527
+ }, null, 2));
3528
+ let renown = null;
3529
+ try {
3530
+ renown = await initRenown(options.identity);
3531
+ } catch (e) {
3532
+ logger.warn("Failed to initialize ConnectCrypto: @error", e);
3533
+ if (options.identity.requireExisting) throw new Error("Identity required but failed to initialize. Run \"ph login\" first.", { cause: e });
3534
+ }
3535
+ try {
3536
+ return await initServer(serverPort, options, renown, renownConfig);
3537
+ } catch (e) {
3538
+ Sentry.captureException(e);
3539
+ if (StoredDocumentsRefusedError.isError(e)) logger.error(e.message);
3540
+ else logger.error("App crashed: @error", e);
3541
+ throw e;
3542
+ }
3543
+ };
3544
+ if (import.meta.main) await startSwitchboard({ fatalErrorShutdown: true });
3545
+ //#endregion
3546
+ export { StoredDocumentsRefusedError as a, initProfilerFromEnv as c, startSwitchboard as i, parseForcePgVersion as l, deriveAttachmentServiceConfig as n, resolveUnsupportedStoredDocuments as o, isPortAvailable as r, applySwitchboardReactorDefaults as s, createReactorKysely as t };
3547
+
3548
+ //# sourceMappingURL=server-J9fpd42v.mjs.map
3549
+ //# debugId=e3d937b6-2957-5fe0-8fc9-bf4fd0c18c93