@powerhousedao/switchboard 6.2.3-dev.6 → 6.2.3-dev.60

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 (177) 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-inspection-enabled.test.d.ts +2 -0
  12. package/.tsbuild/test/boot-inspection-enabled.test.d.ts.map +1 -0
  13. package/.tsbuild/test/boot-mcp-enabled.test.d.ts +2 -0
  14. package/.tsbuild/test/boot-mcp-enabled.test.d.ts.map +1 -0
  15. package/.tsbuild/test/boot-privacy.test.d.ts +2 -0
  16. package/.tsbuild/test/boot-privacy.test.d.ts.map +1 -0
  17. package/.tsbuild/test/boot-unsupported-stored-documents.test.d.ts +2 -0
  18. package/.tsbuild/test/boot-unsupported-stored-documents.test.d.ts.map +1 -0
  19. package/.tsbuild/test/boot-without-renown.test.d.ts +2 -0
  20. package/.tsbuild/test/boot-without-renown.test.d.ts.map +1 -0
  21. package/.tsbuild/test/boot-without-require-signatures.test.d.ts +2 -0
  22. package/.tsbuild/test/boot-without-require-signatures.test.d.ts.map +1 -0
  23. package/.tsbuild/test/boot-worker-trust-policy.test.d.ts +2 -0
  24. package/.tsbuild/test/boot-worker-trust-policy.test.d.ts.map +1 -0
  25. package/.tsbuild/test/boot-workflow-singleton-conflict.test.d.ts +2 -0
  26. package/.tsbuild/test/boot-workflow-singleton-conflict.test.d.ts.map +1 -0
  27. package/.tsbuild/test/boot-workflow-singleton-retry.test.d.ts +2 -0
  28. package/.tsbuild/test/boot-workflow-singleton-retry.test.d.ts.map +1 -0
  29. package/.tsbuild/test/builder-defaults.test.d.ts +2 -0
  30. package/.tsbuild/test/builder-defaults.test.d.ts.map +1 -0
  31. package/.tsbuild/test/create-signature-policy.test.d.ts +2 -0
  32. package/.tsbuild/test/create-signature-policy.test.d.ts.map +1 -0
  33. package/.tsbuild/test/durable-node-fs-pg16.test.d.ts +2 -0
  34. package/.tsbuild/test/durable-node-fs-pg16.test.d.ts.map +1 -0
  35. package/.tsbuild/test/fatal-shutdown.test.d.ts +2 -0
  36. package/.tsbuild/test/fatal-shutdown.test.d.ts.map +1 -0
  37. package/.tsbuild/test/inspection-flag.test.d.ts +2 -0
  38. package/.tsbuild/test/inspection-flag.test.d.ts.map +1 -0
  39. package/.tsbuild/test/inspection-throttle.test.d.ts +2 -0
  40. package/.tsbuild/test/inspection-throttle.test.d.ts.map +1 -0
  41. package/.tsbuild/test/mcp-flag.test.d.ts +2 -0
  42. package/.tsbuild/test/mcp-flag.test.d.ts.map +1 -0
  43. package/.tsbuild/test/observability-signals.test.d.ts +2 -0
  44. package/.tsbuild/test/observability-signals.test.d.ts.map +1 -0
  45. package/.tsbuild/test/pglite-preflight.test.d.ts +2 -0
  46. package/.tsbuild/test/pglite-preflight.test.d.ts.map +1 -0
  47. package/.tsbuild/test/plugin-presence.test.d.ts +2 -0
  48. package/.tsbuild/test/plugin-presence.test.d.ts.map +1 -0
  49. package/.tsbuild/test/renown-trust-policy.test.d.ts +2 -0
  50. package/.tsbuild/test/renown-trust-policy.test.d.ts.map +1 -0
  51. package/.tsbuild/test/snapshot-writer.d.ts +18 -0
  52. package/.tsbuild/test/snapshot-writer.d.ts.map +1 -0
  53. package/.tsbuild/test/unsupported-stored-documents.test.d.ts +2 -0
  54. package/.tsbuild/test/unsupported-stored-documents.test.d.ts.map +1 -0
  55. package/.tsbuild/test/workflow/harness.d.ts +56 -0
  56. package/.tsbuild/test/workflow/harness.d.ts.map +1 -0
  57. package/.tsbuild/test/workflow/oauth.test.d.ts +2 -0
  58. package/.tsbuild/test/workflow/oauth.test.d.ts.map +1 -0
  59. package/.tsbuild/test/workflow/resolvers.test.d.ts +2 -0
  60. package/.tsbuild/test/workflow/resolvers.test.d.ts.map +1 -0
  61. package/.tsbuild/test/workflow/webhook-dedupe.test.d.ts +2 -0
  62. package/.tsbuild/test/workflow/webhook-dedupe.test.d.ts.map +1 -0
  63. package/.tsbuild/test/workflow/webhook-signed.test.d.ts +2 -0
  64. package/.tsbuild/test/workflow/webhook-signed.test.d.ts.map +1 -0
  65. package/.tsbuild/test/workflow/webhook-trigger-test.test.d.ts +2 -0
  66. package/.tsbuild/test/workflow/webhook-trigger-test.test.d.ts.map +1 -0
  67. package/.tsbuild/test/workflow/webhook-unsigned.test.d.ts +2 -0
  68. package/.tsbuild/test/workflow/webhook-unsigned.test.d.ts.map +1 -0
  69. package/.tsbuild/test/workflow-reactor-access.test.d.ts +2 -0
  70. package/.tsbuild/test/workflow-reactor-access.test.d.ts.map +1 -0
  71. package/.tsbuild/test/workflow-reactor-enforcement.test.d.ts +2 -0
  72. package/.tsbuild/test/workflow-reactor-enforcement.test.d.ts.map +1 -0
  73. package/.tsbuild/test/workflow-read-gate.test.d.ts +2 -0
  74. package/.tsbuild/test/workflow-read-gate.test.d.ts.map +1 -0
  75. package/.tsbuild/test/workflow-runtime.test.d.ts +2 -0
  76. package/.tsbuild/test/workflow-runtime.test.d.ts.map +1 -0
  77. package/.tsbuild/tsconfig.tsbuildinfo +1 -1
  78. package/.tsbuild/tsdown.config.d.ts.map +1 -1
  79. package/.tsbuild/vitest.config.d.ts.map +1 -1
  80. package/Auth.md +144 -2
  81. package/CHANGELOG.md +736 -0
  82. package/README.md +47 -10
  83. package/dist/index.d.mts +2 -1
  84. package/dist/index.mjs +50 -50
  85. package/dist/index.mjs.map +1 -1
  86. package/dist/install-packages.d.mts +2 -1
  87. package/dist/install-packages.mjs +2 -2
  88. package/dist/install-packages.mjs.map +1 -1
  89. package/dist/mcp-cNWW82NH.mjs +27 -0
  90. package/dist/mcp-cNWW82NH.mjs.map +1 -0
  91. package/dist/migrate.d.mts +2 -1
  92. package/dist/migrate.mjs +4 -3
  93. package/dist/migrate.mjs.map +1 -1
  94. package/dist/plugin-host-CGO4XZzK.d.mts +38 -0
  95. package/dist/plugin-host-CGO4XZzK.d.mts.map +1 -0
  96. package/dist/plugins/attachments.d.mts +23 -0
  97. package/dist/plugins/attachments.d.mts.map +1 -0
  98. package/dist/plugins/attachments.mjs +4 -0
  99. package/dist/plugins/mcp.d.mts +21 -0
  100. package/dist/plugins/mcp.d.mts.map +1 -0
  101. package/dist/plugins/mcp.mjs +4 -0
  102. package/dist/plugins/privacy.d.mts +12 -0
  103. package/dist/plugins/privacy.d.mts.map +1 -0
  104. package/dist/plugins/privacy.mjs +4 -0
  105. package/dist/plugins/workflows.d.mts +36 -0
  106. package/dist/plugins/workflows.d.mts.map +1 -0
  107. package/dist/plugins/workflows.mjs +4 -0
  108. package/dist/privacy-C8KVimKF.mjs +113 -0
  109. package/dist/privacy-C8KVimKF.mjs.map +1 -0
  110. package/dist/{server-CiKkVE6g.mjs → server-C9RQTWTA.mjs} +1132 -222
  111. package/dist/server-C9RQTWTA.mjs.map +1 -0
  112. package/dist/server.d.mts +158 -30
  113. package/dist/server.d.mts.map +1 -1
  114. package/dist/server.mjs +4 -5
  115. package/dist/{utils-Baw7rThP.mjs → utils-uaBlzyjS.mjs} +15 -9
  116. package/dist/utils-uaBlzyjS.mjs.map +1 -0
  117. package/dist/utils.d.mts +4 -5
  118. package/dist/utils.d.mts.map +1 -1
  119. package/dist/utils.mjs +3 -3
  120. package/dist/workflow-runtime-7GaJ13c9.d.mts +30 -0
  121. package/dist/workflow-runtime-7GaJ13c9.d.mts.map +1 -0
  122. package/dist/workflows-qKtqZhn3.mjs +1338 -0
  123. package/dist/workflows-qKtqZhn3.mjs.map +1 -0
  124. package/package.json +49 -20
  125. package/scripts/install-packages.sh +0 -0
  126. package/test/attachment-reference-read-model.test.ts +6 -1
  127. package/test/attachments/auth.test.ts +85 -0
  128. package/test/attachments/byte-grants.test.ts +290 -0
  129. package/test/attachments/byte-routes-read-gate.integration.test.ts +314 -0
  130. package/test/attachments/download-target.test.ts +201 -32
  131. package/test/attachments/index.test.ts +47 -4
  132. package/test/attachments/reserve-metadata-parity.test.ts +96 -0
  133. package/test/attachments/routes-integration.test.ts +60 -4
  134. package/test/attachments/routes.test.ts +271 -24
  135. package/test/attachments/service-config.test.ts +13 -3
  136. package/test/attachments/url-signer.test.ts +105 -0
  137. package/test/boot-create-signature-policy.test.ts +108 -0
  138. package/test/boot-inspection-enabled.test.ts +150 -0
  139. package/test/boot-mcp-enabled.test.ts +130 -0
  140. package/test/boot-privacy.test.ts +243 -0
  141. package/test/boot-unsupported-stored-documents.test.ts +213 -0
  142. package/test/boot-without-renown.test.ts +81 -0
  143. package/test/boot-without-require-signatures.test.ts +74 -0
  144. package/test/boot-worker-trust-policy.test.ts +90 -0
  145. package/test/boot-workflow-singleton-conflict.test.ts +107 -0
  146. package/test/boot-workflow-singleton-retry.test.ts +133 -0
  147. package/test/builder-defaults.test.ts +80 -0
  148. package/test/create-signature-policy.test.ts +69 -0
  149. package/test/durable-node-fs-pg16.test.ts +80 -0
  150. package/test/fatal-shutdown.test.ts +165 -0
  151. package/test/inspection-flag.test.ts +62 -0
  152. package/test/inspection-throttle.test.ts +23 -0
  153. package/test/mcp-flag.test.ts +56 -0
  154. package/test/observability-signals.test.ts +131 -0
  155. package/test/pglite-dialect.test.ts +217 -2
  156. package/test/pglite-preflight.test.ts +313 -0
  157. package/test/pglite-version.test.ts +9 -1
  158. package/test/plugin-presence.test.ts +269 -0
  159. package/test/renown-trust-policy.test.ts +315 -0
  160. package/test/snapshot-writer.ts +94 -0
  161. package/test/unsupported-stored-documents.test.ts +72 -0
  162. package/test/worker-pool.test.ts +27 -1
  163. package/test/workflow/harness.ts +289 -0
  164. package/test/workflow/oauth.test.ts +214 -0
  165. package/test/workflow/resolvers.test.ts +357 -0
  166. package/test/workflow/webhook-dedupe.test.ts +295 -0
  167. package/test/workflow/webhook-signed.test.ts +509 -0
  168. package/test/workflow/webhook-trigger-test.test.ts +82 -0
  169. package/test/workflow/webhook-unsigned.test.ts +345 -0
  170. package/test/workflow-reactor-access.test.ts +384 -0
  171. package/test/workflow-reactor-enforcement.test.ts +808 -0
  172. package/test/workflow-read-gate.test.ts +213 -0
  173. package/test/workflow-runtime.test.ts +1122 -0
  174. package/tsconfig.json +11 -2
  175. package/tsdown.config.ts +9 -1
  176. package/dist/server-CiKkVE6g.mjs.map +0 -1
  177. package/dist/utils-Baw7rThP.mjs.map +0 -1
@@ -1,34 +1,39 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="e2c62b7b-68fd-59c2-ab82-7d035e11698b")}catch(e){}}();
3
- import { n as addDefaultReactorDrive, r as isPostgresUrl, t as addDefaultDrive } from "./utils-Baw7rThP.mjs";
4
- import { register } from "node:module";
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]="df5034a8-237d-504e-8285-9d6b6c57229a")}catch(e){}}();
3
+ import { a as composeWorkflowRuntime, c as resolveWorkflowsEnabled, d as installFatalErrorShutdown, f as triggerFatalShutdown, i as assertWorkflowPackageLoadable, l as retryWorkflowSingleton, n as WORKFLOW_PACKAGE_NAME, o as isWorkflowSingletonConflict, r as WORKFLOW_TELEMETRY_SCOPE, s as modelManifestSource, t as workflowsPlugin, u as workflowSingletonLossHandler } from "./workflows-qKtqZhn3.mjs";
4
+ import { n as resolvePrivacy, r as startPrivacy, t as privacyPlugin } from "./privacy-C8KVimKF.mjs";
5
+ import { t as mcpPlugin } from "./mcp-cNWW82NH.mjs";
6
+ import { n as addDefaultReactorDrive, r as isPostgresUrl, t as addDefaultDrive } from "./utils-uaBlzyjS.mjs";
7
+ import { createRequire, register } from "node:module";
8
+ import { metrics, trace } from "@opentelemetry/api";
5
9
  import { ReactorInstrumentation } from "@powerhousedao/opentelemetry-instrumentation-reactor";
6
10
  import * as Sentry from "@sentry/node";
7
- import { childLogger, documentModelDocumentModelModule, setLogLevel } from "document-model";
11
+ import { childLogger, setLogLevel } from "document-model";
8
12
  import dotenv from "dotenv";
9
13
  import { getConfig } from "@powerhousedao/config/node";
10
14
  import { existsSync, promises, realpathSync } from "node:fs";
11
- import path from "node:path";
12
- import { AtomicNodeFs } from "@powerhousedao/pglite-fs";
13
- import { ChannelScheme, DriveCollectionId, EventBus, REACTOR_SCHEMA, ReactorBuilder, ReactorClientBuilder, createHybridProjectionCoordinatorFactory, instrumentPgPool, parseDriveUrl, supportsLiveReadModelRegistration } from "@powerhousedao/reactor";
14
- import { HttpPackageLoader, ImportPackageLoader, PGLITE_UTC_PARSERS, PackageManagementService, PackagesSubgraph, getUniqueDocumentModels, initializeAndStartAPI, resolveRenownConfig } from "@powerhousedao/reactor-api";
15
+ import path, { resolve } from "node:path";
16
+ import { createDurableNodeFs, preparePgliteDataDir, removeStalePgliteFiles, resolvePgliteFsync, syncTree } from "@powerhousedao/reactor-api/pglite-node";
17
+ import { ChannelScheme, DriveCollectionId, EventBus, HardenedPGliteDialect, IN_MEMORY_PGLITE_STORAGE_FACTS, PGLITE_PATH_STORAGE_FACTS, POSTGRES_STORAGE_FACTS, REACTOR_SCHEMA, ReactorBuilder, ReactorClientBuilder, UnsupportedStoredProtocolError, createHybridProjectionCoordinatorFactory, instrumentPgPool, parseDriveUrl, supportsLiveReadModelRegistration } from "@powerhousedao/reactor";
18
+ import { HttpPackageLoader, ImportPackageLoader, PGLITE_UTC_PARSERS, PackageManagementService, PackagesSubgraph, baseDocumentModels, getUniqueDocumentModels, initializeAndStartAPI, reportFailure, resolveRenownConfig, runDetached } from "@powerhousedao/reactor-api";
15
19
  import { httpsHooksPath } from "@powerhousedao/reactor-api/https-hooks";
