@powerhousedao/switchboard 6.2.3-staging.0 → 6.3.0-dev.1

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