@burdenoff/be-sdk 2026.1110.1 → 2026.1110.3

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 (469) hide show
  1. package/configs/eslint/index.js +1 -1
  2. package/configs/tsconfig/tsconfig.json +1 -1
  3. package/dist/EventQueueFactory-9NGZV9jl.js +1457 -0
  4. package/dist/EventQueueFactory-9NGZV9jl.js.map +1 -0
  5. package/dist/RedisStreamsConnection-CY8WySJy.js +283 -0
  6. package/dist/RedisStreamsConnection-CY8WySJy.js.map +1 -0
  7. package/dist/ai-credits/index.d.ts +2 -3
  8. package/dist/ai-credits/index.js +3 -4
  9. package/dist/ai-credits/index.js.map +1 -1
  10. package/dist/ai-credits-Ca-NNcVx.js +546 -0
  11. package/dist/ai-credits-Ca-NNcVx.js.map +1 -0
  12. package/dist/{assistant-session-CJZhF4D6.d.ts → assistant-session-DA5ZKJOr.d.ts} +4 -5
  13. package/dist/auth/index.d.ts +2 -77
  14. package/dist/auth/index.js +3 -7
  15. package/dist/auth/index.js.map +1 -1
  16. package/dist/auth-CEuBEBQN.js +228 -0
  17. package/dist/auth-CEuBEBQN.js.map +1 -0
  18. package/dist/cache/index.d.ts +2 -3
  19. package/dist/cache/index.js +3 -7
  20. package/dist/cache/index.js.map +1 -1
  21. package/dist/cache-CU0uLwcS.js +1837 -0
  22. package/dist/cache-CU0uLwcS.js.map +1 -0
  23. package/dist/captcha/index.d.ts +2 -1
  24. package/dist/captcha/index.js +3 -3
  25. package/dist/captcha/index.js.map +1 -1
  26. package/dist/captcha-BT7yh1YS.js +77 -0
  27. package/dist/captcha-BT7yh1YS.js.map +1 -0
  28. package/dist/client/internal-client.d.ts +4 -7
  29. package/dist/client/internal-client.js +172 -4
  30. package/dist/client/internal-client.js.map +1 -1
  31. package/dist/client-BgAEvDC2.d.ts +86 -0
  32. package/dist/client-DcZ3iGES.js +565 -0
  33. package/dist/client-DcZ3iGES.js.map +1 -0
  34. package/dist/collector-endpoint-iyQYeI50.js +50 -0
  35. package/dist/collector-endpoint-iyQYeI50.js.map +1 -0
  36. package/dist/context-CZnXf2yb.js +247 -0
  37. package/dist/context-CZnXf2yb.js.map +1 -0
  38. package/dist/crypto/index.d.ts +2 -1
  39. package/dist/crypto/index.js +3 -3
  40. package/dist/crypto/index.js.map +1 -1
  41. package/dist/crypto-DO9fM0FO.js +145 -0
  42. package/dist/crypto-DO9fM0FO.js.map +1 -0
  43. package/dist/database/index.d.ts +104 -108
  44. package/dist/database/index.js +468 -6
  45. package/dist/database/index.js.map +1 -1
  46. package/dist/dataloader/index.d.ts +2 -1
  47. package/dist/dataloader/index.js +3 -3
  48. package/dist/dataloader/index.js.map +1 -1
  49. package/dist/dataloader-DwpT3YoS.js +294 -0
  50. package/dist/dataloader-DwpT3YoS.js.map +1 -0
  51. package/dist/deployed-environment-p_Tdl3sT.js +38 -0
  52. package/dist/deployed-environment-p_Tdl3sT.js.map +1 -0
  53. package/dist/dist-BGKdXVy3.js +1718 -0
  54. package/dist/dist-BGKdXVy3.js.map +1 -0
  55. package/dist/env-DdaoGjIt.js +74 -0
  56. package/dist/env-DdaoGjIt.js.map +1 -0
  57. package/dist/event-queue/index.d.ts +2 -7
  58. package/dist/event-queue/index.js +7 -9
  59. package/dist/event-queue/index.js.map +1 -1
  60. package/dist/event-queue-Cw-YJPY_.js +1384 -0
  61. package/dist/event-queue-Cw-YJPY_.js.map +1 -0
  62. package/dist/{explicit-activity-scope-CCoxVwAr.d.ts → explicit-activity-scope-D8VeGGpt.d.ts} +1 -2
  63. package/dist/export/index.d.ts +2 -2
  64. package/dist/export/index.js +3 -14
  65. package/dist/export/index.js.map +1 -1
  66. package/dist/export-B6fphx8a.js +642 -0
  67. package/dist/export-B6fphx8a.js.map +1 -0
  68. package/dist/feature-flags/index.d.ts +2 -10
  69. package/dist/feature-flags/index.js +3 -6
  70. package/dist/feature-flags/index.js.map +1 -1
  71. package/dist/feature-flags-71oDkrUe.js +422 -0
  72. package/dist/feature-flags-71oDkrUe.js.map +1 -0
  73. package/dist/files/index.d.ts +2 -3
  74. package/dist/files/index.js +3 -4
  75. package/dist/files/index.js.map +1 -1
  76. package/dist/files-DjH0099H.js +830 -0
  77. package/dist/files-DjH0099H.js.map +1 -0
  78. package/dist/gateway/index.d.ts +4 -6
  79. package/dist/gateway/index.js +7 -13
  80. package/dist/gateway/index.js.map +1 -1
  81. package/dist/gateway/security/index.d.ts +2 -2
  82. package/dist/gateway/security/index.js +3 -5
  83. package/dist/gateway/security/index.js.map +1 -1
  84. package/dist/gateway-DBFmxWks.js +50 -0
  85. package/dist/gateway-DBFmxWks.js.map +1 -0
  86. package/dist/graph/index.d.ts +3 -10
  87. package/dist/graph/index.js +4 -13
  88. package/dist/graph/index.js.map +1 -1
  89. package/dist/graph-DDYgIryR.js +2152 -0
  90. package/dist/graph-DDYgIryR.js.map +1 -0
  91. package/dist/graph-emitter-CdOXP7Tn.js +621 -0
  92. package/dist/graph-emitter-CdOXP7Tn.js.map +1 -0
  93. package/dist/graphql/index.d.ts +3 -2
  94. package/dist/graphql/index.js +4 -6
  95. package/dist/graphql/index.js.map +1 -1
  96. package/dist/graphql/services/index.d.ts +2 -24
  97. package/dist/graphql/services/index.js +3 -4
  98. package/dist/graphql/services/index.js.map +1 -1
  99. package/dist/graphql-DHAHHcww.js +161 -0
  100. package/dist/graphql-DHAHHcww.js.map +1 -0
  101. package/dist/graphql-DNkMkGBZ.d.ts +21 -0
  102. package/dist/i18n/index.d.ts +3 -3
  103. package/dist/i18n/index.js +3 -4
  104. package/dist/i18n/index.js.map +1 -1
  105. package/dist/i18n-BBMYFd0P.js +860 -0
  106. package/dist/i18n-BBMYFd0P.js.map +1 -0
  107. package/dist/import-optional-peer-B82VYxeX.js +18 -0
  108. package/dist/import-optional-peer-B82VYxeX.js.map +1 -0
  109. package/dist/index-3KOZ1zN9.d.ts +233 -0
  110. package/dist/index-BBqooJ52.d.ts +45 -0
  111. package/dist/index-BGzMYJsm.d.ts +209 -0
  112. package/dist/index-BKwHQtHQ.d.ts +63 -0
  113. package/dist/index-BMIMnp6T.d.ts +8 -0
  114. package/dist/index-BQDsNAMR.d.ts +81 -0
  115. package/dist/index-BVOL7458.d.ts +10 -0
  116. package/dist/index-BcqQs-Uq.d.ts +69 -0
  117. package/dist/index-BeVtqGO-.d.ts +208 -0
  118. package/dist/index-BiTzGUZP.d.ts +114 -0
  119. package/dist/index-BqYfCQSP.d.ts +500 -0
  120. package/dist/index-C0qLquY0.d.ts +150 -0
  121. package/dist/index-C5uEKchX.d.ts +60 -0
  122. package/dist/index-CDOqxSIi.d.ts +37 -0
  123. package/dist/index-CG6wj66Y.d.ts +148 -0
  124. package/dist/index-CIgoeobA.d.ts +145 -0
  125. package/dist/index-CPQDMSFS.d.ts +103 -0
  126. package/dist/index-CSRcgkVi.d.ts +23 -0
  127. package/dist/index-CZTnQIRU.d.ts +341 -0
  128. package/dist/index-CaM9JUcc.d.ts +144 -0
  129. package/dist/index-CkT2aUr3.d.ts +704 -0
  130. package/dist/index-CliOgq6L.d.ts +203 -0
  131. package/dist/index-CnzbJZP7.d.ts +999 -0
  132. package/dist/index-D6UeLAye.d.ts +63 -0
  133. package/dist/index-DGgh9DWn.d.ts +59 -0
  134. package/dist/index-DY3dNhMN.d.ts +420 -0
  135. package/dist/index-DZC-2o9R.d.ts +207 -0
  136. package/dist/index-DqbGqfAy.d.ts +127 -0
  137. package/dist/index-Dt1HJPTX.d.ts +12 -0
  138. package/dist/index-DtI6aBtB.d.ts +22 -0
  139. package/dist/index-FKohsiex.d.ts +38 -0
  140. package/dist/index-FbXPfen7.d.ts +132 -0
  141. package/dist/index-MArCb8Aq.d.ts +306 -0
  142. package/dist/index-N-huORcj.d.ts +303 -0
  143. package/dist/index-YOShAwkq.d.ts +45 -0
  144. package/dist/index-bZKZUvBu.d.ts +646 -0
  145. package/dist/index-yBSjMY32.d.ts +24 -0
  146. package/dist/index.d.ts +501 -544
  147. package/dist/index.js +1820 -2171
  148. package/dist/index.js.map +1 -1
  149. package/dist/init/index.d.ts +2 -2
  150. package/dist/init/index.js +3 -16
  151. package/dist/init/index.js.map +1 -1
  152. package/dist/init-Dy3KhT6Y.js +325 -0
  153. package/dist/init-Dy3KhT6Y.js.map +1 -0
  154. package/dist/instrumentation/index.d.ts +3 -4
  155. package/dist/instrumentation/index.js +5 -5
  156. package/dist/instrumentation/index.js.map +1 -1
  157. package/dist/instrumentation-xkkmDgJ0.js +1678 -0
  158. package/dist/instrumentation-xkkmDgJ0.js.map +1 -0
  159. package/dist/lake/index.d.ts +50 -54
  160. package/dist/lake/index.js +169 -193
  161. package/dist/lake/index.js.map +1 -1
  162. package/dist/layer/index.d.ts +3 -2
  163. package/dist/layer/index.js +4 -5
  164. package/dist/layer/index.js.map +1 -1
  165. package/dist/layer-BZBZZWeV.d.ts +69 -0
  166. package/dist/layer-Bcix-WCl.js +105 -0
  167. package/dist/layer-Bcix-WCl.js.map +1 -0
  168. package/dist/layer-CEKy6cm8.js +252 -0
  169. package/dist/layer-CEKy6cm8.js.map +1 -0
  170. package/dist/lifecycle/index.d.ts +2 -1
  171. package/dist/lifecycle/index.js +3 -4
  172. package/dist/lifecycle/index.js.map +1 -1
  173. package/dist/lifecycle-DeoLSX0U.js +76 -0
  174. package/dist/lifecycle-DeoLSX0U.js.map +1 -0
  175. package/dist/logger/index.d.ts +2 -3
  176. package/dist/logger/index.js +3 -3
  177. package/dist/logger/index.js.map +1 -1
  178. package/dist/logger-B6rCpb7D.js +290 -0
  179. package/dist/logger-B6rCpb7D.js.map +1 -0
  180. package/dist/metrics/index.d.ts +13 -14
  181. package/dist/metrics/index.js +3 -4
  182. package/dist/metrics/index.js.map +1 -1
  183. package/dist/metrics-BrLwNUrb.js +52 -0
  184. package/dist/metrics-BrLwNUrb.js.map +1 -0
  185. package/dist/metrics-collector-C2eShrlW.js +922 -0
  186. package/dist/metrics-collector-C2eShrlW.js.map +1 -0
  187. package/dist/middleware/index.d.ts +3 -3
  188. package/dist/middleware/index.js +3 -4
  189. package/dist/middleware/index.js.map +1 -1
  190. package/dist/middleware-CUxJVUpD.js +1243 -0
  191. package/dist/middleware-CUxJVUpD.js.map +1 -0
  192. package/dist/middleware-Cq0zFMGp.js +253 -0
  193. package/dist/middleware-Cq0zFMGp.js.map +1 -0
  194. package/dist/notifications/index.d.ts +2 -5
  195. package/dist/notifications/index.js +3 -6
  196. package/dist/notifications/index.js.map +1 -1
  197. package/dist/notifications-CdETrtFK.js +869 -0
  198. package/dist/notifications-CdETrtFK.js.map +1 -0
  199. package/dist/observability/index.d.ts +2 -3
  200. package/dist/observability/index.js +3 -4
  201. package/dist/observability/index.js.map +1 -1
  202. package/dist/observability-DBDXipTU.js +272 -0
  203. package/dist/observability-DBDXipTU.js.map +1 -0
  204. package/dist/platform/index.d.ts +2 -1
  205. package/dist/platform/index.js +3 -5
  206. package/dist/platform/index.js.map +1 -1
  207. package/dist/platform-DZwczW7v.js +1510 -0
  208. package/dist/platform-DZwczW7v.js.map +1 -0
  209. package/dist/prisma/generator/index.d.ts +1 -1
  210. package/dist/prisma/generator/index.js +97 -84
  211. package/dist/prisma/generator/index.js.map +1 -1
  212. package/dist/prisma/index.d.ts +4 -7
  213. package/dist/prisma/index.js +5 -12
  214. package/dist/prisma/index.js.map +1 -1
  215. package/dist/prisma-BzOOdt79.js +863 -0
  216. package/dist/prisma-BzOOdt79.js.map +1 -0
  217. package/dist/prisma-extension-Cfl09swM.d.ts +172 -0
  218. package/dist/product-alias/index.d.ts +2 -1
  219. package/dist/product-alias/index.js +3 -3
  220. package/dist/product-alias/index.js.map +1 -1
  221. package/dist/product-alias-BPqtskMq.js +273 -0
  222. package/dist/product-alias-BPqtskMq.js.map +1 -0
  223. package/dist/rbac/index.d.ts +2 -122
  224. package/dist/rbac/index.js +3 -6
  225. package/dist/rbac/index.js.map +1 -1
  226. package/dist/rbac-BB9l9Xph.js +1486 -0
  227. package/dist/rbac-BB9l9Xph.js.map +1 -0
  228. package/dist/resource-caps/index.d.ts +66 -72
  229. package/dist/resource-caps/index.js +430 -5
  230. package/dist/resource-caps/index.js.map +1 -1
  231. package/dist/rolldown-runtime-ad2WFvuA.js +17 -0
  232. package/dist/sdk-Dju9o-sq.js +124 -0
  233. package/dist/sdk-Dju9o-sq.js.map +1 -0
  234. package/dist/security-DIG-95Ic.js +1647 -0
  235. package/dist/security-DIG-95Ic.js.map +1 -0
  236. package/dist/server/index.d.ts +7 -164
  237. package/dist/server/index.js +2000 -1507
  238. package/dist/server/index.js.map +1 -1
  239. package/dist/service-jwt-Bu-WNA_-.js +80 -0
  240. package/dist/service-jwt-Bu-WNA_-.js.map +1 -0
  241. package/dist/services-BWzfz7vG.js +102 -0
  242. package/dist/services-BWzfz7vG.js.map +1 -0
  243. package/dist/sharding/index.d.ts +41 -44
  244. package/dist/sharding/index.js +156 -137
  245. package/dist/sharding/index.js.map +1 -1
  246. package/dist/sharing/index.d.ts +2 -1
  247. package/dist/sharing/index.js +3 -4
  248. package/dist/sharing/index.js.map +1 -1
  249. package/dist/sharing-CflDsSJ-.js +911 -0
  250. package/dist/sharing-CflDsSJ-.js.map +1 -0
  251. package/dist/stub-BqwKn4eh.js +630 -0
  252. package/dist/stub-BqwKn4eh.js.map +1 -0
  253. package/dist/tags/index.d.ts +2 -3
  254. package/dist/tags/index.js +3 -4
  255. package/dist/tags/index.js.map +1 -1
  256. package/dist/tags-B5xpbgsk.js +868 -0
  257. package/dist/{chunk-PBZFAAOM.js.map → tags-B5xpbgsk.js.map} +1 -1
  258. package/dist/telemetry/index.d.ts +64 -76
  259. package/dist/telemetry/index.js +369 -201
  260. package/dist/telemetry/index.js.map +1 -1
  261. package/dist/temporal/index.d.ts +2 -148
  262. package/dist/temporal/index.js +3 -5
  263. package/dist/temporal/index.js.map +1 -1
  264. package/dist/temporal-B534uYK8.js +706 -0
  265. package/dist/temporal-B534uYK8.js.map +1 -0
  266. package/dist/tracker/index.d.ts +5 -11
  267. package/dist/tracker/index.js +5 -20
  268. package/dist/tracker/index.js.map +1 -1
  269. package/dist/tracker-BQVoEFUo.js +839 -0
  270. package/dist/tracker-BQVoEFUo.js.map +1 -0
  271. package/dist/types-BYMYND1L.js +44 -0
  272. package/dist/types-BYMYND1L.js.map +1 -0
  273. package/dist/types-C6EKaS3V.d.ts +106 -0
  274. package/dist/types-CWybW61E.d.ts +323 -0
  275. package/dist/types-C_yfu3XK.d.ts +34 -0
  276. package/dist/types-Cj2RWXbz.js +90 -0
  277. package/dist/types-Cj2RWXbz.js.map +1 -0
  278. package/dist/types-DgaQqvxo.d.ts +70 -0
  279. package/dist/usage/index.d.ts +2 -213
  280. package/dist/usage/index.js +3 -15
  281. package/dist/usage/index.js.map +1 -1
  282. package/dist/usage-BKFZiWQn.js +682 -0
  283. package/dist/usage-BKFZiWQn.js.map +1 -0
  284. package/dist/utils/index.d.ts +2 -1
  285. package/dist/utils/index.js +3 -3
  286. package/dist/utils/index.js.map +1 -1
  287. package/dist/utils-DL85Tnbn.js +500 -0
  288. package/dist/utils-DL85Tnbn.js.map +1 -0
  289. package/dist/validation/index.d.ts +2 -2
  290. package/dist/validation/index.js +3 -3
  291. package/dist/validation/index.js.map +1 -1
  292. package/dist/validation-CPUITdMk.js +762 -0
  293. package/dist/validation-CPUITdMk.js.map +1 -0
  294. package/dist/workspace-extension-COrC0dYi.js +979 -0
  295. package/dist/workspace-extension-COrC0dYi.js.map +1 -0
  296. package/dist/{workspace-extension-BGwTOV_r.d.ts → workspace-extension-DTFTdGVF.d.ts} +43 -45
  297. package/package.json +7 -10
  298. package/dist/EventQueueFactory-PP534MBQ.js +0 -8
  299. package/dist/EventQueueFactory-PP534MBQ.js.map +0 -1
  300. package/dist/chunk-4XIBXZ6J.js +0 -276
  301. package/dist/chunk-4XIBXZ6J.js.map +0 -1
  302. package/dist/chunk-554Z4C2K.js +0 -1006
  303. package/dist/chunk-554Z4C2K.js.map +0 -1
  304. package/dist/chunk-5CAFHK2Z.js +0 -107
  305. package/dist/chunk-5CAFHK2Z.js.map +0 -1
  306. package/dist/chunk-63ZXJ42X.js +0 -451
  307. package/dist/chunk-63ZXJ42X.js.map +0 -1
  308. package/dist/chunk-6XEXJATV.js +0 -304
  309. package/dist/chunk-6XEXJATV.js.map +0 -1
  310. package/dist/chunk-726AR6Q7.js +0 -1532
  311. package/dist/chunk-726AR6Q7.js.map +0 -1
  312. package/dist/chunk-7EISSMFP.js +0 -617
  313. package/dist/chunk-7EISSMFP.js.map +0 -1
  314. package/dist/chunk-A5F6Z5UE.js +0 -21
  315. package/dist/chunk-A5F6Z5UE.js.map +0 -1
  316. package/dist/chunk-A6DE32ZS.js +0 -1507
  317. package/dist/chunk-A6DE32ZS.js.map +0 -1
  318. package/dist/chunk-BJQOGOVW.js +0 -602
  319. package/dist/chunk-BJQOGOVW.js.map +0 -1
  320. package/dist/chunk-CFXWH2IS.js +0 -52
  321. package/dist/chunk-CFXWH2IS.js.map +0 -1
  322. package/dist/chunk-DIOS6L7M.js +0 -690
  323. package/dist/chunk-DIOS6L7M.js.map +0 -1
  324. package/dist/chunk-DJNHR37J.js +0 -1185
  325. package/dist/chunk-DJNHR37J.js.map +0 -1
  326. package/dist/chunk-DRWH5XCJ.js +0 -876
  327. package/dist/chunk-DRWH5XCJ.js.map +0 -1
  328. package/dist/chunk-E4QNLVY4.js +0 -909
  329. package/dist/chunk-E4QNLVY4.js.map +0 -1
  330. package/dist/chunk-E6OAFS7A.js +0 -1346
  331. package/dist/chunk-E6OAFS7A.js.map +0 -1
  332. package/dist/chunk-EBDHIL7V.js +0 -774
  333. package/dist/chunk-EBDHIL7V.js.map +0 -1
  334. package/dist/chunk-ELU7VL3E.js +0 -245
  335. package/dist/chunk-ELU7VL3E.js.map +0 -1
  336. package/dist/chunk-FZRODKIN.js +0 -31
  337. package/dist/chunk-FZRODKIN.js.map +0 -1
  338. package/dist/chunk-GCIB76AJ.js +0 -882
  339. package/dist/chunk-GCIB76AJ.js.map +0 -1
  340. package/dist/chunk-HC6MPUIH.js +0 -1571
  341. package/dist/chunk-HC6MPUIH.js.map +0 -1
  342. package/dist/chunk-I3KOWRT3.js +0 -89
  343. package/dist/chunk-I3KOWRT3.js.map +0 -1
  344. package/dist/chunk-ID3WR4JS.js +0 -509
  345. package/dist/chunk-ID3WR4JS.js.map +0 -1
  346. package/dist/chunk-JVMAQOA3.js +0 -521
  347. package/dist/chunk-JVMAQOA3.js.map +0 -1
  348. package/dist/chunk-K56L7NUR.js +0 -1444
  349. package/dist/chunk-K56L7NUR.js.map +0 -1
  350. package/dist/chunk-KH4TRQCO.js +0 -1063
  351. package/dist/chunk-KH4TRQCO.js.map +0 -1
  352. package/dist/chunk-KJOSPVB2.js +0 -57
  353. package/dist/chunk-KJOSPVB2.js.map +0 -1
  354. package/dist/chunk-KO2ZXZ7W.js +0 -61
  355. package/dist/chunk-KO2ZXZ7W.js.map +0 -1
  356. package/dist/chunk-KS2HQCJR.js +0 -56
  357. package/dist/chunk-KS2HQCJR.js.map +0 -1
  358. package/dist/chunk-LA5KPWZ2.js +0 -413
  359. package/dist/chunk-LA5KPWZ2.js.map +0 -1
  360. package/dist/chunk-MESLAC5W.js +0 -574
  361. package/dist/chunk-MESLAC5W.js.map +0 -1
  362. package/dist/chunk-MWPYA2HD.js +0 -94
  363. package/dist/chunk-MWPYA2HD.js.map +0 -1
  364. package/dist/chunk-NUB5GQTU.js +0 -270
  365. package/dist/chunk-NUB5GQTU.js.map +0 -1
  366. package/dist/chunk-O2JMZHNH.js +0 -1908
  367. package/dist/chunk-O2JMZHNH.js.map +0 -1
  368. package/dist/chunk-OBBCR6WY.js +0 -277
  369. package/dist/chunk-OBBCR6WY.js.map +0 -1
  370. package/dist/chunk-OBZQ4AJC.js +0 -272
  371. package/dist/chunk-OBZQ4AJC.js.map +0 -1
  372. package/dist/chunk-OXNCBE7P.js +0 -971
  373. package/dist/chunk-OXNCBE7P.js.map +0 -1
  374. package/dist/chunk-PBZFAAOM.js +0 -941
  375. package/dist/chunk-PYD44IHJ.js +0 -728
  376. package/dist/chunk-PYD44IHJ.js.map +0 -1
  377. package/dist/chunk-QVPIACWD.js +0 -679
  378. package/dist/chunk-QVPIACWD.js.map +0 -1
  379. package/dist/chunk-QWNNFE4P.js +0 -41
  380. package/dist/chunk-QWNNFE4P.js.map +0 -1
  381. package/dist/chunk-RU266375.js +0 -327
  382. package/dist/chunk-RU266375.js.map +0 -1
  383. package/dist/chunk-RYTSVGGA.js +0 -1624
  384. package/dist/chunk-RYTSVGGA.js.map +0 -1
  385. package/dist/chunk-RZOFS2BQ.js +0 -225
  386. package/dist/chunk-RZOFS2BQ.js.map +0 -1
  387. package/dist/chunk-SBS4S2PJ.js +0 -100
  388. package/dist/chunk-SBS4S2PJ.js.map +0 -1
  389. package/dist/chunk-SPRG6G6G.js +0 -530
  390. package/dist/chunk-SPRG6G6G.js.map +0 -1
  391. package/dist/chunk-STWFX5E2.js +0 -233
  392. package/dist/chunk-STWFX5E2.js.map +0 -1
  393. package/dist/chunk-UNASM5VJ.js +0 -419
  394. package/dist/chunk-UNASM5VJ.js.map +0 -1
  395. package/dist/chunk-VAT66FJA.js +0 -245
  396. package/dist/chunk-VAT66FJA.js.map +0 -1
  397. package/dist/chunk-VFCMR5GX.js +0 -49
  398. package/dist/chunk-VFCMR5GX.js.map +0 -1
  399. package/dist/chunk-VGAHZKNJ.js +0 -66
  400. package/dist/chunk-VGAHZKNJ.js.map +0 -1
  401. package/dist/chunk-VTJTAAXC.js +0 -627
  402. package/dist/chunk-VTJTAAXC.js.map +0 -1
  403. package/dist/chunk-VXVLKRU6.js +0 -758
  404. package/dist/chunk-VXVLKRU6.js.map +0 -1
  405. package/dist/chunk-WWUU5ETI.js +0 -163
  406. package/dist/chunk-WWUU5ETI.js.map +0 -1
  407. package/dist/chunk-XE4OXN2W.js +0 -10
  408. package/dist/chunk-XE4OXN2W.js.map +0 -1
  409. package/dist/chunk-XOJORS75.js +0 -1853
  410. package/dist/chunk-XOJORS75.js.map +0 -1
  411. package/dist/chunk-YMZEUTD2.js +0 -110
  412. package/dist/chunk-YMZEUTD2.js.map +0 -1
  413. package/dist/chunk-ZZK3WEDI.js +0 -181
  414. package/dist/chunk-ZZK3WEDI.js.map +0 -1
  415. package/dist/client-CCXpAZ2r.d.ts +0 -89
  416. package/dist/client-DSI_760t.d.ts +0 -36
  417. package/dist/client-JU6T3UPB.js +0 -11
  418. package/dist/client-JU6T3UPB.js.map +0 -1
  419. package/dist/dist-2X4Q7PJA.js +0 -1491
  420. package/dist/dist-2X4Q7PJA.js.map +0 -1
  421. package/dist/env-4UWSUS64.js +0 -4
  422. package/dist/env-4UWSUS64.js.map +0 -1
  423. package/dist/graph-emitter-r5TylDBm.d.ts +0 -47
  424. package/dist/graphql-CMHMQjvd.d.ts +0 -23
  425. package/dist/i18n-Qm2AkPC-.d.ts +0 -33
  426. package/dist/index--yvpa6ay.d.ts +0 -83
  427. package/dist/index-4gKQKZ2B.d.ts +0 -71
  428. package/dist/index-5x0XMKXN.d.ts +0 -149
  429. package/dist/index-B70b5mYS.d.ts +0 -33
  430. package/dist/index-B8KrxO4j.d.ts +0 -755
  431. package/dist/index-BOuDKnqD.d.ts +0 -201
  432. package/dist/index-BTMt4OjA.d.ts +0 -201
  433. package/dist/index-BejbszA7.d.ts +0 -39
  434. package/dist/index-BkeOYZye.d.ts +0 -198
  435. package/dist/index-BuAj5nXg.d.ts +0 -83
  436. package/dist/index-BvkVcW8I.d.ts +0 -349
  437. package/dist/index-CWmH_-RZ.d.ts +0 -247
  438. package/dist/index-CbgWNcus.d.ts +0 -258
  439. package/dist/index-CmfPeQza.d.ts +0 -166
  440. package/dist/index-CmpG-zak.d.ts +0 -607
  441. package/dist/index-CoMKgL-p.d.ts +0 -12
  442. package/dist/index-D8HGwglK.d.ts +0 -541
  443. package/dist/index-DCaVm66D.d.ts +0 -1101
  444. package/dist/index-DE2w7E0d.d.ts +0 -83
  445. package/dist/index-DSOpj8DI.d.ts +0 -17
  446. package/dist/index-DW9q22GH.d.ts +0 -75
  447. package/dist/index-DnjJ9CwI.d.ts +0 -347
  448. package/dist/index-DwMJZ8PP.d.ts +0 -317
  449. package/dist/index-PaojfSdd.d.ts +0 -71
  450. package/dist/index-aHtYvc3i.d.ts +0 -284
  451. package/dist/index-e_18DzAg.d.ts +0 -18
  452. package/dist/index-ffmipXSA.d.ts +0 -55
  453. package/dist/index-joONjwLt.d.ts +0 -33
  454. package/dist/index-kssw5ziY.d.ts +0 -250
  455. package/dist/index-lFffh5-G.d.ts +0 -125
  456. package/dist/index-pxYge_6k.d.ts +0 -79
  457. package/dist/layer-Cv9vSwBx.d.ts +0 -70
  458. package/dist/pino-logger-H4HPW5P6.js +0 -5
  459. package/dist/pino-logger-H4HPW5P6.js.map +0 -1
  460. package/dist/prisma-extension-gYhYriA0.d.ts +0 -174
  461. package/dist/sdk-L75WWUP3.js +0 -156
  462. package/dist/sdk-L75WWUP3.js.map +0 -1
  463. package/dist/shutdown-registry-CW9LryO8.d.ts +0 -10
  464. package/dist/types-Bo2wkjSP.d.ts +0 -35
  465. package/dist/types-DVpvrAhd.d.ts +0 -71
  466. package/dist/types-DgJ4lDYA.d.ts +0 -108
  467. package/dist/types-USOv09qy.d.ts +0 -327
  468. package/dist/workspace-guard-NXVYYBVJ.js +0 -5
  469. package/dist/workspace-guard-NXVYYBVJ.js.map +0 -1
