@powerhousedao/switchboard 6.2.3-dev.7 → 6.2.3-dev.70

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