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