@@ -1,1635 +1,2128 @@
1
- import { createHumanReadableErrorPlugin, formatHttpError, normalizeGraphQLResponse, createHttpErrorResponse } from '../chunk-BJQOGOVW.js';
2
- export { UserFacingGraphQLError, createHttpErrorResponse, createHumanReadableErrorPlugin, createWorkspaceGuardPlugin, formatHttpError, normalizeError, normalizeExecutionResultErrors, normalizeGraphQLResponse, normalizeGraphQLResponsePayload, toUserFacingGraphQLError } from '../chunk-BJQOGOVW.js';
3
- import { getWorkspaceQuotaRegistry } from '../chunk-VGAHZKNJ.js';
4
- import { parseAssistantSessionHeaders, readAssistantSessionAttribution, trackOperation, createExplicitActivityScope, runInExplicitActivityScope } from '../chunk-JVMAQOA3.js';
5
- export { ACTOR_ORIGIN_HEADER, AI_ASSISTANT_ACTOR_ORIGIN, ASSISTANT_CORRELATION_ID_HEADER, ASSISTANT_SESSION_ID_HEADER, parseAssistantSessionHeaders, readAssistantSessionAttribution, suppressMutationAudit, toAssistantSessionAttribution } from '../chunk-JVMAQOA3.js';
6
- import { setWorkspaceContext, withWorkspaceContext } from '../chunk-E4QNLVY4.js';
7
- import { I18n } from '../chunk-EBDHIL7V.js';
8
- import { getMetricsRegistry } from '../chunk-GCIB76AJ.js';
9
- import { ContextManager } from '../chunk-RZOFS2BQ.js';
10
- import { logger } from '../chunk-RU266375.js';
11
- import { __name } from '../chunk-XE4OXN2W.js';
12
- import crypto from 'crypto';
13
- import { Kind, OperationTypeNode } from 'graphql';
1
+ import { t as __exportAll } from "../rolldown-runtime-ad2WFvuA.js";
2
+ import { a as logger } from "../logger-B6rCpb7D.js";
3
+ import { _ as runInExplicitActivityScope, c as ACTOR_ORIGIN_HEADER, d as ASSISTANT_SESSION_ID_HEADER, f as parseAssistantSessionHeaders, h as createExplicitActivityScope, l as AI_ASSISTANT_ACTOR_ORIGIN, m as toAssistantSessionAttribution, o as trackOperation, p as readAssistantSessionAttribution, u as ASSISTANT_CORRELATION_ID_HEADER, v as suppressMutationAudit } from "../stub-BqwKn4eh.js";
4
+ import { h as withWorkspaceContext, m as setWorkspaceContext } from "../workspace-extension-COrC0dYi.js";
5
+ import { t as ContextManager } from "../context-CZnXf2yb.js";
6
+ import { l as I18n } from "../i18n-BBMYFd0P.js";
7
+ import { o as getMetricsRegistry } from "../metrics-collector-C2eShrlW.js";
8
+ import { t as getWorkspaceQuotaRegistry } from "../metrics-BrLwNUrb.js";
9
+ import { GraphQLError, Kind, OperationTypeNode } from "graphql";
10
+ import crypto from "node:crypto";
14
11
 
15
12
  // src/server/delegated-identity.ts
13
+ /**
14
+ * The principal recorded as `onBehalfOf` for an operation.
15
+ *
16
+ * With a verified delegation the gateway has already authenticated the
17
+ * represented user as the actor, so the represented user is the principal.
18
+ * Without one the actor acts for itself. Caller-supplied consent headers are
19
+ * never consulted.
20
+ */
16
21
  function resolveOnBehalfOf(actor, verifiedDelegation) {
17
- if (verifiedDelegation && actor && verifiedDelegation.representedUserId === actor.id) {
18
- return verifiedDelegation.representedUserId;
19
- }
20
- return actor?.id;
22
+ if (verifiedDelegation && actor && verifiedDelegation.representedUserId === actor.id) return verifiedDelegation.representedUserId;
23
+ return actor?.id;
21
24
  }
22
- __name(resolveOnBehalfOf, "resolveOnBehalfOf");
25
+ /**
26
+ * Returns the verified delegated principal for a request context, or null when
27
+ * the request was not made under a verified `app_as_user` delegation.
28
+ */
23
29
  function getDelegatedPrincipal(context) {
24
- const delegation = context.verifiedDelegation;
25
- if (!delegation || !context.actor || delegation.representedUserId !== context.actor.id) {
26
- return null;
27
- }
28
- return {
29
- agentAppId: delegation.originatingAppId,
30
- onBehalfOfUserId: delegation.representedUserId,
31
- delegationId: delegation.delegationId,
32
- scopes: delegation.scopes,
33
- allowedWorkspaceIds: delegation.allowedWorkspaceIds,
34
- grantedBy: delegation.consent?.grantedBy ?? null,
35
- grantExpiresAt: delegation.consent?.expiresAt ?? null,
36
- tokenExpiresAt: delegation.tokenExpiresAt
37
- };
38
- }
39
- __name(getDelegatedPrincipal, "getDelegatedPrincipal");
30
+ const delegation = context.verifiedDelegation;
31
+ if (!delegation || !context.actor || delegation.representedUserId !== context.actor.id) return null;
32
+ return {
33
+ agentAppId: delegation.originatingAppId,
34
+ onBehalfOfUserId: delegation.representedUserId,
35
+ delegationId: delegation.delegationId,
36
+ scopes: delegation.scopes,
37
+ allowedWorkspaceIds: delegation.allowedWorkspaceIds,
38
+ grantedBy: delegation.consent?.grantedBy ?? null,
39
+ grantExpiresAt: delegation.consent?.expiresAt ?? null,
40
+ tokenExpiresAt: delegation.tokenExpiresAt
41
+ };
42
+ }
40
43
 
41
44
  // src/server/auth.ts
42
- var getDbFn = null;
45
+ /**
46
+ * Server Auth Module
47
+ *
48
+ * JWT verification with workspace secret fetching for microservices.
49
+ * Handles HS256 tokens with secrets stored in workspace database.
50
+ */
51
+ let getDbFn = null;
43
52
  async function getDb() {
44
- if (!getDbFn) {
45
- const prismaModule = await import('../prisma/index.js');
46
- getDbFn = prismaModule.getDb;
47
- }
48
- return getDbFn();
49
- }
50
- __name(getDb, "getDb");
51
- var joseModule = null;
52
- var jwtModule = null;
53
+ if (!getDbFn) getDbFn = (await import("../prisma/index.js")).getDb;
54
+ return getDbFn();
55
+ }
56
+ let joseModule = null;
57
+ let jwtModule = null;
53
58
  async function getJose() {
54
- if (!joseModule) {
55
- joseModule = await import('jose');
56
- }
57
- return joseModule;
59
+ if (!joseModule) joseModule = await import("jose");
60
+ return joseModule;
58
61
  }
59
- __name(getJose, "getJose");
60
62
  async function getJwt() {
61
- if (!jwtModule) {
62
- const jwt = await import('jsonwebtoken');
63
- jwtModule = jwt.default ?? jwt;
64
- }
65
- return jwtModule;
66
- }
67
- __name(getJwt, "getJwt");
68
- var authConfig = null;
63
+ if (!jwtModule) {
64
+ const jwt = await import("jsonwebtoken");
65
+ jwtModule = jwt.default ?? jwt;
66
+ }
67
+ return jwtModule;
68
+ }
69
+ let authConfig = null;
70
+ /**
71
+ * Configure auth module with workspace secret fetching
72
+ */
69
73
  function configureAuth(config) {
70
- authConfig = config;
71
- logger.debug("[ServerAuth] Auth configured");
72
- }
73
- __name(configureAuth, "configureAuth");
74
+ authConfig = config;
75
+ logger.debug("[ServerAuth] Auth configured");
76
+ }
77
+ /**
78
+ * Default workspace secret fetcher
79
+ *
80
+ * Fetches JWT secret from workspace database. This is the standard implementation
81
+ * that works with any microservice that has access to the workspace model.
82
+ *
83
+ * @param workspaceId - Workspace ID from JWT
84
+ * @returns WorkspaceSecret or null if not found
85
+ */
74
86
  async function fetchWorkspaceSecret(workspaceId) {
75
- try {
76
- const db = await getDb();
77
- const workspace = await db.client.workspace.findUnique({
78
- where: {
79
- id: workspaceId
80
- }
81
- });
82
- if (!workspace?.jwtSecret) {
83
- logger.debug("[ServerAuth] No JWT secret found for workspace", {
84
- workspaceId
85
- });
86
- return null;
87
- }
88
- return JSON.parse(JSON.stringify(workspace.jwtSecret));
89
- } catch (error) {
90
- logger.warn("[ServerAuth] Error fetching workspace secret", {
91
- workspaceId,
92
- error
93
- });
94
- return null;
95
- }
96
- }
97
- __name(fetchWorkspaceSecret, "fetchWorkspaceSecret");
87
+ try {
88
+ const workspace = await (await getDb()).client.workspace.findUnique({ where: { id: workspaceId } });
89
+ if (!workspace?.jwtSecret) {
90
+ logger.debug("[ServerAuth] No JWT secret found for workspace", { workspaceId });
91
+ return null;
92
+ }
93
+ return JSON.parse(JSON.stringify(workspace.jwtSecret));
94
+ } catch (error) {
95
+ logger.warn("[ServerAuth] Error fetching workspace secret", {
96
+ workspaceId,
97
+ error
98
+ });
99
+ return null;
100
+ }
101
+ }
102
+ /**
103
+ * Configure auth with default workspace secret fetcher
104
+ *
105
+ * This is automatically called by createServer if no custom auth is configured.
106
+ */
98
107
  function configureDefaultAuth() {
99
- if (!authConfig) {
100
- configureAuth({
101
- fetchWorkspaceSecret
102
- });
103
- logger.debug("[ServerAuth] Default auth configured with built-in workspace secret fetcher");
104
- }
105
- }
106
- __name(configureDefaultAuth, "configureDefaultAuth");
108
+ if (!authConfig) {
109
+ configureAuth({ fetchWorkspaceSecret });
110
+ logger.debug("[ServerAuth] Default auth configured with built-in workspace secret fetcher");
111
+ }
112
+ }
113
+ /**
114
+ * Generate a symmetric secret key for JWT signing
115
+ * @returns JWK object with the generated key
116
+ */
107
117
  async function generateSymmetricSecret() {
108
- const joseLib = await getJose();
109
- const secret = await joseLib.generateSecret("HS256");
110
- const jwk = await joseLib.exportJWK(secret);
111
- return jwk;
112
- }
113
- __name(generateSymmetricSecret, "generateSymmetricSecret");
118
+ const joseLib = await getJose();
119
+ const secret = await joseLib.generateSecret("HS256");
120
+ return await joseLib.exportJWK(secret);
121
+ }
122
+ /**
123
+ * Verify JWT token for workspace-scoped authentication
124
+ *
125
+ * @param token - JWT token to verify
126
+ * @param secret - Optional secret for verification (if not provided, fetches from workspace)
127
+ * @param options - JWT verification options
128
+ * @returns Verified actor information or null if invalid
129
+ */
114
130
  async function verifyJWT(token, secret, options = {}) {
115
- try {
116
- const jwt = await getJwt();
117
- const joseLib = await getJose();
118
- const decoded = jwt.decode(token, {
119
- complete: true
120
- });
121
- if (!decoded || typeof decoded === "string" || !decoded.payload || typeof decoded.payload !== "object") {
122
- logger.warn("[ServerAuth] Invalid token format");
123
- return null;
124
- }
125
- if (secret) {
126
- const verifiedJwt2 = jwt.verify(token, secret, options);
127
- return mapPayloadToActor(verifiedJwt2);
128
- }
129
- const decodedJwt = joseLib.decodeJwt(token);
130
- if (!decodedJwt.workspace_id) {
131
- logger.warn("[ServerAuth] No workspace_id found in token");
132
- return null;
133
- }
134
- if (!authConfig?.fetchWorkspaceSecret) {
135
- logger.error("[ServerAuth] Auth not configured - call configureAuth() first");
136
- return null;
137
- }
138
- const workspaceSecret = await authConfig.fetchWorkspaceSecret(decodedJwt.workspace_id);
139
- if (!workspaceSecret) {
140
- logger.warn("[ServerAuth] Workspace secret not found");
141
- return null;
142
- }
143
- const keyLikeSecret = await joseLib.importJWK(workspaceSecret, "HS256");
144
- const verifiedJwt = await joseLib.jwtVerify(token, keyLikeSecret, options);
145
- return mapPayloadToActor(verifiedJwt.payload);
146
- } catch (err) {
147
- logger.warn("[ServerAuth] Error verifying JWT:", err);
148
- return null;
149
- }
150
- }
151
- __name(verifyJWT, "verifyJWT");
131
+ try {
132
+ const jwt = await getJwt();
133
+ const joseLib = await getJose();
134
+ const decoded = jwt.decode(token, { complete: true });
135
+ if (!decoded || typeof decoded === "string" || !decoded.payload || typeof decoded.payload !== "object") {
136
+ logger.warn("[ServerAuth] Invalid token format");
137
+ return null;
138
+ }
139
+ if (secret) return mapPayloadToActor(jwt.verify(token, secret, options));
140
+ const decodedJwt = joseLib.decodeJwt(token);
141
+ if (!decodedJwt.workspace_id) {
142
+ logger.warn("[ServerAuth] No workspace_id found in token");
143
+ return null;
144
+ }
145
+ if (!authConfig?.fetchWorkspaceSecret) {
146
+ logger.error("[ServerAuth] Auth not configured - call configureAuth() first");
147
+ return null;
148
+ }
149
+ const workspaceSecret = await authConfig.fetchWorkspaceSecret(decodedJwt.workspace_id);
150
+ if (!workspaceSecret) {
151
+ logger.warn("[ServerAuth] Workspace secret not found");
152
+ return null;
153
+ }
154
+ const keyLikeSecret = await joseLib.importJWK(workspaceSecret, "HS256");
155
+ return mapPayloadToActor((await joseLib.jwtVerify(token, keyLikeSecret, options)).payload);
156
+ } catch (err) {
157
+ logger.warn("[ServerAuth] Error verifying JWT:", err);
158
+ return null;
159
+ }
160
+ }
161
+ /**
162
+ * Decode JWT without verification (for extracting claims)
163
+ */
152
164
  async function decodeJWT(token) {
153
- try {
154
- const joseLib = await getJose();
155
- return joseLib.decodeJwt(token);
156
- } catch {
157
- return null;
158
- }
159
- }
160
- __name(decodeJWT, "decodeJWT");
165
+ try {
166
+ return (await getJose()).decodeJwt(token);
167
+ } catch {
168
+ return null;
169
+ }
170
+ }
171
+ /**
172
+ * Map JWT payload to IActor interface
173
+ */
161
174
  function mapPayloadToActor(payload) {
162
- return {
163
- id: payload.sub,
164
- type: payload.actor_type ?? "user",
165
- workspace_id: payload.workspace_id,
166
- tenant_id: payload.tenant_id,
167
- org_id: payload.org_id,
168
- isAdmin: payload["isAdmin"]
169
- };
170
- }
171
- __name(mapPayloadToActor, "mapPayloadToActor");
175
+ return {
176
+ id: payload.sub,
177
+ type: payload.actor_type ?? "user",
178
+ workspace_id: payload.workspace_id,
179
+ tenant_id: payload.tenant_id,
180
+ org_id: payload.org_id,
181
+ isAdmin: payload["isAdmin"]
182
+ };
183
+ }
184
+ /**
185
+ * Check if actor is authenticated
186
+ */
172
187
  function authCheck(actor) {
173
- if (!actor) {
174
- throw new Error("Please sign in");
175
- }
176
- return actor;
188
+ if (!actor) throw new Error("Please sign in");
189
+ return actor;
177
190
  }
178
- __name(authCheck, "authCheck");
191
+ /**
192
+ * Check workspace context and return actor ID and workspace ID
193
+ */
179
194
  function workspaceCheck(context) {
180
- const actor = authCheck(context.actor);
181
- if (!context.workspace?.id) {
182
- throw new Error("Please switch to a workspace");
183
- }
184
- return {
185
- actorId: actor.id,
186
- workspaceId: context.workspace.id
187
- };
188
- }
189
- __name(workspaceCheck, "workspaceCheck");
195
+ const actor = authCheck(context.actor);
196
+ if (!context.workspace?.id) throw new Error("Please switch to a workspace");
197
+ return {
198
+ actorId: actor.id,
199
+ workspaceId: context.workspace.id
200
+ };
201
+ }
202
+ /**
203
+ * Require workspace context - type narrowing guard for wspace layer services
204
+ *
205
+ * Validates that both actor and workspace are present in the context,
206
+ * and returns a type-narrowed context where workspace and actor are guaranteed non-null.
207
+ * Use this at the start of resolvers in wspace services to get typed access
208
+ * to workspace context without optional chaining.
209
+ *
210
+ * @throws Error if actor is not authenticated
211
+ * @throws Error if workspace context is missing
212
+ *
213
+ * @example
214
+ * ```typescript
215
+ * // In a resolver:
216
+ * const ctx = requireWorkspace(context);
217
+ * const workspaceId = ctx.workspace.id; // no optional chaining needed
218
+ * const actorId = ctx.actor.id; // no optional chaining needed
219
+ * ```
220
+ */
190
221
  function requireWorkspace(context) {
191
- authCheck(context.actor);
192
- if (!context.workspace?.id) {
193
- throw new Error("Please switch to a workspace");
194
- }
195
- return context;
222
+ authCheck(context.actor);
223
+ if (!context.workspace?.id) throw new Error("Please switch to a workspace");
224
+ return context;
196
225
  }
197
- __name(requireWorkspace, "requireWorkspace");
226
+ /**
227
+ * Check organization context and return actor ID and org ID
228
+ */
198
229
  function orgCheck(context) {
199
- const actor = authCheck(context.actor);
200
- if (!context.organization?.id) {
201
- throw new Error("Please switch to an organization");
202
- }
203
- return {
204
- actorId: actor.id,
205
- orgId: context.organization.id
206
- };
207
- }
208
- __name(orgCheck, "orgCheck");
230
+ const actor = authCheck(context.actor);
231
+ if (!context.organization?.id) throw new Error("Please switch to an organization");
232
+ return {
233
+ actorId: actor.id,
234
+ orgId: context.organization.id
235
+ };
236
+ }
237
+ /**
238
+ * Check tenant context and return tenant ID
239
+ */
209
240
  function tenantCheck(context) {
210
- if (!context.tenant?.id) {
211
- throw new Error("Tenant context is required");
212
- }
213
- return context.tenant.id;
241
+ if (!context.tenant?.id) throw new Error("Tenant context is required");
242
+ return context.tenant.id;
214
243
  }
215
- __name(tenantCheck, "tenantCheck");
216
244
 
217
245
  // src/server/verified-delegation.ts
