@burdenoff/be-sdk 2026.1110.2 → 2026.1110.4

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