@powerhousedao/switchboard 6.2.3-dev.4 → 6.2.3-dev.41

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