218
246
  function object(value) {
219
- return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
247
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
220
248
  }
221
- __name(object, "object");
222
249
  function identifier(value) {
223
- return typeof value === "string" && value["length"] > 0 && value["length"] <= 200 && value["trim"]() === value && Array.from(value).every((character) => character.charCodeAt(0) >= 32 && character.charCodeAt(0) !== 127);
250
+ return typeof value === "string" && value["length"] > 0 && value["length"] <= 200 && value["trim"]() === value && Array.from(value).every((character) => character.charCodeAt(0) >= 32 && character.charCodeAt(0) !== 127);
224
251
  }
225
- __name(identifier, "identifier");
226
252
  function list(value) {
227
- return Array.isArray(value) && value["length"] <= 1e3 && value["every"](identifier);
253
+ return Array.isArray(value) && value["length"] <= 1e3 && value["every"](identifier);
228
254
  }
229
- __name(list, "list");
230
255
  function instant(value) {
231
- if (typeof value !== "string") return null;
232
- const time = Date.parse(value);
233
- return Number.isFinite(time) && new Date(time).toISOString() === value ? new Date(time) : null;
256
+ if (typeof value !== "string") return null;
257
+ const time = Date.parse(value);
258
+ return Number.isFinite(time) && new Date(time).toISOString() === value ? new Date(time) : null;
234
259
  }
235
- __name(instant, "instant");
260
+ /** Decodes transport only; JWT verification remains the gateway's responsibility. */
236
261
  function decodeVerifiedDelegation(header, actor, workspaceId, trustedGateway, now = Date.now()) {
237
- if (!trustedGateway || !actor || actor.provenance !== "delegated" || ![
238
- "user",
239
- "super_admin"
240
- ].includes(actor.type) || header === void 0) return void 0;
241
- const invalid = /* @__PURE__ */ __name(() => new Error("Invalid verified delegation context"), "invalid");
242
- let raw;
243
- try {
244
- raw = JSON.parse(header);
245
- } catch {
246
- throw invalid();
247
- }
248
- const value = object(raw);
249
- const tokenExpiresAt = instant(value?.["tokenExpiresAt"]);
250
- if (!value || !identifier(value["representedUserId"]) || value["representedUserId"] !== actor.id || !identifier(value["originatingAppId"]) || !identifier(value["delegationId"]) || !list(value["scopes"]) || !list(value["allowedWorkspaceIds"]) || !tokenExpiresAt || tokenExpiresAt.getTime() <= now || workspaceId && value["allowedWorkspaceIds"].length > 0 && !value["allowedWorkspaceIds"].includes(workspaceId)) throw invalid();
251
- let consent = null;
252
- if (value["consent"] !== null) {
253
- const facts = object(value["consent"]);
254
- const grantedAt = instant(facts?.["grantedAt"]);
255
- const expiresAt = facts?.["expiresAt"] === null ? null : instant(facts?.["expiresAt"]);
256
- if (!facts || !identifier(facts["grantedBy"]) || !grantedAt || grantedAt.getTime() > now || facts["expiresAt"] !== null && (!expiresAt || expiresAt.getTime() <= grantedAt.getTime() || tokenExpiresAt.getTime() > expiresAt.getTime())) throw invalid();
257
- consent = {
258
- grantedBy: facts["grantedBy"],
259
- grantedAt,
260
- expiresAt
261
- };
262
- }
263
- return {
264
- representedUserId: value["representedUserId"],
265
- originatingAppId: value["originatingAppId"],
266
- delegationId: value["delegationId"],
267
- scopes: [
268
- ...value["scopes"]
269
- ],
270
- allowedWorkspaceIds: [
271
- ...value["allowedWorkspaceIds"]
272
- ],
273
- tokenExpiresAt,
274
- consent
275
- };
276
- }
277
- __name(decodeVerifiedDelegation, "decodeVerifiedDelegation");
262
+ if (!trustedGateway || !actor || actor.provenance !== "delegated" || !["user", "super_admin"].includes(actor.type) || header === void 0) return void 0;
263
+ const invalid = () => /* @__PURE__ */ new Error("Invalid verified delegation context");
264
+ let raw;
265
+ try {
266
+ raw = JSON.parse(header);
267
+ } catch {
268
+ throw invalid();
269
+ }
270
+ const value = object(raw);
271
+ const tokenExpiresAt = instant(value?.["tokenExpiresAt"]);
272
+ if (!value || !identifier(value["representedUserId"]) || value["representedUserId"] !== actor.id || !identifier(value["originatingAppId"]) || !identifier(value["delegationId"]) || !list(value["scopes"]) || !list(value["allowedWorkspaceIds"]) || !tokenExpiresAt || tokenExpiresAt.getTime() <= now || workspaceId && value["allowedWorkspaceIds"].length > 0 && !value["allowedWorkspaceIds"].includes(workspaceId)) throw invalid();
273
+ let consent = null;
274
+ if (value["consent"] !== null) {
275
+ const facts = object(value["consent"]);
276
+ const grantedAt = instant(facts?.["grantedAt"]);
277
+ const expiresAt = facts?.["expiresAt"] === null ? null : instant(facts?.["expiresAt"]);
278
+ if (!facts || !identifier(facts["grantedBy"]) || !grantedAt || grantedAt.getTime() > now || facts["expiresAt"] !== null && (!expiresAt || expiresAt.getTime() <= grantedAt.getTime() || tokenExpiresAt.getTime() > expiresAt.getTime())) throw invalid();
279
+ consent = {
280
+ grantedBy: facts["grantedBy"],
281
+ grantedAt,
282
+ expiresAt
283
+ };
284
+ }
285
+ return {
286
+ representedUserId: value["representedUserId"],
287
+ originatingAppId: value["originatingAppId"],
288
+ delegationId: value["delegationId"],
289
+ scopes: [...value["scopes"]],
290
+ allowedWorkspaceIds: [...value["allowedWorkspaceIds"]],
291
+ tokenExpiresAt,
292
+ consent
293
+ };
294
+ }
278
295
 
279
296
  // src/server/context.ts
280
- var contextOptions = null;
297
+ /**
298
+ * Server Context Module
299
+ *
300
+ * Builds GraphQL context from request headers, JWT, and configuration.
301
+ * Automatically populates actor, tenant, workspace, and tracking information.
302
+ *
303
+ * **Actor-Based Authentication:**
304
+ * - Production: Gateway verifies JWT → populates x-actor-* headers → services trust headers
305
+ * - Development: Services verify JWT directly and build actor from payload
306
+ *
307
+ * Uses standard Web API Request (compatible with Bun/Elysia).
308
+ */
309
+ let contextOptions = null;
310
+ /**
311
+ * Configure context builder
312
+ */
281
313
  function configureContext(options) {
282
- contextOptions = options;
283
- logger.debug("[ServerContext] Context builder configured");
314
+ contextOptions = options;
315
+ logger.debug("[ServerContext] Context builder configured");
284
316
  }
285
- __name(configureContext, "configureContext");
317
+ /**
318
+ * Extract header value from standard Web API Request
319
+ */
286
320
  function getHeader(request, key) {
287
- return request.headers.get(key.toLowerCase()) ?? void 0;
321
+ return request.headers.get(key.toLowerCase()) ?? void 0;
288
322
  }
289
- __name(getHeader, "getHeader");
290
323
  function compareSecret(provided, expected) {
291
- const providedBuffer = Buffer.from(provided);
292
- const expectedBuffer = Buffer.from(expected);
293
- if (providedBuffer.length !== expectedBuffer.length) {
294
- return false;
295
- }
296
- return crypto.timingSafeEqual(providedBuffer, expectedBuffer);
297
- }
298
- __name(compareSecret, "compareSecret");
324
+ const providedBuffer = Buffer.from(provided);
325
+ const expectedBuffer = Buffer.from(expected);
326
+ if (providedBuffer.length !== expectedBuffer.length) return false;
327
+ return crypto.timingSafeEqual(providedBuffer, expectedBuffer);
328
+ }
299
329
  function shouldTrustActorHeaders(request, nodeEnv = process.env["NODE_ENV"], expectedGatewayToken = process.env["TRUSTED_GATEWAY_TOKEN"] ?? process.env["INTERNAL_SERVICE_TOKEN"]) {
300
- if (!getHeader(request, "x-actor-id")) {
301
- return false;
302
- }
303
- if (nodeEnv === "production") {
304
- return true;
305
- }
306
- const providedGatewayToken = getHeader(request, "x-internal-service-token") || getHeader(request, "x-gateway-auth-token");
307
- if (!expectedGatewayToken || !providedGatewayToken) {
308
- return false;
309
- }
310
- return compareSecret(providedGatewayToken, expectedGatewayToken);
311
- }
312
- __name(shouldTrustActorHeaders, "shouldTrustActorHeaders");
330
+ if (!getHeader(request, "x-actor-id")) return false;
331
+ if (nodeEnv === "production") return true;
332
+ const providedGatewayToken = getHeader(request, "x-internal-service-token") || getHeader(request, "x-gateway-auth-token");
333
+ if (!expectedGatewayToken || !providedGatewayToken) return false;
334
+ return compareSecret(providedGatewayToken, expectedGatewayToken);
335
+ }
336
+ /**
337
+ * Extract tracking information from request
338
+ */
313
339
  function extractTracking(request) {
314
- const forwardedFor = getHeader(request, "x-forwarded-for");
315
- const realIp = getHeader(request, "x-real-ip");
316
- const ip = forwardedFor?.split(",")[0]?.trim() || realIp || void 0;
317
- return {
318
- ip,
319
- userAgent: getHeader(request, "user-agent")
320
- };
321
- }
322
- __name(extractTracking, "extractTracking");
340
+ const forwardedFor = getHeader(request, "x-forwarded-for");
341
+ const realIp = getHeader(request, "x-real-ip");
342
+ return {
343
+ ip: forwardedFor?.split(",")[0]?.trim() || realIp || void 0,
344
+ userAgent: getHeader(request, "user-agent")
345
+ };
346
+ }
347
+ /**
348
+ * Extract actor from gateway-injected headers or authorization header
349
+ *
350
+ * **Actor-Based Authentication:**
351
+ * - If x-actor-id header exists, trust it (gateway-authenticated)
352
+ * - Otherwise fall back to JWT verification (direct access in dev)
353
+ *
354
+ * This allows:
355
+ * - Production: Gateway verifies JWT → populates x-actor-* headers → services trust headers
356
+ * - Development: Direct service access with JWT → service verifies JWT itself
357
+ * - Development testing: Direct headers → service trusts headers
358
+ */
323
359
  function actorProvenance(request) {
324
- const value = getHeader(request, "x-verified-actor-provenance");
325
- return value === "direct_human" || value === "delegated" || value === "non_human" ? value : "unknown";
360
+ const value = getHeader(request, "x-verified-actor-provenance");
361
+ return value === "direct_human" || value === "delegated" || value === "non_human" ? value : "unknown";
326
362
  }
327
- __name(actorProvenance, "actorProvenance");
328
363
  async function extractActor(request) {
329
- const actorId = getHeader(request, "x-actor-id");
330
- if (actorId && shouldTrustActorHeaders(request)) {
331
- logger.debug("[ServerContext] Using gateway-authenticated actor from headers");
332
- const actorType = getHeader(request, "x-actor-type") || "user";
333
- const userRole = getHeader(request, "x-user-role");
334
- return {
335
- id: actorId,
336
- type: actorType,
337
- provenance: actorProvenance(request),
338
- workspace_id: getHeader(request, "x-workspace-id"),
339
- tenant_id: getHeader(request, "x-tenant-id"),
340
- org_id: getHeader(request, "x-org-id") || getHeader(request, "x-organization-id"),
341
- isAdmin: actorType === "super_admin" || userRole === "TENANT_ADMIN" || userRole === "SUPER_ADMIN" || userRole === "PLATFORM_ADMIN"
342
- };
343
- }
344
- if (actorId) {
345
- logger.warn("[ServerContext] Ignoring untrusted actor headers and falling back to JWT verification");
346
- }
347
- const authHeader = getHeader(request, "authorization");
348
- if (!authHeader?.startsWith("Bearer ")) {
349
- return null;
350
- }
351
- const token = authHeader.substring(7);
352
- try {
353
- logger.debug("[ServerContext] No gateway headers, verifying JWT directly for actor (dev mode)");
354
- const payload = await verifyJWT(token);
355
- if (!payload) {
356
- return null;
357
- }
358
- return {
359
- id: payload.id,
360
- type: "user",
361
- provenance: "unknown",
362
- workspace_id: payload.workspace_id
363
- };
364
- } catch (error) {
365
- logger.warn("[ServerContext] Invalid JWT token:", error);
366
- return null;
367
- }
368
- }
369
- __name(extractActor, "extractActor");
364
+ const actorId = getHeader(request, "x-actor-id");
365
+ if (actorId && shouldTrustActorHeaders(request)) {
366
+ logger.debug("[ServerContext] Using gateway-authenticated actor from headers");
367
+ const actorType = getHeader(request, "x-actor-type") || "user";
368
+ const userRole = getHeader(request, "x-user-role");
369
+ return {
370
+ id: actorId,
371
+ type: actorType,
372
+ provenance: actorProvenance(request),
373
+ workspace_id: getHeader(request, "x-workspace-id"),
374
+ tenant_id: getHeader(request, "x-tenant-id"),
375
+ org_id: getHeader(request, "x-org-id") || getHeader(request, "x-organization-id"),
376
+ isAdmin: actorType === "super_admin" || userRole === "TENANT_ADMIN" || userRole === "SUPER_ADMIN" || userRole === "PLATFORM_ADMIN"
377
+ };
378
+ }
379
+ if (actorId) logger.warn("[ServerContext] Ignoring untrusted actor headers and falling back to JWT verification");
380
+ const authHeader = getHeader(request, "authorization");
381
+ if (!authHeader?.startsWith("Bearer ")) return null;
382
+ const token = authHeader.substring(7);
383
+ try {
384
+ logger.debug("[ServerContext] No gateway headers, verifying JWT directly for actor (dev mode)");
385
+ const payload = await verifyJWT(token);
386
+ if (!payload) return null;
387
+ return {
388
+ id: payload.id,
389
+ type: "user",
390
+ provenance: "unknown",
391
+ workspace_id: payload.workspace_id
392
+ };
393
+ } catch (error) {
394
+ logger.warn("[ServerContext] Invalid JWT token:", error);
395
+ return null;
396
+ }
397
+ }
398
+ /**
399
+ * Extract tenant from headers
400
+ */
370
401
  function extractTenant(request) {
371
- const tenantId = getHeader(request, "x-tenant-id");
372
- const tenantEndpoint = getHeader(request, "x-tenant-endpoint");
373
- if (tenantId) {
374
- return {
375
- id: tenantId,
376
- endpoint: tenantEndpoint || ""
377
- };
378
- }
379
- return contextOptions?.defaultTenant || null;
380
- }
381
- __name(extractTenant, "extractTenant");
402
+ const tenantId = getHeader(request, "x-tenant-id");
403
+ const tenantEndpoint = getHeader(request, "x-tenant-endpoint");
404
+ if (tenantId) return {
405
+ id: tenantId,
406
+ endpoint: tenantEndpoint || ""
407
+ };
408
+ return contextOptions?.defaultTenant || null;
409
+ }
410
+ /**
411
+ * Extract organization from headers
412
+ */
382
413
  function extractOrganization(request) {
383
- const orgId = getHeader(request, "x-org-id") || getHeader(request, "x-organization-id");
384
- if (orgId) {
385
- return {
386
- id: orgId
387
- };
388
- }
389
- return null;
390
- }
391
- __name(extractOrganization, "extractOrganization");
414
+ const orgId = getHeader(request, "x-org-id") || getHeader(request, "x-organization-id");
415
+ if (orgId) return { id: orgId };
416
+ return null;
417
+ }
418
+ /**
419
+ * Extract workspace from headers or actor
420
+ */
392
421
  function extractWorkspace(request, actor) {
393
- const workspaceId = getHeader(request, "x-workspace-id");
394
- if (workspaceId) {
395
- return {
396
- id: workspaceId
397
- };
398
- }
399
- if (actor?.workspace_id) {
400
- return {
401
- id: actor.workspace_id
402
- };
403
- }
404
- return null;
405
- }
406
- __name(extractWorkspace, "extractWorkspace");
422
+ const workspaceId = getHeader(request, "x-workspace-id");
423
+ if (workspaceId) return { id: workspaceId };
424
+ if (actor?.workspace_id) return { id: actor.workspace_id };
425
+ return null;
426
+ }
427
+ /**
428
+ * Extract project from headers
429
+ */
407
430
  function extractProject(request) {
408
- const projectId = getHeader(request, "x-project-id");
409
- if (projectId) {
410
- return {
411
- id: projectId
412
- };
413
- }
414
- return null;
415
- }
416
- __name(extractProject, "extractProject");
431
+ const projectId = getHeader(request, "x-project-id");
432
+ if (projectId) return { id: projectId };
433
+ return null;
434
+ }
435
+ /**
436
+ * Extract product from headers
437
+ */
417
438
  function extractProduct(request) {
418
- const productId = getHeader(request, "x-product-id");
419
- if (productId) {
420
- return {
421
- id: productId
422
- };
423
- }
424
- return null;
425
- }
426
- __name(extractProduct, "extractProduct");
439
+ const productId = getHeader(request, "x-product-id");
440
+ if (productId) return { id: productId };
441
+ return null;
442
+ }
443
+ /**
444
+ * Extract geography context from headers
445
+ *
446
+ * Geography headers carry the user's selected location context,
447
+ * used for currency defaults, tax calculations, payment routing,
448
+ * data residency, and regional support.
449
+ *
450
+ * Headers:
451
+ * - x-geo-country: ISO 3166-1 alpha-2 country code (e.g., 'IN', 'US', 'DE')
452
+ * - x-geo-currency: ISO 4217 currency code (e.g., 'INR', 'USD', 'EUR')
453
+ * - x-geo-timezone: IANA timezone (e.g., 'Asia/Kolkata', 'America/New_York')
454
+ */
427
455
  function extractGeography(request) {
428
- const country = getHeader(request, "x-geo-country");
429
- const currency = getHeader(request, "x-geo-currency");
430
- const timezone = getHeader(request, "x-geo-timezone");
431
- return {
432
- country: country?.toUpperCase() || void 0,
433
- currency: currency?.toUpperCase() || void 0,
434
- timezone: timezone || void 0
435
- };
436
- }
437
- __name(extractGeography, "extractGeography");
456
+ const country = getHeader(request, "x-geo-country");
457
+ const currency = getHeader(request, "x-geo-currency");
458
+ const timezone = getHeader(request, "x-geo-timezone");
459
+ return {
460
+ country: country?.toUpperCase() || void 0,
461
+ currency: currency?.toUpperCase() || void 0,
462
+ timezone: timezone || void 0
463
+ };
464
+ }
465
+ /**
466
+ * Build GraphQL context from standard Web Request
467
+ *
468
+ * Also sets the workspace context in AsyncLocalStorage for automatic
469
+ * Prisma workspaceId injection via the workspace extension.
470
+ */
438
471
  async function buildContext(request) {
439
- if (!contextOptions) {
440
- throw new Error("[ServerContext] Context not configured - call configureContext() first");
441
- }
442
- const actor = await extractActor(request);
443
- const tenant = extractTenant(request);
444
- const organization = extractOrganization(request);
445
- const workspace = extractWorkspace(request, actor);
446
- const project = extractProject(request);
447
- const product = extractProduct(request);
448
- const tracking = extractTracking(request);
449
- const trustedGatewayHeaders = shouldTrustActorHeaders(request);
450
- const verifiedDelegation = decodeVerifiedDelegation(getHeader(request, "x-verified-delegation"), actor, workspace?.id, trustedGatewayHeaders);
451
- const assistantSession = actor && trustedGatewayHeaders ? parseAssistantSessionHeaders((name) => getHeader(request, name)) : void 0;
452
- let i18n;
453
- if (contextOptions.i18n) {
454
- i18n = contextOptions.i18n.createContextFromRequest(request);
455
- }
456
- const geo = extractGeography(request);
457
- if (geo.country || geo.currency || geo.timezone) {
458
- if (i18n) {
459
- if (geo.country) i18n.country = geo.country;
460
- if (geo.currency) i18n.currency = geo.currency;
461
- if (geo.timezone) i18n.timezone = geo.timezone;
462
- } else {
463
- i18n = {
464
- locale: "en-US",
465
- language: "en",
466
- country: geo.country,
467
- currency: geo.currency,
468
- timezone: geo.timezone,
469
- t: /* @__PURE__ */ __name((key) => key, "t"),
470
- tp: /* @__PURE__ */ __name((key) => key, "tp"),
471
- formatNumber: /* @__PURE__ */ __name((value) => String(value), "formatNumber"),
472
- formatCurrency: /* @__PURE__ */ __name((value, currency) => `${currency} ${value}`, "formatCurrency"),
473
- formatDate: /* @__PURE__ */ __name((date) => String(date), "formatDate"),
474
- formatRelativeTime: /* @__PURE__ */ __name((value, unit) => `${value} ${unit}`, "formatRelativeTime")
475
- };
476
- }
477
- }
478
- const onBehalfOf = resolveOnBehalfOf(actor, verifiedDelegation);
479
- const wsCtxPayload = {
480
- workspaceId: workspace?.id,
481
- tenantId: tenant?.id,
482
- actorId: actor?.id,
483
- actorType: actor?.type,
484
- organizationId: organization?.id,
485
- projectId: project?.id,
486
- onBehalfOf,
487
- ...assistantSession ? {
488
- assistantSession
489
- } : {}
490
- };
491
- logger.debug("[ServerContext] Setting workspace context", {
492
- workspaceId: wsCtxPayload.workspaceId ?? "NONE",
493
- actorId: wsCtxPayload.actorId ?? "NONE",
494
- rawHeader: getHeader(request, "x-workspace-id") ?? "MISSING"
495
- });
496
- setWorkspaceContext(wsCtxPayload);
497
- ContextManager.setCfAccessContext(getHeader(request, "cf-access-client-id"), getHeader(request, "cf-access-client-secret"), getHeader(request, "x-cf-authorization"));
498
- return {
499
- request,
500
- actor,
501
- tenant,
502
- organization,
503
- workspace,
504
- project,
505
- product,
506
- tracking,
507
- verifiedDelegation,
508
- ...assistantSession ? {
509
- assistantSession
510
- } : {},
511
- onBehalfOf: onBehalfOf || actor?.id || "",
512
- db: contextOptions.getDb(),
513
- i18n,
514
- responseHeaders: new Headers()
515
- };
516
- }
517
- __name(buildContext, "buildContext");
472
+ if (!contextOptions) throw new Error("[ServerContext] Context not configured - call configureContext() first");
473
+ const actor = await extractActor(request);
474
+ const tenant = extractTenant(request);
475
+ const organization = extractOrganization(request);
476
+ const workspace = extractWorkspace(request, actor);
477
+ const project = extractProject(request);
478
+ const product = extractProduct(request);
479
+ const tracking = extractTracking(request);
480
+ const trustedGatewayHeaders = shouldTrustActorHeaders(request);
481
+ const verifiedDelegation = decodeVerifiedDelegation(getHeader(request, "x-verified-delegation"), actor, workspace?.id, trustedGatewayHeaders);
482
+ const assistantSession = actor && trustedGatewayHeaders ? parseAssistantSessionHeaders((name) => getHeader(request, name)) : void 0;
483
+ let i18n;
484
+ if (contextOptions.i18n) i18n = contextOptions.i18n.createContextFromRequest(request);
485
+ const geo = extractGeography(request);
486
+ if (geo.country || geo.currency || geo.timezone) {
487
+ if (i18n) {
488
+ if (geo.country) i18n.country = geo.country;
489
+ if (geo.currency) i18n.currency = geo.currency;
490
+ if (geo.timezone) i18n.timezone = geo.timezone;
491
+ } else i18n = {
492
+ locale: "en-US",
493
+ language: "en",
494
+ country: geo.country,
495
+ currency: geo.currency,
496
+ timezone: geo.timezone,
497
+ t: (key) => key,
498
+ tp: (key) => key,
499
+ formatNumber: (value) => String(value),
500
+ formatCurrency: (value, currency) => `${currency} ${value}`,
501
+ formatDate: (date) => String(date),
502
+ formatRelativeTime: (value, unit) => `${value} ${unit}`
503
+ };
504
+ }
505
+ const onBehalfOf = resolveOnBehalfOf(actor, verifiedDelegation);
506
+ const wsCtxPayload = {
507
+ workspaceId: workspace?.id,
508
+ tenantId: tenant?.id,
509
+ actorId: actor?.id,
510
+ actorType: actor?.type,
511
+ organizationId: organization?.id,
512
+ projectId: project?.id,
513
+ onBehalfOf,
514
+ ...assistantSession ? { assistantSession } : {}
515
+ };
516
+ logger.debug("[ServerContext] Setting workspace context", {
517
+ workspaceId: wsCtxPayload.workspaceId ?? "NONE",
518
+ actorId: wsCtxPayload.actorId ?? "NONE",
519
+ rawHeader: getHeader(request, "x-workspace-id") ?? "MISSING"
520
+ });
521
+ setWorkspaceContext(wsCtxPayload);
522
+ ContextManager.setCfAccessContext(getHeader(request, "cf-access-client-id"), getHeader(request, "cf-access-client-secret"), getHeader(request, "x-cf-authorization"));
523
+ return {
524
+ request,
525
+ actor,
526
+ tenant,
527
+ organization,
528
+ workspace,
529
+ project,
530
+ product,
531
+ tracking,
532
+ verifiedDelegation,
533
+ ...assistantSession ? { assistantSession } : {},
534
+ onBehalfOf: onBehalfOf || actor?.id || "",
535
+ db: contextOptions.getDb(),
536
+ i18n,
537
+ responseHeaders: new Headers()
538
+ };
539
+ }
540
+ /**
541
+ * Get context options
542
+ */
518
543
  function getContextOptions() {
519
- return contextOptions;
544
+ return contextOptions;
520
545
  }