16
- import { AttachmentAlreadyExists, AttachmentNotFound, AttachmentPending, AttachmentReferenceReadModel, AttachmentSchemaCompiler, HashMismatch, InvalidAttachmentRef, ReservationNotFound, SizeMismatch, UploadTooLarge, createRef, createRemoteAttachmentService, parseAttachmentDownloadTarget } from "@powerhousedao/reactor-attachments";
17
- import { DriveNodeView, NodeProcessor, ReactorDriveClient, createReactorDriveResolvers, reactorDriveDocumentModelModule, reactorDriveSubgraphTypeDefs } from "@powerhousedao/reactor-drive";
18
- import { DEFAULT_RENOWN_URL, NodeKeyStorage, RENOWN_READ_MODEL_SUBGRAPH, RenownBuilder, RenownCryptoBuilder, createLocalCredentialVerifier, createSignatureVerifier } from "@renown/sdk/node";
20
+ import { AttachmentAlreadyExists, AttachmentNotFound, AttachmentPending, AttachmentReferenceReadModel, AttachmentSchemaCompiler, HashMismatch, InvalidAttachmentMetadata, InvalidAttachmentRef, ReservationNotFound, SizeMismatch, UploadTooLarge, createRef, createRemoteAttachmentService, parseAttachmentDownloadTarget, validateReserveMetadata } from "@powerhousedao/reactor-attachments";
21
+ import { createAttachmentClient } from "@powerhousedao/reactor-attachments/client";
22
+ import { DriveNodeView, NodeProcessor, REACTOR_DRIVE_SUBGRAPH_NAME, ReactorDriveClient, createReactorDriveResolvers, reactorDriveSubgraphTypeDefs } from "@powerhousedao/reactor-drive";
23
+ import { DEFAULT_KEYPAIR_PATH, DEFAULT_RENOWN_URL, NodeKeyStorage, RENOWN_READ_MODEL_SUBGRAPH, RenownBuilder, RenownCryptoBuilder, createLocalCredentialVerifier, createRenownTrustPolicy, resolveSwitchboardEndpoint } from "@renown/sdk/node";
19
24
  import { Kysely, PostgresDialect } from "kysely";
20
25
  import net from "node:net";
21
26
  import path$1 from "path";
22
27
  import { Pool } from "pg";
23
28
  import { Readable } from "node:stream";
24
- import { ReactorGroupV1 } from "@powerhousedao/reactor-group";
25
- import { driveDocumentModelModule } from "@powerhousedao/shared/document-drive";
29
+ import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
30
+ import { mergeContributions, resolveOrder, runObserveHook, runObserveHookSequential, runTransformHook } from "@powerhousedao/host-core";
31
+ import { DEFAULT_SIGNATURE_POLICY, isSignaturePolicy } from "@powerhousedao/shared/document-model";
26
32
  import { readFile } from "node:fs/promises";
27
33
  import os from "node:os";
28
- import { fileURLToPath } from "node:url";
34
+ import { fileURLToPath, pathToFileURL } from "node:url";
29
35
  import { EnvVarProvider } from "@openfeature/env-var-provider";
30
36
  import { OpenFeature } from "@openfeature/server-sdk";
31
- import { PGliteDialect } from "kysely-pglite-dialect";
32
37
  //#region src/pglite-version.ts
33
38
  const SUPPORTED_PG_MAJORS = [16, 17];