521
- __name(getContextOptions, "getContextOptions");
522
546
 
523
547
  // src/server/workspace-execution-context.ts
524
548
  function record(value) {
525
- return typeof value === "object" && value !== null && !Array.isArray(value);
549
+ return typeof value === "object" && value !== null && !Array.isArray(value);
526
550
  }
527
- __name(record, "record");
528
551
  function string(value) {
529
- return typeof value === "string" && value.length > 0 ? value : void 0;
552
+ return typeof value === "string" && value.length > 0 ? value : void 0;
530
553
  }
531
- __name(string, "string");
532
554
  function id(value) {
533
- return record(value) ? string(value["id"]) : void 0;
555
+ return record(value) ? string(value["id"]) : void 0;
534
556
  }
535
- __name(id, "id");
536
557
  function executionContext(value) {
537
- if (!record(value)) return {};
538
- const assistantSession = readAssistantSessionAttribution(value["assistantSession"]);
539
- return {
540
- ...assistantSession ? {
541
- assistantSession
542
- } : {},
543
- workspaceId: id(value["workspace"]),
544
- tenantId: id(value["tenant"]),
545
- organizationId: id(value["organization"]),
546
- projectId: id(value["project"]),
547
- actorId: id(value["actor"]),
548
- actorType: record(value["actor"]) ? string(value["actor"]["type"]) : void 0,
549
- onBehalfOf: string(value["onBehalfOf"])
550
- };
551
- }
552
- __name(executionContext, "executionContext");
558
+ if (!record(value)) return {};
559
+ const assistantSession = readAssistantSessionAttribution(value["assistantSession"]);
560
+ return {
561
+ ...assistantSession ? { assistantSession } : {},
562
+ workspaceId: id(value["workspace"]),
563
+ tenantId: id(value["tenant"]),
564
+ organizationId: id(value["organization"]),
565
+ projectId: id(value["project"]),
566
+ actorId: id(value["actor"]),
567
+ actorType: record(value["actor"]) ? string(value["actor"]["type"]) : void 0,
568
+ onBehalfOf: string(value["onBehalfOf"])
569
+ };
570
+ }
553
571
  function scopedIterable(source, scope) {
554
- return {
555
- [Symbol.asyncIterator]() {
556
- const iterator = source[Symbol.asyncIterator]();
557
- const finish = iterator.return?.bind(iterator);
558
- const fail = iterator.throw?.bind(iterator);
559
- return {
560
- next: /* @__PURE__ */ __name((...args) => withWorkspaceContext(scope, async () => iterator.next(...args)), "next"),
561
- return: finish ? (value) => withWorkspaceContext(scope, async () => finish(value)) : void 0,
562
- throw: fail ? (error) => withWorkspaceContext(scope, async () => fail(error)) : void 0
563
- };
564
- }
565
- };
566
- }
567
- __name(scopedIterable, "scopedIterable");
572
+ return { [Symbol.asyncIterator]() {
573
+ const iterator = source[Symbol.asyncIterator]();
574
+ const finish = iterator.return?.bind(iterator);
575
+ const fail = iterator.throw?.bind(iterator);
576
+ return {
577
+ next: (...args) => withWorkspaceContext(scope, async () => iterator.next(...args)),
578
+ return: finish ? (value) => withWorkspaceContext(scope, async () => finish(value)) : void 0,
579
+ throw: fail ? (error) => withWorkspaceContext(scope, async () => fail(error)) : void 0
580
+ };
581
+ } };
582
+ }
583
+ /** Context creation and GraphQL execution may run in different async chains.
584
+ * Bind execution to its own verified context instead of the most recent request's fallback.
585
+ */
568
586
  function createWorkspaceExecutionContextPlugin() {
569
- return {
570
- onExecute({ executeFn, setExecuteFn }) {
571
- setExecuteFn((args) => {
572
- const scope = executionContext(args.contextValue);
573
- return withWorkspaceContext(scope, async () => {
574
- const result = await executeFn(args);
575
- return Symbol.asyncIterator in result ? scopedIterable(result, scope) : result;
576
- });
577
- });
578
- },
579
- onSubscribe({ subscribeFn, setSubscribeFn }) {
580
- setSubscribeFn((args) => {
581
- const scope = executionContext(args.contextValue);
582
- return withWorkspaceContext(scope, async () => {
583
- const result = await subscribeFn(args);
584
- return Symbol.asyncIterator in result ? scopedIterable(result, scope) : result;
585
- });
586
- });
587
- }
588
- };
589
- }
590
- __name(createWorkspaceExecutionContextPlugin, "createWorkspaceExecutionContextPlugin");
587
+ return {
588
+ onExecute({ executeFn, setExecuteFn }) {
589
+ setExecuteFn((args) => {
590
+ const scope = executionContext(args.contextValue);
591
+ return withWorkspaceContext(scope, async () => {
592
+ const result = await executeFn(args);
593
+ return Symbol.asyncIterator in result ? scopedIterable(result, scope) : result;
594
+ });
595
+ });
596
+ },
597
+ onSubscribe({ subscribeFn, setSubscribeFn }) {
598
+ setSubscribeFn((args) => {
599
+ const scope = executionContext(args.contextValue);
600
+ return withWorkspaceContext(scope, async () => {
601
+ const result = await subscribeFn(args);
602
+ return Symbol.asyncIterator in result ? scopedIterable(result, scope) : result;
603
+ });
604
+ });
605
+ }
606
+ };
607
+ }
591
608
 
592
609
  // src/server/security.ts
593
- var LOCALHOST_ORIGINS = [
594
- "http://localhost:3000",
595
- "http://localhost:4000",
596
- "http://localhost:5173",
597
- "http://127.0.0.1:3000",
598
- "http://127.0.0.1:4000",
599
- "http://127.0.0.1:5173"
610
+ const LOCALHOST_ORIGINS = [
611
+ "http://localhost:3000",
612
+ "http://localhost:4000",
613
+ "http://localhost:5173",
614
+ "http://127.0.0.1:3000",
615
+ "http://127.0.0.1:4000",
616
+ "http://127.0.0.1:5173"
600
617
  ];
601
618
  function normalizeCorsOrigins(origins, environment) {
602
- const normalized = (Array.isArray(origins) ? origins : origins?.split(",") || []).map((origin) => origin.trim()).filter(Boolean);
603
- if (normalized.length === 0) {
604
- return environment === "production" ? [] : LOCALHOST_ORIGINS;
605
- }
606
- if (normalized.includes("*")) {
607
- return environment === "production" ? [] : LOCALHOST_ORIGINS;
608
- }
609
- return normalized;
610
- }
611
- __name(normalizeCorsOrigins, "normalizeCorsOrigins");
619
+ const normalized = (Array.isArray(origins) ? origins : origins?.split(",") || []).map((origin) => origin.trim()).filter(Boolean);
620
+ if (normalized.length === 0) return environment === "production" ? [] : LOCALHOST_ORIGINS;
621
+ if (normalized.includes("*")) return environment === "production" ? [] : LOCALHOST_ORIGINS;
622
+ return normalized;
623
+ }
612
624
  function resolveAllowedCorsOrigin(requestOrigin, allowedOrigins) {
613
- if (!requestOrigin) {
614
- return allowedOrigins[0] ?? null;
615
- }
616
- return allowedOrigins.includes(requestOrigin) ? requestOrigin : null;
625
+ if (!requestOrigin) return allowedOrigins[0] ?? null;
626
+ return allowedOrigins.includes(requestOrigin) ? requestOrigin : null;
617
627
  }
618
- __name(resolveAllowedCorsOrigin, "resolveAllowedCorsOrigin");
619
628
  function canAccessGraphExport(actor) {
620
- if (!actor) {
621
- return false;
622
- }
623
- return actor.isAdmin === true || [
624
- "service",
625
- "super_admin"
626
- ].includes(actor.type);
627
- }
628
- __name(canAccessGraphExport, "canAccessGraphExport");
629
+ if (!actor) return false;
630
+ return actor.isAdmin === true || ["service", "super_admin"].includes(actor.type);
631
+ }
629
632
 
630
633
  // src/server/quotaGaugeRefresh.ts
634
+ /**
635
+ * Workspace quota gauge refresh throttling for the `/metrics` route.
636
+ *
637
+ * `WorkspaceQuotaRegistry.collectAll()` issues Prisma groupBy queries. Running
638
+ * it inline on every Prometheus scrape made `/metrics` exactly as slow as the
639
+ * database: services that registered quota collectors routinely exceeded a 30s
640
+ * `scrape_timeout` and were recorded as down, even though the endpoint itself
641
+ * was healthy.
642
+ *
643
+ * Scrapes are far more frequent than these values meaningfully change, so
644
+ * refresh on a TTL, bound each refresh, and let concurrent scrapes share one
645
+ * in-flight attempt. A slow or unavailable database then degrades gauge
646
+ * freshness instead of failing the scrape.
647
+ *
648
+ * @module server/quotaGaugeRefresh
649
+ */
650
+ /**
651
+ * Read a positive-integer millisecond setting from the environment.
652
+ *
653
+ * Anything unset, non-numeric, or <= 0 falls back to the default: an operator
654
+ * typo must not silently disable the throttle that keeps `/metrics` fast.
655
+ */
631
656
  function envMs(name, fallback) {
632
- const raw = process.env[name];
633
- if (!raw) return fallback;
634
- const parsed = Number.parseInt(raw, 10);
635
- return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
636
- }
637
- __name(envMs, "envMs");
638
- var QUOTA_GAUGE_TTL_MS = envMs("BOFF_QUOTA_GAUGE_TTL_MS", 6e4);
639
- var QUOTA_GAUGE_REFRESH_TIMEOUT_MS = envMs("BOFF_QUOTA_GAUGE_TIMEOUT_MS", 5e3);
657
+ const raw = process.env[name];
658
+ if (!raw) return fallback;
659
+ const parsed = Number.parseInt(raw, 10);
660
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
661
+ }
662
+ /**
663
+ * How long a gauge snapshot is considered fresh.
664
+ *
665
+ * Override with `BOFF_QUOTA_GAUGE_TTL_MS` — raise it when the database is under
666
+ * load and quota freshness matters less than scrape latency.
667
+ */
668
+ const QUOTA_GAUGE_TTL_MS = envMs("BOFF_QUOTA_GAUGE_TTL_MS", 6e4);
669
+ /**
670
+ * Upper bound on a single refresh, so a slow database cannot stall a scrape.
671
+ *
672
+ * Override with `BOFF_QUOTA_GAUGE_TIMEOUT_MS`. Keep it comfortably below the
673
+ * Prometheus `scrape_timeout`, or a slow refresh still fails the scrape.
674
+ */
675
+ const QUOTA_GAUGE_REFRESH_TIMEOUT_MS = envMs("BOFF_QUOTA_GAUGE_TIMEOUT_MS", 5e3);
676
+ /**
677
+ * Build a TTL-throttled, timeout-bounded, single-flight refresher.
678
+ *
679
+ * `refresh()` never rejects — `/metrics` must keep serving prom-client and SDK
680
+ * registry output even when the quota registry is unconfigured or erroring.
681
+ * A failed attempt does not advance the TTL, so the next scrape retries.
682
+ */
640
683
  function createQuotaGaugeRefresher(opts) {
641
- const ttlMs = opts.ttlMs ?? QUOTA_GAUGE_TTL_MS;
642
- const timeoutMs = opts.timeoutMs ?? QUOTA_GAUGE_REFRESH_TIMEOUT_MS;
643
- const now = opts.now ?? (() => Date.now());
644
- let refreshedAt = 0;
645
- let inFlight = null;
646
- const refresh = /* @__PURE__ */ __name(async () => {
647
- if (refreshedAt !== 0 && now() - refreshedAt < ttlMs) return;
648
- if (!inFlight) {
649
- inFlight = (async () => {
650
- let timer;
651
- try {
652
- await Promise.race([
653
- Promise.resolve(opts.collect()).then(() => void 0),
654
- new Promise((resolve) => {
655
- timer = setTimeout(resolve, timeoutMs);
656
- })
657
- ]);
658
- refreshedAt = now();
659
- } catch {
660
- } finally {
661
- if (timer !== void 0) clearTimeout(timer);
662
- inFlight = null;
663
- }
664
- })();
665
- }
666
- await inFlight;
667
- }, "refresh");
668
- return {
669
- refresh,
670
- lastRefreshedAt: /* @__PURE__ */ __name(() => refreshedAt, "lastRefreshedAt")
671
- };
672
- }
673
- __name(createQuotaGaugeRefresher, "createQuotaGaugeRefresher");
684
+ const ttlMs = opts.ttlMs ?? QUOTA_GAUGE_TTL_MS;
685
+ const timeoutMs = opts.timeoutMs ?? QUOTA_GAUGE_REFRESH_TIMEOUT_MS;
686
+ const now = opts.now ?? (() => Date.now());
687
+ let refreshedAt = 0;
688
+ let inFlight = null;
689
+ const refresh = async () => {
690
+ if (refreshedAt !== 0 && now() - refreshedAt < ttlMs) return;
691
+ if (!inFlight) inFlight = (async () => {
692
+ let timer;
693
+ try {
694
+ await Promise.race([Promise.resolve(opts.collect()).then(() => void 0), new Promise((resolve) => {
695
+ timer = setTimeout(resolve, timeoutMs);
696
+ })]);
697
+ refreshedAt = now();
698
+ } catch {} finally {
699
+ if (timer !== void 0) clearTimeout(timer);
700
+ inFlight = null;
701
+ }
702
+ })();
703
+ await inFlight;
704
+ };
705
+ return {
706
+ refresh,
707
+ lastRefreshedAt: () => refreshedAt
708
+ };
709
+ }
674
710
 
675
711
  // src/server/raw-body-routes.ts
676
- var REGEX_SPECIAL = /[.*+?^${}()|[\]\\]/g;
712
+ const REGEX_SPECIAL = /[.*+?^${}()|[\]\\]/g;
677
713
  function compile(path) {
678
- if (!path.includes(":") && !path.includes("*")) return {
679
- exact: path,
680
- regex: null
681
- };
682
- const pattern = path.split("/").map((segment) => {
683
- if (segment === "*") return ".*";
684
- if (segment.startsWith(":")) return "[^/]+";
685
- return segment.replace(REGEX_SPECIAL, "\\$&");
686
- }).join("/");
687
- return {
688
- exact: null,
689
- regex: new RegExp(`^${pattern}$`)
690
- };
691
- }
692
- __name(compile, "compile");
714
+ if (!path.includes(":") && !path.includes("*")) return {
715
+ exact: path,
716
+ regex: null
717
+ };
718
+ const pattern = path.split("/").map((segment) => {
719
+ if (segment === "*") return ".*";
720
+ if (segment.startsWith(":")) return "[^/]+";
721
+ return segment.replace(REGEX_SPECIAL, "\\$&");
722
+ }).join("/");
723
+ return {
724
+ exact: null,
725
+ regex: new RegExp(`^${pattern}$`)
726
+ };
727
+ }
693
728
  function matches(route, pathname) {
694
- return route.exact !== null ? route.exact === pathname : route.regex?.test(pathname) ?? false;
729
+ return route.exact !== null ? route.exact === pathname : route.regex?.test(pathname) ?? false;
695
730
  }
696
- __name(matches, "matches");
697
731
  function keyOf(route) {
698
- return route.exact ?? route.regex?.source ?? "";
699
- }
700
- __name(keyOf, "keyOf");
701
- var METHOD_ORDER = [
702
- "GET",
703
- "HEAD",
704
- "POST",
705
- "PUT",
706
- "PATCH",
707
- "DELETE",
708
- "OPTIONS"
732
+ return route.exact ?? route.regex?.source ?? "";
733
+ }
734
+ /** Order the methods an `Allow` header lists: the usual verbs first, then anything else. */
735
+ const METHOD_ORDER = [
736
+ "GET",
737
+ "HEAD",
738
+ "POST",
739
+ "PUT",
740
+ "PATCH",
741
+ "DELETE",
742
+ "OPTIONS"
709
743
  ];
710
- var rank = /* @__PURE__ */ __name((method) => {
711
- const index = METHOD_ORDER.indexOf(method);
712
- return index === -1 ? METHOD_ORDER.length : index;
713
- }, "rank");
744
+ const rank = (method) => {
745
+ const index = METHOD_ORDER.indexOf(method);
746
+ return index === -1 ? METHOD_ORDER.length : index;
747
+ };
748
+ /**
749
+ * Build the resolver for a service's raw-body endpoints. `ordinaryRoutes` lists the routes Elysia
750
+ * itself serves; it is read lazily, only when a method misses, so routes a service registers after
751
+ * `createServer` still count.
752
+ */
714
753
  function createRawBodyRouter(endpoints, ordinaryRoutes = () => []) {
715
- const routes = [];
716
- for (const endpoint of endpoints.filter((ep) => ep.rawBody)) {
717
- const method = endpoint.method.toUpperCase();
718
- const compiled = compile(endpoint.path);
719
- let route = routes.find((candidate) => keyOf(candidate) === keyOf(compiled));
720
- if (!route) {
721
- route = {
722
- ...compiled,
723
- byMethod: /* @__PURE__ */ new Map()
724
- };
725
- routes.push(route);
726
- }
727
- if (!route.byMethod.has(method)) route.byMethod.set(method, endpoint);
728
- }
729
- const ordinaryMatchers = /* @__PURE__ */ new Map();
730
- const ordinaryVerbsOn = /* @__PURE__ */ __name((pathname) => {
731
- const verbs = /* @__PURE__ */ new Set();
732
- for (const route of ordinaryRoutes()) {
733
- let matcher = ordinaryMatchers.get(route.path);
734
- if (!matcher) {
735
- matcher = compile(route.path);
736
- ordinaryMatchers.set(route.path, matcher);
737
- }
738
- if (matches(matcher, pathname)) verbs.add(route.method.toUpperCase());
739
- }
740
- return verbs;
741
- }, "ordinaryVerbsOn");
742
- return {
743
- size: routes.length,
744
- hasPath(pathname) {
745
- return routes.some((route) => matches(route, pathname));
746
- },
747
- resolve(pathname, rawMethod) {
748
- const method = rawMethod.toUpperCase();
749
- const candidates = [
750
- ...routes.filter((route) => route.exact !== null && matches(route, pathname)),
751
- ...routes.filter((route) => route.exact === null && matches(route, pathname))
752
- ];
753
- if (candidates.length === 0) return null;
754
- for (const route of candidates) {
755
- const endpoint = route.byMethod.get(method) ?? (method === "HEAD" ? route.byMethod.get("GET") : void 0);
756
- if (endpoint) return {
757
- kind: "endpoint",
758
- endpoint
759
- };
760
- }
761
- const ordinaryVerbs = ordinaryVerbsOn(pathname);
762
- const servedElsewhere = ordinaryVerbs.has(method) || ordinaryVerbs.has("ALL") || method === "HEAD" && ordinaryVerbs.has("GET");
763
- if (servedElsewhere) return null;
764
- const allowed = new Set(ordinaryVerbs);
765
- for (const route of candidates) for (const verb of route.byMethod.keys()) allowed.add(verb);
766
- if (allowed.has("GET")) allowed.add("HEAD");
767
- allowed.add("OPTIONS");
768
- return {
769
- kind: "method-not-allowed",
770
- allowed: [
771
- ...allowed
772
- ].sort((a, b) => rank(a) - rank(b))
773
- };
774
- }
775
- };
776
- }
777
- __name(createRawBodyRouter, "createRawBodyRouter");
778
- var requestServers = /* @__PURE__ */ new WeakMap();
754
+ const routes = [];
755
+ for (const endpoint of endpoints.filter((ep) => ep.rawBody)) {
756
+ const method = endpoint.method.toUpperCase();
757
+ const compiled = compile(endpoint.path);
758
+ let route = routes.find((candidate) => keyOf(candidate) === keyOf(compiled));
759
+ if (!route) {
760
+ route = {
761
+ ...compiled,
762
+ byMethod: /* @__PURE__ */ new Map()
763
+ };
764
+ routes.push(route);
765
+ }
766
+ if (!route.byMethod.has(method)) route.byMethod.set(method, endpoint);
767
+ }
768
+ const ordinaryMatchers = /* @__PURE__ */ new Map();
769
+ const ordinaryVerbsOn = (pathname) => {
770
+ const verbs = /* @__PURE__ */ new Set();
771
+ for (const route of ordinaryRoutes()) {
772
+ let matcher = ordinaryMatchers.get(route.path);
773
+ if (!matcher) {
774
+ matcher = compile(route.path);
775
+ ordinaryMatchers.set(route.path, matcher);
776
+ }
777
+ if (matches(matcher, pathname)) verbs.add(route.method.toUpperCase());
778
+ }
779
+ return verbs;
780
+ };
781
+ return {
782
+ size: routes.length,
783
+ hasPath(pathname) {
784
+ return routes.some((route) => matches(route, pathname));
785
+ },
786
+ resolve(pathname, rawMethod) {
787
+ const method = rawMethod.toUpperCase();
788
+ const candidates = [...routes.filter((route) => route.exact !== null && matches(route, pathname)), ...routes.filter((route) => route.exact === null && matches(route, pathname))];
789
+ if (candidates.length === 0) return null;
790
+ for (const route of candidates) {
791
+ const endpoint = route.byMethod.get(method) ?? (method === "HEAD" ? route.byMethod.get("GET") : void 0);
792
+ if (endpoint) return {
793
+ kind: "endpoint",
794
+ endpoint
795
+ };
796
+ }
797
+ const ordinaryVerbs = ordinaryVerbsOn(pathname);
798
+ if (ordinaryVerbs.has(method) || ordinaryVerbs.has("ALL") || method === "HEAD" && ordinaryVerbs.has("GET")) return null;
799
+ const allowed = new Set(ordinaryVerbs);
800
+ for (const route of candidates) for (const verb of route.byMethod.keys()) allowed.add(verb);
801
+ if (allowed.has("GET")) allowed.add("HEAD");
802
+ allowed.add("OPTIONS");
803
+ return {
804
+ kind: "method-not-allowed",
805
+ allowed: [...allowed].sort((a, b) => rank(a) - rank(b))
806
+ };
807
+ }
808
+ };
809
+ }
810
+ /**
811
+ * The Bun server that accepted each in-flight raw-body request, so a handler can extend its idle
812
+ * timeout (see `extendRequestIdleTimeout`). A WeakMap: entries die with the request.
813
+ */
814
+ const requestServers = /* @__PURE__ */ new WeakMap();
779
815
  function canTimeout(server) {
780
- return typeof server?.timeout === "function";
816
+ return typeof server?.timeout === "function";
781
817
  }
782
- __name(canTimeout, "canTimeout");
783
818
  function rememberRequestServer(request, server) {
784
- if (canTimeout(server)) requestServers.set(request, server);
785
- }
786
- __name(rememberRequestServer, "rememberRequestServer");
787
- var MAX_IDLE_TIMEOUT_SECONDS = 255;
819
+ if (canTimeout(server)) requestServers.set(request, server);
820
+ }
821
+ /** Bun caps a connection's idle timeout at 255 seconds. */
822
+ const MAX_IDLE_TIMEOUT_SECONDS = 255;
823
+ /**
824
+ * Let one raw-body request stay idle for longer than the server default (Elysia's Bun adapter sets
825
+ * 30 s). For handlers that legitimately hold a request open — a webhook answering with its
826
+ * workflow's result. `seconds` is clamped to Bun's 255 s cap; 0 disables the timeout for the
827
+ * request. Returns false when the request was not served by a Bun server that supports it.
828
+ */
788
829
  function extendRequestIdleTimeout(request, seconds) {
789
- const server = requestServers.get(request);
790
- if (!server || !Number.isFinite(seconds) || seconds < 0) return false;
791
- server.timeout(request, Math.min(Math.floor(seconds), MAX_IDLE_TIMEOUT_SECONDS));
792
- return true;
830
+ const server = requestServers.get(request);
831
+ if (!server || !Number.isFinite(seconds) || seconds < 0) return false;
832
+ server.timeout(request, Math.min(Math.floor(seconds), 255));
833
+ return true;
793
834
  }
794
- __name(extendRequestIdleTimeout, "extendRequestIdleTimeout");
795
835
 
796
836
  // src/server/readiness.ts
797
- var READINESS_CACHE_MS = 1e3;
798
- var READINESS_PROBE_TIMEOUT_MS = 2e3;
799
- var DEFAULT_REQUIRED = [
800
- "postgres"
801
- ];
837
+ /**
838
+ * Result cache TTL. Kubernetes probes every 10s across N replicas, Gatus every
839
+ * 300s, plus any load balancer — without this each of them becomes a `SELECT 1`
840
+ * on a connection from the same bounded pool the application needs.
841
+ */
842
+ const READINESS_CACHE_MS = 1e3;
843
+ /** Hard ceiling on a single dependency check, so readiness cannot hang. */
844
+ const READINESS_PROBE_TIMEOUT_MS = 2e3;
845
+ const DEFAULT_REQUIRED = ["postgres"];
802
846
  async function withTimeout(work, ms, label) {
803
- let timer;
804
- try {
805
- return await Promise.race([
806
- work,
807
- new Promise((_, reject) => {
808
- timer = setTimeout(() => reject(new Error(`${label} check timed out after ${ms}ms`)), ms);
809
- })
810
- ]);
811
- } finally {
812
- if (timer) clearTimeout(timer);
813
- }
814
- }
815
- __name(withTimeout, "withTimeout");
847
+ let timer;
848
+ try {
849
+ return await Promise.race([work, new Promise((_, reject) => {
850
+ timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`${label} check timed out after ${ms}ms`)), ms);
851
+ })]);
852
+ } finally {
853
+ if (timer) clearTimeout(timer);
854
+ }
855
+ }
816
856
  async function runCheck(name, required, work, now) {
817
- const started = now();
818
- try {
819
- await withTimeout(Promise.resolve(work()), READINESS_PROBE_TIMEOUT_MS, name);
820
- return {
821
- ok: true,
822
- required,
823
- latencyMs: now() - started
824
- };
825
- } catch (err) {
826
- return {
827
- ok: false,
828
- required,
829
- error: err instanceof Error ? err.message : String(err),
830
- latencyMs: now() - started
831
- };
832
- }
833
- }
834
- __name(runCheck, "runCheck");
857
+ const started = now();
858
+ try {
859
+ await withTimeout(Promise.resolve(work()), READINESS_PROBE_TIMEOUT_MS, name);
860
+ return {
861
+ ok: true,
862
+ required,
863
+ latencyMs: now() - started
864
+ };
865
+ } catch (err) {
866
+ return {
867
+ ok: false,
868
+ required,
869
+ error: err instanceof Error ? err.message : String(err),
870
+ latencyMs: now() - started
871
+ };
872
+ }
873
+ }
874
+ /**
875
+ * Build a cached readiness prober. Each call site gets its own cache so tests
876
+ * never share state with a running server.
877
+ */
835
878
  function createReadinessProbe(deps, now = Date.now) {
836
- const required = new Set(deps.requiredDependencies ?? DEFAULT_REQUIRED);
837
- let cache = null;
838
- let inFlight = null;
839
- async function probe() {
840
- const checks = {};
841
- const jobs = [];
842
- if (deps.prisma) {
843
- jobs.push(runCheck("postgres", required.has("postgres"), async () => {
844
- const client = deps.prisma?.();
845
- if (!client) throw new Error("prisma client not initialised");
846
- await client.$queryRaw`SELECT 1`;
847
- }, now).then((r) => {
848
- checks.postgres = r;
849
- }));
850
- }
851
- if (deps.valkey) {
852
- jobs.push(runCheck("valkey", required.has("valkey"), async () => {
853
- const client = await deps.valkey?.();
854
- if (!client) throw new Error("valkey client not initialised");
855
- await client.ping();
856
- }, now).then((r) => {
857
- checks.valkey = r;
858
- }));
859
- }
860
- if (deps.eventQueue) {
861
- jobs.push(runCheck("eventQueue", required.has("eventQueue"), async () => {
862
- const q = deps.eventQueue?.();
863
- if (!q) throw new Error("event queue not initialised");
864
- if (typeof q.isConnected === "function") {
865
- const connected = await Promise.resolve(q.isConnected());
866
- if (!connected) throw new Error("event queue reports disconnected");
867
- return;
868
- }
869
- if (typeof q.healthCheck === "function") {
870
- const res = await q.healthCheck();
871
- if (!res.ok) throw new Error("event queue health check failed");
872
- }
873
- }, now).then((r) => {
874
- checks.eventQueue = r;
875
- }));
876
- }
877
- await Promise.all(jobs);
878
- const results = Object.values(checks);
879
- return {
880
- ready: results.every((c) => c.ok || !c.required),
881
- healthy: results.every((c) => c.ok),
882
- checks
883
- };
884
- }
885
- __name(probe, "probe");
886
- return /* @__PURE__ */ __name(async function getReadiness() {
887
- const at = now();
888
- if (cache && at - cache.at < READINESS_CACHE_MS) return cache.snapshot;
889
- if (inFlight) return inFlight;
890
- inFlight = probe().then((snapshot) => {
891
- cache = {
892
- snapshot,
893
- at: now()
894
- };
895
- return snapshot;
896
- }).finally(() => {
897
- inFlight = null;
898
- });
899
- return inFlight;
900
- }, "getReadiness");
901
- }
902
- __name(createReadinessProbe, "createReadinessProbe");
879
+ const required = new Set(deps.requiredDependencies ?? DEFAULT_REQUIRED);
880
+ let cache = null;
881
+ let inFlight = null;
882
+ async function probe() {
883
+ const checks = {};
884
+ const jobs = [];
885
+ if (deps.prisma) jobs.push(runCheck("postgres", required.has("postgres"), async () => {
886
+ const client = deps.prisma?.();
887
+ if (!client) throw new Error("prisma client not initialised");
888
+ await client.$queryRaw`SELECT 1`;
889
+ }, now).then((r) => {
890
+ checks.postgres = r;
891
+ }));
892
+ if (deps.valkey) jobs.push(runCheck("valkey", required.has("valkey"), async () => {
893
+ const client = await deps.valkey?.();
894
+ if (!client) throw new Error("valkey client not initialised");
895
+ await client.ping();
896
+ }, now).then((r) => {
897
+ checks.valkey = r;
898
+ }));
899
+ if (deps.eventQueue) jobs.push(runCheck("eventQueue", required.has("eventQueue"), async () => {
900
+ const q = deps.eventQueue?.();
901
+ if (!q) throw new Error("event queue not initialised");
902
+ if (typeof q.isConnected === "function") {
903
+ if (!await Promise.resolve(q.isConnected())) throw new Error("event queue reports disconnected");
904
+ return;
905
+ }
906
+ if (typeof q.healthCheck === "function") {
907
+ if (!(await q.healthCheck()).ok) throw new Error("event queue health check failed");
908
+ }
909
+ }, now).then((r) => {
910
+ checks.eventQueue = r;
911
+ }));
912
+ await Promise.all(jobs);
913
+ const results = Object.values(checks);
914
+ return {
915
+ ready: results.every((c) => c.ok || !c.required),
916
+ healthy: results.every((c) => c.ok),
917
+ checks
918
+ };
919
+ }
920
+ return async function getReadiness() {
921
+ const at = now();
922
+ if (cache && at - cache.at < 1e3) return cache.snapshot;
923
+ if (inFlight) return inFlight;
924
+ inFlight = probe().then((snapshot) => {
925
+ cache = {
926
+ snapshot,
927
+ at: now()
928
+ };
929
+ return snapshot;
930
+ }).finally(() => {
931
+ inFlight = null;
932
+ });
933
+ return inFlight;
934
+ };
935
+ }
936
+ /** HTTP status for the readiness and aggregate endpoints. */
903
937
  function readinessStatusCode(snapshot) {
904
- return snapshot.ready ? 200 : 503;
938
+ return snapshot.ready ? 200 : 503;
905
939
  }
906
- __name(readinessStatusCode, "readinessStatusCode");
907
940
  function readinessBody(snapshot, service, version, timestamp, uptimeSeconds) {
908
- const status = !snapshot.ready ? "unavailable" : snapshot.healthy ? "healthy" : "degraded";
909
- return {
910
- status,
911
- service,
912
- version,
913
- timestamp,
914
- checks: snapshot.checks,
915
- ...uptimeSeconds === void 0 ? {} : {
916
- uptimeSeconds
917
- }
918
- };
919
- }
920
- __name(readinessBody, "readinessBody");
941
+ return {
942
+ status: !snapshot.ready ? "unavailable" : snapshot.healthy ? "healthy" : "degraded",
943
+ service,
944
+ version,
945
+ timestamp,
946
+ checks: snapshot.checks,
947
+ ...uptimeSeconds === void 0 ? {} : { uptimeSeconds }
948
+ };
949
+ }
950
+ /** Liveness body — deliberately free of any dependency information. */
921
951
  function livenessBody(service, version, timestamp) {
922
- return {
923
- status: "healthy",
924
- service,
925
- version,
926
- timestamp
927
- };
928
- }
929
- __name(livenessBody, "livenessBody");
952
+ return {
953
+ status: "healthy",
954
+ service,
955
+ version,
956
+ timestamp
957
+ };
958
+ }
959
+
960
+ // src/server/errors.ts
961
+ const DEFAULT_ERROR_CODE = "INTERNAL_SERVER_ERROR";
962
+ const DEFAULT_HTTP_STATUS = 500;
963
+ const DEFAULT_USER_MESSAGES = {
964
+ BAD_REQUEST: "Please check the request and try again.",
965
+ BAD_USER_INPUT: "Please check the information and try again.",
966
+ CAPTCHA_FAILED: "The verification failed. Please try again.",
967
+ CAPTCHA_REQUIRED: "Please complete the verification to continue.",
968
+ COMPLEXITY_TOO_HIGH: "This request is too large to process. Please simplify it and try again.",
969
+ CONFLICT: "This change conflicts with existing data. Please refresh and try again.",
970
+ FORBIDDEN: "You do not have permission to do that.",
971
+ INTERNAL_SERVER_ERROR: "Something went wrong. Please try again.",
972
+ INVALID_PASSWORD: "The password you entered is incorrect.",
973
+ NOT_FOUND: "We could not find the requested item.",
974
+ PERMISSION_DENIED: "You do not have permission to do that.",
975
+ QUOTA_EXCEEDED: "You've reached your usage limit.",
976
+ QUOTA_EXHAUSTED: "You've reached your usage limit.",
977
+ RATE_LIMITED: "Too many requests. Please wait a moment and try again.",
978
+ RESOURCE_CAP_EXCEEDED: "You've reached your plan limit. Upgrade your plan to continue.",
979
+ STORAGE_QUOTA_EXCEEDED: "You've reached your storage limit. Upgrade your plan to continue.",
980
+ TIMEOUT: "The request took too long. Please try again.",
981
+ UNAUTHENTICATED: "Please sign in to continue.",
982
+ VALIDATION_ERROR: "Please check the information and try again.",
983
+ WORKSPACE_REQUIRED: "Please choose a workspace and try again."
984
+ };
985
+ const DEFAULT_STATUS_BY_CODE = {
986
+ BAD_REQUEST: 400,
987
+ BAD_USER_INPUT: 400,
988
+ CAPTCHA_FAILED: 400,
989
+ CAPTCHA_REQUIRED: 400,
990
+ COMPLEXITY_TOO_HIGH: 400,
991
+ CONFLICT: 409,
992
+ FORBIDDEN: 403,
993
+ INVALID_PASSWORD: 400,
994
+ NOT_FOUND: 404,
995
+ PERMISSION_DENIED: 403,
996
+ QUOTA_EXCEEDED: 429,
997
+ QUOTA_EXHAUSTED: 429,
998
+ RATE_LIMITED: 429,
999
+ RESOURCE_CAP_EXCEEDED: 429,
1000
+ STORAGE_QUOTA_EXCEEDED: 429,
1001
+ TIMEOUT: 504,
1002
+ UNAUTHENTICATED: 401,
1003
+ VALIDATION_ERROR: 400,
1004
+ WORKSPACE_REQUIRED: 403
1005
+ };
1006
+ const SENSITIVE_EXTENSION_KEYS = /* @__PURE__ */ new Set([
1007
+ "exception",
1008
+ "originalError",
1009
+ "stack",
1010
+ "stacktrace"
1011
+ ]);
1012
+ const TECHNICAL_MESSAGE_PATTERNS = [
1013
+ /\bprisma\b/i,
1014
+ /\bsql\b/i,
1015
+ /\bconstraint\b/i,
1016
+ /\bstack\b/i,
1017
+ /\bundefined\b/i,
1018
+ /\bnull\b/i,
1019
+ /\bECONN[A-Z_]*\b/,
1020
+ /\bETIMEDOUT\b/,
1021
+ /\bENOTFOUND\b/,
1022
+ /\bP\d{4}\b/,
1023
+ /Cannot (read|set|find|access)/i,
1024
+ /Build failed \(exit \d+\)/i,
1025
+ /JSON\.stringify/i
1026
+ ];
1027
+ const GRAPHQL_VALIDATION_MESSAGE_PATTERNS = [
1028
+ /^Syntax Error:/i,
1029
+ /^Cannot query field\b/i,
1030
+ /^Cannot return null for non-nullable field\b/i,
1031
+ /^Unknown (argument|directive|type)\b/i,
1032
+ /^Variable "\$[^"]+" got invalid value/i,
1033
+ /^Field "[^"]+" of required type/i,
1034
+ /^Field "[^"]+" must not have a selection/i,
1035
+ /^Field "[^"]+" must have a selection/i,
1036
+ /^Fragment "[^"]+" cannot be spread here/i,
1037
+ /^There can be only one/i,
1038
+ /Did you mean /i
1039
+ ];
1040
+ function isRecord$1(value) {
1041
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1042
+ }
1043
+ function readString(record, key) {
1044
+ const value = record[key];
1045
+ return typeof value === "string" && value.trim().length > 0 ? value : null;
1046
+ }
1047
+ function readExtensions(error) {
1048
+ if (!isRecord$1(error)) return {};
1049
+ const extensions = error["extensions"];
1050
+ return isRecord$1(extensions) ? extensions : {};
1051
+ }
1052
+ function readOriginalError(error) {
1053
+ if (error instanceof GraphQLError && error.originalError instanceof Error) return error.originalError;
1054
+ }
1055
+ function sanitizeExtensions(extensions) {
1056
+ const sanitized = {};
1057
+ for (const [key, value] of Object.entries(extensions)) if (!SENSITIVE_EXTENSION_KEYS.has(key)) sanitized[key] = value;
1058
+ return sanitized;
1059
+ }
1060
+ function normalizeCode(code) {
1061
+ if (!code) return DEFAULT_ERROR_CODE;
1062
+ return code.trim().replace(/[\s-]+/g, "_").toUpperCase();
1063
+ }
1064
+ function inferCodeFromMessage(message) {
1065
+ const lower = message.toLowerCase();
1066
+ if (GRAPHQL_VALIDATION_MESSAGE_PATTERNS.some((pattern) => pattern.test(message))) return "BAD_USER_INPUT";
1067
+ if (lower.includes("unauthenticated") || lower.includes("not authenticated") || lower.includes("authentication required") || lower.includes("unauthorized") || lower.includes("please sign in") || lower.includes("sign in to")) return "UNAUTHENTICATED";
1068
+ if (lower.includes("workspace context") || lower.includes("switch to a workspace")) return "WORKSPACE_REQUIRED";
1069
+ if (lower.includes("forbidden") || lower.includes("access denied") || lower.includes("permission denied") || lower.includes("not authorized")) return "FORBIDDEN";
1070
+ if (lower.includes("not found") || lower.includes("disappeared")) return "NOT_FOUND";
1071
+ if (lower.includes("already exists") || lower.includes("already taken") || lower.includes("conflict")) return "CONFLICT";
1072
+ if (lower.includes("quota") || lower.includes("cap exceeded") || lower.includes("limit reached")) return "QUOTA_EXCEEDED";
1073
+ if (lower.includes("timeout") || lower.includes("timed out")) return "TIMEOUT";
1074
+ if (lower.includes("required") || lower.includes("invalid") || lower.includes("missing") || lower.includes("unsupported")) return "BAD_USER_INPUT";
1075
+ return DEFAULT_ERROR_CODE;
1076
+ }
1077
+ function inferCode(error, extensions, originalError) {
1078
+ const extensionCode = typeof extensions["code"] === "string" ? extensions["code"] : null;
1079
+ if (extensionCode) return normalizeCode(extensionCode);
1080
+ if (isRecord$1(originalError)) {
1081
+ const originalCode = readString(originalError, "code");
1082
+ if (originalCode) return normalizeCode(originalCode);
1083
+ }
1084
+ if (isRecord$1(error)) {
1085
+ const directCode = readString(error, "code");
1086
+ if (directCode) return normalizeCode(directCode);
1087
+ }
1088
+ return inferCodeFromMessage(readErrorMessage(error));
1089
+ }
1090
+ function readErrorMessage(error) {
1091
+ if (error instanceof Error && error.message.trim().length > 0) return error.message;
1092
+ if (isRecord$1(error)) {
1093
+ const message = readString(error, "message");
1094
+ if (message) return message;
1095
+ }
1096
+ return DEFAULT_USER_MESSAGES[DEFAULT_ERROR_CODE] ?? "Something went wrong. Please try again.";
1097
+ }
1098
+ function isLikelyTechnicalMessage(message) {
1099
+ if (message.length > 220) return true;
1100
+ if (message.includes("\n")) return true;
1101
+ if (message.includes("{") && message.includes("}")) return true;
1102
+ if (GRAPHQL_VALIDATION_MESSAGE_PATTERNS.some((pattern) => pattern.test(message))) return true;
1103
+ return TECHNICAL_MESSAGE_PATTERNS.some((pattern) => pattern.test(message));
1104
+ }
1105
+ function readExplicitUserMessage(extensions) {
1106
+ return readString(extensions, "userMessage") ?? readString(extensions, "humanMessage") ?? readString(extensions, "displayMessage");
1107
+ }
1108
+ function resolveUserMessage(code, message, extensions) {
1109
+ const explicit = readExplicitUserMessage(extensions);
1110
+ if (explicit) return explicit;
1111
+ const fallback = DEFAULT_USER_MESSAGES[code] ?? DEFAULT_USER_MESSAGES[DEFAULT_ERROR_CODE] ?? "Something went wrong. Please try again.";
1112
+ if (code === DEFAULT_ERROR_CODE) return fallback;
1113
+ if (!isLikelyTechnicalMessage(message)) return message;
1114
+ return fallback;
1115
+ }
1116
+ function resolveTechnicalMessage(code, message, extensions, options) {
1117
+ const explicit = readString(extensions, "technicalMessage");
1118
+ if (explicit) return explicit;
1119
+ if (options.environment === "production" && code === DEFAULT_ERROR_CODE) return options.serviceName ? `${options.serviceName} returned ${DEFAULT_ERROR_CODE}` : DEFAULT_ERROR_CODE;
1120
+ return message;
1121
+ }
1122
+ function isValidHttpStatus(status) {
1123
+ return typeof status === "number" && Number.isInteger(status) && status >= 200 && status <= 599;
1124
+ }
1125
+ function readHttpStatus(extensions, code) {
1126
+ const http = extensions["http"];
1127
+ if (isRecord$1(http) && isValidHttpStatus(http["status"])) return http["status"];
1128
+ return DEFAULT_STATUS_BY_CODE[code] ?? DEFAULT_HTTP_STATUS;
1129
+ }
1130
+ function normalizeError(error, options = {}) {
1131
+ const originalError = readOriginalError(error);
1132
+ const originalExtensions = readExtensions(originalError);
1133
+ const directExtensions = readExtensions(error);
1134
+ const mergedExtensions = sanitizeExtensions({
1135
+ ...originalExtensions,
1136
+ ...directExtensions
1137
+ });
1138
+ const message = readErrorMessage(error);
1139
+ const code = inferCode(error, mergedExtensions, originalError);
1140
+ const userMessage = resolveUserMessage(code, message, mergedExtensions);
1141
+ const technicalMessage = resolveTechnicalMessage(code, message, mergedExtensions, options);
1142
+ const status = readHttpStatus(mergedExtensions, code);
1143
+ const extensions = {
1144
+ ...mergedExtensions,
1145
+ code,
1146
+ userMessage,
1147
+ technicalMessage
1148
+ };
1149
+ if (options.serviceName) extensions["serviceName"] = options.serviceName;
1150
+ const http = extensions["http"];
1151
+ extensions["http"] = {
1152
+ ...isRecord$1(http) ? http : {},
1153
+ status
1154
+ };
1155
+ return {
1156
+ code,
1157
+ userMessage,
1158
+ technicalMessage,
1159
+ extensions,
1160
+ status
1161
+ };
1162
+ }
1163
+ var UserFacingGraphQLError = class extends GraphQLError {
1164
+ constructor(options) {
1165
+ const extensions = {
1166
+ code: normalizeCode(options.code),
1167
+ userMessage: options.userMessage,
1168
+ technicalMessage: options.technicalMessage ?? options.userMessage
1169
+ };
1170
+ if (options.details) extensions["details"] = options.details;
1171
+ if (options.httpStatus) extensions["http"] = { status: options.httpStatus };
1172
+ super(options.userMessage, {
1173
+ originalError: options.cause,
1174
+ extensions
1175
+ });
1176
+ this.name = "UserFacingGraphQLError";
1177
+ }
1178
+ };
1179
+ function toUserFacingGraphQLError(error, options = {}) {
1180
+ const normalized = normalizeError(error, options);
1181
+ if (error instanceof GraphQLError) return new GraphQLError(normalized.userMessage, {
1182
+ nodes: error.nodes,
1183
+ source: error.source,
1184
+ positions: error.positions,
1185
+ path: error.path,
1186
+ originalError: error.originalError,
1187
+ extensions: normalized.extensions
1188
+ });
1189
+ return new GraphQLError(normalized.userMessage, {
1190
+ originalError: error instanceof Error ? error : void 0,
1191
+ extensions: normalized.extensions
1192
+ });
1193
+ }
1194
+ function normalizeExecutionResultErrors(result, options = {}) {
1195
+ if (Array.isArray(result)) {
1196
+ result.forEach((entry) => normalizeExecutionResultErrors(entry, options));
1197
+ return;
1198
+ }
1199
+ if (!isRecord$1(result)) return;
1200
+ const errors = result["errors"];
1201
+ if (!Array.isArray(errors) || errors.length === 0) return;
1202
+ result["errors"] = errors.map((error) => toUserFacingGraphQLError(error, options));
1203
+ }
1204
+ function normalizeGraphQLResponsePayload(payload, options = {}) {
1205
+ normalizeExecutionResultErrors(payload, options);
1206
+ return payload;
1207
+ }
1208
+ function restoreSerializedHttpStatuses(payload, responseStatus) {
1209
+ if (Array.isArray(payload)) {
1210
+ payload.forEach((entry) => restoreSerializedHttpStatuses(entry, responseStatus));
1211
+ return;
1212
+ }
1213
+ if (!isRecord$1(payload) || !Array.isArray(payload["errors"])) return;
1214
+ for (const error of payload["errors"]) {
1215
+ if (!isRecord$1(error)) continue;
1216
+ const extensions = readExtensions(error);
1217
+ const http = extensions["http"];
1218
+ if (isRecord$1(http) && isValidHttpStatus(http["status"])) continue;
1219
+ const code = inferCode(error, extensions, void 0);
1220
+ const status = DEFAULT_STATUS_BY_CODE[code] ?? (code !== DEFAULT_ERROR_CODE && responseStatus >= 400 ? responseStatus : DEFAULT_HTTP_STATUS);
1221
+ error["extensions"] = {
1222
+ ...extensions,
1223
+ http: {
1224
+ ...isRecord$1(http) ? http : {},
1225
+ status
1226
+ }
1227
+ };
1228
+ }
1229
+ }
1230
+ async function normalizeGraphQLResponse(response, options = {}) {
1231
+ if (!(response.headers.get("content-type") ?? "").toLowerCase().includes("json")) return response;
1232
+ const text = await response.text();
1233
+ if (!text) return new Response(text, {
1234
+ status: response.status,
1235
+ statusText: response.statusText,
1236
+ headers: response.headers
1237
+ });
1238
+ let payload;
1239
+ try {
1240
+ payload = JSON.parse(text);
1241
+ } catch {
1242
+ return new Response(text, {
1243
+ status: response.status,
1244
+ statusText: response.statusText,
1245
+ headers: response.headers
1246
+ });
1247
+ }
1248
+ restoreSerializedHttpStatuses(payload, response.status);
1249
+ normalizeGraphQLResponsePayload(payload, options);
1250
+ return new Response(JSON.stringify(payload), {
1251
+ status: response.status,
1252
+ statusText: response.statusText,
1253
+ headers: response.headers
1254
+ });
1255
+ }
1256
+ function createHumanReadableErrorPlugin(options = {}) {
1257
+ return { onExecute() {
1258
+ return { onExecuteDone({ result }) {
1259
+ normalizeExecutionResultErrors(result, options);
1260
+ } };
1261
+ } };
1262
+ }
1263
+ function formatHttpError(error, options = {}) {
1264
+ const normalized = normalizeError(error, options);
1265
+ return {
1266
+ status: normalized.status,
1267
+ body: {
1268
+ error: normalized.userMessage,
1269
+ message: normalized.userMessage,
1270
+ userMessage: normalized.userMessage,
1271
+ technicalMessage: normalized.technicalMessage,
1272
+ code: normalized.code,
1273
+ extensions: normalized.extensions
1274
+ }
1275
+ };
1276
+ }
1277
+ function createHttpErrorResponse(error, options = {}) {
1278
+ const formatted = formatHttpError(error, options);
1279
+ return new Response(JSON.stringify(formatted.body), {
1280
+ status: formatted.status,
1281
+ headers: { "Content-Type": "application/json" }
1282
+ });
1283
+ }
930
1284
 