34
39
  async function readPgVersionFile(dataDir) {
@@ -59,11 +64,63 @@ async function loadPGliteModule(major) {
59
64
  if (major === 16) return await import("pglite-legacy-02");
60
65
  return import("@electric-sql/pglite");
61
66
  }
67
+ /** The stock NodeFS class of the PGlite module that opens `major` dirs. */
68
+ async function loadNodeFsClass(major) {
69
+ if (major === 16) return (await import("pglite-legacy-02/nodefs")).NodeFS;
70
+ return (await import("@electric-sql/pglite/nodefs")).NodeFS;
71
+ }
72
+ /** Opens a converted dir over stock NodeFS so the conversion can check it. */
73
+ async function openForVerify(major, dataDir) {
74
+ if (!isSupportedMajor(major)) throw new Error(`Cannot verify PGlite data dir ${dataDir}: PG_VERSION=${major} is not supported (expected one of ${SUPPORTED_PG_MAJORS.join(", ")})`);
75
+ const [{ PGlite }, NodeFS] = await Promise.all([loadPGliteModule(major), loadNodeFsClass(major)]);
76
+ const pg = new PGlite({ fs: new NodeFS(dataDir) });
77
+ await pg.waitReady;
78
+ return pg;
79
+ }
62
80
  async function loadPgDump(major) {
63
81
  if (major === 16) return (await import("pglite-tools-legacy-02/pg_dump")).pgDump;
64
82
  return (await import("@electric-sql/pglite-tools/pg_dump")).pgDump;
65
83
  }
66
84
  //#endregion
85
+ //#region src/profiler.ts
86
+ let started = false;
87
+ async function initProfilerFromEnv(env) {
88
+ if (started || !env.PYROSCOPE_SERVER_ADDRESS) return;
89
+ started = true;
90
+ const { PYROSCOPE_SERVER_ADDRESS: serverAddress, PYROSCOPE_APPLICATION_NAME: appName, PYROSCOPE_USER: basicAuthUser, PYROSCOPE_PASSWORD: basicAuthPassword, PYROSCOPE_WALL_ENABLED: wallEnabled, PYROSCOPE_HEAP_ENABLED: heapEnabled } = env;
91
+ return initProfiler({
92
+ serverAddress,
93
+ appName,
94
+ basicAuthUser,
95
+ basicAuthPassword,
96
+ wall: {
97
+ samplingDurationMs: 1e4,
98
+ samplingIntervalMicros: 1e4,
99
+ collectCpuTime: true
100
+ },
101
+ heap: {
102
+ samplingIntervalBytes: 524288,
103
+ stackDepth: 64
104
+ }
105
+ }, {
106
+ wallEnabled: wallEnabled !== "false",
107
+ heapEnabled: heapEnabled === "true"
108
+ });
109
+ }
110
+ async function initProfiler(options, flags = {
111
+ wallEnabled: true,
112
+ heapEnabled: false
113
+ }) {
114
+ console.log("Initializing Pyroscope profiler at:", options?.serverAddress);
115
+ console.log(" Wall profiling:", flags.wallEnabled ? "enabled" : "disabled");
116
+ console.log(" Heap profiling:", flags.heapEnabled ? "enabled" : "disabled");
117
+ const { default: Pyroscope } = await import("@pyroscope/nodejs");
118
+ Pyroscope.init(options);
119
+ if (flags.wallEnabled) Pyroscope.startWallProfiling();
120
+ Pyroscope.startCpuProfiling();
121
+ if (flags.heapEnabled) Pyroscope.startHeapProfiling();
122
+ }
123
+ //#endregion
67
124
  //#region src/attachments/auth.ts
68
125
  const ANONYMOUS_ACTOR = {
69
126
  user: void 0,
@@ -74,7 +131,15 @@ const ANONYMOUS_ACTOR = {
74
131
  * enabled, the request must carry a verifiable Bearer token. The handler always
75
132
  * receives an actor context: the verified bearer user when auth is enabled, or
76
133
  * the anonymous context when it is disabled. With `allowAnonymous`, a missing
77
- * bearer yields an anonymous actor with `authEnabled: true` instead of a 401.
134
+ * bearer yields an anonymous actor with `authEnabled: true` instead of a 401 —
135
+ * unless `requireAuthenticatedCaller` says the deployment refuses anonymous
136
+ * callers outright, which overrides it.
137
+ *
138
+ * With no `authService` there is no bearer to read and every caller is
139
+ * anonymous, so nothing is refused here. That combination cannot carry the
140
+ * floor: `assertRequireAuthenticatedCallerAllowed` refuses to boot with
141
+ * `REQUIRE_AUTHENTICATED_CALLER` set and no identity resolution, and identity
142
+ * resolution is what builds the service.
78
143
  */
79
144
  function requireAuth(authService, handler, options) {
80
145
  if (!authService) return (req, res, body) => handler(req, res, body, ANONYMOUS_ACTOR);
@@ -96,11 +161,13 @@ function requireAuth(authService, handler, options) {
96
161
  res.end(body);
97
162
  return;
98
163
  }
99
- if (result.auth_enabled && !result.user && !options?.allowAnonymous) {
100
- res.statusCode = 401;
101
- res.setHeader("Content-Type", "application/json");
102
- res.end(JSON.stringify({ error: "Authentication required" }));
103
- return;
164
+ if (!result.user) {
165
+ if (options?.requireAuthenticatedCaller === true || result.auth_enabled && !options?.allowAnonymous) {
166
+ res.statusCode = 401;
167
+ res.setHeader("Content-Type", "application/json");
168
+ res.end(JSON.stringify({ error: "Authentication required" }));
169
+ return;
170
+ }
104
171
  }
105
172
  await handler(req, res, body, {
106
173
  user: result.user,
@@ -118,20 +185,25 @@ function requireAuth(authService, handler, options) {
118
185
  * wrapping you must call `api.httpAdapter.mountNodeRoute` directly.
119
186
  *
120
187
  * `allowAnonymous` is reserved for routes whose handlers make a per-document
121
- * authorization decision themselves; identity-only routes must not use it.
188
+ * authorization decision themselves; identity-only routes must not use it. It
189
+ * is also not the last word: a deployment that refuses anonymous callers
190
+ * (`REQUIRE_AUTHENTICATED_CALLER`) refuses them here too, because these routes
191
+ * are mounted on the HTTP adapter and never reach the fetch chain that carries
192
+ * that floor for GraphQL. The flag is read from the API, so every route
193
+ * mounted through here inherits it without each one remembering to.
122
194
  */
123
195
  function mountAuthenticatedNodeRoute(api, method, path, handler, options) {
124
- api.httpAdapter.mountNodeRoute(method, path, requireAuth(api.authService, handler, options));
196
+ const { rawBody, ...authOptions } = options ?? {};
197
+ api.httpAdapter.mountNodeRoute(method, path, requireAuth(api.authService, handler, {
198
+ ...authOptions,
199
+ requireAuthenticatedCaller: api.requireAuthenticatedCaller
200
+ }), { rawBody: rawBody ?? false });
125
201
  }
126
202
  //#endregion
127
203
  //#region src/attachments/routes.ts
128
- const logger$1 = childLogger(["switchboard", "attachments"]);
204
+ const logger$2 = childLogger(["switchboard", "attachments"]);
129
205
  const RETRY_AFTER_SECONDS = 5;
130
206
  const HASH_PATTERN = /^[a-f0-9]{64}$/i;
131
- const CONTROL_CHARS = /[\x00-\x1f\x7f]/;
132
- const MIME_TYPE_PATTERN = /^[!#$%&'*+\-.^_`|~\w]+\/[!#$%&'*+\-.^_`|~\w]+(?:\s*;\s*[!#$%&'*+\-.^_`|~\w]+=(?:[!#$%&'*+\-.^_`|~\w]+|"(?:[^"\\\r\n]|\\[^\r\n])*"))*$/;
133
- const MAX_FILENAME_LEN = 255;
134
- const MAX_MIMETYPE_LEN = 255;
135
207
  function sendJson(res, status, body) {
136
208
  res.statusCode = status;
137
209
  res.setHeader("Content-Type", "application/json");
@@ -150,7 +222,7 @@ function statusForError(err) {
150
222
  function sendErrorFromException(res, err) {
151
223
  const status = statusForError(err);
152
224
  if (status >= 500) {
153
- logger$1.error("Attachment route error: @error", err);
225
+ logger$2.error("Attachment route error: @error", err);
154
226
  sendError(res, status, "Internal error");
155
227
  return;
156
228
  }
@@ -168,27 +240,34 @@ async function readJsonBody(req, body) {
168
240
  function parseReserveOptions(input) {
169
241
  if (input === null || typeof input !== "object") return null;
170
242
  const obj = input;
171
- if (typeof obj.mimeType !== "string" || obj.mimeType.length === 0 || obj.mimeType.length > MAX_MIMETYPE_LEN || !MIME_TYPE_PATTERN.test(obj.mimeType)) return null;
172
- if (typeof obj.fileName !== "string" || obj.fileName.length === 0 || obj.fileName.length > MAX_FILENAME_LEN || CONTROL_CHARS.test(obj.fileName)) return null;
173
- let extension = null;
174
- if (typeof obj.extension === "string") {
175
- if (obj.extension.length === 0 || /[\\/]/.test(obj.extension)) return null;
176
- extension = obj.extension;
177
- } else if (obj.extension !== void 0 && obj.extension !== null) return null;
243
+ const { mimeType, fileName } = obj;
244
+ const extension = obj.extension ?? null;
245
+ try {
246
+ validateReserveMetadata({
247
+ mimeType,
248
+ fileName,
249
+ extension
250
+ });
251
+ } catch (err) {
252
+ if (err instanceof InvalidAttachmentMetadata) return null;
253
+ throw err;
254
+ }
255
+ if (typeof mimeType !== "string" || typeof fileName !== "string") return null;
256
+ if (extension !== null && typeof extension !== "string") return null;
178
257
  if (obj.clientHash !== void 0) {
179
258
  if (typeof obj.clientHash !== "string" || !HASH_PATTERN.test(obj.clientHash)) return null;
180
259
  if (typeof obj.sizeBytes !== "number" || !Number.isInteger(obj.sizeBytes) || obj.sizeBytes <= 0 || !Number.isSafeInteger(obj.sizeBytes)) return null;
181
260
  return {
182
- mimeType: obj.mimeType,
183
- fileName: obj.fileName,
261
+ mimeType,
262
+ fileName,
184
263
  extension,
185
264
  clientHash: obj.clientHash.toLowerCase(),
186
265
  sizeBytes: obj.sizeBytes
187
266
  };
188
267
  }
189
268
  return {
190
- mimeType: obj.mimeType,
191
- fileName: obj.fileName,
269
+ mimeType,
270
+ fileName,
192
271
  extension
193
272
  };
194
273
  }
@@ -279,24 +358,27 @@ function makeUploadHandler(attachments) {
279
358
  }
280
359
  };
281
360
  }
282
- function makeDownloadHandler(attachments) {
283
- return async (req, res) => {
361
+ function makeDownloadHandler(attachments, attachmentAccess, urlSigner) {
362
+ return async (req, res, _body, actor) => {
284
363
  const hash = extractParam(req, "hash");
285
364
  if (!hash || !HASH_PATTERN.test(hash)) {
286
365
  sendError(res, 400, "Invalid attachment hash");
287
366
  return;
288
367
  }
368
+ const canonicalHash = hash.toLowerCase();
369
+ const grant = await resolveByteGrant(req, canonicalHash, actor, attachmentAccess, urlSigner);
370
+ if (!admitGrant(res, grant)) return;
289
371
  const controller = new AbortController();
290
372
  req.once("close", () => controller.abort());
291
- const canonicalHash = hash.toLowerCase();
292
373
  let response;
293
374
  try {
294
- response = await attachments.store.get(canonicalHash, controller.signal);
375
+ response = await attachments.store.get(canonicalHash, controller.signal, grant.documentId);
295
376
  } catch (err) {
296
377
  if (err instanceof AttachmentPending) {
297
378
  res.statusCode = 202;
379
+ res.setHeader("Cache-Control", "private");
298
380
  res.setHeader("Retry-After", String(RETRY_AFTER_SECONDS));
299
- res.setHeader("Attachment-Pending", JSON.stringify({
381
+ res.setHeader("Attachment-Pending", buildPendingHeader({
300
382
  expiresAtUtc: err.expiresAtUtc,
301
383
  ...err.metadata ?? {}
302
384
  }));
@@ -308,15 +390,41 @@ function makeDownloadHandler(attachments) {
308
390
  }
309
391
  const { header, body } = response;
310
392
  res.statusCode = 200;
393
+ res.setHeader("Cache-Control", "private");
311
394
  res.setHeader("Content-Type", header.mimeType);
312
395
  res.setHeader("Content-Length", String(header.sizeBytes));
313
396
  res.setHeader("Content-Disposition", buildContentDisposition(header.fileName));
314
397
  res.setHeader("Attachment-Metadata", buildMetadataHeader(header));
315
- Readable.fromWeb(body).pipe(res);
398
+ const source = Readable.fromWeb(body);
399
+ source.once("error", (err) => handleDownloadStreamError(res, hash, err));
400
+ source.pipe(res);
316
401
  };
317
402
  }
403
+ function handleDownloadStreamError(res, hash, err) {
404
+ if (res.headersSent) {
405
+ logger$2.error("Attachment stream failed mid-download: @error", err);
406
+ res.destroy();
407
+ return;
408
+ }
409
+ res.removeHeader("Content-Length");
410
+ res.removeHeader("Content-Disposition");
411
+ res.removeHeader("Attachment-Metadata");
412
+ if (err?.code === "ENOENT") {
413
+ logger$2.warn("Attachment @hash is recorded as available but its blob is missing", hash);
414
+ sendJson(res, 404, ATTACHMENT_NOT_FOUND_BODY);
415
+ return;
416
+ }
417
+ logger$2.error("Attachment stream failed before sending: @error", err);
418
+ sendError(res, 500, "Internal error");
419
+ }
420
+ function toAsciiJson(value) {
421
+ return JSON.stringify(value).replace(/[\u007f-\uffff]/g, (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`);
422
+ }
423
+ function buildPendingHeader(pending) {
424
+ return toAsciiJson(pending);
425
+ }
318
426
  function buildMetadataHeader(header) {
319
- return JSON.stringify({
427
+ return toAsciiJson({
320
428
  mimeType: header.mimeType,
321
429
  fileName: header.fileName,
322
430
  sizeBytes: header.sizeBytes,
@@ -325,14 +433,15 @@ function buildMetadataHeader(header) {
325
433
  lastAccessedAtUtc: header.lastAccessedAtUtc
326
434
  });
327
435
  }
328
- function makeStatHandler(attachments) {
329
- return async (req, res) => {
436
+ function makeStatHandler(attachments, attachmentAccess, urlSigner) {
437
+ return async (req, res, _body, actor) => {
330
438
  const hash = extractParam(req, "hash");
331
439
  if (!hash || !HASH_PATTERN.test(hash)) {
332
440
  sendError(res, 400, "Invalid attachment hash");
333
441
  return;
334
442
  }
335
443
  const canonicalHash = hash.toLowerCase();
444
+ if (!admitGrant(res, await resolveByteGrant(req, canonicalHash, actor, attachmentAccess, urlSigner))) return;
336
445
  let header;
337
446
  try {
338
447
  header = await attachments.store.stat(canonicalHash);
@@ -340,10 +449,11 @@ function makeStatHandler(attachments) {
340
449
  sendErrorFromException(res, err);
341
450
  return;
342
451
  }
452
+ res.setHeader("Cache-Control", "private");
343
453
  if (header.status === "pending") {
344
454
  res.statusCode = 202;
345
455
  res.setHeader("Retry-After", String(RETRY_AFTER_SECONDS));
346
- res.setHeader("Attachment-Pending", JSON.stringify({
456
+ res.setHeader("Attachment-Pending", buildPendingHeader({
347
457
  expiresAtUtc: header.expiresAtUtc,
348
458
  mimeType: header.mimeType,
349
459
  fileName: header.fileName,
@@ -395,7 +505,37 @@ function extractParam(req, name) {
395
505
  }
396
506
  const MAX_DOCUMENT_ID_LEN = 512;
397
507
  const ATTACHMENT_NOT_FOUND_BODY = { error: "Attachment not found" };
398
- const MAX_DOWNLOAD_TARGET_TTL_SECONDS = 10080 * 60;
508
+ const MAX_DOWNLOAD_TARGET_TTL_SECONDS = 604800;
509
+ /**
510
+ * How long a download target may live, by default.
511
+ *
512
+ * The authorization behind a presigned URL is decided once, when it is issued,
513
+ * and the URL keeps working until it expires however the document's policy
514
+ * changes in between. A week of that is a revocation that does not revoke: an
515
+ * account deactivated, a company reassigned or a group left, and the bytes stay
516
+ * fetchable by anyone holding the link. Minutes are enough to open a file;
517
+ * days are only enough to lose control of it.
518
+ *
519
+ * A deployment that needs longer sets ATTACHMENT_DOWNLOAD_TARGET_MAX_TTL_SECONDS,
520
+ * still bounded by the signing ceiling above.
521
+ */
522
+ const DEFAULT_DOWNLOAD_TARGET_TTL_SECONDS = 300;
523
+ /**
524
+ * The ceiling in force, read per call so a deployment can set it without the
525
+ * value being frozen at import — which is also what lets a test cover it.
526
+ * Anything unparseable falls back to the default rather than to the maximum:
527
+ * a typo must not quietly widen the window it was meant to narrow.
528
+ */
529
+ function downloadTargetTtlCapSeconds() {
530
+ const configured = process.env.ATTACHMENT_DOWNLOAD_TARGET_MAX_TTL_SECONDS;
531
+ if (configured === void 0) return DEFAULT_DOWNLOAD_TARGET_TTL_SECONDS;
532
+ const parsed = Number(configured);
533
+ if (!Number.isInteger(parsed) || parsed <= 0) {
534
+ 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}`);
535
+ return DEFAULT_DOWNLOAD_TARGET_TTL_SECONDS;
536
+ }
537
+ return Math.min(parsed, MAX_DOWNLOAD_TARGET_TTL_SECONDS);
538
+ }
399
539
  /**
400
540
  * Returns the single `documentId` query value, or null when it is missing,
401
541
  * duplicated, blank, or oversized. Validation happens before authorization so
@@ -416,29 +556,95 @@ function extractSingleDocumentId(req) {
416
556
  return value;
417
557
  }
418
558
  /**
419
- * Returns the requested target TTL in seconds: undefined when absent,
420
- * "invalid" when malformed (duplicated, non-integer, or non-positive), and
421
- * otherwise the value clamped to the presigning ceiling.
559
+ * Returns the target TTL in seconds, or "invalid" when the caller's own value
560
+ * is malformed (duplicated, non-integer, or non-positive).
561
+ *
562
+ * The cap applies whether or not the caller asked for a lifetime: omitting
563
+ * `expiresIn` used to fall through to whatever the storage backend was
564
+ * configured with, which would make the ceiling something a client opts out of
565
+ * by saying nothing.
422
566
  */
423
567
  function extractExpiresIn(req) {
424
- if (!req.url) return void 0;
568
+ const cap = downloadTargetTtlCapSeconds();
569
+ if (!req.url) return cap;
425
570
  let url;
426
571
  try {
427
572
  url = new URL(req.url, "http://switchboard.invalid");
428
573
  } catch {
429
- return;
574
+ return cap;
430
575
  }
431
576
  const values = url.searchParams.getAll("expiresIn");
432
- if (values.length === 0) return void 0;
577
+ if (values.length === 0) return cap;
433
578
  if (values.length > 1) return "invalid";
434
579
  const parsed = Number(values[0]);
435
580
  if (!Number.isInteger(parsed) || parsed <= 0) return "invalid";
436
- return Math.min(parsed, MAX_DOWNLOAD_TARGET_TTL_SECONDS);
581
+ return Math.min(parsed, cap);
582
+ }
583
+ function singleQueryValue(params, name) {
584
+ const values = params.getAll(name);
585
+ return values.length === 1 ? values[0] : null;
586
+ }
587
+ /**
588
+ * Byte routes serve only under a grant: a signed URL minted by the
589
+ * download-target route, or a documentId the caller may read the attachment
590
+ * through. A signed request is judged by its signature alone.
591
+ */
592
+ async function resolveByteGrant(req, hash, actor, attachmentAccess, urlSigner) {
593
+ let params;
594
+ try {
595
+ params = new URL(req.url ?? "", "http://switchboard.invalid").searchParams;
596
+ } catch {
597
+ return { kind: "denied" };
598
+ }
599
+ const documentId = extractSingleDocumentId(req);
600
+ if (documentId === null) return { kind: "denied" };
601
+ if (params.has("signature") || params.has("expires")) {
602
+ const signature = singleQueryValue(params, "signature");
603
+ const expires = singleQueryValue(params, "expires");
604
+ if (!urlSigner || signature === null || expires === null) return { kind: "denied" };
605
+ return urlSigner.verify(hash, documentId, expires, signature) ? {
606
+ kind: "granted",
607
+ documentId
608
+ } : { kind: "denied" };
609
+ }
610
+ let decision;
611
+ try {
612
+ decision = await attachmentAccess.canReadAttachment({
613
+ documentId,
614
+ attachmentRef: createRef(hash),
615
+ userAddress: actor?.user?.address,
616
+ appKey: actor?.user?.appKey
617
+ });
618
+ } catch (err) {
619
+ logger$2.error("Attachment access decision failed: @error", err);
620
+ return { kind: "error" };
621
+ }
622
+ if (decision.kind === "projection-unavailable") return { kind: "unavailable" };
623
+ if (decision.kind === "denied") return { kind: "denied" };
624
+ return {
625
+ kind: "granted",
626
+ documentId: decision.documentId
627
+ };
628
+ }
629
+ /** Answers a refused grant; true when the request may proceed. */
630
+ function admitGrant(res, grant) {
631
+ switch (grant.kind) {
632
+ case "granted": return true;
633
+ case "denied":
634
+ sendJson(res, 404, ATTACHMENT_NOT_FOUND_BODY);
635
+ return false;
636
+ case "unavailable":
637
+ sendError(res, 503, "Attachment downloads are temporarily unavailable");
638
+ return false;
639
+ case "error":
640
+ sendError(res, 500, "Internal error");
641
+ return false;
642
+ }
437
643
  }
438
644
  /**
439
645
  * Base URL of this Switchboard as seen by the caller, used to build
440
- * filesystem `switchboard` download targets that point back at the existing
441
- * authenticated byte route.
646
+ * filesystem `switchboard` download targets that point back at the signed
647
+ * byte route.
442
648
  */
443
649
  function requestBaseUrl(req) {
444
650
  const forwardedProto = req.headers["x-forwarded-proto"];
@@ -448,7 +654,7 @@ function requestBaseUrl(req) {
448
654
  if (!host) return null;
449
655
  return `${proto}://${host}`;
450
656
  }
451
- function makeDownloadTargetHandler(attachments, attachmentAccess) {
657
+ function makeDownloadTargetHandler(attachments, attachmentAccess, urlSigner) {
452
658
  return async (req, res, _body, actor) => {
453
659
  res.setHeader("Cache-Control", "no-store");
454
660
  const hash = extractParam(req, "hash");
@@ -472,10 +678,11 @@ function makeDownloadTargetHandler(attachments, attachmentAccess) {
472
678
  decision = await attachmentAccess.canReadAttachment({
473
679
  documentId,
474
680
  attachmentRef: createRef(canonicalHash),
475
- userAddress: actor?.user?.address
681
+ userAddress: actor?.user?.address,
682
+ appKey: actor?.user?.appKey
476
683
  });
477
684
  } catch (err) {
478
- logger$1.error("Attachment access decision failed: @error", err);
685
+ logger$2.error("Attachment access decision failed: @error", err);
479
686
  sendError(res, 500, "Internal error");
480
687
  return;
481
688
  }
@@ -495,7 +702,7 @@ function makeDownloadTargetHandler(attachments, attachmentAccess) {
495
702
  sendJson(res, 404, ATTACHMENT_NOT_FOUND_BODY);
496
703
  return;
497
704
  }
498
- logger$1.error("Attachment metadata lookup failed: @error", err);
705
+ logger$2.error("Attachment metadata lookup failed: @error", err);
499
706
  sendError(res, 500, "Internal error");
500
707
  return;
501
708
  }
@@ -511,17 +718,23 @@ function makeDownloadTargetHandler(attachments, attachmentAccess) {
511
718
  return;
512
719
  }
513
720
  else {
721
+ if (!urlSigner) {
722
+ sendError(res, 503, "Attachment download signing is not configured");
723
+ return;
724
+ }
514
725
  const base = requestBaseUrl(req);
515
726
  if (!base) {
516
727
  sendError(res, 500, "Internal error");
517
728
  return;
518
729
  }
730
+ const signed = urlSigner.sign(canonicalHash, decision.documentId, expiresIn);
519
731
  try {
520
732
  target = parseAttachmentDownloadTarget({
521
733
  kind: "switchboard",
522
734
  method: "GET",
523
- url: `${base}/attachments/${canonicalHash}`,
524
- headers: {}
735
+ url: `${base}/attachments/${canonicalHash}?${signed.query}`,
736
+ headers: {},
737
+ expiresAtUtc: signed.expiresAtUtc
525
738
  });
526
739
  } catch {
527
740
  sendError(res, 500, "Internal error");
@@ -532,16 +745,82 @@ function makeDownloadTargetHandler(attachments, attachmentAccess) {
532
745
  };
533
746
  }
534
747
  //#endregion
748
+ //#region src/attachments/url-signer.ts
749
+ const ATTACHMENT_URL_SIGNING_SECRET_ENV = "PH_ATTACHMENT_URL_SIGNING_SECRET";
750
+ const MIN_SECRET_LENGTH = 32;
751
+ const EXPIRES_PATTERN = /^[1-9]\d{0,15}$/;
752
+ const SIGNATURE_PATTERN = /^[A-Za-z0-9_-]{43}$/;
753
+ var AttachmentUrlSigner = class {
754
+ secret;
755
+ now;
756
+ constructor(secret, now = Date.now) {
757
+ this.secret = secret;
758
+ this.now = now;
759
+ }
760
+ sign(hash, documentId, ttlSeconds) {
761
+ const expires = Math.floor(this.now() / 1e3) + ttlSeconds;
762
+ return {
763
+ query: new URLSearchParams({
764
+ documentId,
765
+ expires: String(expires),
766
+ signature: this.mac(hash, documentId, String(expires))
767
+ }).toString(),
768
+ expiresAtUtc: (/* @__PURE__ */ new Date(expires * 1e3)).toISOString()
769
+ };
770
+ }
771
+ verify(hash, documentId, expires, signature) {
772
+ if (!EXPIRES_PATTERN.test(expires) || !SIGNATURE_PATTERN.test(signature)) return false;
773
+ if (Number(expires) * 1e3 <= this.now()) return false;
774
+ const expected = Buffer.from(this.mac(hash, documentId, expires));
775
+ const presented = Buffer.from(signature);
776
+ return expected.length === presented.length && timingSafeEqual(expected, presented);
777
+ }
778
+ mac(hash, documentId, expires) {
779
+ return createHmac("sha256", this.secret).update(JSON.stringify([
780
+ "attachment-download/v1",
781
+ hash,
782
+ documentId,
783
+ expires
784
+ ])).digest("base64url");
785
+ }
786
+ };
787
+ function resolveAttachmentUrlSigning(env = process.env) {
788
+ const secret = env[ATTACHMENT_URL_SIGNING_SECRET_ENV];
789
+ if (secret !== void 0) {
790
+ 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`);
791
+ return {
792
+ status: "configured",
793
+ signer: new AttachmentUrlSigner(secret)
794
+ };
795
+ }
796
+ if (env.NODE_ENV === "production") return { status: "unconfigured" };
797
+ return {
798
+ status: "ephemeral",
799
+ signer: new AttachmentUrlSigner(randomBytes(32))
800
+ };
801
+ }
802
+ //#endregion
535
803
  //#region src/attachments/index.ts
536
- function registerAttachmentRoutes(api) {
537
- const { attachments } = api;
804
+ const logger$1 = childLogger(["switchboard", "attachments"]);
805
+ function registerAttachmentRoutes(api, options = {}) {
806
+ const { attachments, attachmentAccess } = api;
807
+ const urlSigner = options.urlSigner === void 0 ? signerFromEnvironment(attachments.backend?.kind ?? "filesystem") : options.urlSigner;
538
808
  mountAuthenticatedNodeRoute(api, "POST", "/attachments/reservations", makeReserveHandler(attachments));
539
809
  mountAuthenticatedNodeRoute(api, "GET", "/attachments/reservations/:reservationId", makeGetReservationHandler(attachments));
540
810
  mountAuthenticatedNodeRoute(api, "DELETE", "/attachments/reservations/:reservationId", makeDeleteReservationHandler(attachments));
541
- mountAuthenticatedNodeRoute(api, "PUT", "/attachments/reservations/:reservationId", makeUploadHandler(attachments));
542
- mountAuthenticatedNodeRoute(api, "HEAD", "/attachments/:hash", makeStatHandler(attachments));
543
- mountAuthenticatedNodeRoute(api, "GET", "/attachments/:hash/download-target", makeDownloadTargetHandler(attachments, api.attachmentAccess), { allowAnonymous: true });
544
- mountAuthenticatedNodeRoute(api, "GET", "/attachments/:hash", makeDownloadHandler(attachments));
811
+ mountAuthenticatedNodeRoute(api, "PUT", "/attachments/reservations/:reservationId", makeUploadHandler(attachments), { rawBody: true });
812
+ mountAuthenticatedNodeRoute(api, "HEAD", "/attachments/:hash", makeStatHandler(attachments, attachmentAccess, urlSigner), { allowAnonymous: true });
813
+ mountAuthenticatedNodeRoute(api, "GET", "/attachments/:hash/download-target", makeDownloadTargetHandler(attachments, attachmentAccess, urlSigner), { allowAnonymous: true });
814
+ mountAuthenticatedNodeRoute(api, "GET", "/attachments/:hash", makeDownloadHandler(attachments, attachmentAccess, urlSigner), { allowAnonymous: true });
815
+ }
816
+ function signerFromEnvironment(backend) {
817
+ const signing = resolveAttachmentUrlSigning();
818
+ if (signing.status === "unconfigured") {
819
+ if (backend === "filesystem") logger$1.error(`${ATTACHMENT_URL_SIGNING_SECRET_ENV} is not set: filesystem attachment download targets are refused until it is`);
820
+ return null;
821
+ }
822
+ 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`);
823
+ return signing.signer;
545
824
  }
546
825
  //#endregion
547
826
  //#region src/attachment-reference-read-model.mts
@@ -596,12 +875,7 @@ async function registerAttachmentReferenceReadModelOnModule(clientModule, attach
596
875
  */
597
876
  /** The models switchboard always registers alongside package models. */
598
877
  function switchboardBaseDocumentModels() {
599
- return [
600
- documentModelDocumentModelModule,
601
- driveDocumentModelModule,
602
- reactorDriveDocumentModelModule,
603
- ReactorGroupV1
604
- ];
878
+ return baseDocumentModels.map(([, model]) => model);
605
879
  }
606
880
  function applySwitchboardReactorDefaults(reactorBuilder, clientBuilder, options = {}) {
607
881
  const baseModels = options.includeBaseModels !== false ? switchboardBaseDocumentModels() : [];
@@ -617,7 +891,184 @@ function applySwitchboardReactorDefaults(reactorBuilder, clientBuilder, options
617
891
  });
618
892
  if (options.documentModelLoader) reactorBuilder.withDocumentModelLoader(options.documentModelLoader);
619
893
  if (options.logger) reactorBuilder.withLogger(options.logger);
620
- if (options.signer) clientBuilder.withSigner(options.signer);
894
+ if (options.signer) {
895
+ clientBuilder.withSigner(options.signer);
896
+ reactorBuilder.withSigner(options.signer.signer, options.signer.workerSigner);
897
+ }
898
+ if (options.createSignaturePolicy) clientBuilder.withCreateSignaturePolicy(options.createSignaturePolicy);
899
+ const trust = options.trustPolicy ?? options.signer;
900
+ if (trust?.trustPolicy) reactorBuilder.withTrustPolicy(trust.trustPolicy, trust.workerTrustPolicy);
901
+ }
902
+ //#endregion
903
+ //#region src/plugins/attachments.mts
904
+ /**
905
+ * R2.3 — the attachments subsystem as a built-in plugin: the six /attachments
906
+ * routes mount at onHttpMounting and the remote attachment service is created
907
+ * for the returned handle. Presence is activation — removed from the
908
+ * composition, the routes and service do not exist. NOT yet carved: the
909
+ * attachment-reference read model registered inside reactor construction
910
+ * (carve map: server.mts initializeClient) — it follows with the
911
+ * onReadModelsRegistering step in R2 step 2; until then it registers on both
912
+ * paths (a dormant read model when the plugin is absent, harmless).
913
+ *
914
+ * Inputs (carve map): api (routes), options.attachmentServiceUrl /
915
+ * PH_SWITCHBOARD_PUBLIC_URL / https + serverPort + renown (service config).
916
+ */
917
+ const attachmentsPlugin = {
918
+ name: "switchboard-attachments",
919
+ appliesTo: "switchboard",
920
+ hooks: { onHttpMounting: (ctx) => {
921
+ registerAttachmentRoutes(ctx.api);
922
+ ctx.attachmentService = createRemoteAttachmentService(deriveAttachmentServiceConfig(ctx.options, ctx.serverPort, ctx.renown));
923
+ } }
924
+ };
925
+ //#endregion
926
+ //#region src/plugin-host.mts
927
+ /**
928
+ * R2 — SwitchboardCore's plugin pipeline (rewire plan, carve map:
929
+ * uniform-runners-plan/rewire/r2-carve-map.md). Behind
930
+ * FEATURE_PLUGIN_HOST_ENABLED: flag off, startSwitchboard runs the existing
931
+ * inline path byte-identically; flag on, the five subsystems run as built-in
932
+ * plugins through these hook moments. Subsystems carve one per commit; until
933
+ * a subsystem is carved, its inline code runs on BOTH paths and its plugin
934
+ * twin does not exist.
935
+ *
936
+ * Hook vocabulary (SwitchboardHooks), anchored to the boot spine:
937
+ * - transformServerOptions — after option/flag resolution, before anything opens
938
+ * - onReadModelsRegistering — inside reactor construction (build-time read models)
939
+ * - onHttpMounting — api exists; routes mount here
940
+ * - onSubgraphsRegistering — push into lateSubgraphs before the drain
941
+ * - onReactorReady — client + graphqlManager destructured
942
+ * - onDrivesReady — after core drive seeding / remote attachment
943
+ * - onShutdown — first in the subsystem-ordered teardown
944
+ */
945
+ const PLUGIN_HOST_FLAG = "FEATURE_PLUGIN_HOST_ENABLED";
946
+ function isPluginHostEnabled(env = process.env) {
947
+ const value = env[PLUGIN_HOST_FLAG]?.trim().toLowerCase();
948
+ return value === "1" || value === "true";
949
+ }
950
+ /** Built-in plugins, pre-listed (the default composition until host.js
951
+ * entries map in R2 step 2). Subsystems join as R2 carves them. */
952
+ function builtinSwitchboardPlugins() {
953
+ const entry = {
954
+ enabled: true,
955
+ verbs: "*",
956
+ config: {}
957
+ };
958
+ return [
959
+ {
960
+ plugin: mcpPlugin,
961
+ provenance: "built-in",
962
+ entry: {
963
+ ...entry,
964
+ module: "@powerhousedao/switchboard/plugins/mcp"
965
+ }
966
+ },
967
+ {
968
+ plugin: attachmentsPlugin,
969
+ provenance: "built-in",
970
+ entry: {
971
+ ...entry,
972
+ module: "@powerhousedao/switchboard/plugins/attachments"
973
+ }
974
+ },
975
+ {
976
+ plugin: privacyPlugin,
977
+ provenance: "built-in",
978
+ entry: {
979
+ ...entry,
980
+ module: "@powerhousedao/switchboard/plugins/privacy"
981
+ }
982
+ },
983
+ {
984
+ plugin: workflowsPlugin,
985
+ provenance: "built-in",
986
+ entry: {
987
+ ...entry,
988
+ module: "@powerhousedao/switchboard/plugins/workflows"
989
+ }
990
+ }
991
+ ];
992
+ }
993
+ function createSwitchboardPluginHost(ctx, resolved) {
994
+ resolved ??= builtinSwitchboardPlugins();
995
+ const ordered = resolveOrder(resolved.map((r) => r.plugin));
996
+ const contributions = mergeContributions(resolved.map((r) => ({
997
+ plugin: r.plugin,
998
+ provenance: r.provenance
999
+ })));
1000
+ const fullCtx = {
1001
+ ...ctx,
1002
+ contributions
1003
+ };
1004
+ const LOG = "[switchboard:plugins]";
1005
+ console.log(`${LOG} composition: ${ordered.length} plugin(s) in order — ${ordered.map((p) => p.name).join(", ") || "(none)"}`);
1006
+ for (const r of resolved) {
1007
+ const cfg = Object.keys(r.entry.config ?? {});
1008
+ console.log(`${LOG} • ${r.plugin.name} [${r.provenance}] (${r.entry.module})` + (cfg.length ? ` config: {${cfg.join(", ")}}` : ""));
1009
+ }
1010
+ const ranBy = (hook) => ordered.filter((p) => p.hooks?.[hook]);
1011
+ const logHook = (hook) => {
1012
+ const names = ranBy(hook).map((p) => p.name);
1013
+ console.log(`${LOG} hook ${hook} → ${names.length ? names.join(", ") : "(no implementers)"}`);
1014
+ };
1015
+ return {
1016
+ plugins: ordered,
1017
+ ctx: fullCtx,
1018
+ transformOptions: (seed) => {
1019
+ logHook("transformServerOptions");
1020
+ return runTransformHook("transformServerOptions", ordered, fullCtx, seed);
1021
+ },
1022
+ observe: (hook) => {
1023
+ logHook(hook);
1024
+ return hook === "onShutdown" ? runObserveHookSequential(hook, ordered, fullCtx) : runObserveHook(hook, ordered, fullCtx);
1025
+ }
1026
+ };
1027
+ }
1028
+ //#endregion
1029
+ //#region src/env.mts
1030
+ function parseNonNegativeInt(raw, name) {
1031
+ if (raw === void 0 || raw.trim() === "") return;
1032
+ const value = Number.parseInt(raw, 10);
1033
+ if (!Number.isInteger(value) || value < 0 || String(value) !== raw.trim()) throw new Error(`${name} must be a non-negative integer, got "${raw}"`);
1034
+ return value;
1035
+ }
1036
+ //#endregion
1037
+ //#region src/projection-worker.mts
1038
+ const DEFAULT_DB_POOL_SIZE_PROJECTION = 8;
1039
+ const ON_TOKENS = [
1040
+ "1",
1041
+ "true",
1042
+ "on",
1043
+ "yes"
1044
+ ];
1045
+ const OFF_TOKENS = [
1046
+ "0",
1047
+ "false",
1048
+ "off",
1049
+ "no"
1050
+ ];
1051
+ /**
1052
+ * Enabled by REACTOR_PROJECTION_WORKER (1/true/on/yes, case-insensitive) or
1053
+ * `input.enabled`, which wins when defined; null when off (the default).
1054
+ */
1055
+ function resolveProjectionWorkerOptions(input, env) {
1056
+ if (!(input?.enabled ?? parseOnOff(env.REACTOR_PROJECTION_WORKER) ?? false)) return null;
1057
+ const dbPoolSize = input?.dbPoolSize ?? parseNonNegativeInt(env.REACTOR_DB_POOL_SIZE_PROJECTION, "REACTOR_DB_POOL_SIZE_PROJECTION") ?? DEFAULT_DB_POOL_SIZE_PROJECTION;
1058
+ if (dbPoolSize < 1) throw new Error("REACTOR_DB_POOL_SIZE_PROJECTION must be at least 1; the projection worker cannot run without a pool");
1059
+ return { dbPoolSize };
1060
+ }
1061
+ /** Same preconditions as the executor worker pool; message shape mirrors server.mts. */
1062
+ function assertProjectionWorkerSupported(args) {
1063
+ 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");
1064
+ 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.");
1065
+ }
1066
+ function parseOnOff(raw) {
1067
+ if (raw === void 0 || raw.trim() === "") return;
1068
+ const token = raw.trim().toLowerCase();
1069
+ if (ON_TOKENS.includes(token)) return true;
1070
+ if (OFF_TOKENS.includes(token)) return false;
1071
+ throw new Error(`REACTOR_PROJECTION_WORKER must be one of 1, true, on, yes, 0, false, off, no, got "${raw}"`);
621
1072
  }
622
1073
  //#endregion
623
1074
  //#region src/worker-pool.mts
@@ -700,6 +1151,20 @@ const BASE_MODEL_SPECIFIERS = [
700
1151
  "@powerhousedao/reactor-drive",
701
1152
  "@powerhousedao/reactor-group/document-models"
702
1153
  ];
1154
+ function isModelModule(value) {
1155
+ const candidate = value;
1156
+ return typeof candidate?.reducer === "function" && typeof candidate.documentModel?.global?.id === "string";
1157
+ }
1158
+ async function keepImportableSources(sources, logger) {
1159
+ const kept = [];
1160
+ for (const source of sources) try {
1161
+ const exports = await import(pathToFileURL(source.filePath).href);
1162
+ if (Object.values(exports).some(isModelModule)) kept.push(source);
1163
+ } catch (error) {
1164
+ logger.warn(`Worker model sources: "${source.filePath}" does not import, so workflow pieces will not see its models: ${String(error)}`);
1165
+ }
1166
+ return kept;
1167
+ }
703
1168
  /**
704
1169
  * Resolves base models and configured package identifiers to `{ filePath }`
705
1170
  * sources for the reactor builder. Resolution to absolute paths happens here
@@ -708,10 +1173,10 @@ const BASE_MODEL_SPECIFIERS = [
708
1173
  * packages. Unresolvable identifiers are skipped with a warning; the builder
709
1174
  * fails the boot if a registered model ends up without an importable source.
710
1175
  */
711
- async function resolveWorkerModelSources(packages, logger) {
1176
+ async function resolveWorkerModelSources(packages, logger, options = {}) {
712
1177
  const sources = [];
713
1178
  for (const identifier of [...BASE_MODEL_SPECIFIERS, ...packages]) {
714
- const filePath = await resolveModelModuleFile(identifier);
1179
+ const filePath = await resolveModelModuleFile(identifier) ?? await resolveRemoteSafely(identifier, options.resolveRemote, logger);
715
1180
  if (!filePath) {
716
1181
  logger.warn(`Worker model sources: no importable document-models entry for "${identifier}", skipping`);
717
1182
  continue;
@@ -720,6 +1185,15 @@ async function resolveWorkerModelSources(packages, logger) {
720
1185
  }
721
1186
  return sources;
722
1187
  }
1188
+ async function resolveRemoteSafely(identifier, resolveRemote, logger) {
1189
+ if (!resolveRemote) return null;
1190
+ try {
1191
+ return await resolveRemote(identifier);
1192
+ } catch (error) {
1193
+ logger.warn(`Worker model sources: could not cache "${identifier}" from the registry: ${String(error)}`);
1194
+ return null;
1195
+ }
1196
+ }
723
1197
  /**
724
1198
  * Absolute file path of a source's models barrel. Mirrors reactor-api's
725
1199
  * import-resolver: import.meta.resolve, then the project's node_modules via
@@ -814,48 +1288,15 @@ function parseWorkerCount(raw) {
814
1288
  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}"`);
815
1289
  return value;
816
1290
  }
817
- function parseNonNegativeInt(raw, name) {
818
- if (raw === void 0 || raw.trim() === "") return;
819
- const value = Number.parseInt(raw, 10);
820
- if (!Number.isInteger(value) || value < 0 || String(value) !== raw.trim()) throw new Error(`${name} must be a non-negative integer, got "${raw}"`);
821
- return value;
822
- }
823
1291
  //#endregion
824
- //#region src/projection-worker.mts
825
- const DEFAULT_DB_POOL_SIZE_PROJECTION = 8;
826
- const ON_TOKENS = [
827
- "1",
828
- "true",
829
- "on",
830
- "yes"
831
- ];
832
- const OFF_TOKENS = [
833
- "0",
834
- "false",
835
- "off",
836
- "no"
837
- ];
838
- /**
839
- * Enabled by REACTOR_PROJECTION_WORKER (1/true/on/yes, case-insensitive) or
840
- * `input.enabled`, which wins when defined; null when off (the default).
841
- */
842
- function resolveProjectionWorkerOptions(input, env) {
843
- if (!(input?.enabled ?? parseOnOff(env.REACTOR_PROJECTION_WORKER) ?? false)) return null;
844
- const dbPoolSize = input?.dbPoolSize ?? parseNonNegativeInt(env.REACTOR_DB_POOL_SIZE_PROJECTION, "REACTOR_DB_POOL_SIZE_PROJECTION") ?? DEFAULT_DB_POOL_SIZE_PROJECTION;
845
- if (dbPoolSize < 1) throw new Error("REACTOR_DB_POOL_SIZE_PROJECTION must be at least 1; the projection worker cannot run without a pool");
846
- return { dbPoolSize };
847
- }
848
- /** Same preconditions as the executor worker pool; message shape mirrors server.mts. */
849
- function assertProjectionWorkerSupported(args) {
850
- 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");
851
- 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.");
852
- }
853
- function parseOnOff(raw) {
854
- if (raw === void 0 || raw.trim() === "") return;
855
- const token = raw.trim().toLowerCase();
856
- if (ON_TOKENS.includes(token)) return true;
857
- if (OFF_TOKENS.includes(token)) return false;
858
- throw new Error(`REACTOR_PROJECTION_WORKER must be one of 1, true, on, yes, 0, false, off, no, got "${raw}"`);
1292
+ //#region src/inspection-throttle.mts
1293
+ const NAME = "PH_INSPECTION_CALLS_PER_MINUTE";
1294
+ /** Unset keeps reactor-api's default; an invalid value fails boot. */
1295
+ function inspectionThrottleFromEnv(env) {
1296
+ const callsPerMinute = parseNonNegativeInt(env[NAME], NAME);
1297
+ if (callsPerMinute === void 0) return {};
1298
+ if (callsPerMinute < 1) throw new Error(`${NAME} must be at least 1, got "${env[NAME]}"`);
1299
+ return { callsPerMinute };
859
1300
  }
860
1301
  //#endregion
861
1302
  //#region src/feature-flags.ts
@@ -865,23 +1306,70 @@ async function initFeatureFlags() {
865
1306
  return OpenFeature.getClient();
866
1307
  }
867
1308
  //#endregion
1309
+ //#region src/inspection-flag.mts
1310
+ /** The env var and OpenFeature flag key that can keep the inspection subgraph unmounted. */
1311
+ const INSPECTION_ENABLED = "INSPECTION_ENABLED";
1312
+ /** Whether to mount `/graphql/inspection`. A host's `inspection: false` wins;
1313
+ * otherwise INSPECTION_ENABLED decides, falling back to the host's option and
1314
+ * then INSPECTION_ENABLED_DEFAULT. */
1315
+ async function resolveInspectionEnabled({ featureFlags, option }) {
1316
+ if (option === false) return false;
1317
+ return featureFlags.getBooleanValue(INSPECTION_ENABLED, option ?? true);
1318
+ }
1319
+ //#endregion
1320
+ //#region src/mcp-flag.mts
1321
+ /** The env var and OpenFeature flag key that can keep the MCP server unmounted. */
1322
+ const MCP_ENABLED = "MCP_ENABLED";
1323
+ /** Whether to mount the MCP server at `/mcp`. On unless the host passes
1324
+ * `mcp: false` or MCP_ENABLED is "false": the env var can turn a host's MCP
1325
+ * off, never on, so a deployment that serves no MCP client can close the
1326
+ * endpoint without the bin growing a flag of its own. */
1327
+ async function resolveMcpEnabled({ featureFlags, option }) {
1328
+ if (option === false) return false;
1329
+ return featureFlags.getBooleanValue(MCP_ENABLED, true);
1330
+ }
1331
+ //#endregion
868
1332
  //#region src/pglite-dialect.ts
869
- var ClosablePGliteDialect = class extends PGliteDialect {
1333
+ /** A poisoned store cannot recover in process, so it takes the fatal shutdown and a supervisor restart. */
1334
+ function reactorPgliteDialectOptions(logger, proc) {
1335
+ return {
1336
+ onDiagnostic: (message, error) => logger.error(`[pglite-dialect] ${message}: @error`, error),
1337
+ onPoisoned: (cause) => {
1338
+ if (!triggerFatalShutdown("PGlite session poisoned", cause, proc)) logger.error("PGlite session poisoned: @error", cause);
1339
+ }
1340
+ };
1341
+ }
1342
+ var ClosablePGliteDialect = class {
1343
+ #inner;
870
1344
  #pglite;
871
- constructor(pglite) {
872
- super(pglite);
1345
+ constructor(pglite, options = {}) {
873
1346
  this.#pglite = pglite;
1347
+ this.#inner = new HardenedPGliteDialect(pglite, options);
1348
+ }
1349
+ createAdapter() {
1350
+ return this.#inner.createAdapter();
874
1351
  }
875
1352
  createDriver() {
876
- const driver = super.createDriver();
1353
+ const driver = this.#inner.createDriver();
877
1354
  const pglite = this.#pglite;
878
1355
  const innerDestroy = driver.destroy.bind(driver);
879
1356
  driver.destroy = async () => {
880
1357
  await innerDestroy();
881
- if (!pglite.closed) await pglite.close();
1358
+ if (pglite.closed) return;
1359
+ try {
1360
+ await pglite.close();
1361
+ } catch (err) {
1362
+ if (!/PGlite aborted/.test(String(err))) throw err;
1363
+ }
882
1364
  };
883
1365
  return driver;
884
1366
  }
1367
+ createQueryCompiler() {
1368
+ return this.#inner.createQueryCompiler();
1369
+ }
1370
+ createIntrospector(db) {
1371
+ return this.#inner.createIntrospector(db);
1372
+ }
885
1373
  };
886
1374
  //#endregion
887
1375
  //#region src/pglite-migration.ts
@@ -933,7 +1421,15 @@ async function migratePgliteDir(dataDir, logger) {
933
1421
  try {
934
1422
  const [legacyMod, pgDump] = await Promise.all([loadPGliteModule(major), loadPgDump(major)]);
935
1423
  const LegacyPGlite = legacyMod.PGlite;
936
- const pg = new LegacyPGlite(backupDir);
1424
+ const onDisk = new LegacyPGlite(backupDir);
1425
+ let tar;
1426
+ try {
1427
+ await onDisk.waitReady;
1428
+ tar = await onDisk.dumpDataDir("none");
1429
+ } finally {
1430
+ await onDisk.close();
1431
+ }
1432
+ const pg = new LegacyPGlite({ loadDataDir: tar });
937
1433
  try {
938
1434
  await pg.waitReady;
939
1435
  sql = await (await pgDump({ pg })).text();
@@ -963,6 +1459,7 @@ async function migratePgliteDir(dataDir, logger) {
963
1459
  } finally {
964
1460
  await pg.close();
965
1461
  }
1462
+ syncTree(dataDir);
966
1463
  } catch (err) {
967
1464
  await rollback(dataDir, backupDir, err, logger);
968
1465
  throw err;
@@ -983,6 +1480,59 @@ async function rollback(dataDir, backupDir, originalError, logger) {
983
1480
  logger.error(`[pglite-migration] Migration failed for ${dataDir}; rolled back from ${backupDir}. Original error: ${String(originalError)}`);
984
1481
  }
985
1482
  //#endregion
1483
+ //#region src/pglite-preflight.ts
1484
+ const RM_OPTIONS = {
1485
+ recursive: true,
1486
+ force: true,
1487
+ maxRetries: 10,
1488
+ retryDelay: 100
1489
+ };
1490
+ /**
1491
+ * Prepares every local PGlite dir before the first open and returns the
1492
+ * PG major detected on disk per dir. Conversion of an AtomicNodeFs snapshot
1493
+ * runs for every dir, before the major is read, so a pure-snapshot PG16 dir
1494
+ * is converted and then migrated.
1495
+ */
1496
+ async function runPglitePreflight(options) {
1497
+ const { dirs, logger } = options;
1498
+ const detectedMajors = /* @__PURE__ */ new Map();
1499
+ if (options.inMemory || dirs.length === 0) return detectedMajors;
1500
+ if (options.forcePgVersion !== void 0) {
1501
+ if (options.migratePglite) logger.warn("PH_FORCE_PG_VERSION is set; ignoring --migrate-pglite/PH_MIGRATE_PGLITE because the data dirs will be wiped.");
1502
+ logger.warn(`PH_FORCE_PG_VERSION=${options.forcePgVersion} set; wiping PGLite data dirs and re-initializing at PG${options.forcePgVersion}.`);
1503
+ for (const dir of dirs) {
1504
+ for (const p of [
1505
+ dir,
1506
+ `${dir}.converting`,
1507
+ `${dir}.old`
1508
+ ]) await promises.rm(p, RM_OPTIONS);
1509
+ logger.info(`Wiped PGLite data dir ${dir}`);
1510
+ }
1511
+ return detectedMajors;
1512
+ }
1513
+ const deps = {
1514
+ openForVerify: options.openForVerify ?? openForVerify,
1515
+ logger
1516
+ };
1517
+ for (const dir of dirs) {
1518
+ await preparePgliteDataDir(dir, deps);
1519
+ const major = await readPgVersionFile(dir);
1520
+ if (major !== null) detectedMajors.set(dir, major);
1521
+ }
1522
+ if (options.migratePglite) for (const [dir, major] of detectedMajors) {
1523
+ if (major === 17) continue;
1524
+ await migratePgliteDir(dir, logger);
1525
+ await removeStalePgliteFiles(dir, logger);
1526
+ const after = await readPgVersionFile(dir);
1527
+ if (after !== null) detectedMajors.set(dir, after);
1528
+ }
1529
+ else for (const [dir, major] of detectedMajors) {
1530
+ if (major === 17) continue;
1531
+ 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.`);
1532
+ }
1533
+ return detectedMajors;
1534
+ }
1535
+ //#endregion
986
1536
  //#region src/reactor-feature-flags.mts
987
1537
  /**
988
1538
  * Enforcement flags from the REACTOR_* env vars. Each flag requires the ones
@@ -1003,6 +1553,26 @@ function resolveReactorFeatureFlags(env) {
1003
1553
  };
1004
1554
  }
1005
1555
  //#endregion
1556
+ //#region src/create-signature-policy.mts
1557
+ /**
1558
+ * What new documents are created as, from CREATE_SIGNATURE_POLICY. Without a
1559
+ * signer this switchboard cannot write to a v2-required document, so it falls
1560
+ * back to legacy and says so.
1561
+ */
1562
+ function resolveCreateSignaturePolicy(env, options) {
1563
+ const raw = env.CREATE_SIGNATURE_POLICY?.trim();
1564
+ let policy = DEFAULT_SIGNATURE_POLICY;
1565
+ if (raw) {
1566
+ if (!isSignaturePolicy(raw)) throw new Error(`CREATE_SIGNATURE_POLICY must be "legacy" or "v2-required", got "${raw}"`);
1567
+ policy = raw;
1568
+ }
1569
+ if (policy === "v2-required" && !options.hasSigner) {
1570
+ 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.");
1571
+ return "legacy";
1572
+ }
1573
+ return policy;
1574
+ }
1575
+ //#endregion
1006
1576
  //#region src/renown.ts
1007
1577
  const logger = childLogger(["switchboard", "renown"]);
1008
1578
  /**
@@ -1025,15 +1595,123 @@ async function initRenown(options = {}) {
1025
1595
  * Get the signer config for the given renown instance.
1026
1596
  *
1027
1597
  * @param renown - The renown instance
1028
- * @param requireSignature - If true, unsigned actions are rejected
1598
+ * @param keypairPath - Where `initRenown` loaded the key from
1029
1599
  */
1030
- function getRenownSignerConfig(renown, requireSignature) {
1600
+ function getRenownSignerConfig(renown, keypairPath) {
1031
1601
  return {
1032
1602
  signer: renown.signer,
1033
- verifier: createSignatureVerifier(requireSignature)
1603
+ workerSigner: getRenownWorkerSignerSpec(renown, keypairPath)
1604
+ };
1605
+ }
1606
+ /**
1607
+ * What a pooled executor worker imports to sign as this switchboard: it
1608
+ * reloads the key `initRenown` stored, and takes the user known at boot.
1609
+ */
1610
+ function getRenownWorkerSignerSpec(renown, keypairPath) {
1611
+ const { signer } = renown;
1612
+ const user = signer.user;
1613
+ return {
1614
+ module: {
1615
+ filePath: createRequire(import.meta.url).resolve("@renown/sdk/node"),
1616
+ exportName: "createNodeRenownSigner"
1617
+ },
1618
+ initArgs: {
1619
+ appName: signer.app?.name ?? "switchboard",
1620
+ keypairPath: resolve(keypairPath ?? DEFAULT_KEYPAIR_PATH),
1621
+ ...signer.app?.key ? { did: signer.app.key } : {},
1622
+ ...user ? { user: {
1623
+ address: user.address,
1624
+ networkId: user.networkId,
1625
+ chainId: user.chainId
1626
+ } } : {}
1627
+ }
1628
+ };
1629
+ }
1630
+ /**
1631
+ * Admits a key as a signer for an address a Renown credential binds it to; a
1632
+ * `self` source has no worker spec. In process, the switchboard's own key is
1633
+ * matched against its current user; the worker spec carries the user known now.
1634
+ */
1635
+ async function getRenownTrustPolicyConfig(trustSource, renown) {
1636
+ const ownSigner = renown?.signer;
1637
+ if (trustSource.source === "self") return { trustPolicy: createRenownTrustPolicy({
1638
+ switchboard: trustSource.request,
1639
+ ownSigner
1640
+ }) };
1641
+ const switchboardUrl = await resolveSwitchboardEndpoint({
1642
+ switchboardUrl: trustSource.switchboardUrl,
1643
+ baseUrl: trustSource.renownUrl
1644
+ });
1645
+ const options = {
1646
+ ...switchboardUrl ? { switchboard: switchboardUrl } : {},
1647
+ ...trustSource.renownUrl ? { renownUrl: trustSource.renownUrl } : {}
1648
+ };
1649
+ const self = ownIdentity(renown);
1650
+ return {
1651
+ trustPolicy: createRenownTrustPolicy({
1652
+ ...options,
1653
+ ownSigner
1654
+ }),
1655
+ workerTrustPolicy: {
1656
+ module: {
1657
+ filePath: createRequire(import.meta.url).resolve("@renown/sdk/node"),
1658
+ exportName: "createRenownTrustPolicy"
1659
+ },
1660
+ initArgs: {
1661
+ ...options,
1662
+ ...self ? { self } : {}
1663
+ }
1664
+ }
1665
+ };
1666
+ }
1667
+ /**
1668
+ * Fails the boot when pooled workers would refuse every signed write the
1669
+ * in-process executor accepts: a `self` Renown source gives workers no trust
1670
+ * policy spec, so under authEnforcement they apply the default.
1671
+ */
1672
+ function assertWorkerTrustPolicy(config) {
1673
+ 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).");
1674
+ }
1675
+ function ownIdentity(renown) {
1676
+ const key = renown?.signer.app?.key;
1677
+ if (!key) return;
1678
+ const user = renown.signer.user;
1679
+ return {
1680
+ key,
1681
+ user: {
1682
+ address: user?.address ?? "",
1683
+ networkId: user?.networkId ?? "",
1684
+ chainId: user?.chainId ?? 0
1685
+ }
1034
1686
  };
1035
1687
  }
1036
1688
  //#endregion
1689
+ //#region src/unsupported-stored-documents.mts
1690
+ const MODES = ["refuse", "read-only"];
1691
+ /** From REACTOR_UNSUPPORTED_STORED_DOCUMENTS; `input` wins when defined. */
1692
+ function resolveUnsupportedStoredDocuments(input, env) {
1693
+ if (input !== void 0) return input;
1694
+ const raw = env.REACTOR_UNSUPPORTED_STORED_DOCUMENTS?.trim();
1695
+ if (!raw) return "refuse";
1696
+ if (!MODES.includes(raw)) throw new Error(`REACTOR_UNSUPPORTED_STORED_DOCUMENTS must be "refuse" or "read-only", got "${raw}"`);
1697
+ return raw;
1698
+ }
1699
+ /** The reactor refused to start over documents this build does not run. */
1700
+ var StoredDocumentsRefusedError = class extends Error {
1701
+ versions;
1702
+ documents;
1703
+ constructor(cause) {
1704
+ const named = cause.versions.map(({ protocol, version }) => `${protocol} ${version}`).join(", ");
1705
+ 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 });
1706
+ this.name = "StoredDocumentsRefusedError";
1707
+ this.versions = cause.versions;
1708
+ this.documents = cause.documents;
1709
+ }
1710
+ static isError(error) {
1711
+ return Error.isError(error) && error.name === "StoredDocumentsRefusedError";
1712
+ }
1713
+ };
1714
+ //#endregion
1037
1715
  //#region src/server.mts
1038
1716
  const defaultLogger = childLogger(["switchboard"]);
1039
1717
  const LogLevel = process.env.LOG_LEVEL || "info";
@@ -1041,16 +1719,32 @@ setLogLevel(LogLevel);
1041
1719
  dotenv.config();
1042
1720
  const DOCUMENT_MODEL_SUBGRAPHS_ENABLED = "DOCUMENT_MODEL_SUBGRAPHS_ENABLED";
1043
1721
  const DOCUMENT_MODEL_SUBGRAPHS_ENABLED_DEFAULT = true;
1044
- const REQUIRE_SIGNATURES = "REQUIRE_SIGNATURES";
1045
- const REQUIRE_SIGNATURES_DEFAULT = false;
1046
1722
  const DEFAULT_PORT = process.env.PORT ? Number(process.env.PORT) : 4001;
1047
1723
  const PORT_FALLBACK_ATTEMPTS = 20;
1048
- const PGLITE_FLUSH_INTERVAL_MS = (() => {
1049
- const raw = process.env.PGLITE_FLUSH_INTERVAL_MS;
1050
- if (raw === void 0) return 100;
1051
- const parsed = Number(raw);
1052
- return Number.isFinite(parsed) && parsed >= 0 ? parsed : 100;
1053
- })();
1724
+ let flushIntervalWarned = false;
1725
+ function warnIgnoredFlushInterval(logger) {
1726
+ if (flushIntervalWarned) return;
1727
+ if (process.env.PGLITE_FLUSH_INTERVAL_MS === void 0) return;
1728
+ flushIntervalWarned = true;
1729
+ logger.warn("PGLITE_FLUSH_INTERVAL_MS is set but ignored: PGlite stores no longer snapshot on a timer.");
1730
+ }
1731
+ function onPgliteAbort(logger, what) {
1732
+ if (!triggerFatalShutdown("PGlite aborted", what)) logger.error("PGlite aborted: @error", what);
1733
+ }
1734
+ function pgliteFsyncFor(major, dir, logger) {
1735
+ const wanted = resolvePgliteFsync(process.env);
1736
+ if (wanted && major === 16) logger.warn(`PGlite data dir ${dir} is PG16 on pglite-legacy-02, which does not sync commits to disk; only checkpoints are synced until --migrate-pglite upgrades it.`);
1737
+ return wanted;
1738
+ }
1739
+ /** Preloads the module's NodeFS so the returned factory can be synchronous. */
1740
+ async function loadDurableFsFactory(major, logger) {
1741
+ const NodeFS = await loadNodeFsClass(major);
1742
+ return (dir) => createDurableNodeFs(NodeFS, dir, {
1743
+ fsync: pgliteFsyncFor(major, dir, logger),
1744
+ logger,
1745
+ onAbort: (what) => onPgliteAbort(logger, what)
1746
+ });
1747
+ }
1054
1748
  const PGLITE_IN_MEMORY = process.env.PH_PGLITE_IN_MEMORY === "1";
1055
1749
  /**
1056
1750
  * Attempt to bind a throwaway TCP server to the given port. Resolves true if
@@ -1077,6 +1771,13 @@ function isPortAvailable(port) {
1077
1771
  function resolveConfigPath(configFile) {
1078
1772
  return configFile ?? path$1.join(process.cwd(), "powerhouse.config.json");
1079
1773
  }
1774
+ function readConfigWorkflowsEnabled(configPath) {
1775
+ try {
1776
+ return getConfig(configPath).workflows?.enabled ?? false;
1777
+ } catch {
1778
+ return false;
1779
+ }
1780
+ }
1080
1781
  async function resolveServerPort(requested, strictPort, logger) {
1081
1782
  if (strictPort) return requested;
1082
1783
  for (let i = 0; i < PORT_FALLBACK_ATTEMPTS; i++) {
@@ -1089,7 +1790,7 @@ async function resolveServerPort(requested, strictPort, logger) {
1089
1790
  return requested;
1090
1791
  }
1091
1792
  async function createReactorKysely(opts) {
1092
- const { reactorDbUrl, reactorPgliteDir, reactorPgliteMajor, inMemory, flushIntervalMs, hostPoolSize, logger } = opts;
1793
+ const { reactorDbUrl, reactorPgliteDir, reactorPgliteMajor, inMemory, hostPoolSize, logger } = opts;
1093
1794
  if (reactorDbUrl && isPostgresUrl(reactorDbUrl)) {
1094
1795
  const connectionString = reactorDbUrl.includes("?") ? reactorDbUrl : `${reactorDbUrl}?sslmode=disable`;
1095
1796
  const poolSize = hostPoolSize();
@@ -1101,19 +1802,18 @@ async function createReactorKysely(opts) {
1101
1802
  logger.info(`Using PostgreSQL for reactor storage (host pool max ${poolSize})`);
1102
1803
  return {
1103
1804
  kysely: new Kysely({ dialect: new PostgresDialect({ pool }) }),
1104
- poolInstrumentation
1805
+ poolInstrumentation,
1806
+ storageFacts: POSTGRES_STORAGE_FACTS
1105
1807
  };
1106
1808
  }
1107
1809
  if (!reactorPgliteDir || reactorPgliteMajor === null) throw new Error("Reactor PGLite directory not resolved");
1108
1810
  const { PGlite } = await loadPGliteModule(reactorPgliteMajor);
1109
- const pglite = inMemory ? new PGlite() : new PGlite({ fs: new AtomicNodeFs(reactorPgliteDir, {
1110
- logger,
1111
- flushIntervalMs
1112
- }) });
1811
+ const pglite = inMemory ? new PGlite() : new PGlite({ fs: (await loadDurableFsFactory(reactorPgliteMajor, logger))(reactorPgliteDir) });
1113
1812
  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}`);
1114
1813
  return {
1115
- kysely: new Kysely({ dialect: new ClosablePGliteDialect(pglite) }),
1116
- poolInstrumentation: void 0
1814
+ kysely: new Kysely({ dialect: new ClosablePGliteDialect(pglite, reactorPgliteDialectOptions(logger)) }),
1815
+ poolInstrumentation: void 0,
1816
+ storageFacts: inMemory ? IN_MEMORY_PGLITE_STORAGE_FACTS : PGLITE_PATH_STORAGE_FACTS
1117
1817
  };
1118
1818
  }
1119
1819
  /** Derive the remote attachment service config for switchboard's own `/attachments/*` API. */
@@ -1129,6 +1829,16 @@ function deriveAttachmentServiceConfig(options, serverPort, renown) {
1129
1829
  }
1130
1830
  async function initServer(serverPort, options, renown, renownConfig) {
1131
1831
  const { dev, packages = [], remoteDrives = [], logger = defaultLogger } = options;
1832
+ const pluginHost = isPluginHostEnabled() ? createSwitchboardPluginHost({
1833
+ logger,
1834
+ options,
1835
+ renown
1836
+ }, options.pluginComposition) : null;
1837
+ if (pluginHost) {
1838
+ options = await pluginHost.transformOptions(options);
1839
+ options.mcp ??= false;
1840
+ options.workflows = { enabled: options.workflows?.enabled === true };
1841
+ }
1132
1842
  logger.level = LogLevel;
1133
1843
  const dbPath = options.dbPath ?? process.env.DATABASE_URL ?? process.env.PH_SWITCHBOARD_DATABASE_URL;
1134
1844
  const readModelPath = dbPath || ".ph/read-storage";
@@ -1137,42 +1847,14 @@ async function initServer(serverPort, options, renown, renownConfig) {
1137
1847
  const reactorPgliteDir = options.reactor ? null : !reactorDbUrl || !isPostgresUrl(reactorDbUrl) ? reactorPath : null;
1138
1848
  const readModelPgliteDir = !dbPath || !isPostgresUrl(dbPath) ? readModelPath : null;
1139
1849
  const pgliteDirs = [reactorPgliteDir, readModelPgliteDir].filter((d) => d !== null);
1140
- const detectedMajors = /* @__PURE__ */ new Map();
1141
- for (const dir of pgliteDirs) {
1142
- const lockPath = path$1.join(dir, "postmaster.pid");
1143
- try {
1144
- await promises.unlink(lockPath);
1145
- logger.warn(`Removed stale PGLite lockfile ${lockPath}`);
1146
- } catch (err) {
1147
- if (err.code !== "ENOENT") throw err;
1148
- }
1149
- }
1150
- if (options.forcePgVersion !== void 0 && pgliteDirs.length > 0) {
1151
- if (options.migratePglite) logger.warn("PH_FORCE_PG_VERSION is set; ignoring --migrate-pglite/PH_MIGRATE_PGLITE because the data dirs will be wiped.");
1152
- logger.warn(`PH_FORCE_PG_VERSION=${options.forcePgVersion} set; wiping PGLite data dirs and re-initializing at PG${options.forcePgVersion}.`);
1153
- for (const dir of pgliteDirs) {
1154
- await promises.rm(dir, {
1155
- recursive: true,
1156
- force: true
1157
- });
1158
- logger.info(`Wiped PGLite data dir ${dir}`);
1159
- }
1160
- } else if (options.forcePgVersion === void 0) {
1161
- for (const dir of pgliteDirs) {
1162
- const major = await readPgVersionFile(dir);
1163
- if (major !== null) detectedMajors.set(dir, major);
1164
- }
1165
- if (options.migratePglite) for (const [dir, major] of detectedMajors) {
1166
- if (major === 17) continue;
1167
- await migratePgliteDir(dir, logger);
1168
- const after = await readPgVersionFile(dir);
1169
- if (after !== null) detectedMajors.set(dir, after);
1170
- }
1171
- else for (const [dir, major] of detectedMajors) {
1172
- if (major === 17) continue;
1173
- 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.`);
1174
- }
1175
- }
1850
+ warnIgnoredFlushInterval(logger);
1851
+ const detectedMajors = await runPglitePreflight({
1852
+ dirs: pgliteDirs,
1853
+ forcePgVersion: options.forcePgVersion,
1854
+ migratePglite: options.migratePglite,
1855
+ inMemory: PGLITE_IN_MEMORY,
1856
+ logger
1857
+ });
1176
1858
  function resolvePgliteMajorForDir(dir) {
1177
1859
  if (options.forcePgVersion !== void 0) return options.forcePgVersion;
1178
1860
  const detected = detectedMajors.get(dir);
@@ -1182,6 +1864,7 @@ async function initServer(serverPort, options, renown, renownConfig) {
1182
1864
  }
1183
1865
  const reactorPgliteMajor = reactorPgliteDir ? resolvePgliteMajorForDir(reactorPgliteDir) : null;
1184
1866
  const readModelPgliteMajor = readModelPgliteDir ? resolvePgliteMajorForDir(readModelPgliteDir) : null;
1867
+ const inspectionThrottle = inspectionThrottleFromEnv(process.env);
1185
1868
  let workerPool = resolveWorkerPoolOptions(options.workerPool, process.env);
1186
1869
  if (workerPool && options.reactor) {
1187
1870
  logger.warn("Worker pool configuration ignored: the caller-provided reactor owns its own executor");
@@ -1189,8 +1872,14 @@ async function initServer(serverPort, options, renown, renownConfig) {
1189
1872
  }
1190
1873
  if (workerPool) {
1191
1874
  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");
1875
+ assertWorkerTrustPolicy({
1876
+ workers: workerPool.numWorkers,
1877
+ authEnforcement: resolveReactorFeatureFlags(process.env).flags.authEnforcement === true,
1878
+ renownSource: renownConfig.source
1879
+ });
1192
1880
  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.");
1193
1881
  }
1882
+ const unsupportedStoredDocuments = resolveUnsupportedStoredDocuments(options.unsupportedStoredDocuments, process.env);
1194
1883
  let projectionWorker = resolveProjectionWorkerOptions(options.projectionWorker, process.env);
1195
1884
  if (projectionWorker && options.reactor) {
1196
1885
  logger.warn("Projection worker configuration ignored: the caller-provided reactor owns its own read-model coordinator");
@@ -1216,6 +1905,8 @@ async function initServer(serverPort, options, renown, renownConfig) {
1216
1905
  if (!packages.includes(name)) packages.push(name);
1217
1906
  });
1218
1907
  }
1908
+ const registryPackageNames = new Set((registryPackages ?? "").split(",").map((p) => p.trim()).filter(Boolean));
1909
+ const resolveRegistryModels = async (identifier) => httpLoader && registryPackageNames.has(identifier) ? (await httpLoader.cachePackage(identifier)).entries.documentModels ?? null : null;
1219
1910
  const reactorLogger = logger.child(["reactor"]);
1220
1911
  let projectionWorkerFatalFired = false;
1221
1912
  const onProjectionWorkerFatal = (shardId, reason) => {
@@ -1224,7 +1915,15 @@ async function initServer(serverPort, options, renown, renownConfig) {
1224
1915
  reactorLogger.error(`Projection worker ${shardId} died; shutting down so the supervisor restarts a healthy process`, reason);
1225
1916
  process.kill(process.pid, "SIGTERM");
1226
1917
  };
1918
+ const workflowsEnabled = options.workflows?.enabled === true;
1919
+ const privacyConfig = pluginHost ? { enabled: false } : resolvePrivacy(options.privacy, process.env);
1920
+ if (workflowsEnabled) {
1921
+ await assertWorkflowPackageLoadable();
1922
+ if (!packages.includes("@powerhousedao/workflow")) packages.push(WORKFLOW_PACKAGE_NAME);
1923
+ }
1227
1924
  let ownedReactorModule;
1925
+ let workerModels;
1926
+ let localRenownRequest;
1228
1927
  const initializeClient = async (documentModels, { attachmentReferenceWriter, upgradeManifests }) => {
1229
1928
  if (options.reactor) {
1230
1929
  const attachmentReferenceProjection = await registerAttachmentReferenceReadModelOnModule(options.reactor, attachmentReferenceWriter);
@@ -1237,12 +1936,11 @@ async function initServer(serverPort, options, renown, renownConfig) {
1237
1936
  attachmentReferenceProjection
1238
1937
  };
1239
1938
  }
1240
- const { kysely: baseKysely, poolInstrumentation } = await createReactorKysely({
1939
+ const { kysely: baseKysely, poolInstrumentation, storageFacts } = await createReactorKysely({
1241
1940
  reactorDbUrl,
1242
1941
  reactorPgliteDir,
1243
1942
  reactorPgliteMajor,
1244
1943
  inMemory: PGLITE_IN_MEMORY,
1245
- flushIntervalMs: PGLITE_FLUSH_INTERVAL_MS,
1246
1944
  hostPoolSize: () => resolveHostPoolSize(process.env),
1247
1945
  logger
1248
1946
  });
@@ -1251,7 +1949,7 @@ async function initServer(serverPort, options, renown, renownConfig) {
1251
1949
  if (hasSkipThreshold) logger.info(`Reactor maxSkipThreshold set to ${maxSkipThreshold}`);
1252
1950
  const { flags: reactorFeatureFlags, enabled: enabledFeatureFlags } = resolveReactorFeatureFlags(process.env);
1253
1951
  if (enabledFeatureFlags.length > 0) logger.info(`Reactor feature flags enabled: ${enabledFeatureFlags.join(", ")}`);
1254
- const reactorBuilder = new ReactorBuilder().withEventBus(new EventBus()).withKysely(baseKysely).withFeatures({ legacyProcessorIds: process.env.REACTOR_LEGACY_PROCESSOR_IDS !== "false" });
1952
+ const reactorBuilder = new ReactorBuilder().withEventBus(new EventBus()).withKysely(baseKysely).withStorageFacts(storageFacts).withFeatures({ legacyProcessorIds: process.env.REACTOR_LEGACY_PROCESSOR_IDS !== "false" }).withUnsupportedStoredDocuments(unsupportedStoredDocuments);
1255
1953
  if (poolInstrumentation) reactorBuilder.withInstrumentedPool(poolInstrumentation);
1256
1954
  const clientBuilder = new ReactorClientBuilder().withReactorBuilder(reactorBuilder);
1257
1955
  const vetraDocumentModels = dev ? Object.values(await import("@powerhousedao/vetra/document-models")).filter((m) => typeof m === "object" && m !== null && "documentModel" in m && "reducer" in m) : [];
@@ -1264,12 +1962,28 @@ async function initServer(serverPort, options, renown, renownConfig) {
1264
1962
  } : void 0,
1265
1963
  documentModelLoader: httpLoader && dynamicModelLoading ? httpLoader.documentModelLoader : void 0,
1266
1964
  logger: reactorLogger,
1267
- signer: renown ? getRenownSignerConfig(renown, options.identity?.requireSignatures) : void 0
1965
+ signer: renown ? getRenownSignerConfig(renown, options.identity?.keypairPath) : void 0,
1966
+ createSignaturePolicy: resolveCreateSignaturePolicy(process.env, {
1967
+ hasSigner: renown !== null,
1968
+ logger
1969
+ }),
1970
+ trustPolicy: reactorFeatureFlags.authEnforcement ? await getRenownTrustPolicyConfig(renownConfig.source === "self" ? {
1971
+ source: "self",
1972
+ request: (query, variables) => localRenownRequest ? localRenownRequest(query, variables) : Promise.reject(/* @__PURE__ */ new Error("The local renown read model is not bound yet"))
1973
+ } : {
1974
+ source: "remote",
1975
+ renownUrl: renownConfig.url,
1976
+ switchboardUrl: renownConfig.switchboardUrl
1977
+ }, renown) : void 0
1268
1978
  });
1979
+ if (workerPool || projectionWorker || workflowsEnabled) {
1980
+ const sources = await resolveWorkerModelSources(packages, reactorLogger, { resolveRemote: resolveRegistryModels });
1981
+ reactorBuilder.withDocumentModelSources(workerPool || projectionWorker ? sources : await keepImportableSources(sources, reactorLogger));
1982
+ }
1983
+ workerModels = modelManifestSource(reactorBuilder);
1269
1984
  if (workerPool) {
1270
1985
  if (!reactorDbUrl) throw new Error("unreachable: worker pool enabled without a reactor database URL");
1271
- const workerSources = await resolveWorkerModelSources(packages, reactorLogger);
1272
- reactorBuilder.withDocumentModelSources(workerSources).withWorkerPool({
1986
+ reactorBuilder.withWorkerPool({
1273
1987
  numWorkers: workerPool.numWorkers,
1274
1988
  db: buildWorkerDbConfig(reactorDbUrl, workerPool)
1275
1989
  });
@@ -1286,10 +2000,6 @@ async function initServer(serverPort, options, renown, renownConfig) {
1286
2000
  });
1287
2001
  if (projectionWorker) {
1288
2002
  if (!reactorDbUrl) throw new Error("unreachable: projection worker enabled without a reactor database URL");
1289
- if (!workerPool) {
1290
- const workerSources = await resolveWorkerModelSources(packages, reactorLogger);
1291
- reactorBuilder.withDocumentModelSources(workerSources);
1292
- }
1293
2003
  const db = {
1294
2004
  ...buildWorkerDbConfig(reactorDbUrl, {
1295
2005
  dbPoolSizePerWorker: projectionWorker.dbPoolSize,
@@ -1308,17 +2018,30 @@ async function initServer(serverPort, options, renown, renownConfig) {
1308
2018
  reactorBuilder.withShutdownHook(async () => {
1309
2019
  if (apiRef.current) await apiRef.current.dispose();
1310
2020
  });
1311
- const module = await clientBuilder.buildModule();
2021
+ let module;
2022
+ try {
2023
+ module = await clientBuilder.buildModule();
2024
+ } catch (error) {
2025
+ try {
2026
+ await baseKysely.destroy();
2027
+ } catch (destroyError) {
2028
+ logger.error("Aborting boot: reactor database destroy failed: @error", destroyError);
2029
+ }
2030
+ if (UnsupportedStoredProtocolError.isError(error)) throw new StoredDocumentsRefusedError(error);
2031
+ throw error;
2032
+ }
1312
2033
  if (module.reactorModule) {
1313
2034
  new ReactorInstrumentation(module.reactorModule).start();
1314
2035
  reactorLogger.info("Reactor metrics instrumentation started");
1315
2036
  }
1316
- driveNodeView = new DriveNodeView(baseKysely.withSchema(REACTOR_SCHEMA));
2037
+ const reactorDriveSchemaDb = baseKysely.withSchema(REACTOR_SCHEMA);
2038
+ driveNodeView = new DriveNodeView(reactorDriveSchemaDb);
1317
2039
  const reactorDriveClient = new ReactorDriveClient({
1318
2040
  reactor: module.client,
1319
2041
  readModel: driveNodeView
1320
2042
  });
1321
2043
  ownedReactorModule = module;
2044
+ if (options.fatalErrorShutdown) installFatalErrorShutdown(logger);
1322
2045
  return {
1323
2046
  module,
1324
2047
  reactorDriveClient,
@@ -1347,12 +2070,22 @@ async function initServer(serverPort, options, renown, renownConfig) {
1347
2070
  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;
1348
2071
  let defaultDriveUrl = void 0;
1349
2072
  const basePath = process.cwd();
2073
+ const reportError = (error) => {
2074
+ Sentry.captureException(error);
2075
+ };
2076
+ const reporting = {
2077
+ logger,
2078
+ report: reportError
2079
+ };
1350
2080
  let vite;
1351
2081
  let viteLoader;
1352
2082
  if (dev) {
1353
2083
  const { VitePackageLoader, createViteLogger, startViteServer } = await import("@powerhousedao/reactor-api/vite");
1354
2084
  vite = await startViteServer(process.cwd(), createViteLogger(logger));
1355
- viteLoader = VitePackageLoader.build(vite);
2085
+ viteLoader = VitePackageLoader.build(vite, {
2086
+ resolveFrom: [import.meta.url],
2087
+ reportError
2088
+ });
1356
2089
  }
1357
2090
  const vetraProcessorFactory = dev ? (await import("@powerhousedao/vetra/processors")).processorFactory : void 0;
1358
2091
  if (!options.disableLocalPackages) packages.push(basePath);
@@ -1370,11 +2103,9 @@ async function initServer(serverPort, options, renown, renownConfig) {
1370
2103
  let pgliteFactory;
1371
2104
  if (readModelPgliteDir && readModelPgliteMajor !== null) {
1372
2105
  const { PGlite: ReadModelPGlite } = await loadPGliteModule(readModelPgliteMajor);
2106
+ const durableFs = await loadDurableFsFactory(readModelPgliteMajor, logger);
1373
2107
  pgliteFactory = PGLITE_IN_MEMORY ? () => new ReadModelPGlite({ parsers: PGLITE_UTC_PARSERS }) : (connectionString) => new ReadModelPGlite({
1374
- fs: new AtomicNodeFs(connectionString ?? readModelPgliteDir, {
1375
- logger,
1376
- flushIntervalMs: PGLITE_FLUSH_INTERVAL_MS
1377
- }),
2108
+ fs: durableFs(connectionString ?? readModelPgliteDir),
1378
2109
  parsers: PGLITE_UTC_PARSERS
1379
2110
  });
1380
2111
  }
@@ -1389,7 +2120,9 @@ async function initServer(serverPort, options, renown, renownConfig) {
1389
2120
  processors: vetraProcessorFactory ? { "@powerhousedao/vetra": [vetraProcessorFactory] } : {},
1390
2121
  configFile: configPath,
1391
2122
  mcp: options.mcp ?? true,
2123
+ inspection: options.inspection === false ? false : { throttle: inspectionThrottle },
1392
2124
  logger: apiLogger,
2125
+ reportError,
1393
2126
  enableDocumentModelSubgraphs: options.enableDocumentModelSubgraphs,
1394
2127
  renown: renownConfig,
1395
2128
  verifyCredential
@@ -1401,14 +2134,155 @@ async function initServer(serverPort, options, renown, renownConfig) {
1401
2134
  await abortBoot(api);
1402
2135
  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.`);
1403
2136
  }
1404
- localCredentialCheck = createLocalCredentialVerifier((query, variables) => manager.executeSubgraphQuery(RENOWN_READ_MODEL_SUBGRAPH, query, variables), { onError: (error) => logger.error("Renown read model query failed: @error", error) });
2137
+ localRenownRequest = (query, variables) => manager.executeSubgraphQuery(RENOWN_READ_MODEL_SUBGRAPH, query, variables);
2138
+ localCredentialCheck = createLocalCredentialVerifier(localRenownRequest, { onError: (error) => logger.error("Renown read model query failed: @error", error) });
1405
2139
  logger.info("Renown credentials will be verified against this switchboard's own renown read model");
1406
2140
  }
1407
- registerAttachmentRoutes(api);
1408
- const attachmentService = createRemoteAttachmentService(deriveAttachmentServiceConfig(options, serverPort, renown));
2141
+ let attachmentService;
2142
+ if (pluginHost) {
2143
+ pluginHost.ctx.api = api;
2144
+ pluginHost.ctx.serverPort = serverPort;
2145
+ await pluginHost.observe("onHttpMounting");
2146
+ attachmentService = pluginHost.ctx.attachmentService;
2147
+ } else {
2148
+ registerAttachmentRoutes(api);
2149
+ attachmentService = createRemoteAttachmentService(deriveAttachmentServiceConfig(options, serverPort, renown));
2150
+ }
1409
2151
  if (process.env.SENTRY_DSN) api.httpAdapter.setupSentryErrorHandler(Sentry);
1410
2152
  const { client, graphqlManager, documentModelRegistry } = api;
1411
2153
  const lateSubgraphs = [];
2154
+ if (pluginHost) {
2155
+ pluginHost.ctx.client = client;
2156
+ pluginHost.ctx.graphqlManager = graphqlManager;
2157
+ pluginHost.ctx.lateSubgraphs = lateSubgraphs;
2158
+ pluginHost.ctx.reactorClientModule = options.reactor ?? ownedReactorModule;
2159
+ await pluginHost.observe("onReactorReady");
2160
+ }
2161
+ let workflows;
2162
+ let workflowsRetry;
2163
+ const composeWorkflows = () => composeWorkflowRuntime({
2164
+ reactorClient: client,
2165
+ clientModule: options.reactor ?? ownedReactorModule,
2166
+ relationalDb: api.relationalDb,
2167
+ secretsKeyFile: readModelPgliteDir === null ? false : void 0,
2168
+ storageId: readModelPgliteDir === null ? readModelPath : path$1.resolve(readModelPath),
2169
+ attachments: createAttachmentClient(api.attachments.service),
2170
+ attachmentAccess: api.attachmentAccess,
2171
+ webhooks: api.httpRoutes.scopeFor(WORKFLOW_PACKAGE_NAME).webhooks,
2172
+ http: api.httpRoutes.scopeFor(WORKFLOW_PACKAGE_NAME),
2173
+ authorizationService: api.authorizationService,
2174
+ pieces: api.packageManager,
2175
+ pieceRegistryUrl: registryUrl,
2176
+ models: workerModels,
2177
+ reactorThreads: (workerPool?.numWorkers ?? 0) + (projectionWorker ? 1 : 0),
2178
+ logger: logger.child(["workflow-runtime"]),
2179
+ exclusiveJournal: readModelPgliteDir !== null,
2180
+ onSingletonLost: workflowSingletonLossHandler(logger),
2181
+ telemetry: {
2182
+ tracer: trace.getTracer(WORKFLOW_TELEMETRY_SCOPE),
2183
+ meter: metrics.getMeter(WORKFLOW_TELEMETRY_SCOPE)
2184
+ }
2185
+ });
2186
+ const registerWorkflowSubgraph = (composed) => {
2187
+ const WorkflowRuntimeSubgraph = composed.subgraph;
2188
+ const workflowSubgraph = new WorkflowRuntimeSubgraph({
2189
+ reactorClient: client,
2190
+ http: graphqlManager.scopeForPackage(WORKFLOW_PACKAGE_NAME),
2191
+ relationalDb: api.relationalDb,
2192
+ analyticsStore: void 0,
2193
+ graphqlManager,
2194
+ syncManager: api.syncManager,
2195
+ authorizationService: graphqlManager.getAuthorizationService(),
2196
+ path: graphqlManager.getBasePath(),
2197
+ attachments: api.attachmentClientProvider
2198
+ });
2199
+ return graphqlManager.registerSubgraphInstance(workflowSubgraph, "graphql", false).catch((error) => {
2200
+ reportFailure(reporting, error, "Failed to register workflow-runtime subgraph: @error");
2201
+ });
2202
+ };
2203
+ if (!pluginHost && workflowsEnabled) try {
2204
+ workflows = await composeWorkflows();
2205
+ } catch (error) {
2206
+ if (!isWorkflowSingletonConflict(error)) throw error;
2207
+ logger.warn(`Workflows are enabled but another live process ("${error.owner ?? "unknown"}") holds the workflow singleton until ${error.expiresAt ?? "unknown"}. This Switchboard has booted WITHOUT the workflow runtime: no trigger of any kind fires here, and the workflow GraphQL face is absent. Everything else serves normally. Stop the other owner, or set PH_WORKFLOWS_SINGLETON_OWNER to the same stable name on the slot that owns workflows. This Switchboard retries the claim and starts workflows once the lease comes free.`);
2208
+ workflowsRetry = retryWorkflowSingleton({
2209
+ compose: composeWorkflows,
2210
+ onComposed: async (composed) => {
2211
+ try {
2212
+ await composed.start();
2213
+ } catch (error) {
2214
+ try {
2215
+ await composed.stop();
2216
+ } catch (stopError) {
2217
+ logger.error("Stopping the late workflow runtime failed: @error", stopError);
2218
+ }
2219
+ throw error;
2220
+ }
2221
+ logger.info("Workflow runtime started");
2222
+ workflows = composed;
2223
+ await registerWorkflowSubgraph(composed);
2224
+ try {
2225
+ await graphqlManager.updateRouter(true);
2226
+ } catch (error) {
2227
+ reportFailure(reporting, error, "Mounting the late workflow-runtime subgraph failed: @error");
2228
+ }
2229
+ },
2230
+ logger
2231
+ });
2232
+ }
2233
+ if (workflows) {
2234
+ lateSubgraphs.push(registerWorkflowSubgraph(workflows));
2235
+ await workflows.start();
2236
+ logger.info("Workflow runtime started");
2237
+ api.inspection?.facts.setWorkflows(true);
2238
+ }
2239
+ if (pluginHost) {
2240
+ pluginHost.ctx.workflowsOrchestration = {
2241
+ enabled: options.workflows?.enabled === true,
2242
+ composeWorkflows,
2243
+ registerWorkflowSubgraph,
2244
+ updateRouter: () => graphqlManager.updateRouter(true),
2245
+ reportMountFailure: (error) => reportFailure(reporting, error, "Mounting the late workflow-runtime subgraph failed: @error"),
2246
+ setWorkflowsFact: () => api.inspection?.facts.setWorkflows(true)
2247
+ };
2248
+ try {
2249
+ await pluginHost.observe("onSubgraphsRegistering");
2250
+ } catch (error) {
2251
+ await pluginHost.ctx.workflowsRetry?.stop();
2252
+ await pluginHost.ctx.workflows?.stop();
2253
+ await abortBoot(api);
2254
+ throw error;
2255
+ }
2256
+ }
2257
+ let privacy;
2258
+ if (!pluginHost && privacyConfig.enabled) {
2259
+ const signer = options.reactor ? options.privacy?.signer : options.privacy?.signer ?? renown?.signer;
2260
+ try {
2261
+ privacy = await startPrivacy({
2262
+ config: privacyConfig,
2263
+ reactorModule: (options.reactor ?? ownedReactorModule)?.reactorModule,
2264
+ signer,
2265
+ authorizationService: api.authorizationService,
2266
+ documentPermissionService: api.documentPermissionService,
2267
+ graphqlManager,
2268
+ reactorClient: client,
2269
+ logger: logger.child(["privacy"])
2270
+ });
2271
+ } catch (error) {
2272
+ await workflowsRetry?.stop();
2273
+ await workflows?.stop();
2274
+ await abortBoot(api);
2275
+ throw error;
2276
+ }
2277
+ }
2278
+ const shutdown = async () => {
2279
+ if (pluginHost) await pluginHost.observe("onShutdown");
2280
+ await privacy?.stop();
2281
+ await workflowsRetry?.stop();
2282
+ await workflows?.stop();
2283
+ await api.dispose();
2284
+ };
2285
+ apiRef.current = { dispose: shutdown };
1412
2286
  if (httpLoader) {
1413
2287
  const packageManagementService = new PackageManagementService({
1414
2288
  defaultRegistryUrl: registryUrl,
@@ -1418,7 +2292,7 @@ async function initServer(serverPort, options, renown, renownConfig) {
1418
2292
  });
1419
2293
  packageManagementService.setOnModelsChanged(() => {
1420
2294
  graphqlManager.regenerateDocumentModelSubgraphs().catch((error) => {
1421
- logger.error("Failed to regenerate document model subgraphs: @error", error);
2295
+ reportFailure(reporting, error, "Failed to regenerate document model subgraphs: @error");
1422
2296
  });
1423
2297
  });
1424
2298
  const packagesSubgraph = new PackagesSubgraph({
@@ -1430,35 +2304,41 @@ async function initServer(serverPort, options, renown, renownConfig) {
1430
2304
  path: graphqlManager.getBasePath(),
1431
2305
  authorizationService: graphqlManager.getAuthorizationService(),
1432
2306
  packageManagementService,
1433
- http: graphqlManager.scopeForPackage("@powerhousedao/switchboard")
2307
+ http: graphqlManager.scopeForPackage("@powerhousedao/switchboard"),
2308
+ attachments: api.attachmentClientProvider
1434
2309
  });
1435
2310
  lateSubgraphs.push(graphqlManager.registerSubgraphInstance(packagesSubgraph, "graphql", false).catch((error) => {
1436
- logger.error("Failed to register packages subgraph: @error", error);
2311
+ reportFailure(reporting, error, "Failed to register packages subgraph: @error");
1437
2312
  }));
1438
2313
  }
1439
2314
  if (driveNodeView) {
1440
2315
  graphqlManager.setAdditionalContextFields({ readModel: driveNodeView });
2316
+ const authorizationService = graphqlManager.getAuthorizationService();
1441
2317
  const reactorDriveSubgraph = {
1442
- name: "reactor-drive",
2318
+ name: REACTOR_DRIVE_SUBGRAPH_NAME,
1443
2319
  path: graphqlManager.getBasePath(),
1444
- resolvers: createReactorDriveResolvers(),
2320
+ resolvers: createReactorDriveResolvers({
2321
+ reactorClient: client,
2322
+ readModel: driveNodeView,
2323
+ hostCanRead: (documentId, address) => authorizationService.canRead(documentId, address)
2324
+ }),
1445
2325
  typeDefs: reactorDriveSubgraphTypeDefs,
1446
2326
  reactorClient: client,
1447
2327
  relationalDb: void 0
1448
2328
  };
1449
2329
  lateSubgraphs.push(graphqlManager.registerSubgraphInstance(reactorDriveSubgraph, "graphql", false).catch((error) => {
1450
- logger.error("Failed to register reactor-drive subgraph: @error", error);
2330
+ reportFailure(reporting, error, "Failed to register reactor-drive subgraph: @error");
1451
2331
  }));
1452
2332
  }
1453
- (async () => {
1454
- await Promise.all(lateSubgraphs);
2333
+ runDetached("Marking the API ready", async () => {
2334
+ await Promise.allSettled(lateSubgraphs);
1455
2335
  try {
1456
2336
  await graphqlManager.updateRouter(true);
1457
2337
  } catch (error) {
1458
- logger.error("Final router update before readiness failed: @error", error);
2338
+ reportFailure(reporting, error, "Final router update before readiness failed: @error");
1459
2339
  }
1460
2340
  api.readiness.markReady();
1461
- })();
2341
+ }, reporting);
1462
2342
  if (options.drive) {
1463
2343
  if (!renown) throw new Error("Cannot create default drive without Renown identity");
1464
2344
  if ((options.drive.documentType ?? "powerhouse/document-drive") === "powerhouse/reactor-drive") defaultDriveUrl = await addDefaultReactorDrive(client, options.drive, serverPort);
@@ -1486,15 +2366,27 @@ async function initServer(serverPort, options, renown, renownConfig) {
1486
2366
  if (!defaultDriveUrl && driveId) defaultDriveUrl = `${options.https ? "https" : "http"}://localhost:${serverPort}/d/${driveId}`;
1487
2367
  }
1488
2368
  }
2369
+ if (pluginHost) await pluginHost.observe("onDrivesReady");
1489
2370
  return {
1490
2371
  defaultDriveUrl,
1491
2372
  api,
1492
2373
  reactor: client,
1493
2374
  attachmentService,
1494
2375
  attachmentReferenceProjection: api.attachmentReferenceProjection,
2376
+ get workflowTriggers() {
2377
+ return (workflows ?? pluginHost?.ctx.workflows)?.triggers;
2378
+ },
2379
+ workflowsEnabled,
2380
+ modelManifest: () => workerModels?.modelManifest() ?? [],
2381
+ privacy: (() => {
2382
+ const running = privacy ?? pluginHost?.ctx.privacy;
2383
+ return running ? { erasure: running.erasure } : void 0;
2384
+ })(),
2385
+ mcpEnabled: options.mcp !== false,
2386
+ inspectionEnabled: options.inspection !== false,
1495
2387
  renown,
1496
2388
  port: serverPort,
1497
- shutdown: () => api.dispose()
2389
+ shutdown
1498
2390
  };
1499
2391
  }
1500
2392
  /**
@@ -1517,20 +2409,37 @@ async function initServer(serverPort, options, renown, renownConfig) {
1517
2409
  const startSwitchboard = async (options = {}) => {
1518
2410
  const requestedPort = options.port ?? DEFAULT_PORT;
1519
2411
  const logger = options.logger ?? defaultLogger;
2412
+ if (process.env.PYROSCOPE_SERVER_ADDRESS) await initProfilerFromEnv(process.env).catch((error) => logger.error("Error starting profiler: @error", error));
1520
2413
  const serverPort = await resolveServerPort(requestedPort, options.strictPort ?? false, logger);
1521
2414
  const featureFlags = await initFeatureFlags();
1522
2415
  const enableDocumentModelSubgraphs = await featureFlags.getBooleanValue(DOCUMENT_MODEL_SUBGRAPHS_ENABLED, options.enableDocumentModelSubgraphs ?? DOCUMENT_MODEL_SUBGRAPHS_ENABLED_DEFAULT);
1523
2416
  options.enableDocumentModelSubgraphs = enableDocumentModelSubgraphs;
1524
- const requireSignatures = options.identity?.requireSignatures ?? await featureFlags.getBooleanValue(REQUIRE_SIGNATURES, REQUIRE_SIGNATURES_DEFAULT);
2417
+ if (!isPluginHostEnabled()) {
2418
+ options.mcp = await resolveMcpEnabled({
2419
+ featureFlags,
2420
+ option: options.mcp
2421
+ });
2422
+ const configPathForFlags = resolveConfigPath(options.configFile);
2423
+ options.workflows = { enabled: await resolveWorkflowsEnabled({
2424
+ featureFlags,
2425
+ override: options.workflows?.enabled,
2426
+ configEnabled: readConfigWorkflowsEnabled(configPathForFlags)
2427
+ }) };
2428
+ }
2429
+ options.inspection = await resolveInspectionEnabled({
2430
+ featureFlags,
2431
+ option: options.inspection
2432
+ });
1525
2433
  const renownConfig = resolveRenownConfig(getConfig(resolveConfigPath(options.configFile)).auth?.renown, process.env, logger);
1526
2434
  options.identity = {
1527
2435
  ...options.identity,
1528
- requireSignatures,
1529
2436
  baseUrl: options.identity?.baseUrl ?? renownConfig.url
1530
2437
  };
1531
2438
  logger.info("Feature flags: @flags", JSON.stringify({
1532
2439
  DOCUMENT_MODEL_SUBGRAPHS_ENABLED: enableDocumentModelSubgraphs,
1533
- REQUIRE_SIGNATURES: requireSignatures
2440
+ MCP_ENABLED: options.mcp,
2441
+ INSPECTION_ENABLED: options.inspection,
2442
+ PH_WORKFLOWS_ENABLED: options.workflows?.enabled
1534
2443
  }, null, 2));
1535
2444
  let renown = null;
1536
2445
  try {
@@ -1543,13 +2452,14 @@ const startSwitchboard = async (options = {}) => {
1543
2452
  return await initServer(serverPort, options, renown, renownConfig);
1544
2453
  } catch (e) {
1545
2454
  Sentry.captureException(e);
1546
- logger.error("App crashed: @error", e);
2455
+ if (StoredDocumentsRefusedError.isError(e)) logger.error(e.message);
2456
+ else logger.error("App crashed: @error", e);
1547
2457
  throw e;
1548
2458
  }
1549
2459
  };
1550
- if (import.meta.main) await startSwitchboard();
2460
+ if (import.meta.main) await startSwitchboard({ fatalErrorShutdown: true });
1551
2461
  //#endregion
1552
- export { parseForcePgVersion as a, applySwitchboardReactorDefaults as i, isPortAvailable as n, startSwitchboard as r, deriveAttachmentServiceConfig as t };
2462
+ export { StoredDocumentsRefusedError as a, applySwitchboardReactorDefaults as c, startSwitchboard as i, initProfilerFromEnv as l, deriveAttachmentServiceConfig as n, resolveUnsupportedStoredDocuments as o, isPortAvailable as r, attachmentsPlugin as s, createReactorKysely as t, parseForcePgVersion as u };
1553
2463
 
1554
- //# sourceMappingURL=server-CiKkVE6g.mjs.map
1555
- //# debugId=e2c62b7b-68fd-59c2-ab82-7d035e11698b
2464
+ //# sourceMappingURL=server-C9RQTWTA.mjs.map
2465
+ //# debugId=df5034a8-237d-504e-8285-9d6b6c57229a