931
1285
  // src/server/server.ts
932
- var serverStartTime = null;
933
- var quotaGaugeRefresher = createQuotaGaugeRefresher({
934
- collect: /* @__PURE__ */ __name(() => getWorkspaceQuotaRegistry().collectAll(), "collect")
935
- });
1286
+ /**
1287
+ * Server Module
1288
+ *
1289
+ * Main server bootstrapping with Elysia, GraphQL Yoga, and middleware.
1290
+ * Uses Bun runtime for high-performance GraphQL services.
1291
+ *
1292
+ * Provides a simple API for microservices to start a fully configured server.
1293
+ */
1294
+ let serverStartTime = null;
1295
+ const quotaGaugeRefresher = createQuotaGaugeRefresher({ collect: () => getWorkspaceQuotaRegistry().collectAll() });
1296
+ /**
1297
+ * Create and configure a server instance using Elysia + GraphQL Yoga
1298
+ */
936
1299
  async function createServer(definition) {
937
- const { config, prismaClient, schema, moduleGraph, restEndpoints, yogaPlugins, buildContext: customBuildContext, workspaceExtensionConfig, disableWorkspaceExtension, onShutdown } = definition;
938
- const { Elysia } = await import('elysia');
939
- const { BunAdapter } = await import('elysia/adapter/bun');
940
- const { cors } = await import('@elysiajs/cors');
941
- const { createYoga } = await import('graphql-yoga');
942
- const { initializeDatabase, getDb: getDb2, getDatabaseManager } = await import('../prisma/index.js');
943
- const { createSecurityPlugin } = await import('../middleware/index.js');
944
- const { createMetricsPlugin } = await import('../observability/index.js');
945
- const { createWorkspaceGuardPlugin: createWorkspaceGuardPlugin2 } = await import('../workspace-guard-NXVYYBVJ.js');
946
- logger.info(`[Server] Initializing ${config.serviceName}...`);
947
- const boundary = config.boundary ?? (config.serviceName.startsWith("wspace-") ? "wspace" : config.serviceName.startsWith("global-") ? "global" : "wspace");
948
- const shouldEnableWorkspaceExtension = disableWorkspaceExtension === true ? false : disableWorkspaceExtension === false ? true : boundary === "wspace";
949
- logger.info("[Server] Initializing database...", {
950
- boundary,
951
- workspaceExtension: shouldEnableWorkspaceExtension
952
- });
953
- const { connect } = initializeDatabase(prismaClient, config.serviceName, {
954
- registerShutdownHandlers: false,
955
- enableWorkspaceExtension: shouldEnableWorkspaceExtension,
956
- ...workspaceExtensionConfig ? {
957
- workspaceExtensionConfig
958
- } : {}
959
- });
960
- await connect();
961
- let i18nInstance;
962
- if (config.i18n?.enabled && config.i18n.localesPath) {
963
- logger.info("[Server] Initializing i18n...");
964
- i18nInstance = new I18n({
965
- defaultLocale: config.i18n.defaultLocale || "en-US",
966
- fallbackLocale: config.i18n.fallbackLocale || "en-US",
967
- localesPath: config.i18n.localesPath,
968
- supportedLocales: config.i18n.supportedLocales,
969
- namespace: config.i18n.namespace || config.serviceName,
970
- lazyLoad: config.i18n.lazyLoad,
971
- logMissing: config.i18n.logMissing ?? true,
972
- enableCache: true,
973
- returnKeyOnMissing: true
974
- });
975
- await i18nInstance.initialize();
976
- logger.info(`[Server] i18n initialized with locales: ${i18nInstance.getSupportedLocales().join(", ")}`);
977
- }
978
- configureContext({
979
- getDb: /* @__PURE__ */ __name(() => getDb2(), "getDb"),
980
- i18n: i18nInstance
981
- });
982
- configureDefaultAuth();
983
- if (moduleGraph) {
984
- logger.info("[Server] Initializing module graph...");
985
- await moduleGraph.initialize();
986
- }
987
- const isDev = config.environment !== "production";
988
- const enablePlayground = config.enablePlayground ?? isDev;
989
- const batching = config.batching ?? true;
990
- const workspaceGuardEnabled = config.workspaceGuard?.enabled ?? boundary === "wspace";
991
- logger.info(`[Server] Boundary: ${boundary}, workspace guard: ${workspaceGuardEnabled ? "enabled" : "disabled"}`);
992
- const workspaceGuardPlugins = workspaceGuardEnabled ? [
993
- createWorkspaceGuardPlugin2({
994
- enabled: true,
995
- whitelistedOperations: config.workspaceGuard?.whitelistedOperations,
996
- whitelistedFields: config.workspaceGuard?.whitelistedFields,
997
- validateWorkspaceMembership: config.workspaceGuard?.validateWorkspaceMembership
998
- })
999
- ] : [];
1000
- const graphqlEndpoint = config.graphqlEndpoint || "/graphql";
1001
- logger.info("[Server] Setting up GraphQL Yoga with provided schema...", {
1002
- batching
1003
- });
1004
- const responseHeadersPlugin = {
1005
- onResponse: /* @__PURE__ */ __name(({ response, serverContext }) => {
1006
- const yogaContext = serverContext;
1007
- if (yogaContext?.responseHeaders) {
1008
- yogaContext.responseHeaders.forEach((value, key) => {
1009
- response.headers.append(key, value);
1010
- });
1011
- }
1012
- }, "onResponse")
1013
- };
1014
- const yoga = createYoga({
1015
- graphqlEndpoint,
1016
- schema,
1017
- graphiql: enablePlayground,
1018
- batching,
1019
- logging: {
1020
- debug: /* @__PURE__ */ __name((...args) => logger.debug("[GraphQL]", ...args), "debug"),
1021
- info: /* @__PURE__ */ __name((...args) => logger.info("[GraphQL]", ...args), "info"),
1022
- warn: /* @__PURE__ */ __name((...args) => logger.warn("[GraphQL]", ...args), "warn"),
1023
- error: /* @__PURE__ */ __name((...args) => logger.error("[GraphQL]", ...args), "error")
1024
- },
1025
- plugins: [
1026
- createHumanReadableErrorPlugin({
1027
- serviceName: config.serviceName,
1028
- environment: config.environment
1029
- }),
1030
- ...workspaceGuardPlugins,
1031
- responseHeadersPlugin,
1032
- ...yogaPlugins || [],
1033
- // Consumers such as GraphQL Modules replace execute/subscribe; bind their final functions.
1034
- createWorkspaceExecutionContextPlugin()
1035
- ],
1036
- context: /* @__PURE__ */ __name(async ({ request }) => {
1037
- const defaultContext = await buildContext(request);
1038
- if (customBuildContext) {
1039
- return customBuildContext(defaultContext);
1040
- }
1041
- return defaultContext;
1042
- }, "context")
1043
- });
1044
- const app = new Elysia({
1045
- adapter: BunAdapter
1046
- });
1047
- const corsOrigins = normalizeCorsOrigins(config.corsOrigins, config.environment);
1048
- app.use(cors({
1049
- origin: corsOrigins,
1050
- credentials: corsOrigins.length > 0,
1051
- allowedHeaders: [
1052
- "Content-Type",
1053
- "Authorization",
1054
- "X-Tenant-ID",
1055
- "X-Workspace-ID",
1056
- "X-Org-ID",
1057
- "X-Project-ID",
1058
- "X-Product-ID",
1059
- "X-CSRF-Token",
1060
- "X-Service-Name",
1061
- "Accept-Language",
1062
- "X-Locale",
1063
- "X-Language",
1064
- "X-Geo-Country",
1065
- "X-Geo-Currency",
1066
- "X-Geo-Timezone",
1067
- // Actor headers (gateway-injected or dev mode)
1068
- "X-Actor-ID",
1069
- "X-Actor-Type",
1070
- "X-Internal-Service-Token",
1071
- "X-Gateway-Auth-Token"
1072
- ],
1073
- methods: [
1074
- "GET",
1075
- "POST",
1076
- "PUT",
1077
- "PATCH",
1078
- "DELETE",
1079
- "OPTIONS"
1080
- ]
1081
- }));
1082
- const rawBodyRouter = createRawBodyRouter(restEndpoints || [], () => app.routes);
1083
- app.onRequest(async ({ request, server }) => {
1084
- const url = new URL(request.url);
1085
- const pathname = url.pathname;
1086
- logger.debug(`[Server] onRequest: ${request.method} ${pathname}`);
1087
- const isHealthRoute = pathname === "/health" || pathname.startsWith("/health/");
1088
- const buildCorsHeaders = /* @__PURE__ */ __name(() => {
1089
- const origin = request.headers.get("origin") || "*";
1090
- const allowedOrigin = resolveAllowedCorsOrigin(origin === "*" ? null : origin, corsOrigins);
1091
- const headers = {
1092
- "Access-Control-Allow-Methods": "GET, POST, PUT, PATCH, DELETE, OPTIONS",
1093
- "Access-Control-Allow-Headers": "Content-Type, Authorization, X-Tenant-ID, X-Workspace-ID, X-Org-ID, X-Project-ID, X-Product-ID, X-CSRF-Token, X-Service-Name, Accept-Language, X-Locale, X-Language, X-Geo-Country, X-Geo-Currency, X-Geo-Timezone, X-Actor-ID, X-Actor-Type, X-Internal-Service-Token, X-Gateway-Auth-Token"
1094
- };
1095
- if (allowedOrigin) {
1096
- headers["Access-Control-Allow-Origin"] = allowedOrigin;
1097
- headers["Access-Control-Allow-Credentials"] = "true";
1098
- }
1099
- return headers;
1100
- }, "buildCorsHeaders");
1101
- if (!isHealthRoute && rawBodyRouter.size > 0 && rawBodyRouter.hasPath(pathname)) {
1102
- const corsHeaders = buildCorsHeaders();
1103
- if (request.method === "OPTIONS") {
1104
- return new Response(null, {
1105
- status: 204,
1106
- headers: corsHeaders
1107
- });
1108
- }
1109
- const resolution = rawBodyRouter.resolve(pathname, request.method);
1110
- if (!resolution) return void 0;
1111
- if (resolution.kind === "method-not-allowed") {
1112
- return new Response(JSON.stringify({
1113
- error: `Method ${request.method} is not allowed`,
1114
- allowed: resolution.allowed
1115
- }), {
1116
- status: 405,
1117
- headers: {
1118
- "Content-Type": "application/json",
1119
- Allow: resolution.allowed.join(", "),
1120
- ...corsHeaders
1121
- }
1122
- });
1123
- }
1124
- const rawBodyEndpoint = resolution.endpoint;
1125
- logger.debug(`[Server] Matched raw body endpoint: ${request.method} ${pathname} -> ${rawBodyEndpoint.path}`);
1126
- rememberRequestServer(request, server);
1127
- const isHead = request.method === "HEAD";
1128
- try {
1129
- const rawBody = await request.text();
1130
- const context = await buildContext(request);
1131
- const result = await rawBodyEndpoint.handler(request, context, rawBody);
1132
- if (result instanceof Response) {
1133
- const headers2 = new Headers(result.headers);
1134
- for (const [key, value] of Object.entries(corsHeaders)) {
1135
- headers2.set(key, value);
1136
- }
1137
- return new Response(isHead ? null : result.body, {
1138
- status: result.status,
1139
- statusText: result.statusText,
1140
- headers: headers2
1141
- });
1142
- }
1143
- const headers = new Headers({
1144
- "Content-Type": "application/json",
1145
- ...corsHeaders
1146
- });
1147
- return new Response(isHead ? null : JSON.stringify(result), {
1148
- status: 200,
1149
- headers
1150
- });
1151
- } catch (error) {
1152
- logger.error(`[Server] Raw body endpoint error (${pathname}):`, error);
1153
- const corsHeaders2 = buildCorsHeaders();
1154
- const formatted = formatHttpError(error, {
1155
- serviceName: config.serviceName,
1156
- environment: config.environment
1157
- });
1158
- return new Response(isHead ? null : JSON.stringify(formatted.body), {
1159
- status: formatted.status,
1160
- headers: {
1161
- "Content-Type": "application/json",
1162
- ...corsHeaders2
1163
- }
1164
- });
1165
- }
1166
- }
1167
- if (pathname === "/metrics" && request.method === "GET") {
1168
- try {
1169
- const promClientMod = "prom-client";
1170
- const prom = await import(promClientMod);
1171
- try {
1172
- prom.collectDefaultMetrics({
1173
- register: prom.register
1174
- });
1175
- } catch {
1176
- }
1177
- const promBody = await prom.register.metrics();
1178
- let sdkBody = "";
1179
- await quotaGaugeRefresher.refresh();
1180
- try {
1181
- sdkBody = getMetricsRegistry().toPrometheusFormat();
1182
- } catch {
1183
- }
1184
- const combined = sdkBody ? `${promBody}
1185
- ${sdkBody}` : promBody;
1186
- return new Response(combined, {
1187
- status: 200,
1188
- headers: {
1189
- "Content-Type": prom.register.contentType ?? "text/plain; version=0.0.4; charset=utf-8"
1190
- }
1191
- });
1192
- } catch {
1193
- }
1194
- }
1195
- const yogaRoutes = [
1196
- graphqlEndpoint,
1197
- `${graphqlEndpoint}/`,
1198
- "/metrics"
1199
- ];
1200
- const shouldHandleByYoga = yogaRoutes.includes(pathname);
1201
- if (shouldHandleByYoga) {
1202
- const corsHeaders = buildCorsHeaders();
1203
- if (request.method === "OPTIONS") {
1204
- return new Response(null, {
1205
- status: 204,
1206
- headers: corsHeaders
1207
- });
1208
- }
1209
- const yogaResponse = await normalizeGraphQLResponse(await yoga.fetch(request), {
1210
- serviceName: config.serviceName,
1211
- environment: config.environment
1212
- });
1213
- const headers = new Headers(yogaResponse.headers);
1214
- for (const [key, value] of Object.entries(corsHeaders)) {
1215
- headers.set(key, value);
1216
- }
1217
- return new Response(yogaResponse.body, {
1218
- status: yogaResponse.status,
1219
- statusText: yogaResponse.statusText,
1220
- headers
1221
- });
1222
- }
1223
- return void 0;
1224
- });
1225
- app.use(createMetricsPlugin());
1226
- app.use(createSecurityPlugin({
1227
- csrfSkipRoutes: config.csrfSkipRoutes || [
1228
- "/graphql",
1229
- "/health",
1230
- "/api/graph/"
1231
- ],
1232
- loginEndpoints: config.loginEndpoints || [],
1233
- enableCSRF: config.enableCSRF ?? false,
1234
- enableSessionSecurity: config.enableSessionSecurity ?? false
1235
- }));
1236
- const serviceVersion = config.serviceVersion || "1.0.0";
1237
- const getReadiness = createReadinessProbe({
1238
- prisma: /* @__PURE__ */ __name(() => getDb2(), "prisma"),
1239
- valkey: /* @__PURE__ */ __name(async () => {
1240
- try {
1241
- const { getValkeyClient } = await import('../cache/index.js');
1242
- return await getValkeyClient();
1243
- } catch {
1244
- return void 0;
1245
- }
1246
- }, "valkey"),
1247
- ...config.health?.requiredDependencies ? {
1248
- requiredDependencies: config.health.requiredDependencies
1249
- } : {}
1250
- });
1251
- const shallow = /* @__PURE__ */ __name(() => livenessBody(config.serviceName, serviceVersion, (/* @__PURE__ */ new Date()).toISOString()), "shallow");
1252
- const deep = /* @__PURE__ */ __name(async (ctx) => {
1253
- const snapshot = await getReadiness();
1254
- const ctxWithSet = ctx;
1255
- const code = readinessStatusCode(snapshot);
1256
- if (ctxWithSet.set) ctxWithSet.set.status = code;
1257
- return readinessBody(snapshot, config.serviceName, serviceVersion, (/* @__PURE__ */ new Date()).toISOString(), Math.round(process.uptime()));
1258
- }, "deep");
1259
- app.get("/health", deep);
1260
- app.get("/health/live", shallow);
1261
- app.get("/health/ready", deep);
1262
- app.get("/health/startup", shallow);
1263
- if (moduleGraph) {
1264
- app.get("/api/graph/schema", async ({ request, set }) => {
1265
- const context = await buildContext(request);
1266
- if (!canAccessGraphExport(context.actor)) {
1267
- set.status = 403;
1268
- return {
1269
- error: "Forbidden"
1270
- };
1271
- }
1272
- return moduleGraph.getSchema();
1273
- });
1274
- app.get("/api/graph/export", async ({ query, request, set }) => {
1275
- const context = await buildContext(request);
1276
- if (!canAccessGraphExport(context.actor)) {
1277
- set.status = 403;
1278
- return {
1279
- error: "Forbidden"
1280
- };
1281
- }
1282
- const { organizationId, workspaceId } = query;
1283
- return moduleGraph.exportAll(organizationId, workspaceId);
1284
- });
1285
- app.get("/api/graph/entities", async ({ query, request, set }) => {
1286
- const context = await buildContext(request);
1287
- if (!canAccessGraphExport(context.actor)) {
1288
- set.status = 403;
1289
- return {
1290
- error: "Forbidden"
1291
- };
1292
- }
1293
- const { organizationId, workspaceId, types } = query;
1294
- const entityTypes = types?.split(",").map((t) => t.trim());
1295
- return moduleGraph.exportEntities(organizationId, workspaceId, entityTypes);
1296
- });
1297
- app.get("/api/graph/relationships", async ({ query, request, set }) => {
1298
- const context = await buildContext(request);
1299
- if (!canAccessGraphExport(context.actor)) {
1300
- set.status = 403;
1301
- return {
1302
- error: "Forbidden"
1303
- };
1304
- }
1305
- const { organizationId, workspaceId } = query;
1306
- return moduleGraph.exportRelationships(organizationId, workspaceId);
1307
- });
1308
- }
1309
- if (restEndpoints && restEndpoints.length > 0) {
1310
- for (const endpoint of restEndpoints) {
1311
- if (endpoint.rawBody) {
1312
- logger.info(`[Server] Raw body endpoint registered: ${endpoint.method} ${endpoint.path}`);
1313
- continue;
1314
- }
1315
- const handler = /* @__PURE__ */ __name(async ({ request }) => {
1316
- try {
1317
- const context = await buildContext(request);
1318
- return await endpoint.handler(request, context);
1319
- } catch (error) {
1320
- logger.error(`[Server] REST endpoint error (${endpoint.path}):`, error);
1321
- return createHttpErrorResponse(error, {
1322
- serviceName: config.serviceName,
1323
- environment: config.environment
1324
- });
1325
- }
1326
- }, "handler");
1327
- switch (endpoint.method) {
1328
- case "GET":
1329
- app.get(endpoint.path, handler);
1330
- break;
1331
- case "POST":
1332
- app.post(endpoint.path, handler);
1333
- break;
1334
- case "PUT":
1335
- app.put(endpoint.path, handler);
1336
- break;
1337
- case "PATCH":
1338
- app.patch(endpoint.path, handler);
1339
- break;
1340
- case "DELETE":
1341
- app.delete(endpoint.path, handler);
1342
- break;
1343
- }
1344
- }
1345
- }
1346
- const host = config.host || "0.0.0.0";
1347
- const port = config.port;
1348
- const serverInstance = {
1349
- app,
1350
- server: null,
1351
- start: /* @__PURE__ */ __name(async () => {
1352
- serverStartTime = /* @__PURE__ */ new Date();
1353
- app.listen({
1354
- port,
1355
- hostname: host
1356
- });
1357
- const elysiaApp = app;
1358
- serverInstance.server = elysiaApp.server;
1359
- logger.info(`\u{1F680} ${config.serviceName} is running at http://${host}:${port}${graphqlEndpoint}`);
1360
- }, "start"),
1361
- stop: /* @__PURE__ */ __name(async () => {
1362
- logger.info(`[Server] Stopping ${config.serviceName}...`);
1363
- if (onShutdown) {
1364
- await onShutdown();
1365
- }
1366
- if (moduleGraph) {
1367
- await moduleGraph.shutdown();
1368
- }
1369
- await getDatabaseManager().disconnect();
1370
- if (serverInstance.server) {
1371
- serverInstance.server.stop();
1372
- }
1373
- logger.info(`[Server] ${config.serviceName} stopped`);
1374
- }, "stop"),
1375
- getInfo: /* @__PURE__ */ __name(() => {
1376
- const uptime = serverStartTime ? Math.floor((Date.now() - serverStartTime.getTime()) / 1e3) : 0;
1377
- return {
1378
- serviceName: config.serviceName,
1379
- serviceVersion: config.serviceVersion || "1.0.0",
1380
- environment: config.environment || "development",
1381
- port,
1382
- host,
1383
- graphqlEndpoint,
1384
- startedAt: serverStartTime?.toISOString() || "",
1385
- uptime
1386
- };
1387
- }, "getInfo")
1388
- };
1389
- const gracefulShutdown = /* @__PURE__ */ __name(async (signal) => {
1390
- logger.info(`[Server] ${signal} received, shutting down gracefully...`);
1391
- await serverInstance.stop();
1392
- process.exit(0);
1393
- }, "gracefulShutdown");
1394
- process.on("SIGTERM", () => {
1395
- void gracefulShutdown("SIGTERM");
1396
- });
1397
- process.on("SIGINT", () => {
1398
- void gracefulShutdown("SIGINT");
1399
- });
1400
- return serverInstance;
1401
- }
1402
- __name(createServer, "createServer");
1403
- function configureServerAuth(fetchWorkspaceSecret2) {
1404
- configureAuth({
1405
- fetchWorkspaceSecret: fetchWorkspaceSecret2
1406
- });
1407
- }
1408
- __name(configureServerAuth, "configureServerAuth");
1409
- var MUTATION_AUDIT_ACTIVITY_TYPE = "graphql.mutation";
1410
- var MUTATION_AUDIT_RESOURCE_TYPE = "graphql_mutation";
1411
- var SENSITIVE_KEY_MARKERS = [
1412
- "password",
1413
- "passcode",
1414
- "pass",
1415
- "token",
1416
- "secret",
1417
- "apikey",
1418
- "accesskey",
1419
- "authorization",
1420
- "cookie",
1421
- "credential",
1422
- "clientsecret",
1423
- "privatekey"
1300
+ const { config, prismaClient, schema, moduleGraph, restEndpoints, yogaPlugins, buildContext: customBuildContext, workspaceExtensionConfig, disableWorkspaceExtension, onShutdown } = definition;
1301
+ const { Elysia } = await import("elysia");
1302
+ const { BunAdapter } = await import("elysia/adapter/bun");
1303
+ const { cors } = await import("@elysiajs/cors");
1304
+ const { createYoga } = await import("graphql-yoga");
1305
+ const { initializeDatabase, getDb, getDatabaseManager } = await import("../prisma/index.js");
1306
+ const { createSecurityPlugin } = await import("../middleware/index.js");
1307
+ const { createMetricsPlugin } = await import("../observability/index.js");
1308
+ const { createWorkspaceGuardPlugin } = await Promise.resolve().then(() => workspace_guard_exports);
1309
+ logger.info(`[Server] Initializing ${config.serviceName}...`);
1310
+ const boundary = config.boundary ?? (config.serviceName.startsWith("wspace-") ? "wspace" : config.serviceName.startsWith("global-") ? "global" : "wspace");
1311
+ const shouldEnableWorkspaceExtension = disableWorkspaceExtension === true ? false : disableWorkspaceExtension === false ? true : boundary === "wspace";
1312
+ logger.info("[Server] Initializing database...", {
1313
+ boundary,
1314
+ workspaceExtension: shouldEnableWorkspaceExtension
1315
+ });
1316
+ const { connect } = initializeDatabase(prismaClient, config.serviceName, {
1317
+ registerShutdownHandlers: false,
1318
+ enableWorkspaceExtension: shouldEnableWorkspaceExtension,
1319
+ ...workspaceExtensionConfig ? { workspaceExtensionConfig } : {}
1320
+ });
1321
+ await connect();
1322
+ let i18nInstance;
1323
+ if (config.i18n?.enabled && config.i18n.localesPath) {
1324
+ logger.info("[Server] Initializing i18n...");
1325
+ i18nInstance = new I18n({
1326
+ defaultLocale: config.i18n.defaultLocale || "en-US",
1327
+ fallbackLocale: config.i18n.fallbackLocale || "en-US",
1328
+ localesPath: config.i18n.localesPath,
1329
+ supportedLocales: config.i18n.supportedLocales,
1330
+ namespace: config.i18n.namespace || config.serviceName,
1331
+ lazyLoad: config.i18n.lazyLoad,
1332
+ logMissing: config.i18n.logMissing ?? true,
1333
+ enableCache: true,
1334
+ returnKeyOnMissing: true
1335
+ });
1336
+ await i18nInstance.initialize();
1337
+ logger.info(`[Server] i18n initialized with locales: ${i18nInstance.getSupportedLocales().join(", ")}`);
1338
+ }
1339
+ configureContext({
1340
+ getDb: () => getDb(),
1341
+ i18n: i18nInstance
1342
+ });
1343
+ configureDefaultAuth();
1344
+ if (moduleGraph) {
1345
+ logger.info("[Server] Initializing module graph...");
1346
+ await moduleGraph.initialize();
1347
+ }
1348
+ const isDev = config.environment !== "production";
1349
+ const enablePlayground = config.enablePlayground ?? isDev;
1350
+ const batching = config.batching ?? true;
1351
+ const workspaceGuardEnabled = config.workspaceGuard?.enabled ?? boundary === "wspace";
1352
+ logger.info(`[Server] Boundary: ${boundary}, workspace guard: ${workspaceGuardEnabled ? "enabled" : "disabled"}`);
1353
+ const workspaceGuardPlugins = workspaceGuardEnabled ? [createWorkspaceGuardPlugin({
1354
+ enabled: true,
1355
+ whitelistedOperations: config.workspaceGuard?.whitelistedOperations,
1356
+ whitelistedFields: config.workspaceGuard?.whitelistedFields,
1357
+ validateWorkspaceMembership: config.workspaceGuard?.validateWorkspaceMembership
1358
+ })] : [];
1359
+ const graphqlEndpoint = config.graphqlEndpoint || "/graphql";
1360
+ logger.info("[Server] Setting up GraphQL Yoga with provided schema...", { batching });
1361
+ const responseHeadersPlugin = { onResponse: ({ response, serverContext }) => {
1362
+ const yogaContext = serverContext;
1363
+ if (yogaContext?.responseHeaders) yogaContext.responseHeaders.forEach((value, key) => {
1364
+ response.headers.append(key, value);
1365
+ });
1366
+ } };
1367
+ const yoga = createYoga({
1368
+ graphqlEndpoint,
1369
+ schema,
1370
+ graphiql: enablePlayground,
1371
+ batching,
1372
+ logging: {
1373
+ debug: (...args) => logger.debug("[GraphQL]", ...args),
1374
+ info: (...args) => logger.info("[GraphQL]", ...args),
1375
+ warn: (...args) => logger.warn("[GraphQL]", ...args),
1376
+ error: (...args) => logger.error("[GraphQL]", ...args)
1377
+ },
1378
+ plugins: [
1379
+ createHumanReadableErrorPlugin({
1380
+ serviceName: config.serviceName,
1381
+ environment: config.environment
1382
+ }),
1383
+ ...workspaceGuardPlugins,
1384
+ responseHeadersPlugin,
1385
+ ...yogaPlugins || [],
1386
+ createWorkspaceExecutionContextPlugin()
1387
+ ],
1388
+ context: async ({ request }) => {
1389
+ const defaultContext = await buildContext(request);
1390
+ if (customBuildContext) return customBuildContext(defaultContext);
1391
+ return defaultContext;
1392
+ }
1393
+ });
1394
+ const app = new Elysia({ adapter: BunAdapter });
1395
+ const corsOrigins = normalizeCorsOrigins(config.corsOrigins, config.environment);
1396
+ app.use(cors({
1397
+ origin: corsOrigins,
1398
+ credentials: corsOrigins.length > 0,
1399
+ allowedHeaders: [
1400
+ "Content-Type",
1401
+ "Authorization",
1402
+ "X-Tenant-ID",
1403
+ "X-Workspace-ID",
1404
+ "X-Org-ID",
1405
+ "X-Project-ID",
1406
+ "X-Product-ID",
1407
+ "X-CSRF-Token",
1408
+ "X-Service-Name",
1409
+ "Accept-Language",
1410
+ "X-Locale",
1411
+ "X-Language",
1412
+ "X-Geo-Country",
1413
+ "X-Geo-Currency",
1414
+ "X-Geo-Timezone",
1415
+ "X-Actor-ID",
1416
+ "X-Actor-Type",
1417
+ "X-Internal-Service-Token",
1418
+ "X-Gateway-Auth-Token"
1419
+ ],
1420
+ methods: [
1421
+ "GET",
1422
+ "POST",
1423
+ "PUT",
1424
+ "PATCH",
1425
+ "DELETE",
1426
+ "OPTIONS"
1427
+ ]
1428
+ }));
1429
+ const rawBodyRouter = createRawBodyRouter(restEndpoints || [], () => app.routes);
1430
+ app.onRequest(async ({ request, server }) => {
1431
+ const pathname = new URL(request.url).pathname;
1432
+ logger.debug(`[Server] onRequest: ${request.method} ${pathname}`);
1433
+ const isHealthRoute = pathname === "/health" || pathname.startsWith("/health/");
1434
+ const buildCorsHeaders = () => {
1435
+ const origin = request.headers.get("origin") || "*";
1436
+ const allowedOrigin = resolveAllowedCorsOrigin(origin === "*" ? null : origin, corsOrigins);
1437
+ const headers = {
1438
+ "Access-Control-Allow-Methods": "GET, POST, PUT, PATCH, DELETE, OPTIONS",
1439
+ "Access-Control-Allow-Headers": "Content-Type, Authorization, X-Tenant-ID, X-Workspace-ID, X-Org-ID, X-Project-ID, X-Product-ID, X-CSRF-Token, X-Service-Name, Accept-Language, X-Locale, X-Language, X-Geo-Country, X-Geo-Currency, X-Geo-Timezone, X-Actor-ID, X-Actor-Type, X-Internal-Service-Token, X-Gateway-Auth-Token"
1440
+ };
1441
+ if (allowedOrigin) {
1442
+ headers["Access-Control-Allow-Origin"] = allowedOrigin;
1443
+ headers["Access-Control-Allow-Credentials"] = "true";
1444
+ }
1445
+ return headers;
1446
+ };
1447
+ if (!isHealthRoute && rawBodyRouter.size > 0 && rawBodyRouter.hasPath(pathname)) {
1448
+ const corsHeaders = buildCorsHeaders();
1449
+ if (request.method === "OPTIONS") return new Response(null, {
1450
+ status: 204,
1451
+ headers: corsHeaders
1452
+ });
1453
+ const resolution = rawBodyRouter.resolve(pathname, request.method);
1454
+ if (!resolution) return void 0;
1455
+ if (resolution.kind === "method-not-allowed") return new Response(JSON.stringify({
1456
+ error: `Method ${request.method} is not allowed`,
1457
+ allowed: resolution.allowed
1458
+ }), {
1459
+ status: 405,
1460
+ headers: {
1461
+ "Content-Type": "application/json",
1462
+ Allow: resolution.allowed.join(", "),
1463
+ ...corsHeaders
1464
+ }
1465
+ });
1466
+ const rawBodyEndpoint = resolution.endpoint;
1467
+ logger.debug(`[Server] Matched raw body endpoint: ${request.method} ${pathname} -> ${rawBodyEndpoint.path}`);
1468
+ rememberRequestServer(request, server);
1469
+ const isHead = request.method === "HEAD";
1470
+ try {
1471
+ const rawBody = await request.text();
1472
+ const context = await buildContext(request);
1473
+ const result = await rawBodyEndpoint.handler(request, context, rawBody);
1474
+ if (result instanceof Response) {
1475
+ const headers = new Headers(result.headers);
1476
+ for (const [key, value] of Object.entries(corsHeaders)) headers.set(key, value);
1477
+ return new Response(isHead ? null : result.body, {
1478
+ status: result.status,
1479
+ statusText: result.statusText,
1480
+ headers
1481
+ });
1482
+ }
1483
+ const headers = new Headers({
1484
+ "Content-Type": "application/json",
1485
+ ...corsHeaders
1486
+ });
1487
+ return new Response(isHead ? null : JSON.stringify(result), {
1488
+ status: 200,
1489
+ headers
1490
+ });
1491
+ } catch (error) {
1492
+ logger.error(`[Server] Raw body endpoint error (${pathname}):`, error);
1493
+ const corsHeaders = buildCorsHeaders();
1494
+ const formatted = formatHttpError(error, {
1495
+ serviceName: config.serviceName,
1496
+ environment: config.environment
1497
+ });
1498
+ return new Response(isHead ? null : JSON.stringify(formatted.body), {
1499
+ status: formatted.status,
1500
+ headers: {
1501
+ "Content-Type": "application/json",
1502
+ ...corsHeaders
1503
+ }
1504
+ });
1505
+ }
1506
+ }
1507
+ if (pathname === "/metrics" && request.method === "GET") try {
1508
+ const prom = await import("prom-client");
1509
+ try {
1510
+ prom.collectDefaultMetrics({ register: prom.register });
1511
+ } catch {}
1512
+ const promBody = await prom.register.metrics();
1513
+ let sdkBody = "";
1514
+ await quotaGaugeRefresher.refresh();
1515
+ try {
1516
+ sdkBody = getMetricsRegistry().toPrometheusFormat();
1517
+ } catch {}
1518
+ const combined = sdkBody ? `${promBody}\n${sdkBody}` : promBody;
1519
+ return new Response(combined, {
1520
+ status: 200,
1521
+ headers: { "Content-Type": prom.register.contentType ?? "text/plain; version=0.0.4; charset=utf-8" }
1522
+ });
1523
+ } catch {}
1524
+ if ([
1525
+ graphqlEndpoint,
1526
+ `${graphqlEndpoint}/`,
1527
+ "/metrics"
1528
+ ].includes(pathname)) {
1529
+ const corsHeaders = buildCorsHeaders();
1530
+ if (request.method === "OPTIONS") return new Response(null, {
1531
+ status: 204,
1532
+ headers: corsHeaders
1533
+ });
1534
+ const yogaResponse = await normalizeGraphQLResponse(await yoga.fetch(request), {
1535
+ serviceName: config.serviceName,
1536
+ environment: config.environment
1537
+ });
1538
+ const headers = new Headers(yogaResponse.headers);
1539
+ for (const [key, value] of Object.entries(corsHeaders)) headers.set(key, value);
1540
+ return new Response(yogaResponse.body, {
1541
+ status: yogaResponse.status,
1542
+ statusText: yogaResponse.statusText,
1543
+ headers
1544
+ });
1545
+ }
1546
+ });
1547
+ app.use(createMetricsPlugin());
1548
+ app.use(createSecurityPlugin({
1549
+ csrfSkipRoutes: config.csrfSkipRoutes || [
1550
+ "/graphql",
1551
+ "/health",
1552
+ "/api/graph/"
1553
+ ],
1554
+ loginEndpoints: config.loginEndpoints || [],
1555
+ enableCSRF: config.enableCSRF ?? false,
1556
+ enableSessionSecurity: config.enableSessionSecurity ?? false
1557
+ }));
1558
+ const serviceVersion = config.serviceVersion || "1.0.0";
1559
+ const getReadiness = createReadinessProbe({
1560
+ prisma: () => getDb(),
1561
+ valkey: async () => {
1562
+ try {
1563
+ const { getValkeyClient } = await import("../cache/index.js");
1564
+ return await getValkeyClient();
1565
+ } catch {
1566
+ return;
1567
+ }
1568
+ },
1569
+ ...config.health?.requiredDependencies ? { requiredDependencies: config.health.requiredDependencies } : {}
1570
+ });
1571
+ const shallow = () => livenessBody(config.serviceName, serviceVersion, (/* @__PURE__ */ new Date()).toISOString());
1572
+ const deep = async (ctx) => {
1573
+ const snapshot = await getReadiness();
1574
+ const ctxWithSet = ctx;
1575
+ const code = readinessStatusCode(snapshot);
1576
+ if (ctxWithSet.set) ctxWithSet.set.status = code;
1577
+ return readinessBody(snapshot, config.serviceName, serviceVersion, (/* @__PURE__ */ new Date()).toISOString(), Math.round(process.uptime()));
1578
+ };
1579
+ app.get("/health", deep);
1580
+ app.get("/health/live", shallow);
1581
+ app.get("/health/ready", deep);
1582
+ app.get("/health/startup", shallow);
1583
+ if (moduleGraph) {
1584
+ app.get("/api/graph/schema", async ({ request, set }) => {
1585
+ const context = await buildContext(request);
1586
+ if (!canAccessGraphExport(context.actor)) {
1587
+ set.status = 403;
1588
+ return { error: "Forbidden" };
1589
+ }
1590
+ return moduleGraph.getSchema();
1591
+ });
1592
+ app.get("/api/graph/export", async ({ query, request, set }) => {
1593
+ const context = await buildContext(request);
1594
+ if (!canAccessGraphExport(context.actor)) {
1595
+ set.status = 403;
1596
+ return { error: "Forbidden" };
1597
+ }
1598
+ const { organizationId, workspaceId } = query;
1599
+ return moduleGraph.exportAll(organizationId, workspaceId);
1600
+ });
1601
+ app.get("/api/graph/entities", async ({ query, request, set }) => {
1602
+ const context = await buildContext(request);
1603
+ if (!canAccessGraphExport(context.actor)) {
1604
+ set.status = 403;
1605
+ return { error: "Forbidden" };
1606
+ }
1607
+ const { organizationId, workspaceId, types } = query;
1608
+ const entityTypes = types?.split(",").map((t) => t.trim());
1609
+ return moduleGraph.exportEntities(organizationId, workspaceId, entityTypes);
1610
+ });
1611
+ app.get("/api/graph/relationships", async ({ query, request, set }) => {
1612
+ const context = await buildContext(request);
1613
+ if (!canAccessGraphExport(context.actor)) {
1614
+ set.status = 403;
1615
+ return { error: "Forbidden" };
1616
+ }
1617
+ const { organizationId, workspaceId } = query;
1618
+ return moduleGraph.exportRelationships(organizationId, workspaceId);
1619
+ });
1620
+ }
1621
+ if (restEndpoints && restEndpoints.length > 0) for (const endpoint of restEndpoints) {
1622
+ if (endpoint.rawBody) {
1623
+ logger.info(`[Server] Raw body endpoint registered: ${endpoint.method} ${endpoint.path}`);
1624
+ continue;
1625
+ }
1626
+ const handler = async ({ request }) => {
1627
+ try {
1628
+ const context = await buildContext(request);
1629
+ return await endpoint.handler(request, context);
1630
+ } catch (error) {
1631
+ logger.error(`[Server] REST endpoint error (${endpoint.path}):`, error);
1632
+ return createHttpErrorResponse(error, {
1633
+ serviceName: config.serviceName,
1634
+ environment: config.environment
1635
+ });
1636
+ }
1637
+ };
1638
+ switch (endpoint.method) {
1639
+ case "GET":
1640
+ app.get(endpoint.path, handler);
1641
+ break;
1642
+ case "POST":
1643
+ app.post(endpoint.path, handler);
1644
+ break;
1645
+ case "PUT":
1646
+ app.put(endpoint.path, handler);
1647
+ break;
1648
+ case "PATCH":
1649
+ app.patch(endpoint.path, handler);
1650
+ break;
1651
+ case "DELETE": app.delete(endpoint.path, handler);
1652
+ }
1653
+ }
1654
+ const host = config.host || "0.0.0.0";
1655
+ const port = config.port;
1656
+ const serverInstance = {
1657
+ app,
1658
+ server: null,
1659
+ start: async () => {
1660
+ serverStartTime = /* @__PURE__ */ new Date();
1661
+ app.listen({
1662
+ port,
1663
+ hostname: host
1664
+ });
1665
+ serverInstance.server = app.server;
1666
+ logger.info(`🚀 ${config.serviceName} is running at http://${host}:${port}${graphqlEndpoint}`);
1667
+ },
1668
+ stop: async () => {
1669
+ logger.info(`[Server] Stopping ${config.serviceName}...`);
1670
+ if (onShutdown) await onShutdown();
1671
+ if (moduleGraph) await moduleGraph.shutdown();
1672
+ await getDatabaseManager().disconnect();
1673
+ if (serverInstance.server) serverInstance.server.stop();
1674
+ logger.info(`[Server] ${config.serviceName} stopped`);
1675
+ },
1676
+ getInfo: () => {
1677
+ const uptime = serverStartTime ? Math.floor((Date.now() - serverStartTime.getTime()) / 1e3) : 0;
1678
+ return {
1679
+ serviceName: config.serviceName,
1680
+ serviceVersion: config.serviceVersion || "1.0.0",
1681
+ environment: config.environment || "development",
1682
+ port,
1683
+ host,
1684
+ graphqlEndpoint,
1685
+ startedAt: serverStartTime?.toISOString() || "",
1686
+ uptime
1687
+ };
1688
+ }
1689
+ };
1690
+ const gracefulShutdown = async (signal) => {
1691
+ logger.info(`[Server] ${signal} received, shutting down gracefully...`);
1692
+ await serverInstance.stop();
1693
+ process.exit(0);
1694
+ };
1695
+ process.on("SIGTERM", () => {
1696
+ gracefulShutdown("SIGTERM");
1697
+ });
1698
+ process.on("SIGINT", () => {
1699
+ gracefulShutdown("SIGINT");
1700
+ });
1701
+ return serverInstance;
1702
+ }
1703
+ /**
1704
+ * Configure auth with workspace secret fetcher
1705
+ *
1706
+ * This should be called before creating the server if using workspace-scoped JWT
1707
+ */
1708
+ function configureServerAuth(fetchWorkspaceSecret) {
1709
+ configureAuth({ fetchWorkspaceSecret });
1710
+ }
1711
+
1712
+ // src/server/workspace-guard.ts
1713
+ /**
1714
+ * Workspace Guard Plugin for GraphQL Yoga
1715
+ *
1716
+ * Blocks GraphQL operations that lack a valid workspace context (x-workspace-id header).
1717
+ * This provides defense-in-depth at the GraphQL layer — even if the gateway allows a request
1718
+ * through, the service itself will reject it if workspace context is missing.
1719
+ *
1720
+ * **Whitelisted operations** (e.g., workspace creation) can bypass the guard.
1721
+ *
1722
+ * **Public schema fields** marked with `@public` or `@rbac(public: true)` are auto-bypassed
1723
+ * when `allowPublicDirective` is enabled (default true). This lets anonymous public-link
1724
+ * resolvers (e.g. `accessShare`) be reached through the federation gateway without an
1725
+ * `x-workspace-id` header.
1726
+ *
1727
+ * @module server/workspace-guard
1728
+ * @category Security
1729
+ */
1730
+ var workspace_guard_exports = /* @__PURE__ */ __exportAll({ createWorkspaceGuardPlugin: () => createWorkspaceGuardPlugin });
1731
+ /**
1732
+ * Workspace required error with proper GraphQL error extensions
1733
+ */
1734
+ var WorkspaceRequiredError = class extends UserFacingGraphQLError {
1735
+ constructor(message) {
1736
+ super({
1737
+ code: "WORKSPACE_REQUIRED",
1738
+ userMessage: "Please choose a workspace and try again.",
1739
+ technicalMessage: message,
1740
+ httpStatus: 403
1741
+ });
1742
+ this.name = "WorkspaceRequiredError";
1743
+ }
1744
+ };
1745
+ /**
1746
+ * Rejection for a workspace id the calling actor is not a member of.
1747
+ * Per the platform RBAC guide (Type B convention), non-members get
1748
+ * NOT_FOUND so resource existence is never leaked.
1749
+ */
1750
+ var WorkspaceMembershipError = class extends UserFacingGraphQLError {
1751
+ constructor(workspaceId) {
1752
+ super({
1753
+ code: "NOT_FOUND",
1754
+ userMessage: "We could not find the requested item.",
1755
+ technicalMessage: `Workspace ${workspaceId} was not found for the current actor.`,
1756
+ httpStatus: 404
1757
+ });
1758
+ this.name = "WorkspaceMembershipError";
1759
+ }
1760
+ };
1761
+ /**
1762
+ * Returns true iff the field carries either:
1763
+ * - `@public` directive, OR
1764
+ * - `@rbac(public: true)` directive (any arg-order)
1765
+ */
1766
+ function isFieldPublic(field) {
1767
+ const directives = field?.astNode?.directives;
1768
+ if (!directives || directives.length === 0) return false;
1769
+ for (const dir of directives) {
1770
+ const name = dir.name?.value;
1771
+ if (name === "public") return true;
1772
+ if (name === "rbac") {
1773
+ const args = dir.arguments ?? [];
1774
+ for (const arg of args) if (arg.name?.value === "public" && arg.value?.kind === "BooleanValue" && arg.value.value === true) return true;
1775
+ }
1776
+ }
1777
+ return false;
1778
+ }
1779
+ /**
1780
+ * Resolve the operation type ('query' | 'mutation' | 'subscription') for the
1781
+ * primary operation in the document. Falls back to 'query'.
1782
+ */
1783
+ function resolveOperationType(document, operationName) {
1784
+ const defs = document?.definitions ?? [];
1785
+ for (const def of defs) {
1786
+ if (def.kind !== "OperationDefinition") {}
1787
+ if (def.operation && (!operationName || def.name?.value === operationName)) return def.operation;
1788
+ }
1789
+ return "query";
1790
+ }
1791
+ /**
1792
+ * Resolve the root field names selected by the operation that will execute
1793
+ * (`operationName` identifies it when the document carries multiple
1794
+ * operations). Returns null when no operation definition matches, the
1795
+ * selection set is empty, or a non-Field selection appears at the root
1796
+ * (fragment spreads / inline fragments fail closed — see the public-bypass
1797
+ * rationale above). Introspection fields (`__schema`, `__type`) are omitted;
1798
+ * an introspection-only operation yields an EMPTY array (not null) so callers
1799
+ * can distinguish "only introspection selected" from "fail closed".
1800
+ */
1801
+ function resolveRootFieldNames(document, operationName) {
1802
+ const selections = (document?.definitions ?? []).find((d) => d.operation && (!operationName || d.name?.value === operationName))?.selectionSet?.selections ?? [];
1803
+ if (selections.length === 0) return null;
1804
+ const fieldNames = [];
1805
+ for (const sel of selections) {
1806
+ if (sel.kind && sel.kind !== "Field") return null;
1807
+ const fieldName = sel.name?.value;
1808
+ if (!fieldName) return null;
1809
+ if (fieldName.startsWith("__")) continue;
1810
+ fieldNames.push(fieldName);
1811
+ }
1812
+ return fieldNames;
1813
+ }
1814
+ /**
1815
+ * Returns true iff every root field selected by the operation is present in
1816
+ * the whitelist set. An empty list (introspection-only operation) is NOT
1817
+ * exempt — the whitelist covers named schema fields only. A document mixing
1818
+ * an exempt field with a guarded field is NOT exempt either, so an exempt
1819
+ * bootstrap field cannot smuggle a guarded one.
1820
+ */
1821
+ function allRootFieldsWhitelisted(rootFieldNames, whitelistedFields) {
1822
+ return rootFieldNames.length > 0 && rootFieldNames.every((name) => whitelistedFields.has(name));
1823
+ }
1824
+ /**
1825
+ * Returns true iff every root field in the document selection set is marked
1826
+ * public on the schema. An empty field list (introspection-only operation) is
1827
+ * public — schema discovery never requires workspace context. Null (fail
1828
+ * closed: no matching operation, empty selection set, or fragment at the
1829
+ * root) is not public.
1830
+ */
1831
+ function allRootFieldsPublic(schema, document, operationName, rootFieldNames) {
1832
+ if (!document) return false;
1833
+ if (rootFieldNames === null) return false;
1834
+ if (rootFieldNames.length === 0) return true;
1835
+ if (!schema) return false;
1836
+ const opType = resolveOperationType(document, operationName);
1837
+ let rootType;
1838
+ if (opType === "mutation") rootType = schema.getMutationType?.();
1839
+ else if (opType === "subscription") rootType = schema.getSubscriptionType?.();
1840
+ else rootType = schema.getQueryType?.();
1841
+ if (!rootType) return false;
1842
+ const fields = rootType.getFields();
1843
+ for (const fieldName of rootFieldNames) {
1844
+ const fieldDef = fields[fieldName];
1845
+ if (!isFieldPublic(fieldDef)) return false;
1846
+ }
1847
+ return true;
1848
+ }
1849
+ /**
1850
+ * Create a GraphQL Yoga plugin that guards operations requiring workspace context.
1851
+ *
1852
+ * The plugin inspects the GraphQL context for workspace information (set by the SDK's
1853
+ * buildContext from the x-workspace-id header). If missing and the operation is not
1854
+ * whitelisted (and not all-public per directive), it throws a WORKSPACE_REQUIRED error.
1855
+ *
1856
+ * @param config - Guard configuration
1857
+ * @returns A Yoga-compatible plugin
1858
+ *
1859
+ * @example
1860
+ * ```typescript
1861
+ * import { createWorkspaceGuardPlugin } from '@burdenoff/be-sdk/server';
1862
+ *
1863
+ * const guardPlugin = createWorkspaceGuardPlugin({
1864
+ * whitelistedOperations: ['createWorkspace'],
1865
+ * allowPublicDirective: true, // default
1866
+ * });
1867
+ * ```
1868
+ */
1869
+ function createWorkspaceGuardPlugin(config) {
1870
+ const enabled = config?.enabled ?? true;
1871
+ const whitelistedOperations = new Set(config?.whitelistedOperations ?? []);
1872
+ const whitelistedFields = new Set(config?.whitelistedFields ?? []);
1873
+ const validateWorkspaceMembership = config?.validateWorkspaceMembership;
1874
+ const allowPublicDirective = config?.allowPublicDirective ?? true;
1875
+ const errorMessage = config?.errorMessage ?? "Workspace context required. Ensure the request includes a valid workspace context (x-workspace-id header).";
1876
+ if (!enabled) {
1877
+ logger.info("[WorkspaceGuard] Workspace guard disabled");
1878
+ return {};
1879
+ }
1880
+ logger.info("[WorkspaceGuard] Workspace guard enabled", {
1881
+ whitelistedOperations: [...whitelistedOperations],
1882
+ whitelistedFields: [...whitelistedFields],
1883
+ membershipValidation: validateWorkspaceMembership ? "enabled" : "disabled",
1884
+ allowPublicDirective
1885
+ });
1886
+ return { async onExecute({ args }) {
1887
+ let operationName = args.operationName;
1888
+ if (!operationName && args.document?.definitions) {
1889
+ for (const def of args.document.definitions) if (def.operation && def.name?.value) {
1890
+ operationName = def.name.value;
1891
+ break;
1892
+ }
1893
+ }
1894
+ if (operationName && whitelistedOperations.has(operationName)) return;
1895
+ const rootFieldNames = resolveRootFieldNames(args.document, operationName);
1896
+ if (whitelistedFields.size > 0 && rootFieldNames && allRootFieldsWhitelisted(rootFieldNames, whitelistedFields)) return;
1897
+ if (allowPublicDirective && allRootFieldsPublic(args.schema, args.document, operationName, rootFieldNames)) return;
1898
+ const context = args.contextValue;
1899
+ const workspaceId = context?.workspace?.id;
1900
+ const headerWorkspaceId = context?.request?.headers?.get?.("x-workspace-id");
1901
+ if (!workspaceId && !headerWorkspaceId) {
1902
+ logger.warn("[WorkspaceGuard] Blocked operation without workspace context", { operationName: operationName ?? "<anonymous>" });
1903
+ throw new WorkspaceRequiredError(errorMessage);
1904
+ }
1905
+ if (validateWorkspaceMembership) {
1906
+ const resolvedWorkspaceId = workspaceId ? workspaceId : headerWorkspaceId ?? "";
1907
+ const actor = context?.actor ?? null;
1908
+ let isMember = false;
1909
+ try {
1910
+ isMember = await validateWorkspaceMembership({
1911
+ actorId: actor?.id ?? null,
1912
+ actorType: actor?.type ?? null,
1913
+ workspaceId: resolvedWorkspaceId,
1914
+ contextValue: context
1915
+ });
1916
+ } catch (error) {
1917
+ logger.error("[WorkspaceGuard] Workspace membership validation failed", {
1918
+ operationName: operationName ?? "<anonymous>",
1919
+ workspaceId: resolvedWorkspaceId,
1920
+ error
1921
+ });
1922
+ throw new WorkspaceMembershipError(resolvedWorkspaceId);
1923
+ }
1924
+ if (!isMember) {
1925
+ logger.warn("[WorkspaceGuard] Rejected non-member workspace context", {
1926
+ operationName: operationName ?? "<anonymous>",
1927
+ workspaceId: resolvedWorkspaceId,
1928
+ actorId: actor?.id ?? null
1929
+ });
1930
+ throw new WorkspaceMembershipError(resolvedWorkspaceId);
1931
+ }
1932
+ }
1933
+ } };
1934
+ }
1935
+
1936
+ // src/server/mutation-audit.ts
1937
+ const MUTATION_AUDIT_ACTIVITY_TYPE = "graphql.mutation";
1938
+ const MUTATION_AUDIT_RESOURCE_TYPE = "graphql_mutation";
1939
+ const SENSITIVE_KEY_MARKERS = [
1940
+ "password",
1941
+ "passcode",
1942
+ "pass",
1943
+ "token",
1944
+ "secret",
1945
+ "apikey",
1946
+ "accesskey",
1947
+ "authorization",
1948
+ "cookie",
1949
+ "credential",
1950
+ "clientsecret",
1951
+ "privatekey"
1424
1952
  ];
1425
- var MAX_DEPTH = 2;
1426
- var MAX_ARRAY_ITEMS = 5;
1427
- var MAX_OBJECT_KEYS = 20;
1428
- var MAX_STRING_LENGTH = 200;
1953
+ const MAX_DEPTH = 2;
1954
+ const MAX_ARRAY_ITEMS = 5;
1955
+ const MAX_OBJECT_KEYS = 20;
1956
+ const MAX_STRING_LENGTH = 200;
1429
1957
  function isRecord(value) {
1430
- return typeof value === "object" && value !== null;
1958
+ return typeof value === "object" && value !== null;
1431
1959
  }
1432
- __name(isRecord, "isRecord");
1433
1960
  function isSensitiveKey(key) {
1434
- const normalizedKey = key.toLowerCase().replaceAll(/[-_]/g, "");
1435
- return SENSITIVE_KEY_MARKERS.some((marker) => normalizedKey.includes(marker));
1961
+ const normalizedKey = key.toLowerCase().replaceAll(/[-_]/g, "");
1962
+ return SENSITIVE_KEY_MARKERS.some((marker) => normalizedKey.includes(marker));
1436
1963
  }
1437
- __name(isSensitiveKey, "isSensitiveKey");
1438
1964
  function truncate(value) {
1439
- return value.length > MAX_STRING_LENGTH ? `${value.slice(0, MAX_STRING_LENGTH)}...` : value;
1965
+ return value.length > MAX_STRING_LENGTH ? `${value.slice(0, MAX_STRING_LENGTH)}...` : value;
1440
1966
  }
1441
- __name(truncate, "truncate");
1967
+ /** Redact sensitive keys and bound the size of a value before it is stored as metadata. */
1442
1968
  function sanitizeAuditValue(value, depth = 0) {
1443
- if (value == null || typeof value === "boolean" || typeof value === "number") {
1444
- return value;
1445
- }
1446
- if (typeof value === "string") {
1447
- return truncate(value);
1448
- }
1449
- if (depth >= MAX_DEPTH) {
1450
- return "[Truncated]";
1451
- }
1452
- if (Array.isArray(value)) {
1453
- return value.slice(0, MAX_ARRAY_ITEMS).map((entry) => sanitizeAuditValue(entry, depth + 1));
1454
- }
1455
- if (!isRecord(value)) {
1456
- return `[${typeof value}]`;
1457
- }
1458
- const sanitized = {};
1459
- let count = 0;
1460
- for (const [key, entry] of Object.entries(value)) {
1461
- if (count >= MAX_OBJECT_KEYS) {
1462
- sanitized["__truncated__"] = true;
1463
- break;
1464
- }
1465
- sanitized[key] = isSensitiveKey(key) ? "[REDACTED]" : sanitizeAuditValue(entry, depth + 1);
1466
- count += 1;
1467
- }
1468
- return sanitized;
1469
- }
1470
- __name(sanitizeAuditValue, "sanitizeAuditValue");
1969
+ if (value == null || typeof value === "boolean" || typeof value === "number") return value;
1970
+ if (typeof value === "string") return truncate(value);
1971
+ if (depth >= MAX_DEPTH) return "[Truncated]";
1972
+ if (Array.isArray(value)) return value.slice(0, MAX_ARRAY_ITEMS).map((entry) => sanitizeAuditValue(entry, depth + 1));
1973
+ if (!isRecord(value)) return `[${typeof value}]`;
1974
+ const sanitized = {};
1975
+ let count = 0;
1976
+ for (const [key, entry] of Object.entries(value)) {
1977
+ if (count >= MAX_OBJECT_KEYS) {
1978
+ sanitized["__truncated__"] = true;
1979
+ break;
1980
+ }
1981
+ sanitized[key] = isSensitiveKey(key) ? "[REDACTED]" : sanitizeAuditValue(entry, depth + 1);
1982
+ count += 1;
1983
+ }
1984
+ return sanitized;
1985
+ }
1471
1986
  function findMutation(document, operationName) {
1472
- const operations = document.definitions.filter((definition) => definition.kind === Kind.OPERATION_DEFINITION);
1473
- let operation;
1474
- if (operationName) {
1475
- operation = operations.find((definition) => definition.name?.value === operationName);
1476
- } else if (operations.length === 1) {
1477
- operation = operations[0];
1478
- }
1479
- return operation?.operation === OperationTypeNode.MUTATION ? operation : void 0;
1480
- }
1481
- __name(findMutation, "findMutation");
1987
+ const operations = document.definitions.filter((definition) => definition.kind === Kind.OPERATION_DEFINITION);
1988
+ let operation;
1989
+ if (operationName) operation = operations.find((definition) => definition.name?.value === operationName);
1990
+ else if (operations.length === 1) operation = operations[0];
1991
+ return operation?.operation === OperationTypeNode.MUTATION ? operation : void 0;
1992
+ }
1482
1993
  function collectTopLevelFields(selectionSet, fragments, fields, visitedFragments) {
1483
- for (const selection of selectionSet.selections) {
1484
- if (selection.kind === Kind.FIELD) {
1485
- const name = selection.name.value;
1486
- if (!name.startsWith("__") && !fields.includes(name)) fields.push(name);
1487
- } else if (selection.kind === Kind.INLINE_FRAGMENT) {
1488
- collectTopLevelFields(selection.selectionSet, fragments, fields, visitedFragments);
1489
- } else {
1490
- const fragmentName = selection.name.value;
1491
- const fragment = fragments.get(fragmentName);
1492
- if (fragment && !visitedFragments.has(fragmentName)) {
1493
- visitedFragments.add(fragmentName);
1494
- collectTopLevelFields(fragment.selectionSet, fragments, fields, visitedFragments);
1495
- }
1496
- }
1497
- }
1498
- }
1499
- __name(collectTopLevelFields, "collectTopLevelFields");
1994
+ for (const selection of selectionSet.selections) if (selection.kind === Kind.FIELD) {
1995
+ const name = selection.name.value;
1996
+ if (!name.startsWith("__") && !fields.includes(name)) fields.push(name);
1997
+ } else if (selection.kind === Kind.INLINE_FRAGMENT) collectTopLevelFields(selection.selectionSet, fragments, fields, visitedFragments);
1998
+ else {
1999
+ const fragmentName = selection.name.value;
2000
+ const fragment = fragments.get(fragmentName);
2001
+ if (fragment && !visitedFragments.has(fragmentName)) {
2002
+ visitedFragments.add(fragmentName);
2003
+ collectTopLevelFields(fragment.selectionSet, fragments, fields, visitedFragments);
2004
+ }
2005
+ }
2006
+ }
2007
+ /** Top-level mutation field names the executed operation selects (empty for a query or subscription). */
1500
2008
  function getMutationFieldNames(document, operationName) {
1501
- const operation = findMutation(document, operationName);
1502
- if (!operation) return [];
1503
- const fragments = /* @__PURE__ */ new Map();
1504
- for (const definition of document.definitions) {
1505
- if (definition.kind === Kind.FRAGMENT_DEFINITION) fragments.set(definition.name.value, definition);
1506
- }
1507
- const fields = [];
1508
- collectTopLevelFields(operation.selectionSet, fragments, fields, /* @__PURE__ */ new Set());
1509
- return fields;
1510
- }
1511
- __name(getMutationFieldNames, "getMutationFieldNames");
2009
+ const operation = findMutation(document, operationName);
2010
+ if (!operation) return [];
2011
+ const fragments = /* @__PURE__ */ new Map();
2012
+ for (const definition of document.definitions) if (definition.kind === Kind.FRAGMENT_DEFINITION) fragments.set(definition.name.value, definition);
2013
+ const fields = [];
2014
+ collectTopLevelFields(operation.selectionSet, fragments, fields, /* @__PURE__ */ new Set());
2015
+ return fields;
2016
+ }
1512
2017
  function idOf(value) {
1513
- if (!isRecord(value)) return void 0;
1514
- const id2 = value["id"];
1515
- return typeof id2 === "string" && id2.length > 0 ? id2 : void 0;
2018
+ if (!isRecord(value)) return void 0;
2019
+ const id = value["id"];
2020
+ return typeof id === "string" && id.length > 0 ? id : void 0;
1516
2021
  }
1517
- __name(idOf, "idOf");
1518
2022
  function stringOf(value) {
1519
- return typeof value === "string" && value.length > 0 ? value : void 0;
2023
+ return typeof value === "string" && value.length > 0 ? value : void 0;
1520
2024
  }
1521
- __name(stringOf, "stringOf");
1522
2025
  function findWorkspaceId(value, depth = 0) {
1523
- if (depth > MAX_DEPTH || !isRecord(value)) return void 0;
1524
- const direct = stringOf(value["workspaceId"]);
1525
- if (direct) return direct;
1526
- for (const entry of Object.values(value)) {
1527
- const nested = findWorkspaceId(entry, depth + 1);
1528
- if (nested) return nested;
1529
- }
1530
- return void 0;
1531
- }
1532
- __name(findWorkspaceId, "findWorkspaceId");
2026
+ if (depth > MAX_DEPTH || !isRecord(value)) return void 0;
2027
+ const direct = stringOf(value["workspaceId"]);
2028
+ if (direct) return direct;
2029
+ for (const entry of Object.values(value)) {
2030
+ const nested = findWorkspaceId(entry, depth + 1);
2031
+ if (nested) return nested;
2032
+ }
2033
+ }
1533
2034
  function isExecutionResult(value) {
1534
- return isRecord(value) && ("data" in value || "errors" in value);
2035
+ return isRecord(value) && ("data" in value || "errors" in value);
1535
2036
  }
1536
- __name(isExecutionResult, "isExecutionResult");
1537
2037
  function recordMutationAudit(input) {
1538
- const context = isRecord(input.contextValue) ? input.contextValue : {};
1539
- const actor = isRecord(context["actor"]) ? context["actor"] : void 0;
1540
- const actorId = idOf(actor) ?? stringOf(context["actorId"]) ?? "anonymous";
1541
- const actorType = stringOf(actor?.["type"]) ?? stringOf(context["actorType"]) ?? "unknown";
1542
- const workspaceId = idOf(context["workspace"]) ?? stringOf(context["workspaceId"]) ?? findWorkspaceId(input.variableValues);
1543
- const tenantId = idOf(context["tenant"]) ?? stringOf(context["tenantId"]);
1544
- const executionResult = isExecutionResult(input.result) ? input.result : void 0;
1545
- const errors = executionResult?.errors ?? [];
1546
- const success = errors.length === 0;
1547
- const errorMessage = success ? void 0 : truncate(errors.map((error) => error.message).join("; "));
1548
- const joinedFields = input.fieldNames.join(",");
1549
- void trackOperation({
1550
- operationName: joinedFields,
1551
- userId: actorId,
1552
- // The request context drives the row's actorType/onBehalfOf (BOFF-9684): an `app` actor
1553
- // here is an AI agent or integration. An unknown kind is left unset, never guessed.
1554
- context,
1555
- workspaceId,
1556
- success,
1557
- errorMessage,
1558
- activityOptions: {
1559
- enabled: true,
1560
- activityType: MUTATION_AUDIT_ACTIVITY_TYPE,
1561
- description: `GraphQL mutation executed: ${input.fieldNames.join(", ")}`,
1562
- workspaceId,
1563
- resourceType: MUTATION_AUDIT_RESOURCE_TYPE,
1564
- resourceId: joinedFields,
1565
- metadata: {
1566
- serviceName: input.serviceName,
1567
- source: "mutation-audit-backstop",
1568
- actorType,
1569
- fieldNames: input.fieldNames,
1570
- tenantId,
1571
- tracking: sanitizeAuditValue(context["tracking"]),
1572
- variablePreview: sanitizeAuditValue(input.variableValues),
1573
- resultPreview: sanitizeAuditValue(executionResult ? {
1574
- data: executionResult.data,
1575
- errors: errors.map((error) => ({
1576
- message: error.message,
1577
- path: error.path?.join(".")
1578
- }))
1579
- } : void 0)
1580
- }
1581
- }
1582
- }).catch((error) => {
1583
- logger.warn("[MutationAuditPlugin] Failed to record mutation audit", {
1584
- serviceName: input.serviceName,
1585
- fieldNames: input.fieldNames,
1586
- error: error instanceof Error ? error.message : String(error)
1587
- });
1588
- });
1589
- }
1590
- __name(recordMutationAudit, "recordMutationAudit");
1591
- function shouldWrite(scope, dedupe) {
1592
- if (scope.suppressed) return false;
1593
- return !(dedupe && scope.explicitCount > 0);
2038
+ const context = isRecord(input.contextValue) ? input.contextValue : {};
2039
+ const actor = isRecord(context["actor"]) ? context["actor"] : void 0;
2040
+ const actorId = idOf(actor) ?? stringOf(context["actorId"]) ?? "anonymous";
2041
+ const actorType = stringOf(actor?.["type"]) ?? stringOf(context["actorType"]) ?? "unknown";
2042
+ const workspaceId = idOf(context["workspace"]) ?? stringOf(context["workspaceId"]) ?? findWorkspaceId(input.variableValues);
2043
+ const tenantId = idOf(context["tenant"]) ?? stringOf(context["tenantId"]);
2044
+ const executionResult = isExecutionResult(input.result) ? input.result : void 0;
2045
+ const errors = executionResult?.errors ?? [];
2046
+ const success = errors.length === 0;
2047
+ const errorMessage = success ? void 0 : truncate(errors.map((error) => error.message).join("; "));
2048
+ const joinedFields = input.fieldNames.join(",");
2049
+ trackOperation({
2050
+ operationName: joinedFields,
2051
+ userId: actorId,
2052
+ context,
2053
+ workspaceId,
2054
+ success,
2055
+ errorMessage,
2056
+ activityOptions: {
2057
+ enabled: true,
2058
+ activityType: MUTATION_AUDIT_ACTIVITY_TYPE,
2059
+ description: `GraphQL mutation executed: ${input.fieldNames.join(", ")}`,
2060
+ workspaceId,
2061
+ resourceType: MUTATION_AUDIT_RESOURCE_TYPE,
2062
+ resourceId: joinedFields,
2063
+ metadata: {
2064
+ serviceName: input.serviceName,
2065
+ source: "mutation-audit-backstop",
2066
+ actorType,
2067
+ fieldNames: input.fieldNames,
2068
+ tenantId,
2069
+ tracking: sanitizeAuditValue(context["tracking"]),
2070
+ variablePreview: sanitizeAuditValue(input.variableValues),
2071
+ resultPreview: sanitizeAuditValue(executionResult ? {
2072
+ data: executionResult.data,
2073
+ errors: errors.map((error) => ({
2074
+ message: error.message,
2075
+ path: error.path?.join(".")
2076
+ }))
2077
+ } : void 0)
2078
+ }
2079
+ }
2080
+ }).catch((error) => {
2081
+ logger.warn("[MutationAuditPlugin] Failed to record mutation audit", {
2082
+ serviceName: input.serviceName,
2083
+ fieldNames: input.fieldNames,
2084
+ error: error instanceof Error ? error.message : String(error)
2085
+ });
2086
+ });
1594
2087
  }
1595
- __name(shouldWrite, "shouldWrite");
2088
+ function shouldWrite(scope, dedupe) {
2089
+ if (scope.suppressed) return false;
2090
+ return !(dedupe && scope.explicitCount > 0);
2091
+ }
2092
+ /**
2093
+ * Create the mutation-audit backstop plugin.
2094
+ *
2095
+ * Accepts the bare service name for drop-in compatibility with the per-service copies.
2096
+ */
1596
2097
  function createMutationAuditPlugin(options) {
1597
- const resolved = typeof options === "string" ? {
1598
- serviceName: options
1599
- } : options;
1600
- const excluded = new Set(resolved.excludeFields ?? []);
1601
- const dedupe = resolved.dedupeExplicitActivity !== false;
1602
- return {
1603
- onExecute({ args, executeFn, setExecuteFn }) {
1604
- const fieldNames = getMutationFieldNames(args.document, args.operationName).filter((name) => !excluded.has(name));
1605
- if (fieldNames.length === 0) return;
1606
- setExecuteFn(async (executeArgs) => {
1607
- const scope = createExplicitActivityScope();
1608
- const result = await runInExplicitActivityScope(scope, () => executeFn(executeArgs));
1609
- try {
1610
- if (shouldWrite(scope, dedupe)) {
1611
- recordMutationAudit({
1612
- serviceName: resolved.serviceName,
1613
- fieldNames,
1614
- contextValue: executeArgs.contextValue,
1615
- variableValues: executeArgs.variableValues,
1616
- result
1617
- });
1618
- }
1619
- } catch (error) {
1620
- logger.warn("[MutationAuditPlugin] Failed to prepare mutation audit", {
1621
- serviceName: resolved.serviceName,
1622
- fieldNames,
1623
- error: error instanceof Error ? error.message : String(error)
1624
- });
1625
- }
1626
- return result;
1627
- });
1628
- }
1629
- };
1630
- }
1631
- __name(createMutationAuditPlugin, "createMutationAuditPlugin");
2098
+ const resolved = typeof options === "string" ? { serviceName: options } : options;
2099
+ const excluded = new Set(resolved.excludeFields ?? []);
2100
+ const dedupe = resolved.dedupeExplicitActivity !== false;
2101
+ return { onExecute({ args, executeFn, setExecuteFn }) {
2102
+ const fieldNames = getMutationFieldNames(args.document, args.operationName).filter((name) => !excluded.has(name));
2103
+ if (fieldNames.length === 0) return;
2104
+ setExecuteFn(async (executeArgs) => {
2105
+ const scope = createExplicitActivityScope();
2106
+ const result = await runInExplicitActivityScope(scope, () => executeFn(executeArgs));
2107
+ try {
2108
+ if (shouldWrite(scope, dedupe)) recordMutationAudit({
2109
+ serviceName: resolved.serviceName,
2110
+ fieldNames,
2111
+ contextValue: executeArgs.contextValue,
2112
+ variableValues: executeArgs.variableValues,
2113
+ result
2114
+ });
2115
+ } catch (error) {
2116
+ logger.warn("[MutationAuditPlugin] Failed to prepare mutation audit", {
2117
+ serviceName: resolved.serviceName,
2118
+ fieldNames,
2119
+ error: error instanceof Error ? error.message : String(error)
2120
+ });
2121
+ }
2122
+ return result;
2123
+ });
2124
+ } };
2125
+ }
1632
2126
 
1633
- export { MAX_IDLE_TIMEOUT_SECONDS, MUTATION_AUDIT_ACTIVITY_TYPE, MUTATION_AUDIT_RESOURCE_TYPE, authCheck, buildContext, configureAuth, configureContext, configureDefaultAuth, configureServerAuth, createMutationAuditPlugin, createRawBodyRouter, createServer, decodeJWT, extendRequestIdleTimeout, fetchWorkspaceSecret, generateSymmetricSecret, getContextOptions, getDelegatedPrincipal, getMutationFieldNames, orgCheck, requireWorkspace, resolveOnBehalfOf, sanitizeAuditValue, tenantCheck, verifyJWT, workspaceCheck };
1634
- //# sourceMappingURL=index.js.map
2127
+ export { ACTOR_ORIGIN_HEADER, AI_ASSISTANT_ACTOR_ORIGIN, ASSISTANT_CORRELATION_ID_HEADER, ASSISTANT_SESSION_ID_HEADER, MAX_IDLE_TIMEOUT_SECONDS, MUTATION_AUDIT_ACTIVITY_TYPE, MUTATION_AUDIT_RESOURCE_TYPE, UserFacingGraphQLError, authCheck, buildContext, configureAuth, configureContext, configureDefaultAuth, configureServerAuth, createHttpErrorResponse, createHumanReadableErrorPlugin, createMutationAuditPlugin, createRawBodyRouter, createServer, createWorkspaceGuardPlugin, decodeJWT, extendRequestIdleTimeout, fetchWorkspaceSecret, formatHttpError, generateSymmetricSecret, getContextOptions, getDelegatedPrincipal, getMutationFieldNames, normalizeError, normalizeExecutionResultErrors, normalizeGraphQLResponse, normalizeGraphQLResponsePayload, orgCheck, parseAssistantSessionHeaders, readAssistantSessionAttribution, requireWorkspace, resolveOnBehalfOf, sanitizeAuditValue, suppressMutationAudit, tenantCheck, toAssistantSessionAttribution, toUserFacingGraphQLError, verifyJWT, workspaceCheck };
1635
2128
  //# sourceMappingURL=index.js.map