@burdenoff/be-sdk 2026.1110.2 → 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-GXC3A7DH.js +0 -8
- package/dist/EventQueueFactory-GXC3A7DH.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-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-AXJDGQPE.js +0 -690
- package/dist/chunk-AXJDGQPE.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-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-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-HNMHPSAM.js +0 -272
- package/dist/chunk-HNMHPSAM.js.map +0 -1
- package/dist/chunk-HTLEGD3Q.js +0 -1480
- package/dist/chunk-HTLEGD3Q.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-JS52ZHTK.js +0 -1346
- package/dist/chunk-JS52ZHTK.js.map +0 -1
- package/dist/chunk-JVMAQOA3.js +0 -521
- package/dist/chunk-JVMAQOA3.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-OBBCR6WY.js +0 -277
- package/dist/chunk-OBBCR6WY.js.map +0 -1
- package/dist/chunk-OQDSAOG3.js +0 -1908
- package/dist/chunk-OQDSAOG3.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-PN6GIF3R.js +0 -1185
- package/dist/chunk-PN6GIF3R.js.map +0 -1
- 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-Z77BTSOK.js +0 -617
- package/dist/chunk-Z77BTSOK.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
|
@@ -0,0 +1,1647 @@
|
|
|
1
|
+
import { t as __exportAll } from "./rolldown-runtime-ad2WFvuA.js";
|
|
2
|
+
import { i as defaultCollectorTracesEndpoint } from "./collector-endpoint-iyQYeI50.js";
|
|
3
|
+
import { a as logger } from "./logger-B6rCpb7D.js";
|
|
4
|
+
import { t as importOptionalPeer } from "./import-optional-peer-B82VYxeX.js";
|
|
5
|
+
import { GraphQLError, Kind, validate } from "graphql";
|
|
6
|
+
|
|
7
|
+
// src/gateway/security/actor.ts
|
|
8
|
+
const nonEmpty = (value) => {
|
|
9
|
+
const trimmed = value?.trim();
|
|
10
|
+
return trimmed ? trimmed : void 0;
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* Right-most entry of an `x-forwarded-for` chain.
|
|
14
|
+
*
|
|
15
|
+
* Every proxy appends the address of the peer that connected to it, so the
|
|
16
|
+
* right-most entry was written by the last hop in front of the gateway (the
|
|
17
|
+
* ALB) and cannot be chosen by the caller. The left-most entry can: a client
|
|
18
|
+
* may send any `x-forwarded-for` it likes and Cloudflare and the ALB append to
|
|
19
|
+
* it rather than replace it. Keying the anonymous rate-limit bucket on the
|
|
20
|
+
* left-most entry let a caller get a fresh bucket per request by rotating
|
|
21
|
+
* that header (BOFF-9641).
|
|
22
|
+
*/
|
|
23
|
+
const lastForwardedIp = (header) => {
|
|
24
|
+
if (!header) return void 0;
|
|
25
|
+
const hops = header.split(",").map((hop) => hop.trim()).filter(Boolean);
|
|
26
|
+
return hops[hops.length - 1];
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* Resolve the caller's IP from headers a client cannot forge.
|
|
30
|
+
*
|
|
31
|
+
* Public traffic reaches the gateways only through Cloudflare, and the public
|
|
32
|
+
* ALBs accept connections from Cloudflare's ranges only, so
|
|
33
|
+
* `cf-connecting-ip` is set (and overwritten) by Cloudflare on every external
|
|
34
|
+
* request. Without it (in-cluster callers) the right-most forwarded hop is the
|
|
35
|
+
* best unforgeable signal. `x-real-ip` is not consulted: nothing in front of
|
|
36
|
+
* the gateways sets it, so any value present came from the client.
|
|
37
|
+
*/
|
|
38
|
+
const resolveClientIp = (getHeader) => nonEmpty(getHeader("cf-connecting-ip")) ?? lastForwardedIp(getHeader("x-forwarded-for"));
|
|
39
|
+
/**
|
|
40
|
+
* Map the gateway-verified actor type to a rate-limit tier.
|
|
41
|
+
*
|
|
42
|
+
* Only `x-actor-type` is trusted: the gateways strip any client-supplied value
|
|
43
|
+
* and set it from the verified token. `x-actor-role` is never set by a gateway
|
|
44
|
+
* and was not stripped, so honouring `x-actor-role: super_admin` let any
|
|
45
|
+
* anonymous caller opt out of rate limiting (BOFF-9641).
|
|
46
|
+
*/
|
|
47
|
+
const classify = (actorType) => {
|
|
48
|
+
switch (actorType) {
|
|
49
|
+
case "user": return "user";
|
|
50
|
+
case "app": return "app";
|
|
51
|
+
case "service":
|
|
52
|
+
case "service_account": return "service";
|
|
53
|
+
case "super_admin": return "super_admin";
|
|
54
|
+
default: return "public";
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
/**
|
|
58
|
+
* Resolve the canonical ActorContext for a request.
|
|
59
|
+
* Accepts a `HeaderGetter` so it is trivially testable with a plain function.
|
|
60
|
+
*/
|
|
61
|
+
const resolveActor = (getHeader) => {
|
|
62
|
+
const actorId = getHeader("x-actor-id") ?? void 0;
|
|
63
|
+
const actorType = getHeader("x-actor-type") ?? void 0;
|
|
64
|
+
const actorRole = getHeader("x-actor-role") ?? void 0;
|
|
65
|
+
const workspaceId = getHeader("x-workspace-id") ?? void 0;
|
|
66
|
+
const tenantId = getHeader("x-tenant-id") ?? void 0;
|
|
67
|
+
const orgId = getHeader("x-org-id") ?? void 0;
|
|
68
|
+
const appId = getHeader("x-app-id") ?? void 0;
|
|
69
|
+
const ip = resolveClientIp(getHeader);
|
|
70
|
+
const tier = classify(actorType);
|
|
71
|
+
let identity;
|
|
72
|
+
switch (tier) {
|
|
73
|
+
case "super_admin":
|
|
74
|
+
identity = "bypass";
|
|
75
|
+
break;
|
|
76
|
+
case "service":
|
|
77
|
+
identity = `svc:${actorId ?? "unknown"}`;
|
|
78
|
+
break;
|
|
79
|
+
case "app":
|
|
80
|
+
identity = `${tenantId ?? "notenant"}:${actorId ?? appId ?? "unknown"}`;
|
|
81
|
+
break;
|
|
82
|
+
case "user":
|
|
83
|
+
identity = `${workspaceId ?? "nows"}:${actorId ?? "unknown"}`;
|
|
84
|
+
break;
|
|
85
|
+
default: identity = `ip:${ip ?? "unknown"}`;
|
|
86
|
+
}
|
|
87
|
+
return {
|
|
88
|
+
tier,
|
|
89
|
+
identity,
|
|
90
|
+
headers: {
|
|
91
|
+
actorId,
|
|
92
|
+
actorType,
|
|
93
|
+
actorRole,
|
|
94
|
+
workspaceId,
|
|
95
|
+
tenantId,
|
|
96
|
+
orgId,
|
|
97
|
+
appId,
|
|
98
|
+
ip
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
// src/gateway/security/cost-map.ts
|
|
104
|
+
const DEFAULT_COST_MAP = {
|
|
105
|
+
"Query.searchBigConsole": 200,
|
|
106
|
+
"Query.searchWorkspaces": 100,
|
|
107
|
+
"Query.searchTags": 80,
|
|
108
|
+
"Query.analyticsReport": 300,
|
|
109
|
+
"Query.usageReport": 250,
|
|
110
|
+
"Query.billingReport": 250,
|
|
111
|
+
"Query.auditLog": 150,
|
|
112
|
+
"Query.listUsers": 50,
|
|
113
|
+
"Query.listWorkspaces": 50,
|
|
114
|
+
"Query.listFiles": 40,
|
|
115
|
+
"Query.listTags": 20,
|
|
116
|
+
"Query.listApps": 40,
|
|
117
|
+
"Workspace.members": 5,
|
|
118
|
+
"User.workspaces": 10,
|
|
119
|
+
"User.apps": 5,
|
|
120
|
+
"Tag.appliedTo": 5,
|
|
121
|
+
"Query.__schema": 1e3,
|
|
122
|
+
"Query.__type": 500,
|
|
123
|
+
"Mutation.bulkImport": 500,
|
|
124
|
+
"Mutation.webhookTrigger": 100
|
|
125
|
+
};
|
|
126
|
+
const mergeCostMap = (base, override) => ({
|
|
127
|
+
...base,
|
|
128
|
+
...override
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
// src/gateway/security/tiers.ts
|
|
132
|
+
const DEFAULT_TIERS = {
|
|
133
|
+
public: {
|
|
134
|
+
points: 120,
|
|
135
|
+
duration: 60,
|
|
136
|
+
burst: 60
|
|
137
|
+
},
|
|
138
|
+
user: {
|
|
139
|
+
points: 600,
|
|
140
|
+
duration: 60,
|
|
141
|
+
burst: 120
|
|
142
|
+
},
|
|
143
|
+
app: {
|
|
144
|
+
points: 3e3,
|
|
145
|
+
duration: 60,
|
|
146
|
+
burst: 500
|
|
147
|
+
},
|
|
148
|
+
service: {
|
|
149
|
+
points: 6e3,
|
|
150
|
+
duration: 60,
|
|
151
|
+
burst: 1e3
|
|
152
|
+
},
|
|
153
|
+
super_admin: {
|
|
154
|
+
points: Number.MAX_SAFE_INTEGER,
|
|
155
|
+
duration: 60,
|
|
156
|
+
burst: Number.MAX_SAFE_INTEGER
|
|
157
|
+
}
|
|
158
|
+
};
|
|
159
|
+
const positiveInt = (value, fallback) => {
|
|
160
|
+
if (!value) return fallback;
|
|
161
|
+
const parsed = parseInt(value, 10);
|
|
162
|
+
return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
|
|
163
|
+
};
|
|
164
|
+
/**
|
|
165
|
+
* Read tier overrides from env.
|
|
166
|
+
*
|
|
167
|
+
* Env var pattern: `GATEWAY_RL_{TIER}_{POINTS|DURATION|BURST}`
|
|
168
|
+
* Example: `GATEWAY_RL_USER_POINTS=1200`
|
|
169
|
+
*/
|
|
170
|
+
const resolveTiersFromEnv = (base = DEFAULT_TIERS) => {
|
|
171
|
+
const out = { ...base };
|
|
172
|
+
Object.keys(base).forEach((tier) => {
|
|
173
|
+
const upper = tier.toUpperCase();
|
|
174
|
+
out[tier] = {
|
|
175
|
+
points: positiveInt(process.env[`GATEWAY_RL_${upper}_POINTS`], base[tier].points),
|
|
176
|
+
duration: positiveInt(process.env[`GATEWAY_RL_${upper}_DURATION`], base[tier].duration),
|
|
177
|
+
burst: positiveInt(process.env[`GATEWAY_RL_${upper}_BURST`], base[tier].burst)
|
|
178
|
+
};
|
|
179
|
+
});
|
|
180
|
+
return out;
|
|
181
|
+
};
|
|
182
|
+
|
|
183
|
+
// src/gateway/security/defaults.ts
|
|
184
|
+
/**
|
|
185
|
+
* Gateway Security Defaults
|
|
186
|
+
*
|
|
187
|
+
* Production-safe defaults for the security plugin stack, and helpers to
|
|
188
|
+
* assemble `GatewaySecurityOptions` from environment variables. Each field
|
|
189
|
+
* honors an `*_OBSERVE*` flag so the hardening pass can soft-launch
|
|
190
|
+
* observe-only before flipping to enforce.
|
|
191
|
+
*
|
|
192
|
+
* @module gateway/security/defaults
|
|
193
|
+
* @category Gateway
|
|
194
|
+
*/
|
|
195
|
+
const boolEnv = (key, fallback) => {
|
|
196
|
+
const v = process.env[key];
|
|
197
|
+
if (v === void 0) return fallback;
|
|
198
|
+
return v === "true" || v === "1";
|
|
199
|
+
};
|
|
200
|
+
const intEnv = (key, fallback) => {
|
|
201
|
+
const v = process.env[key];
|
|
202
|
+
if (!v) return fallback;
|
|
203
|
+
const parsed = parseInt(v, 10);
|
|
204
|
+
return Number.isFinite(parsed) ? parsed : fallback;
|
|
205
|
+
};
|
|
206
|
+
const strEnv = (key, fallback) => process.env[key] ?? fallback;
|
|
207
|
+
/**
|
|
208
|
+
* Default armor thresholds for public gateways.
|
|
209
|
+
*/
|
|
210
|
+
const DEFAULT_ARMOR_CONFIG = {
|
|
211
|
+
maxAliases: 15,
|
|
212
|
+
maxTokens: 1e3,
|
|
213
|
+
maxDirectives: 50,
|
|
214
|
+
characterLimit: 15e3,
|
|
215
|
+
costLimit: 5e3,
|
|
216
|
+
observe: true
|
|
217
|
+
};
|
|
218
|
+
/**
|
|
219
|
+
* Build `GatewaySecurityOptions` by reading env vars.
|
|
220
|
+
*
|
|
221
|
+
* All defaults are production-safe but begin in observe-only mode so the
|
|
222
|
+
* first deploy does not reject any traffic. Flip observe flags to `false`
|
|
223
|
+
* after the 48h bake.
|
|
224
|
+
*/
|
|
225
|
+
const resolveSecurityOptionsFromEnv = (gatewayName, costMapOverride) => {
|
|
226
|
+
return {
|
|
227
|
+
gatewayName,
|
|
228
|
+
enabled: boolEnv("SECURITY_PLUGINS_ENABLED", true),
|
|
229
|
+
armor: {
|
|
230
|
+
maxAliases: intEnv("ARMOR_MAX_ALIASES", DEFAULT_ARMOR_CONFIG.maxAliases),
|
|
231
|
+
maxTokens: intEnv("ARMOR_MAX_TOKENS", DEFAULT_ARMOR_CONFIG.maxTokens),
|
|
232
|
+
maxDirectives: intEnv("ARMOR_MAX_DIRECTIVES", DEFAULT_ARMOR_CONFIG.maxDirectives),
|
|
233
|
+
characterLimit: intEnv("ARMOR_CHARACTER_LIMIT", DEFAULT_ARMOR_CONFIG.characterLimit),
|
|
234
|
+
costLimit: intEnv("ARMOR_COST_LIMIT", DEFAULT_ARMOR_CONFIG.costLimit),
|
|
235
|
+
observe: boolEnv("ARMOR_OBSERVE", true)
|
|
236
|
+
},
|
|
237
|
+
queryComplexity: {
|
|
238
|
+
enabled: boolEnv("QUERY_COMPLEXITY_ENABLED", true),
|
|
239
|
+
maxCost: intEnv("QUERY_COMPLEXITY_MAX", 2e3),
|
|
240
|
+
costMap: costMapOverride ? mergeCostMap(DEFAULT_COST_MAP, costMapOverride) : DEFAULT_COST_MAP,
|
|
241
|
+
observe: boolEnv("QUERY_COMPLEXITY_OBSERVE", true)
|
|
242
|
+
},
|
|
243
|
+
rateLimit: {
|
|
244
|
+
tiers: resolveTiersFromEnv(),
|
|
245
|
+
keyPrefix: strEnv("VALKEY_KEY_PREFIX", gatewayName),
|
|
246
|
+
observeOnly: boolEnv("RATE_LIMIT_OBSERVE_ONLY", true),
|
|
247
|
+
failClosed: boolEnv("RATE_LIMIT_FAIL_CLOSED", false),
|
|
248
|
+
perWorkspace: {
|
|
249
|
+
enabled: boolEnv("RATE_LIMIT_WS_ENABLED", true),
|
|
250
|
+
points: intEnv("RATE_LIMIT_WS_POINTS", 6e3),
|
|
251
|
+
duration: intEnv("RATE_LIMIT_WS_DURATION", 60),
|
|
252
|
+
burst: intEnv("RATE_LIMIT_WS_BURST", 2e3),
|
|
253
|
+
observeOnly: boolEnv("RATE_LIMIT_WS_OBSERVE_ONLY", false)
|
|
254
|
+
}
|
|
255
|
+
},
|
|
256
|
+
operationTimeout: {
|
|
257
|
+
timeoutMs: intEnv("OPERATION_TIMEOUT_MS", 15e3),
|
|
258
|
+
mutationTimeoutMs: intEnv("OPERATION_TIMEOUT_MUTATION_MS", 25e3)
|
|
259
|
+
},
|
|
260
|
+
otel: {
|
|
261
|
+
enabled: boolEnv("OTEL_ENABLED", true),
|
|
262
|
+
serviceName: strEnv("OTEL_SERVICE_NAME", gatewayName),
|
|
263
|
+
endpoint: strEnv("OTEL_EXPORTER_OTLP_ENDPOINT", defaultCollectorTracesEndpoint(gatewayName)),
|
|
264
|
+
environment: strEnv("NODE_ENV", "development"),
|
|
265
|
+
version: process.env["APP_VERSION"]
|
|
266
|
+
}
|
|
267
|
+
};
|
|
268
|
+
};
|
|
269
|
+
|
|
270
|
+
// src/gateway/security/valkey.ts
|
|
271
|
+
/**
|
|
272
|
+
* Valkey Client Bootstrap for Gateway Security
|
|
273
|
+
*
|
|
274
|
+
* Wraps the SDK's existing getValkeyClient() (@valkey/valkey-glide) to expose a
|
|
275
|
+
* minimal, stable surface for the rate-limit plugin. Falls back to an
|
|
276
|
+
* in-memory stub so unit tests and local dev without Valkey do not error.
|
|
277
|
+
*
|
|
278
|
+
* @module gateway/security/valkey
|
|
279
|
+
* @category Gateway
|
|
280
|
+
*/
|
|
281
|
+
var IoRedisAdapter = class {
|
|
282
|
+
client;
|
|
283
|
+
constructor(client) {
|
|
284
|
+
this.client = client;
|
|
285
|
+
}
|
|
286
|
+
get(key) {
|
|
287
|
+
return this.client.get(key);
|
|
288
|
+
}
|
|
289
|
+
set(key, value, options) {
|
|
290
|
+
if (options?.EX) return this.client.set(key, value, "EX", options.EX);
|
|
291
|
+
return this.client.set(key, value);
|
|
292
|
+
}
|
|
293
|
+
incrBy(key, amount) {
|
|
294
|
+
return this.client.incrby(key, amount);
|
|
295
|
+
}
|
|
296
|
+
async expire(key, seconds) {
|
|
297
|
+
return await this.client.expire(key, seconds) === 1;
|
|
298
|
+
}
|
|
299
|
+
ttl(key) {
|
|
300
|
+
return this.client.ttl(key);
|
|
301
|
+
}
|
|
302
|
+
ping() {
|
|
303
|
+
return this.client.ping();
|
|
304
|
+
}
|
|
305
|
+
};
|
|
306
|
+
const buildIoRedisClient = async (url) => {
|
|
307
|
+
const mod = await import(
|
|
308
|
+
/* @vite-ignore */
|
|
309
|
+
"ioredis"
|
|
310
|
+
);
|
|
311
|
+
const Ctor = mod.default ?? mod.Redis;
|
|
312
|
+
if (!Ctor) throw new Error("ioredis module has no Redis constructor");
|
|
313
|
+
const client = new Ctor(url);
|
|
314
|
+
client.on("error", (err) => {
|
|
315
|
+
const e = err instanceof Error ? err : new Error(String(err));
|
|
316
|
+
logger.warn("[gateway-security] ioredis error event", { error: e.message });
|
|
317
|
+
});
|
|
318
|
+
return new IoRedisAdapter(client);
|
|
319
|
+
};
|
|
320
|
+
/**
|
|
321
|
+
* Tiny in-memory fallback. Not cross-pod safe; used only when Valkey is
|
|
322
|
+
* absent (e.g., unit tests, local dev without `docker compose up`).
|
|
323
|
+
*/
|
|
324
|
+
var MemoryValkey = class {
|
|
325
|
+
store = /* @__PURE__ */ new Map();
|
|
326
|
+
prune(key) {
|
|
327
|
+
const e = this.store.get(key);
|
|
328
|
+
if (!e) return void 0;
|
|
329
|
+
if (e.expiresAt > 0 && e.expiresAt <= Date.now()) {
|
|
330
|
+
this.store.delete(key);
|
|
331
|
+
return;
|
|
332
|
+
}
|
|
333
|
+
return e;
|
|
334
|
+
}
|
|
335
|
+
get(key) {
|
|
336
|
+
const e = this.prune(key);
|
|
337
|
+
return Promise.resolve(e?.value ?? null);
|
|
338
|
+
}
|
|
339
|
+
set(key, value, options) {
|
|
340
|
+
this.store.set(key, {
|
|
341
|
+
value,
|
|
342
|
+
expiresAt: options?.EX ? Date.now() + options.EX * 1e3 : 0
|
|
343
|
+
});
|
|
344
|
+
return Promise.resolve("OK");
|
|
345
|
+
}
|
|
346
|
+
incrBy(key, amount) {
|
|
347
|
+
const e = this.prune(key);
|
|
348
|
+
const next = (e ? parseInt(e.value, 10) || 0 : 0) + amount;
|
|
349
|
+
this.store.set(key, {
|
|
350
|
+
value: String(next),
|
|
351
|
+
expiresAt: e?.expiresAt ?? 0
|
|
352
|
+
});
|
|
353
|
+
return Promise.resolve(next);
|
|
354
|
+
}
|
|
355
|
+
expire(key, seconds) {
|
|
356
|
+
const e = this.store.get(key);
|
|
357
|
+
if (!e) return Promise.resolve(false);
|
|
358
|
+
e.expiresAt = Date.now() + seconds * 1e3;
|
|
359
|
+
return Promise.resolve(true);
|
|
360
|
+
}
|
|
361
|
+
ttl(key) {
|
|
362
|
+
const e = this.prune(key);
|
|
363
|
+
if (!e) return Promise.resolve(-2);
|
|
364
|
+
if (e.expiresAt === 0) return Promise.resolve(-1);
|
|
365
|
+
return Promise.resolve(Math.max(0, Math.ceil((e.expiresAt - Date.now()) / 1e3)));
|
|
366
|
+
}
|
|
367
|
+
ping() {
|
|
368
|
+
return Promise.resolve("PONG");
|
|
369
|
+
}
|
|
370
|
+
};
|
|
371
|
+
let singleton = null;
|
|
372
|
+
let bootPromise = null;
|
|
373
|
+
/**
|
|
374
|
+
* Initialize the Valkey client for the gateway. Reads `VALKEY_URL` (or
|
|
375
|
+
* `REDIS_URL`) + `VALKEY_PASSWORD` from env. On failure: if `VALKEY_REQUIRED`
|
|
376
|
+
* is set to `"true"`, throws; otherwise logs a warning and returns the memory
|
|
377
|
+
* fallback so the gateway still boots.
|
|
378
|
+
*
|
|
379
|
+
* Safe to call multiple times — the result is memoized.
|
|
380
|
+
*/
|
|
381
|
+
const initializeSecurityValkey = async (gatewayName) => {
|
|
382
|
+
if (singleton) return singleton;
|
|
383
|
+
if (bootPromise) return bootPromise;
|
|
384
|
+
bootPromise = (async () => {
|
|
385
|
+
const url = process.env["VALKEY_URL"] || process.env["REDIS_URL"];
|
|
386
|
+
const required = process.env["VALKEY_REQUIRED"] === "true";
|
|
387
|
+
const clientKind = process.env["VALKEY_CLIENT"] ?? "ioredis";
|
|
388
|
+
if (!url) {
|
|
389
|
+
const msg = "[gateway-security] VALKEY_URL not set";
|
|
390
|
+
if (required) throw new Error(`${msg} and VALKEY_REQUIRED=true`);
|
|
391
|
+
logger.warn(`${msg} — using in-memory fallback (not cross-pod safe)`, { gatewayName });
|
|
392
|
+
singleton = new MemoryValkey();
|
|
393
|
+
return singleton;
|
|
394
|
+
}
|
|
395
|
+
const attempts = [];
|
|
396
|
+
if (clientKind === "ioredis") {
|
|
397
|
+
attempts.push({
|
|
398
|
+
kind: "ioredis",
|
|
399
|
+
factory: () => buildIoRedisClient(url)
|
|
400
|
+
});
|
|
401
|
+
attempts.push({
|
|
402
|
+
kind: "glide (fallback)",
|
|
403
|
+
factory: async () => {
|
|
404
|
+
const { getValkeyClient } = await import("./cache/index.js");
|
|
405
|
+
return getValkeyClient();
|
|
406
|
+
}
|
|
407
|
+
});
|
|
408
|
+
} else {
|
|
409
|
+
attempts.push({
|
|
410
|
+
kind: "glide",
|
|
411
|
+
factory: async () => {
|
|
412
|
+
const { getValkeyClient } = await import("./cache/index.js");
|
|
413
|
+
return getValkeyClient();
|
|
414
|
+
}
|
|
415
|
+
});
|
|
416
|
+
attempts.push({
|
|
417
|
+
kind: "ioredis (fallback)",
|
|
418
|
+
factory: () => buildIoRedisClient(url)
|
|
419
|
+
});
|
|
420
|
+
}
|
|
421
|
+
let lastError = null;
|
|
422
|
+
for (const attempt of attempts) try {
|
|
423
|
+
const client = await attempt.factory();
|
|
424
|
+
const pong = await client.ping();
|
|
425
|
+
if (pong !== "PONG") throw new Error(`ping returned ${pong}`);
|
|
426
|
+
logger.info("[gateway-security] Valkey connected", {
|
|
427
|
+
gatewayName,
|
|
428
|
+
url,
|
|
429
|
+
client: attempt.kind
|
|
430
|
+
});
|
|
431
|
+
singleton = client;
|
|
432
|
+
return client;
|
|
433
|
+
} catch (err) {
|
|
434
|
+
lastError = err instanceof Error ? err : new Error(String(err));
|
|
435
|
+
logger.warn("[gateway-security] Valkey client init failed, will try next", {
|
|
436
|
+
gatewayName,
|
|
437
|
+
client: attempt.kind,
|
|
438
|
+
error: lastError.message
|
|
439
|
+
});
|
|
440
|
+
}
|
|
441
|
+
if (required) {
|
|
442
|
+
logger.error("[gateway-security] Valkey connection failed and required=true", {
|
|
443
|
+
gatewayName,
|
|
444
|
+
error: lastError?.message ?? "all attempts failed"
|
|
445
|
+
});
|
|
446
|
+
throw lastError ?? /* @__PURE__ */ new Error("Valkey connection failed");
|
|
447
|
+
}
|
|
448
|
+
logger.warn("[gateway-security] All Valkey clients failed — using in-memory fallback", {
|
|
449
|
+
gatewayName,
|
|
450
|
+
error: lastError?.message ?? "unknown"
|
|
451
|
+
});
|
|
452
|
+
singleton = new MemoryValkey();
|
|
453
|
+
return singleton;
|
|
454
|
+
})();
|
|
455
|
+
return bootPromise;
|
|
456
|
+
};
|
|
457
|
+
/**
|
|
458
|
+
* Return the initialized client. Throws if `initializeSecurityValkey` was not
|
|
459
|
+
* called first — keeps the plugin wiring explicit.
|
|
460
|
+
*/
|
|
461
|
+
const getSecurityValkey = () => {
|
|
462
|
+
if (!singleton) throw new Error("[gateway-security] Valkey not initialized — call initializeSecurityValkey() first");
|
|
463
|
+
return singleton;
|
|
464
|
+
};
|
|
465
|
+
/**
|
|
466
|
+
* Test-only seam. Replaces the singleton with a stub.
|
|
467
|
+
* Do NOT use in production code.
|
|
468
|
+
*/
|
|
469
|
+
const __setSecurityValkeyForTest = (client) => {
|
|
470
|
+
singleton = client;
|
|
471
|
+
bootPromise = client ? Promise.resolve(client) : null;
|
|
472
|
+
};
|
|
473
|
+
|
|
474
|
+
// src/gateway/security/metrics.ts
|
|
475
|
+
/**
|
|
476
|
+
* Prometheus Metrics for Gateway Security Plugins
|
|
477
|
+
*
|
|
478
|
+
* Thin wrapper over `prom-client` — optional peer dep. When prom-client is
|
|
479
|
+
* not installed or `PROMETHEUS_METRICS_ENABLED !== 'true'`, every emit is a
|
|
480
|
+
* no-op so the SDK remains consumable without pulling the dependency.
|
|
481
|
+
*
|
|
482
|
+
* Metrics:
|
|
483
|
+
* - `gateway_security_rate_limit_total{gateway,tier,decision}`
|
|
484
|
+
* decision ∈ allowed | rejected | observed_reject
|
|
485
|
+
* - `gateway_security_complexity_rejected_total{gateway,observe}`
|
|
486
|
+
* - `gateway_security_armor_rejected_total{gateway,rule}` (reserved —
|
|
487
|
+
* wiring depends on armor plugin emitting hooks)
|
|
488
|
+
* - `gateway_security_valkey_failover_total{gateway}`
|
|
489
|
+
* - `gateway_security_operation_timeout_total{gateway}`
|
|
490
|
+
*
|
|
491
|
+
* Labels:
|
|
492
|
+
* - `gateway` — gateway name (wspace-public-gateway | global-public-gateway)
|
|
493
|
+
* - `tier` — public | user | app | service | super_admin
|
|
494
|
+
* - `decision` — allowed | rejected | observed_reject
|
|
495
|
+
* - `observe` — 'true' | 'false'
|
|
496
|
+
* - `rule` — armor rule ref (max_aliases, max_tokens, …)
|
|
497
|
+
*
|
|
498
|
+
* All metrics are global singletons across plugin instances. Safe to call
|
|
499
|
+
* `initializeMetrics()` multiple times; subsequent calls are no-ops.
|
|
500
|
+
*
|
|
501
|
+
* @module gateway/security/metrics
|
|
502
|
+
* @category Gateway
|
|
503
|
+
*/
|
|
504
|
+
let metrics = null;
|
|
505
|
+
let initializing = false;
|
|
506
|
+
let promMod = null;
|
|
507
|
+
const noopCounter = { inc: () => void 0 };
|
|
508
|
+
const noopMetrics = {
|
|
509
|
+
rateLimit: noopCounter,
|
|
510
|
+
complexityRejected: noopCounter,
|
|
511
|
+
armorRejected: noopCounter,
|
|
512
|
+
valkeyFailover: noopCounter,
|
|
513
|
+
operationTimeout: noopCounter
|
|
514
|
+
};
|
|
515
|
+
/**
|
|
516
|
+
* Initialize the metrics registry. Safe to call multiple times.
|
|
517
|
+
* Returns a no-op metrics object if prom-client is unavailable.
|
|
518
|
+
*/
|
|
519
|
+
const initializeMetrics = async () => {
|
|
520
|
+
if (metrics) return metrics;
|
|
521
|
+
if (initializing) return noopMetrics;
|
|
522
|
+
if (process.env["PROMETHEUS_METRICS_ENABLED"] !== "true") {
|
|
523
|
+
logger.info("[gateway-security] Prometheus metrics disabled (PROMETHEUS_METRICS_ENABLED!=true)");
|
|
524
|
+
metrics = noopMetrics;
|
|
525
|
+
return metrics;
|
|
526
|
+
}
|
|
527
|
+
initializing = true;
|
|
528
|
+
try {
|
|
529
|
+
const imported = await import(
|
|
530
|
+
/* @vite-ignore */
|
|
531
|
+
"prom-client"
|
|
532
|
+
);
|
|
533
|
+
promMod = imported;
|
|
534
|
+
if (typeof imported.Counter !== "function") {
|
|
535
|
+
logger.warn("[gateway-security] prom-client has unexpected shape — metrics disabled");
|
|
536
|
+
metrics = noopMetrics;
|
|
537
|
+
return metrics;
|
|
538
|
+
}
|
|
539
|
+
const { Counter } = imported;
|
|
540
|
+
metrics = {
|
|
541
|
+
rateLimit: new Counter({
|
|
542
|
+
name: "gateway_security_rate_limit_total",
|
|
543
|
+
help: "Rate-limit plugin decisions by tier + gateway",
|
|
544
|
+
labelNames: [
|
|
545
|
+
"gateway",
|
|
546
|
+
"tier",
|
|
547
|
+
"decision"
|
|
548
|
+
]
|
|
549
|
+
}),
|
|
550
|
+
complexityRejected: new Counter({
|
|
551
|
+
name: "gateway_security_complexity_rejected_total",
|
|
552
|
+
help: "Query complexity plugin rejections",
|
|
553
|
+
labelNames: ["gateway", "observe"]
|
|
554
|
+
}),
|
|
555
|
+
armorRejected: new Counter({
|
|
556
|
+
name: "gateway_security_armor_rejected_total",
|
|
557
|
+
help: "graphql-armor rule rejections",
|
|
558
|
+
labelNames: [
|
|
559
|
+
"gateway",
|
|
560
|
+
"rule",
|
|
561
|
+
"mode"
|
|
562
|
+
]
|
|
563
|
+
}),
|
|
564
|
+
valkeyFailover: new Counter({
|
|
565
|
+
name: "gateway_security_valkey_failover_total",
|
|
566
|
+
help: "Rate-limit plugin fail-open events due to Valkey unreachable",
|
|
567
|
+
labelNames: ["gateway"]
|
|
568
|
+
}),
|
|
569
|
+
operationTimeout: new Counter({
|
|
570
|
+
name: "gateway_security_operation_timeout_total",
|
|
571
|
+
help: "Operation timeout plugin aborts",
|
|
572
|
+
labelNames: ["gateway"]
|
|
573
|
+
})
|
|
574
|
+
};
|
|
575
|
+
logger.info("[gateway-security] Prometheus metrics initialized");
|
|
576
|
+
return metrics;
|
|
577
|
+
} catch (err) {
|
|
578
|
+
const e = err instanceof Error ? err : new Error(String(err));
|
|
579
|
+
logger.warn("[gateway-security] prom-client not installed — metrics disabled", { error: e.message });
|
|
580
|
+
metrics = noopMetrics;
|
|
581
|
+
return metrics;
|
|
582
|
+
} finally {
|
|
583
|
+
initializing = false;
|
|
584
|
+
}
|
|
585
|
+
};
|
|
586
|
+
/**
|
|
587
|
+
* Get the current metrics handle. Returns a noop object if
|
|
588
|
+
* `initializeMetrics()` has not been called or prom-client is unavailable.
|
|
589
|
+
* Always safe to call.
|
|
590
|
+
*/
|
|
591
|
+
const getMetrics = () => metrics ?? noopMetrics;
|
|
592
|
+
/**
|
|
593
|
+
* Return the Prometheus registry's default `/metrics` output. Returns
|
|
594
|
+
* `null` if prom-client is not installed.
|
|
595
|
+
*/
|
|
596
|
+
const scrapeMetrics = async () => {
|
|
597
|
+
if (!promMod?.register) return null;
|
|
598
|
+
return {
|
|
599
|
+
body: await promMod.register.metrics(),
|
|
600
|
+
contentType: promMod.register.contentType
|
|
601
|
+
};
|
|
602
|
+
};
|
|
603
|
+
/**
|
|
604
|
+
* Test-only reset. Drops the initialized counters. Do NOT use in production.
|
|
605
|
+
*/
|
|
606
|
+
const __resetMetricsForTest = () => {
|
|
607
|
+
metrics = null;
|
|
608
|
+
initializing = false;
|
|
609
|
+
promMod = null;
|
|
610
|
+
};
|
|
611
|
+
|
|
612
|
+
// src/gateway/security/plugins/armor.ts
|
|
613
|
+
/**
|
|
614
|
+
* GraphQL Armor Plugin Bundle
|
|
615
|
+
*
|
|
616
|
+
* Wraps the `@escape.tech/graphql-armor-*` validation rules into a single
|
|
617
|
+
* Envelop plugin that runs them inside `onValidate` and sets rejection via
|
|
618
|
+
* `setResult(errors)` — the same pattern that `query-complexity` uses and
|
|
619
|
+
* that Hive Gateway Runtime is confirmed to honor.
|
|
620
|
+
*
|
|
621
|
+
* Why not just use each armor package's own `plugin` factory (which wraps
|
|
622
|
+
* the rule via `addValidationRule`)? Because Hive Gateway Runtime's plugin
|
|
623
|
+
* system does not honor the `addValidationRule` registration path during
|
|
624
|
+
* query validation — rules registered that way are silently dropped. Nor
|
|
625
|
+
* does Hive honor `afterValidate` hooks returned from `onValidate`, which
|
|
626
|
+
* was the first workaround we tried. Only `setResult(errors)` called
|
|
627
|
+
* synchronously inside `onValidate` actually propagates to the client.
|
|
628
|
+
*
|
|
629
|
+
* Rule coverage:
|
|
630
|
+
* - max-aliases (graphql-armor rule)
|
|
631
|
+
* - max-directives (graphql-armor rule)
|
|
632
|
+
* - cost-limit (graphql-armor rule; heuristic pre-pass)
|
|
633
|
+
* - character-limit (implemented inline via `onParse.source.length`
|
|
634
|
+
* because the armor package hooks `onParams` which
|
|
635
|
+
* is not exposed by Envelop — equivalent protection)
|
|
636
|
+
* - block-field-suggestions (still uses the armor plugin — hooks onValidate
|
|
637
|
+
* via `setResult`, which does work)
|
|
638
|
+
* - max-tokens (covered by query-complexity, not re-implemented;
|
|
639
|
+
* token blowup shows up as high cost)
|
|
640
|
+
*
|
|
641
|
+
* In observe mode, rule errors are logged but not attached to the final
|
|
642
|
+
* result — the query proceeds as if nothing happened.
|
|
643
|
+
*
|
|
644
|
+
* @module gateway/security/plugins/armor
|
|
645
|
+
* @category Gateway
|
|
646
|
+
*/
|
|
647
|
+
const tryImport = async (specifier) => {
|
|
648
|
+
try {
|
|
649
|
+
return await import(specifier);
|
|
650
|
+
} catch (err) {
|
|
651
|
+
const e = err instanceof Error ? err : new Error(String(err));
|
|
652
|
+
logger.warn("[gateway-security] armor package not installed — rule skipped", {
|
|
653
|
+
specifier,
|
|
654
|
+
error: e.message
|
|
655
|
+
});
|
|
656
|
+
return null;
|
|
657
|
+
}
|
|
658
|
+
};
|
|
659
|
+
const pickFactory = (mod, candidates) => {
|
|
660
|
+
if (!mod) return null;
|
|
661
|
+
for (const name of candidates) {
|
|
662
|
+
const fn = mod[name];
|
|
663
|
+
if (typeof fn === "function") return fn;
|
|
664
|
+
}
|
|
665
|
+
return null;
|
|
666
|
+
};
|
|
667
|
+
const createMaxAliasesRule = (maxAliases) => {
|
|
668
|
+
return (context) => {
|
|
669
|
+
let aliases = 0;
|
|
670
|
+
return { Field(node) {
|
|
671
|
+
if (!node.alias) return;
|
|
672
|
+
aliases += 1;
|
|
673
|
+
if (aliases > maxAliases) context.reportError(new GraphQLError("Too many field aliases.", {
|
|
674
|
+
nodes: node,
|
|
675
|
+
extensions: { code: "ARMOR_MAX_ALIASES" }
|
|
676
|
+
}));
|
|
677
|
+
} };
|
|
678
|
+
};
|
|
679
|
+
};
|
|
680
|
+
const createMaxDirectivesRule = (maxDirectives) => {
|
|
681
|
+
return (context) => {
|
|
682
|
+
let directives = 0;
|
|
683
|
+
return { Directive(node) {
|
|
684
|
+
directives += 1;
|
|
685
|
+
if (directives > maxDirectives) context.reportError(new GraphQLError("Too many directives.", {
|
|
686
|
+
nodes: node,
|
|
687
|
+
extensions: { code: "ARMOR_MAX_DIRECTIVES" }
|
|
688
|
+
}));
|
|
689
|
+
} };
|
|
690
|
+
};
|
|
691
|
+
};
|
|
692
|
+
/**
|
|
693
|
+
* When `ARMOR_LEAN=true` (default: false), the gateway loads only the cost-limit
|
|
694
|
+
* rule and skips `max-aliases`, `max-directives`, and `block-field-suggestions`.
|
|
695
|
+
*
|
|
696
|
+
* Rationale: each `@escape.tech/graphql-armor-*` rule runs its own
|
|
697
|
+
* `graphqlValidate(document, [rule])` — a full AST traversal per request. On
|
|
698
|
+
* busy public gateways this shows up as a measurable fraction of total CPU.
|
|
699
|
+
* The cost-limit rule already covers the DoS surface (it rejects expensive
|
|
700
|
+
* aliased-or-deeply-nested queries via the heuristic cost function), and
|
|
701
|
+
* character-limit is handled inline in `onParse`, so the other three rules
|
|
702
|
+
* are refinements rather than load-bearing defences.
|
|
703
|
+
*
|
|
704
|
+
* Opt-in via env so existing services see no behavior change.
|
|
705
|
+
*/
|
|
706
|
+
const isLean = () => {
|
|
707
|
+
const v = process.env["ARMOR_LEAN"];
|
|
708
|
+
return v === "true" || v === "1";
|
|
709
|
+
};
|
|
710
|
+
const loadRules = async (cfg) => {
|
|
711
|
+
const lean = isLean();
|
|
712
|
+
const [aliasesMod, directivesMod, costMod, blockSuggestionsMod] = await Promise.all([
|
|
713
|
+
lean ? Promise.resolve(null) : tryImport("@escape.tech/graphql-armor-max-aliases"),
|
|
714
|
+
lean ? Promise.resolve(null) : tryImport("@escape.tech/graphql-armor-max-directives"),
|
|
715
|
+
tryImport("@escape.tech/graphql-armor-cost-limit"),
|
|
716
|
+
lean ? Promise.resolve(null) : tryImport("@escape.tech/graphql-armor-block-field-suggestions")
|
|
717
|
+
]);
|
|
718
|
+
const loaded = {};
|
|
719
|
+
const maxAliasesFactory = pickFactory(aliasesMod, ["maxAliasesRule"]);
|
|
720
|
+
loaded.maxAliasesRule = maxAliasesFactory ? maxAliasesFactory({
|
|
721
|
+
n: cfg.maxAliases,
|
|
722
|
+
exposeLimits: cfg.observe
|
|
723
|
+
}) : createMaxAliasesRule(cfg.maxAliases);
|
|
724
|
+
const maxDirectivesFactory = pickFactory(directivesMod, ["maxDirectivesRule"]);
|
|
725
|
+
loaded.maxDirectivesRule = maxDirectivesFactory ? maxDirectivesFactory({
|
|
726
|
+
n: cfg.maxDirectives,
|
|
727
|
+
exposeLimits: cfg.observe
|
|
728
|
+
}) : createMaxDirectivesRule(cfg.maxDirectives);
|
|
729
|
+
const costLimitFactory = pickFactory(costMod, ["costLimitRule"]);
|
|
730
|
+
if (costLimitFactory) loaded.costLimitRule = costLimitFactory({
|
|
731
|
+
maxCost: cfg.costLimit,
|
|
732
|
+
objectCost: 2,
|
|
733
|
+
scalarCost: 1,
|
|
734
|
+
depthCostFactor: 1.5,
|
|
735
|
+
ignoreIntrospection: true,
|
|
736
|
+
exposeLimits: cfg.observe
|
|
737
|
+
});
|
|
738
|
+
const blockSuggestionsFactory = pickFactory(blockSuggestionsMod, ["blockFieldSuggestionsPlugin", "default"]);
|
|
739
|
+
if (blockSuggestionsFactory) loaded.blockSuggestionsPlugin = blockSuggestionsFactory({});
|
|
740
|
+
if (lean) logger.info("[gateway-security] ARMOR_LEAN enabled — running only cost-limit + character-limit", {});
|
|
741
|
+
return loaded;
|
|
742
|
+
};
|
|
743
|
+
/**
|
|
744
|
+
* Build the Envelop/Yoga plugin list for graphql-armor. Returns the
|
|
745
|
+
* block-field-suggestions plugin (armor's own — this one actually works via
|
|
746
|
+
* `setResult`) plus a custom `onValidate` plugin that runs the rule-based
|
|
747
|
+
* armor checks (max-aliases, max-directives, cost-limit) manually inside
|
|
748
|
+
* `AfterValidate.setResult`.
|
|
749
|
+
*
|
|
750
|
+
* The custom plugin also handles character-limit inline via `onParse`.
|
|
751
|
+
*/
|
|
752
|
+
const createArmorPlugins = async (cfg) => {
|
|
753
|
+
const rules = await loadRules(cfg);
|
|
754
|
+
const metrics = getMetrics();
|
|
755
|
+
const enabledRules = [];
|
|
756
|
+
if (rules.maxAliasesRule) enabledRules.push({
|
|
757
|
+
name: "max-aliases",
|
|
758
|
+
rule: rules.maxAliasesRule
|
|
759
|
+
});
|
|
760
|
+
if (rules.maxDirectivesRule) enabledRules.push({
|
|
761
|
+
name: "max-directives",
|
|
762
|
+
rule: rules.maxDirectivesRule
|
|
763
|
+
});
|
|
764
|
+
if (rules.costLimitRule) enabledRules.push({
|
|
765
|
+
name: "cost-limit",
|
|
766
|
+
rule: rules.costLimitRule
|
|
767
|
+
});
|
|
768
|
+
const plugins = [{
|
|
769
|
+
onParse({ params }) {
|
|
770
|
+
const source = typeof params.source === "string" ? params.source : params.source?.body;
|
|
771
|
+
if (typeof source === "string" && source.length > cfg.characterLimit) {
|
|
772
|
+
if (cfg.observe) {
|
|
773
|
+
logger.warn("[gateway-security] armor character-limit exceeded (observe)", {
|
|
774
|
+
length: source.length,
|
|
775
|
+
limit: cfg.characterLimit
|
|
776
|
+
});
|
|
777
|
+
metrics.armorRejected.inc({
|
|
778
|
+
rule: "character-limit",
|
|
779
|
+
mode: "observe"
|
|
780
|
+
}, 1);
|
|
781
|
+
return;
|
|
782
|
+
}
|
|
783
|
+
metrics.armorRejected.inc({
|
|
784
|
+
rule: "character-limit",
|
|
785
|
+
mode: "enforce"
|
|
786
|
+
}, 1);
|
|
787
|
+
throw new GraphQLError("Syntax Error: Query exceeds maximum character limit.", { extensions: {
|
|
788
|
+
code: "CHARACTER_LIMIT_EXCEEDED",
|
|
789
|
+
http: { status: 400 }
|
|
790
|
+
} });
|
|
791
|
+
}
|
|
792
|
+
},
|
|
793
|
+
onValidate({ params, setResult }) {
|
|
794
|
+
if (enabledRules.length === 0) return;
|
|
795
|
+
const armorErrors = [];
|
|
796
|
+
for (const { name, rule } of enabledRules) try {
|
|
797
|
+
const errs = validate(params.schema, params.documentAST, [rule]);
|
|
798
|
+
armorErrors.push(...errs);
|
|
799
|
+
} catch (err) {
|
|
800
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
801
|
+
const wrapped = new GraphQLError(message, {
|
|
802
|
+
originalError: err instanceof Error ? err : void 0,
|
|
803
|
+
extensions: {
|
|
804
|
+
code: "ARMOR_VIOLATION",
|
|
805
|
+
rule: name
|
|
806
|
+
}
|
|
807
|
+
});
|
|
808
|
+
armorErrors.push(wrapped);
|
|
809
|
+
}
|
|
810
|
+
if (armorErrors.length === 0) return;
|
|
811
|
+
for (const err of armorErrors) logger.warn("[gateway-security] armor rule triggered", {
|
|
812
|
+
message: err.message,
|
|
813
|
+
observe: cfg.observe
|
|
814
|
+
});
|
|
815
|
+
metrics.armorRejected.inc({
|
|
816
|
+
rule: "armor",
|
|
817
|
+
mode: cfg.observe ? "observe" : "enforce"
|
|
818
|
+
}, armorErrors.length);
|
|
819
|
+
if (cfg.observe) return;
|
|
820
|
+
setResult(armorErrors);
|
|
821
|
+
}
|
|
822
|
+
}];
|
|
823
|
+
if (rules.blockSuggestionsPlugin) plugins.push(rules.blockSuggestionsPlugin);
|
|
824
|
+
return plugins;
|
|
825
|
+
};
|
|
826
|
+
|
|
827
|
+
// src/gateway/security/plugins/operation-timeout.ts
|
|
828
|
+
/**
|
|
829
|
+
* Operation Timeout Plugin
|
|
830
|
+
*
|
|
831
|
+
* Races each operation against a configurable timer (defaults: 15s for
|
|
832
|
+
* queries, `mutationTimeoutMs` — default 25s — for mutations, both shorter
|
|
833
|
+
* than the 30s request-limiter cap). When the timer fires, the execution
|
|
834
|
+
* errors out with a proper GraphQL error rather than the client seeing an
|
|
835
|
+
* abrupt TCP drop.
|
|
836
|
+
*
|
|
837
|
+
* ## Honest outcome semantics (BOFF-5988)
|
|
838
|
+
*
|
|
839
|
+
* A timeout means the gateway stopped WAITING — it does not mean the
|
|
840
|
+
* operation failed, and for a mutation it does not mean the operation was
|
|
841
|
+
* rolled back. Aborting the downstream fetch cannot un-commit a transaction
|
|
842
|
+
* that already committed in a subgraph, and the gateway cannot observe which
|
|
843
|
+
* side of the commit the timeout landed on. Reporting a plain failure for a
|
|
844
|
+
* committed write is what made clients retry and duplicate side effects.
|
|
845
|
+
*
|
|
846
|
+
* The error contract therefore distinguishes operation kinds:
|
|
847
|
+
*
|
|
848
|
+
* - query / subscription (side-effect-free by GraphQL contract):
|
|
849
|
+
* `extensions.code = OPERATION_TIMEOUT`, `retriable: true`,
|
|
850
|
+
* `outcome: 'NONE'` — retrying the same read is safe.
|
|
851
|
+
* - mutation (may have committed downstream):
|
|
852
|
+
* `extensions.code = OPERATION_TIMEOUT_OUTCOME_UNKNOWN`,
|
|
853
|
+
* `retriable: false`, `outcome: 'UNKNOWN'` — the write MAY have succeeded;
|
|
854
|
+
* the caller must read back the affected state (or use an idempotency
|
|
855
|
+
* mechanism) before attempting again, never blind-retry.
|
|
856
|
+
*
|
|
857
|
+
* Both remain well-formed GraphQL errors in `errors[]` with stable
|
|
858
|
+
* `extensions.code` values; the query-side code is unchanged from the
|
|
859
|
+
* original plugin so existing client handling keeps working.
|
|
860
|
+
*
|
|
861
|
+
* ## Cancellation is best-effort, not rollback
|
|
862
|
+
*
|
|
863
|
+
* The plugin injects an AbortController signal into the execution args
|
|
864
|
+
* (chained to any incoming request signal) and aborts it when the timer
|
|
865
|
+
* fires. `@graphql-hive/gateway-runtime` passes `args.signal` to the
|
|
866
|
+
* federation executor, which hands it to every subgraph HTTP fetch, so the
|
|
867
|
+
* in-flight downstream call IS cancelled where the transport honours aborts.
|
|
868
|
+
* This releases gateway and subgraph resources — it does NOT and cannot roll
|
|
869
|
+
* back work a subgraph already committed, which is exactly why mutations
|
|
870
|
+
* report `OUTCOME_UNKNOWN` above rather than failure.
|
|
871
|
+
*
|
|
872
|
+
* Note the hook coverage: this plugin wraps `onExecute` only. Subscription
|
|
873
|
+
* operations are handled by Yoga through `onSubscribe` and are not raced by
|
|
874
|
+
* this plugin (their lifetime is governed by the request limiter's stream
|
|
875
|
+
* caps instead).
|
|
876
|
+
*
|
|
877
|
+
* ## Competing downstream deadlines (safety net)
|
|
878
|
+
*
|
|
879
|
+
* The gateways also bound every subgraph HTTP call (`SUBGRAPH_REQUEST_TIMEOUT_MS`,
|
|
880
|
+
* default 20s, gateway-local `subgraph-timeout` plugin). When that per-call
|
|
881
|
+
* deadline fires BEFORE this plugin's mutation ceiling, the executor resolves
|
|
882
|
+
* with a transport error (`SUBREQUEST_HTTP_ERROR`, "The operation timed out")
|
|
883
|
+
* instead of racing this plugin — for a mutation that is the same dishonest
|
|
884
|
+
* "plain failure for possibly-committed work" class this module exists to
|
|
885
|
+
* prevent. So the plugin additionally rewrites MUTATION results whose errors
|
|
886
|
+
* are downstream transport TIMEOUT/ABORT failures into the same
|
|
887
|
+
* `OPERATION_TIMEOUT_OUTCOME_UNKNOWN` contract (`source: 'downstream-deadline'`).
|
|
888
|
+
* Deterministic transport failures (e.g. connection refused — the request was
|
|
889
|
+
* never in flight) and business errors (NOT_FOUND, FORBIDDEN, …) are NOT
|
|
890
|
+
* rewritten: they genuinely describe a failed operation. Queries are never
|
|
891
|
+
* rewritten (reads are side-effect-free and stay retriable).
|
|
892
|
+
*
|
|
893
|
+
* @module gateway/security/plugins/operation-timeout
|
|
894
|
+
* @category Gateway
|
|
895
|
+
*/
|
|
896
|
+
const asSignalBearing = (args) => args;
|
|
897
|
+
/** Reason attached to the AbortController when the timeout fires. */
|
|
898
|
+
const OPERATION_TIMEOUT_ABORT_REASON = "OPERATION_TIMEOUT";
|
|
899
|
+
/** Stable extensions code for the mutation "may have committed" contract. */
|
|
900
|
+
const MUTATION_OUTCOME_UNKNOWN_CODE = "OPERATION_TIMEOUT_OUTCOME_UNKNOWN";
|
|
901
|
+
/** Stable extensions code for the read-side timeout (safe to retry). */
|
|
902
|
+
const READ_TIMEOUT_CODE = "OPERATION_TIMEOUT";
|
|
903
|
+
const MUTATION_OUTCOME_UNKNOWN_MESSAGE = "The mutation did not complete within the gateway time limit — outcome unknown. It MAY have committed on the server; a timeout cannot roll back work already committed downstream. Do not retry blindly: read back the affected state (or use an idempotency mechanism) before attempting this mutation again.";
|
|
904
|
+
/**
|
|
905
|
+
* Error names produced when an in-flight `fetch` is cancelled by an
|
|
906
|
+
* AbortSignal: `AbortSignal.timeout()` rejects with a `TimeoutError`
|
|
907
|
+
* DOMException and `AbortController.abort()` with an `AbortError`. These names
|
|
908
|
+
* only ever appear in the chain when the GATEWAY cancelled a request that was
|
|
909
|
+
* already in flight — a subgraph that returns a well-formed GraphQL error over
|
|
910
|
+
* the wire never carries a JS `TimeoutError`/`AbortError` instance in its
|
|
911
|
+
* `originalError` chain (it is serialised JSON). So matching these names
|
|
912
|
+
* precisely identifies "we stopped waiting on a request that may have
|
|
913
|
+
* completed", which is exactly the OUTCOME_UNKNOWN case, and never a
|
|
914
|
+
* deterministic failure like a refused connection (whose chain bottoms out in a
|
|
915
|
+
* plain `Error`).
|
|
916
|
+
*/
|
|
917
|
+
const IN_FLIGHT_ABORT_ERROR_NAMES = /* @__PURE__ */ new Set(["TimeoutError", "AbortError"]);
|
|
918
|
+
/**
|
|
919
|
+
* Walk an error's `originalError` / `cause` chain looking for an in-flight
|
|
920
|
+
* timeout/abort. Cross-realm safe: duck-types on the string `name` property
|
|
921
|
+
* rather than `instanceof`.
|
|
922
|
+
*/
|
|
923
|
+
const isInFlightTimeoutOrAbort = (error) => {
|
|
924
|
+
let current = error;
|
|
925
|
+
for (let depth = 0; current && typeof current === "object" && depth < 8; depth += 1) {
|
|
926
|
+
const candidate = current;
|
|
927
|
+
if (typeof candidate.name === "string" && IN_FLIGHT_ABORT_ERROR_NAMES.has(candidate.name)) return true;
|
|
928
|
+
const next = candidate.originalError ?? candidate.cause;
|
|
929
|
+
if (next === current) break;
|
|
930
|
+
current = next;
|
|
931
|
+
}
|
|
932
|
+
return false;
|
|
933
|
+
};
|
|
934
|
+
const isRecord$1 = (value) => typeof value === "object" && value !== null;
|
|
935
|
+
/**
|
|
936
|
+
* Build the mutation OUTCOME_UNKNOWN GraphQL error, preserving the field
|
|
937
|
+
* `path` of the downstream error it replaces so clients still see which
|
|
938
|
+
* mutation field was affected. `source` records which ceiling fired.
|
|
939
|
+
*/
|
|
940
|
+
const buildMutationOutcomeUnknownError = (original, source) => {
|
|
941
|
+
const originalError = isRecord$1(original) ? original : void 0;
|
|
942
|
+
const path = originalError?.["path"];
|
|
943
|
+
const originalExtensions = isRecord$1(originalError?.["extensions"]) ? originalError?.["extensions"] : void 0;
|
|
944
|
+
const downstreamCode = originalExtensions?.["code"];
|
|
945
|
+
const traceId = originalExtensions?.["traceId"];
|
|
946
|
+
return new GraphQLError(MUTATION_OUTCOME_UNKNOWN_MESSAGE, {
|
|
947
|
+
path: Array.isArray(path) ? path : void 0,
|
|
948
|
+
extensions: {
|
|
949
|
+
code: MUTATION_OUTCOME_UNKNOWN_CODE,
|
|
950
|
+
operationKind: "mutation",
|
|
951
|
+
outcome: "UNKNOWN",
|
|
952
|
+
retriable: false,
|
|
953
|
+
source,
|
|
954
|
+
...typeof downstreamCode === "string" && downstreamCode !== "OPERATION_TIMEOUT_OUTCOME_UNKNOWN" ? { downstreamCode } : {},
|
|
955
|
+
...typeof traceId === "string" ? { traceId } : {}
|
|
956
|
+
}
|
|
957
|
+
});
|
|
958
|
+
};
|
|
959
|
+
/** True when the error already carries this plugin's typed timeout contract. */
|
|
960
|
+
const isTypedTimeoutError = (error) => {
|
|
961
|
+
if (!isRecord$1(error)) return false;
|
|
962
|
+
const code = (isRecord$1(error["extensions"]) ? error["extensions"] : void 0)?.["code"];
|
|
963
|
+
return code === "OPERATION_TIMEOUT_OUTCOME_UNKNOWN" || code === "OPERATION_TIMEOUT";
|
|
964
|
+
};
|
|
965
|
+
/**
|
|
966
|
+
* Rewrite any in-flight timeout/abort field errors in a MUTATION result into
|
|
967
|
+
* the OUTCOME_UNKNOWN contract. This is the safety net for the competing
|
|
968
|
+
* gateway-local subgraph deadline (`SUBGRAPH_REQUEST_TIMEOUT_MS`): when that
|
|
969
|
+
* per-call ceiling aborts a mutation's fetch before this plugin's operation
|
|
970
|
+
* ceiling fires, the executor resolves with a `SUBREQUEST_HTTP_ERROR` whose
|
|
971
|
+
* cause is a `TimeoutError` — a plain "failure" for work that may have
|
|
972
|
+
* committed. Deterministic failures (refused connection → plain `Error`, or a
|
|
973
|
+
* business error like NOT_FOUND) are left untouched, and non-mutation results
|
|
974
|
+
* are never rewritten.
|
|
975
|
+
*/
|
|
976
|
+
const rewriteMutationTimeoutErrors = (result) => {
|
|
977
|
+
if (!isRecord$1(result)) return result;
|
|
978
|
+
const errors = result.errors;
|
|
979
|
+
if (!Array.isArray(errors) || errors.length === 0) return result;
|
|
980
|
+
let changed = false;
|
|
981
|
+
const rewritten = errors.map((error) => {
|
|
982
|
+
if (!isTypedTimeoutError(error) && isInFlightTimeoutOrAbort(error)) {
|
|
983
|
+
changed = true;
|
|
984
|
+
return buildMutationOutcomeUnknownError(error, "downstream-deadline");
|
|
985
|
+
}
|
|
986
|
+
return error;
|
|
987
|
+
});
|
|
988
|
+
if (!changed) return result;
|
|
989
|
+
return {
|
|
990
|
+
...result,
|
|
991
|
+
errors: rewritten
|
|
992
|
+
};
|
|
993
|
+
};
|
|
994
|
+
/**
|
|
995
|
+
* Resolve which operation kind is executing.
|
|
996
|
+
*
|
|
997
|
+
* By the time `onExecute` fires the document has passed parsing and
|
|
998
|
+
* validation: either `operationName` selects one operation, or the document
|
|
999
|
+
* carries exactly one. If the kind still cannot be determined, the plugin
|
|
1000
|
+
* fails CONSERVATIVELY to mutation semantics — telling a caller "outcome
|
|
1001
|
+
* unknown, do not blind-retry" for an operation that might have side effects
|
|
1002
|
+
* is safe, while the reverse is how BOFF-5988 happened.
|
|
1003
|
+
*/
|
|
1004
|
+
const resolveOperationKind = (args) => {
|
|
1005
|
+
const document = args.document;
|
|
1006
|
+
if (!document || !Array.isArray(document.definitions)) return "mutation";
|
|
1007
|
+
const operations = [];
|
|
1008
|
+
for (const definition of document.definitions) if (definition.kind === Kind.OPERATION_DEFINITION) operations.push(definition);
|
|
1009
|
+
if (operations.length === 0) return "mutation";
|
|
1010
|
+
if (args.operationName) {
|
|
1011
|
+
const named = operations.find((operation) => operation.name?.value === args.operationName);
|
|
1012
|
+
if (named) return named.operation;
|
|
1013
|
+
return "mutation";
|
|
1014
|
+
}
|
|
1015
|
+
if (operations.length === 1) {
|
|
1016
|
+
const only = operations[0];
|
|
1017
|
+
return only ? only.operation : "mutation";
|
|
1018
|
+
}
|
|
1019
|
+
return "mutation";
|
|
1020
|
+
};
|
|
1021
|
+
/**
|
|
1022
|
+
* Build the timeout error for an operation kind.
|
|
1023
|
+
*
|
|
1024
|
+
* Query/subscription keep the historical `OPERATION_TIMEOUT` code and
|
|
1025
|
+
* message shape (reads are safe to retry). Mutations get the distinct,
|
|
1026
|
+
* documented `OPERATION_TIMEOUT_OUTCOME_UNKNOWN` code with `retriable:false`
|
|
1027
|
+
* so no caller can mistake a possibly-committed write for a plain failure.
|
|
1028
|
+
*/
|
|
1029
|
+
const buildTimeoutError = (kind, timeoutMs) => {
|
|
1030
|
+
if (kind === "mutation") return new GraphQLError(MUTATION_OUTCOME_UNKNOWN_MESSAGE, { extensions: {
|
|
1031
|
+
code: MUTATION_OUTCOME_UNKNOWN_CODE,
|
|
1032
|
+
operationKind: kind,
|
|
1033
|
+
outcome: "UNKNOWN",
|
|
1034
|
+
retriable: false,
|
|
1035
|
+
timeoutMs,
|
|
1036
|
+
source: "operation-ceiling"
|
|
1037
|
+
} });
|
|
1038
|
+
return new GraphQLError("Operation timeout", { extensions: {
|
|
1039
|
+
code: READ_TIMEOUT_CODE,
|
|
1040
|
+
operationKind: kind,
|
|
1041
|
+
outcome: "NONE",
|
|
1042
|
+
retriable: true,
|
|
1043
|
+
timeoutMs
|
|
1044
|
+
} });
|
|
1045
|
+
};
|
|
1046
|
+
const timeoutFor = (kind, config) => {
|
|
1047
|
+
if (kind === "mutation" && typeof config.mutationTimeoutMs === "number" && config.mutationTimeoutMs > 0) return config.mutationTimeoutMs;
|
|
1048
|
+
return config.timeoutMs;
|
|
1049
|
+
};
|
|
1050
|
+
const createOperationTimeoutPlugin = (deps) => {
|
|
1051
|
+
return { onExecute: ({ executeFn, setExecuteFn }) => {
|
|
1052
|
+
setExecuteFn(async (args) => {
|
|
1053
|
+
const signalCarrier = asSignalBearing(args);
|
|
1054
|
+
const kind = resolveOperationKind(signalCarrier);
|
|
1055
|
+
const timeoutMs = timeoutFor(kind, deps.config);
|
|
1056
|
+
const controller = new AbortController();
|
|
1057
|
+
const incoming = signalCarrier.signal;
|
|
1058
|
+
if (incoming) {
|
|
1059
|
+
if (incoming.aborted) controller.abort(incoming.reason);
|
|
1060
|
+
else incoming.addEventListener("abort", () => controller.abort(incoming.reason), { once: true });
|
|
1061
|
+
}
|
|
1062
|
+
signalCarrier.signal = controller.signal;
|
|
1063
|
+
let timer;
|
|
1064
|
+
const timeoutPromise = new Promise((_, reject) => {
|
|
1065
|
+
timer = setTimeout(() => {
|
|
1066
|
+
reject(buildTimeoutError(kind, timeoutMs));
|
|
1067
|
+
controller.abort(OPERATION_TIMEOUT_ABORT_REASON);
|
|
1068
|
+
}, timeoutMs);
|
|
1069
|
+
});
|
|
1070
|
+
try {
|
|
1071
|
+
const settled = await Promise.race([executeFn(args), timeoutPromise]);
|
|
1072
|
+
return kind === "mutation" ? rewriteMutationTimeoutErrors(settled) : settled;
|
|
1073
|
+
} catch (error) {
|
|
1074
|
+
if (kind === "mutation" && !isTypedTimeoutError(error) && isInFlightTimeoutOrAbort(error)) throw buildMutationOutcomeUnknownError(error, "downstream-deadline");
|
|
1075
|
+
throw error;
|
|
1076
|
+
} finally {
|
|
1077
|
+
clearTimeout(timer);
|
|
1078
|
+
}
|
|
1079
|
+
});
|
|
1080
|
+
} };
|
|
1081
|
+
};
|
|
1082
|
+
|
|
1083
|
+
// src/gateway/security/plugins/otel.ts
|
|
1084
|
+
let shutdownHook = null;
|
|
1085
|
+
/**
|
|
1086
|
+
* Build an OTel Resource across the v1 → v2 API migration.
|
|
1087
|
+
* - v1 (`@opentelemetry/resources` 1.x): `new Resource(attrs)`
|
|
1088
|
+
* - v2 (`@opentelemetry/resources` 2.x): `resourceFromAttributes(attrs)`
|
|
1089
|
+
*/
|
|
1090
|
+
const buildResource = (resMod, attrs) => {
|
|
1091
|
+
if (typeof resMod.resourceFromAttributes === "function") return resMod.resourceFromAttributes(attrs);
|
|
1092
|
+
if (typeof resMod.Resource === "function") return new resMod.Resource(attrs);
|
|
1093
|
+
throw new Error("@opentelemetry/resources module exposes neither Resource nor resourceFromAttributes");
|
|
1094
|
+
};
|
|
1095
|
+
/**
|
|
1096
|
+
* Resolve semantic attribute keys across the v1 → v2 API migration.
|
|
1097
|
+
* - v1: `semcon.SemanticResourceAttributes.SERVICE_NAME` etc.
|
|
1098
|
+
* - v2: top-level `ATTR_SERVICE_NAME` string constants. Deployment
|
|
1099
|
+
* environment was renamed to `ATTR_DEPLOYMENT_ENVIRONMENT_NAME`.
|
|
1100
|
+
*/
|
|
1101
|
+
const resolveSemanticKeys = (semcon) => {
|
|
1102
|
+
if (semcon.SemanticResourceAttributes) return {
|
|
1103
|
+
serviceName: semcon.SemanticResourceAttributes.SERVICE_NAME,
|
|
1104
|
+
deploymentEnv: semcon.SemanticResourceAttributes.DEPLOYMENT_ENVIRONMENT,
|
|
1105
|
+
serviceVersion: semcon.SemanticResourceAttributes.SERVICE_VERSION
|
|
1106
|
+
};
|
|
1107
|
+
return {
|
|
1108
|
+
serviceName: semcon.ATTR_SERVICE_NAME ?? "service.name",
|
|
1109
|
+
deploymentEnv: semcon.ATTR_DEPLOYMENT_ENVIRONMENT_NAME ?? semcon.ATTR_DEPLOYMENT_ENVIRONMENT ?? "deployment.environment",
|
|
1110
|
+
serviceVersion: semcon.ATTR_SERVICE_VERSION ?? "service.version"
|
|
1111
|
+
};
|
|
1112
|
+
};
|
|
1113
|
+
const loadOtelPeerDeps = async () => {
|
|
1114
|
+
const [sdkMod, otlpMod, resMod, semcon] = await Promise.all([
|
|
1115
|
+
importOptionalPeer("@opentelemetry/sdk-node"),
|
|
1116
|
+
importOptionalPeer("@opentelemetry/exporter-trace-otlp-http"),
|
|
1117
|
+
importOptionalPeer("@opentelemetry/resources"),
|
|
1118
|
+
importOptionalPeer("@opentelemetry/semantic-conventions")
|
|
1119
|
+
]);
|
|
1120
|
+
return {
|
|
1121
|
+
NodeSDK: sdkMod.NodeSDK,
|
|
1122
|
+
OTLPTraceExporter: otlpMod.OTLPTraceExporter,
|
|
1123
|
+
resMod,
|
|
1124
|
+
semcon
|
|
1125
|
+
};
|
|
1126
|
+
};
|
|
1127
|
+
const initializeOtel = async (cfg) => {
|
|
1128
|
+
if (!cfg.enabled) {
|
|
1129
|
+
logger.info("[gateway-security] OTel disabled by config");
|
|
1130
|
+
return;
|
|
1131
|
+
}
|
|
1132
|
+
if (shutdownHook) return;
|
|
1133
|
+
try {
|
|
1134
|
+
const { NodeSDK, OTLPTraceExporter, resMod, semcon } = await loadOtelPeerDeps();
|
|
1135
|
+
const keys = resolveSemanticKeys(semcon);
|
|
1136
|
+
const resourceAttributes = {
|
|
1137
|
+
[keys.serviceName]: cfg.serviceName,
|
|
1138
|
+
[keys.deploymentEnv]: cfg.environment
|
|
1139
|
+
};
|
|
1140
|
+
if (cfg.version) resourceAttributes[keys.serviceVersion] = cfg.version;
|
|
1141
|
+
const sdk = new NodeSDK({
|
|
1142
|
+
resource: buildResource(resMod, resourceAttributes),
|
|
1143
|
+
traceExporter: new OTLPTraceExporter({ url: cfg.endpoint })
|
|
1144
|
+
});
|
|
1145
|
+
sdk.start();
|
|
1146
|
+
shutdownHook = () => sdk.shutdown();
|
|
1147
|
+
logger.info("[gateway-security] OTel initialized", {
|
|
1148
|
+
serviceName: cfg.serviceName,
|
|
1149
|
+
endpoint: cfg.endpoint
|
|
1150
|
+
});
|
|
1151
|
+
} catch (err) {
|
|
1152
|
+
const e = err instanceof Error ? err : new Error(String(err));
|
|
1153
|
+
logger.warn("[gateway-security] OTel init failed — continuing without tracing", { error: e.message });
|
|
1154
|
+
}
|
|
1155
|
+
};
|
|
1156
|
+
const shutdownOtel = async () => {
|
|
1157
|
+
if (shutdownHook) {
|
|
1158
|
+
try {
|
|
1159
|
+
await shutdownHook();
|
|
1160
|
+
} catch (err) {
|
|
1161
|
+
const e = err instanceof Error ? err : new Error(String(err));
|
|
1162
|
+
logger.warn("[gateway-security] OTel shutdown error", { error: e.message });
|
|
1163
|
+
}
|
|
1164
|
+
shutdownHook = null;
|
|
1165
|
+
}
|
|
1166
|
+
};
|
|
1167
|
+
/**
|
|
1168
|
+
* Returns an Envelop plugin that adds spans around parse/validate/execute.
|
|
1169
|
+
* Returns an empty plugin when @envelop/opentelemetry is absent.
|
|
1170
|
+
*/
|
|
1171
|
+
const createOtelPlugin = async (cfg) => {
|
|
1172
|
+
if (!cfg.enabled) return {};
|
|
1173
|
+
try {
|
|
1174
|
+
const mod = await importOptionalPeer("@envelop/opentelemetry");
|
|
1175
|
+
if (typeof mod.useOpenTelemetry !== "function") {
|
|
1176
|
+
logger.warn("[gateway-security] @envelop/opentelemetry has unexpected shape — plugin skipped");
|
|
1177
|
+
return {};
|
|
1178
|
+
}
|
|
1179
|
+
return mod.useOpenTelemetry({
|
|
1180
|
+
spans: {
|
|
1181
|
+
execute: true,
|
|
1182
|
+
parse: true,
|
|
1183
|
+
validate: true,
|
|
1184
|
+
subscribe: true
|
|
1185
|
+
},
|
|
1186
|
+
resolvers: false
|
|
1187
|
+
});
|
|
1188
|
+
} catch (err) {
|
|
1189
|
+
const e = err instanceof Error ? err : new Error(String(err));
|
|
1190
|
+
logger.warn("[gateway-security] @envelop/opentelemetry not installed — plugin skipped", { error: e.message });
|
|
1191
|
+
return {};
|
|
1192
|
+
}
|
|
1193
|
+
};
|
|
1194
|
+
|
|
1195
|
+
// src/gateway/security/plugins/query-complexity.ts
|
|
1196
|
+
/**
|
|
1197
|
+
* Query Complexity Plugin
|
|
1198
|
+
*
|
|
1199
|
+
* Scores each incoming query against a per-field cost map. Scoring happens in
|
|
1200
|
+
* the validate phase so rejection is cheap and subgraph fanout is prevented.
|
|
1201
|
+
*
|
|
1202
|
+
* Observe mode logs the computed cost without rejecting — used during the
|
|
1203
|
+
* 48h bake of the hardening pass.
|
|
1204
|
+
*
|
|
1205
|
+
* @module gateway/security/plugins/query-complexity
|
|
1206
|
+
* @category Gateway
|
|
1207
|
+
*/
|
|
1208
|
+
const PAGINATION_ARGUMENTS = /* @__PURE__ */ new Set([
|
|
1209
|
+
"first",
|
|
1210
|
+
"limit",
|
|
1211
|
+
"pageSize"
|
|
1212
|
+
]);
|
|
1213
|
+
const MAX_LIST_MULTIPLIER = 100;
|
|
1214
|
+
const MAX_FAILURE_LOG_VARIANTS = 5;
|
|
1215
|
+
const complexityFailureMessages = /* @__PURE__ */ new Set();
|
|
1216
|
+
const isRecord = (value) => typeof value === "object" && value !== null;
|
|
1217
|
+
const unwrapNamedType = (type) => {
|
|
1218
|
+
let current = type;
|
|
1219
|
+
while (isRecord(current) && current["ofType"] !== void 0) current = current["ofType"];
|
|
1220
|
+
return isRecord(current) ? current : null;
|
|
1221
|
+
};
|
|
1222
|
+
const getSchemaLike = (schema) => schema;
|
|
1223
|
+
const getOperationRootType = (schema, operation) => {
|
|
1224
|
+
const schemaLike = getSchemaLike(schema);
|
|
1225
|
+
if (operation.operation === "mutation") return schemaLike.getMutationType?.() ?? null;
|
|
1226
|
+
if (operation.operation === "subscription") return schemaLike.getSubscriptionType?.() ?? null;
|
|
1227
|
+
return schemaLike.getQueryType?.() ?? null;
|
|
1228
|
+
};
|
|
1229
|
+
const getTypeByName = (schema, name) => {
|
|
1230
|
+
return getSchemaLike(schema).getType?.(name) ?? null;
|
|
1231
|
+
};
|
|
1232
|
+
const getField = (parentType, fieldName) => {
|
|
1233
|
+
return parentType.getFields?.()[fieldName];
|
|
1234
|
+
};
|
|
1235
|
+
const getCostMapValue = (costMap, parentType, fieldName) => {
|
|
1236
|
+
if (!parentType.name) return 1;
|
|
1237
|
+
return costMap[`${parentType.name}.${fieldName}`] ?? 1;
|
|
1238
|
+
};
|
|
1239
|
+
const numericValueFromAst = (value) => {
|
|
1240
|
+
if (value.kind === Kind.INT || value.kind === Kind.FLOAT) {
|
|
1241
|
+
const parsed = Number(value.value);
|
|
1242
|
+
return Number.isFinite(parsed) ? parsed : void 0;
|
|
1243
|
+
}
|
|
1244
|
+
if (value.kind === Kind.STRING) {
|
|
1245
|
+
const parsed = Number(value.value);
|
|
1246
|
+
return Number.isFinite(parsed) ? parsed : void 0;
|
|
1247
|
+
}
|
|
1248
|
+
};
|
|
1249
|
+
const listMultiplierFromArgs = (args) => {
|
|
1250
|
+
if (!args) return 1;
|
|
1251
|
+
for (const arg of args) {
|
|
1252
|
+
if (!PAGINATION_ARGUMENTS.has(arg.name.value)) continue;
|
|
1253
|
+
const raw = numericValueFromAst(arg.value);
|
|
1254
|
+
if (typeof raw !== "number") return 1;
|
|
1255
|
+
return Math.min(Math.max(1, Math.trunc(raw)), MAX_LIST_MULTIPLIER);
|
|
1256
|
+
}
|
|
1257
|
+
return 1;
|
|
1258
|
+
};
|
|
1259
|
+
const calculateFieldComplexity = (schema, fieldNode, parentType, fragments, costMap, activeFragments) => {
|
|
1260
|
+
const fieldName = fieldNode.name.value;
|
|
1261
|
+
const field = getField(parentType, fieldName);
|
|
1262
|
+
const baseCost = getCostMapValue(costMap, parentType, fieldName);
|
|
1263
|
+
const namedFieldType = unwrapNamedType(field?.type);
|
|
1264
|
+
return (baseCost + (fieldNode.selectionSet && namedFieldType ? calculateSelectionSetComplexity(schema, fieldNode.selectionSet, namedFieldType, fragments, costMap, activeFragments) : 0)) * listMultiplierFromArgs(fieldNode.arguments);
|
|
1265
|
+
};
|
|
1266
|
+
const calculateSelectionSetComplexity = (schema, selectionSet, parentType, fragments, costMap, activeFragments) => {
|
|
1267
|
+
let total = 0;
|
|
1268
|
+
for (const selection of selectionSet.selections) total += calculateSelectionComplexity(schema, selection, parentType, fragments, costMap, activeFragments);
|
|
1269
|
+
return total;
|
|
1270
|
+
};
|
|
1271
|
+
const calculateSelectionComplexity = (schema, selection, parentType, fragments, costMap, activeFragments) => {
|
|
1272
|
+
if (selection.kind === Kind.FIELD) return calculateFieldComplexity(schema, selection, parentType, fragments, costMap, activeFragments);
|
|
1273
|
+
if (selection.kind === Kind.INLINE_FRAGMENT) {
|
|
1274
|
+
const fragmentParent = selection.typeCondition ? getTypeByName(schema, selection.typeCondition.name.value) ?? parentType : parentType;
|
|
1275
|
+
return calculateSelectionSetComplexity(schema, selection.selectionSet, fragmentParent, fragments, costMap, activeFragments);
|
|
1276
|
+
}
|
|
1277
|
+
const fragmentName = selection.name.value;
|
|
1278
|
+
if (activeFragments.has(fragmentName)) return 0;
|
|
1279
|
+
const fragment = fragments.get(fragmentName);
|
|
1280
|
+
if (!fragment) return 0;
|
|
1281
|
+
activeFragments.add(fragmentName);
|
|
1282
|
+
const fragmentParent = getTypeByName(schema, fragment.typeCondition.name.value) ?? parentType;
|
|
1283
|
+
const complexity = calculateSelectionSetComplexity(schema, fragment.selectionSet, fragmentParent, fragments, costMap, activeFragments);
|
|
1284
|
+
activeFragments.delete(fragmentName);
|
|
1285
|
+
return complexity;
|
|
1286
|
+
};
|
|
1287
|
+
const calculateDocumentComplexity = (schema, documentAST, costMap) => {
|
|
1288
|
+
const fragments = /* @__PURE__ */ new Map();
|
|
1289
|
+
const operations = [];
|
|
1290
|
+
for (const definition of documentAST.definitions) {
|
|
1291
|
+
if (!isRecord(definition) || typeof definition["kind"] !== "string") continue;
|
|
1292
|
+
if (definition["kind"] === Kind.FRAGMENT_DEFINITION) {
|
|
1293
|
+
const fragment = definition;
|
|
1294
|
+
fragments.set(fragment.name.value, fragment);
|
|
1295
|
+
} else if (definition["kind"] === Kind.OPERATION_DEFINITION) operations.push(definition);
|
|
1296
|
+
}
|
|
1297
|
+
let maxComplexity = 0;
|
|
1298
|
+
for (const operation of operations) {
|
|
1299
|
+
const rootType = getOperationRootType(schema, operation);
|
|
1300
|
+
if (!rootType) continue;
|
|
1301
|
+
const complexity = calculateSelectionSetComplexity(schema, operation.selectionSet, rootType, fragments, costMap, /* @__PURE__ */ new Set());
|
|
1302
|
+
maxComplexity = Math.max(maxComplexity, complexity);
|
|
1303
|
+
}
|
|
1304
|
+
return maxComplexity;
|
|
1305
|
+
};
|
|
1306
|
+
const logComplexityFailure = (error) => {
|
|
1307
|
+
if (!complexityFailureMessages.has(error.message) && complexityFailureMessages.size < MAX_FAILURE_LOG_VARIANTS) {
|
|
1308
|
+
complexityFailureMessages.add(error.message);
|
|
1309
|
+
logger.warn("[gateway-security] complexity scoring failed — fail-open", {
|
|
1310
|
+
error: error.message,
|
|
1311
|
+
suppressedRepeats: true
|
|
1312
|
+
});
|
|
1313
|
+
return;
|
|
1314
|
+
}
|
|
1315
|
+
logger.debug("[gateway-security] repeated complexity scoring failure suppressed", { error: error.message });
|
|
1316
|
+
};
|
|
1317
|
+
const createQueryComplexityPlugin = (deps) => {
|
|
1318
|
+
return { onValidate: ({ params, setResult }) => {
|
|
1319
|
+
try {
|
|
1320
|
+
const complexity = calculateDocumentComplexity(params.schema, params.documentAST, deps.config.costMap);
|
|
1321
|
+
if (complexity > deps.config.maxCost) {
|
|
1322
|
+
getMetrics().complexityRejected.inc({
|
|
1323
|
+
gateway: "unknown",
|
|
1324
|
+
observe: deps.config.observe ? "true" : "false"
|
|
1325
|
+
});
|
|
1326
|
+
if (deps.config.observe) {
|
|
1327
|
+
logger.info("[gateway-security] complexity would_reject (observe)", {
|
|
1328
|
+
complexity,
|
|
1329
|
+
maxCost: deps.config.maxCost
|
|
1330
|
+
});
|
|
1331
|
+
return;
|
|
1332
|
+
}
|
|
1333
|
+
setResult([new GraphQLError(`Query too expensive (cost ${complexity} > limit ${deps.config.maxCost})`, { extensions: {
|
|
1334
|
+
code: "COMPLEXITY_TOO_HIGH",
|
|
1335
|
+
cost: complexity,
|
|
1336
|
+
maxCost: deps.config.maxCost
|
|
1337
|
+
} })]);
|
|
1338
|
+
}
|
|
1339
|
+
} catch (err) {
|
|
1340
|
+
const e = err instanceof Error ? err : new Error(String(err));
|
|
1341
|
+
logComplexityFailure(e);
|
|
1342
|
+
}
|
|
1343
|
+
} };
|
|
1344
|
+
};
|
|
1345
|
+
|
|
1346
|
+
// src/gateway/security/plugins/rate-limit.ts
|
|
1347
|
+
const keyFor = (prefix, tier, identity) => `rl:${prefix}:${tier}:${identity}`;
|
|
1348
|
+
const wsKeyFor = (prefix, workspaceId) => `rl:${prefix}:ws:${workspaceId}`;
|
|
1349
|
+
const stamp = () => Date.now();
|
|
1350
|
+
/**
|
|
1351
|
+
* Atomic-ish INCR + EXPIRE. Valkey does not guarantee atomicity between the
|
|
1352
|
+
* two without a Lua script; the race window here loses at most 1 event per
|
|
1353
|
+
* window-start collision, which is acceptable for a limiter and avoids the
|
|
1354
|
+
* Lua script registration dance.
|
|
1355
|
+
*/
|
|
1356
|
+
const checkRateLimit = async (deps, actor) => {
|
|
1357
|
+
const tier = deps.config.tiers[actor.tier];
|
|
1358
|
+
const metrics = getMetrics();
|
|
1359
|
+
const gateway = deps.config.keyPrefix;
|
|
1360
|
+
if (tier.points === Number.MAX_SAFE_INTEGER) {
|
|
1361
|
+
metrics.rateLimit.inc({
|
|
1362
|
+
gateway,
|
|
1363
|
+
tier: actor.tier,
|
|
1364
|
+
decision: "allowed"
|
|
1365
|
+
});
|
|
1366
|
+
return {
|
|
1367
|
+
allowed: true,
|
|
1368
|
+
remaining: Number.MAX_SAFE_INTEGER,
|
|
1369
|
+
resetAtMs: 0,
|
|
1370
|
+
limit: tier.points
|
|
1371
|
+
};
|
|
1372
|
+
}
|
|
1373
|
+
const key = keyFor(deps.config.keyPrefix, actor.tier, actor.identity);
|
|
1374
|
+
const limit = tier.points + tier.burst;
|
|
1375
|
+
try {
|
|
1376
|
+
const count = await deps.valkey.incrBy(key, 1);
|
|
1377
|
+
if (count === 1) await deps.valkey.expire(key, tier.duration);
|
|
1378
|
+
const ttl = await deps.valkey.ttl(key);
|
|
1379
|
+
const resetAtMs = stamp() + Math.max(0, ttl) * 1e3;
|
|
1380
|
+
if (count > limit) {
|
|
1381
|
+
metrics.rateLimit.inc({
|
|
1382
|
+
gateway,
|
|
1383
|
+
tier: actor.tier,
|
|
1384
|
+
decision: deps.config.observeOnly ? "observed_reject" : "rejected"
|
|
1385
|
+
});
|
|
1386
|
+
return {
|
|
1387
|
+
allowed: false,
|
|
1388
|
+
remaining: 0,
|
|
1389
|
+
resetAtMs,
|
|
1390
|
+
limit
|
|
1391
|
+
};
|
|
1392
|
+
}
|
|
1393
|
+
metrics.rateLimit.inc({
|
|
1394
|
+
gateway,
|
|
1395
|
+
tier: actor.tier,
|
|
1396
|
+
decision: "allowed"
|
|
1397
|
+
});
|
|
1398
|
+
return {
|
|
1399
|
+
allowed: true,
|
|
1400
|
+
remaining: Math.max(0, limit - count),
|
|
1401
|
+
resetAtMs,
|
|
1402
|
+
limit
|
|
1403
|
+
};
|
|
1404
|
+
} catch (err) {
|
|
1405
|
+
const e = err instanceof Error ? err : new Error(String(err));
|
|
1406
|
+
logger.warn("[gateway-security] rate-limit valkey error — fail-open", {
|
|
1407
|
+
key,
|
|
1408
|
+
error: e.message
|
|
1409
|
+
});
|
|
1410
|
+
metrics.valkeyFailover.inc({ gateway });
|
|
1411
|
+
if (deps.config.failClosed) {
|
|
1412
|
+
metrics.rateLimit.inc({
|
|
1413
|
+
gateway,
|
|
1414
|
+
tier: actor.tier,
|
|
1415
|
+
decision: "rejected"
|
|
1416
|
+
});
|
|
1417
|
+
return {
|
|
1418
|
+
allowed: false,
|
|
1419
|
+
remaining: 0,
|
|
1420
|
+
resetAtMs: stamp() + tier.duration * 1e3,
|
|
1421
|
+
limit
|
|
1422
|
+
};
|
|
1423
|
+
}
|
|
1424
|
+
metrics.rateLimit.inc({
|
|
1425
|
+
gateway,
|
|
1426
|
+
tier: actor.tier,
|
|
1427
|
+
decision: "allowed"
|
|
1428
|
+
});
|
|
1429
|
+
return {
|
|
1430
|
+
allowed: true,
|
|
1431
|
+
remaining: -1,
|
|
1432
|
+
resetAtMs: 0,
|
|
1433
|
+
limit
|
|
1434
|
+
};
|
|
1435
|
+
}
|
|
1436
|
+
};
|
|
1437
|
+
/**
|
|
1438
|
+
* Per-workspace AGGREGATE rate limit. The per-actor limiter (checkRateLimit)
|
|
1439
|
+
* caps each user; this caps the whole workspace so that N users in one workspace
|
|
1440
|
+
* cannot collectively starve other workspaces on the shared backend. Runs only
|
|
1441
|
+
* when a workspaceId is present. Emits the decision under `tier: 'workspace'`
|
|
1442
|
+
* (workspaceId is logged, NOT a metric label, to avoid metric cardinality
|
|
1443
|
+
* blow-up). Always fails OPEN on a Valkey error — a fairness signal must never be
|
|
1444
|
+
* an availability dependency.
|
|
1445
|
+
*/
|
|
1446
|
+
const checkWorkspaceRateLimit = async (deps, workspaceId) => {
|
|
1447
|
+
const cfg = deps.config.perWorkspace;
|
|
1448
|
+
const metrics = getMetrics();
|
|
1449
|
+
const gateway = deps.config.keyPrefix;
|
|
1450
|
+
const key = wsKeyFor(deps.config.keyPrefix, workspaceId);
|
|
1451
|
+
const limit = cfg.points + cfg.burst;
|
|
1452
|
+
try {
|
|
1453
|
+
const count = await deps.valkey.incrBy(key, 1);
|
|
1454
|
+
if (count === 1) await deps.valkey.expire(key, cfg.duration);
|
|
1455
|
+
const ttl = await deps.valkey.ttl(key);
|
|
1456
|
+
const resetAtMs = stamp() + Math.max(0, ttl) * 1e3;
|
|
1457
|
+
if (count > limit) {
|
|
1458
|
+
metrics.rateLimit.inc({
|
|
1459
|
+
gateway,
|
|
1460
|
+
tier: "workspace",
|
|
1461
|
+
decision: cfg.observeOnly ? "observed_reject" : "rejected"
|
|
1462
|
+
});
|
|
1463
|
+
logger.warn("[gateway-security] workspace rate-limit exceeded", {
|
|
1464
|
+
workspaceId,
|
|
1465
|
+
count,
|
|
1466
|
+
limit,
|
|
1467
|
+
observe: cfg.observeOnly
|
|
1468
|
+
});
|
|
1469
|
+
return {
|
|
1470
|
+
allowed: false,
|
|
1471
|
+
remaining: 0,
|
|
1472
|
+
resetAtMs,
|
|
1473
|
+
limit
|
|
1474
|
+
};
|
|
1475
|
+
}
|
|
1476
|
+
metrics.rateLimit.inc({
|
|
1477
|
+
gateway,
|
|
1478
|
+
tier: "workspace",
|
|
1479
|
+
decision: "allowed"
|
|
1480
|
+
});
|
|
1481
|
+
return {
|
|
1482
|
+
allowed: true,
|
|
1483
|
+
remaining: Math.max(0, limit - count),
|
|
1484
|
+
resetAtMs,
|
|
1485
|
+
limit
|
|
1486
|
+
};
|
|
1487
|
+
} catch (err) {
|
|
1488
|
+
const e = err instanceof Error ? err : new Error(String(err));
|
|
1489
|
+
logger.warn("[gateway-security] workspace rate-limit valkey error — fail-open", {
|
|
1490
|
+
key,
|
|
1491
|
+
error: e.message
|
|
1492
|
+
});
|
|
1493
|
+
metrics.valkeyFailover.inc({ gateway });
|
|
1494
|
+
return {
|
|
1495
|
+
allowed: true,
|
|
1496
|
+
remaining: -1,
|
|
1497
|
+
resetAtMs: 0,
|
|
1498
|
+
limit
|
|
1499
|
+
};
|
|
1500
|
+
}
|
|
1501
|
+
};
|
|
1502
|
+
/**
|
|
1503
|
+
* Yoga/Envelop plugin factory.
|
|
1504
|
+
*/
|
|
1505
|
+
const createRateLimitPlugin = (deps) => {
|
|
1506
|
+
return {
|
|
1507
|
+
onRequest: async ({ request, fetchAPI, endResponse }) => {
|
|
1508
|
+
const actor = resolveActor((name) => request.headers.get(name));
|
|
1509
|
+
const result = await checkRateLimit(deps, actor);
|
|
1510
|
+
request.__rateLimitResult = result;
|
|
1511
|
+
request.__rateLimitActor = actor;
|
|
1512
|
+
const workspaceId = actor.headers.workspaceId;
|
|
1513
|
+
if (deps.config.perWorkspace.enabled && workspaceId) {
|
|
1514
|
+
const wsResult = await checkWorkspaceRateLimit(deps, workspaceId);
|
|
1515
|
+
if (!wsResult.allowed && !deps.config.perWorkspace.observeOnly) {
|
|
1516
|
+
const retryAfterS = Math.max(1, Math.ceil((wsResult.resetAtMs - stamp()) / 1e3));
|
|
1517
|
+
const body = JSON.stringify({ errors: [{
|
|
1518
|
+
message: "Workspace rate limit exceeded",
|
|
1519
|
+
extensions: {
|
|
1520
|
+
code: "RATE_LIMITED",
|
|
1521
|
+
scope: "workspace",
|
|
1522
|
+
resetAt: new Date(wsResult.resetAtMs).toISOString()
|
|
1523
|
+
}
|
|
1524
|
+
}] });
|
|
1525
|
+
endResponse(new fetchAPI.Response(body, {
|
|
1526
|
+
status: 429,
|
|
1527
|
+
headers: {
|
|
1528
|
+
"content-type": "application/json",
|
|
1529
|
+
"retry-after": String(retryAfterS),
|
|
1530
|
+
"x-ratelimit-scope": "workspace",
|
|
1531
|
+
"x-ratelimit-limit": String(wsResult.limit),
|
|
1532
|
+
"x-ratelimit-remaining": "0",
|
|
1533
|
+
"x-ratelimit-reset": String(Math.floor(wsResult.resetAtMs / 1e3))
|
|
1534
|
+
}
|
|
1535
|
+
}));
|
|
1536
|
+
return;
|
|
1537
|
+
}
|
|
1538
|
+
}
|
|
1539
|
+
if (!result.allowed) {
|
|
1540
|
+
if (deps.config.observeOnly) {
|
|
1541
|
+
logger.info("[gateway-security] rate-limit would_reject (observe)", {
|
|
1542
|
+
tier: actor.tier,
|
|
1543
|
+
identity: actor.identity,
|
|
1544
|
+
limit: result.limit
|
|
1545
|
+
});
|
|
1546
|
+
return;
|
|
1547
|
+
}
|
|
1548
|
+
const retryAfterS = Math.max(1, Math.ceil((result.resetAtMs - stamp()) / 1e3));
|
|
1549
|
+
const body = JSON.stringify({ errors: [{
|
|
1550
|
+
message: "Rate limit exceeded",
|
|
1551
|
+
extensions: {
|
|
1552
|
+
code: "RATE_LIMITED",
|
|
1553
|
+
resetAt: new Date(result.resetAtMs).toISOString()
|
|
1554
|
+
}
|
|
1555
|
+
}] });
|
|
1556
|
+
endResponse(new fetchAPI.Response(body, {
|
|
1557
|
+
status: 429,
|
|
1558
|
+
headers: {
|
|
1559
|
+
"content-type": "application/json",
|
|
1560
|
+
"retry-after": String(retryAfterS),
|
|
1561
|
+
"x-ratelimit-limit": String(result.limit),
|
|
1562
|
+
"x-ratelimit-remaining": "0",
|
|
1563
|
+
"x-ratelimit-reset": String(Math.floor(result.resetAtMs / 1e3))
|
|
1564
|
+
}
|
|
1565
|
+
}));
|
|
1566
|
+
}
|
|
1567
|
+
},
|
|
1568
|
+
onResponse: ({ request, response }) => {
|
|
1569
|
+
const stash = request.__rateLimitResult;
|
|
1570
|
+
if (!stash) return;
|
|
1571
|
+
response.headers.set("x-ratelimit-limit", String(stash.limit));
|
|
1572
|
+
response.headers.set("x-ratelimit-remaining", String(Math.max(0, stash.remaining)));
|
|
1573
|
+
if (stash.resetAtMs > 0) response.headers.set("x-ratelimit-reset", String(Math.floor(stash.resetAtMs / 1e3)));
|
|
1574
|
+
}
|
|
1575
|
+
};
|
|
1576
|
+
};
|
|
1577
|
+
|
|
1578
|
+
// src/gateway/security/plugins/index.ts
|
|
1579
|
+
/**
|
|
1580
|
+
* Bootstraps Valkey + OTel side effects and returns the ordered plugin list.
|
|
1581
|
+
* Safe to call once at gateway boot; subsequent calls reuse the initialized
|
|
1582
|
+
* singletons.
|
|
1583
|
+
*
|
|
1584
|
+
* If `options.enabled === false`, returns an empty array — the master kill
|
|
1585
|
+
* switch for instant rollback via env flag.
|
|
1586
|
+
*/
|
|
1587
|
+
const buildSecurityPlugins = async (options) => {
|
|
1588
|
+
if (!options.enabled) {
|
|
1589
|
+
logger.warn("[gateway-security] SECURITY_PLUGINS_ENABLED=false — plugins disabled", { gatewayName: options.gatewayName });
|
|
1590
|
+
return [];
|
|
1591
|
+
}
|
|
1592
|
+
await initializeMetrics();
|
|
1593
|
+
const valkey = await initializeSecurityValkey(options.gatewayName);
|
|
1594
|
+
const plugins = [];
|
|
1595
|
+
const otelPlugin = await createOtelPlugin(options.otel);
|
|
1596
|
+
plugins.push(otelPlugin);
|
|
1597
|
+
const armorPlugins = await createArmorPlugins(options.armor);
|
|
1598
|
+
plugins.push(...armorPlugins);
|
|
1599
|
+
if (options.queryComplexity.enabled) plugins.push(createQueryComplexityPlugin({ config: options.queryComplexity }));
|
|
1600
|
+
plugins.push(createRateLimitPlugin({
|
|
1601
|
+
valkey,
|
|
1602
|
+
config: options.rateLimit
|
|
1603
|
+
}));
|
|
1604
|
+
plugins.push(createOperationTimeoutPlugin({ config: options.operationTimeout }));
|
|
1605
|
+
logger.info("[gateway-security] plugins wired", {
|
|
1606
|
+
gatewayName: options.gatewayName,
|
|
1607
|
+
count: plugins.length,
|
|
1608
|
+
observe: {
|
|
1609
|
+
armor: options.armor.observe,
|
|
1610
|
+
complexity: options.queryComplexity.observe,
|
|
1611
|
+
rateLimit: options.rateLimit.observeOnly
|
|
1612
|
+
},
|
|
1613
|
+
enabled: { complexity: options.queryComplexity.enabled }
|
|
1614
|
+
});
|
|
1615
|
+
return plugins;
|
|
1616
|
+
};
|
|
1617
|
+
|
|
1618
|
+
// src/gateway/security/index.ts
|
|
1619
|
+
var security_exports = /* @__PURE__ */ __exportAll({
|
|
1620
|
+
DEFAULT_ARMOR_CONFIG: () => DEFAULT_ARMOR_CONFIG,
|
|
1621
|
+
DEFAULT_COST_MAP: () => DEFAULT_COST_MAP,
|
|
1622
|
+
DEFAULT_TIERS: () => DEFAULT_TIERS,
|
|
1623
|
+
MemoryValkey: () => MemoryValkey,
|
|
1624
|
+
__resetMetricsForTest: () => __resetMetricsForTest,
|
|
1625
|
+
__setSecurityValkeyForTest: () => __setSecurityValkeyForTest,
|
|
1626
|
+
buildSecurityPlugins: () => buildSecurityPlugins,
|
|
1627
|
+
checkRateLimit: () => checkRateLimit,
|
|
1628
|
+
createArmorPlugins: () => createArmorPlugins,
|
|
1629
|
+
createOperationTimeoutPlugin: () => createOperationTimeoutPlugin,
|
|
1630
|
+
createOtelPlugin: () => createOtelPlugin,
|
|
1631
|
+
createQueryComplexityPlugin: () => createQueryComplexityPlugin,
|
|
1632
|
+
createRateLimitPlugin: () => createRateLimitPlugin,
|
|
1633
|
+
getMetrics: () => getMetrics,
|
|
1634
|
+
getSecurityValkey: () => getSecurityValkey,
|
|
1635
|
+
initializeMetrics: () => initializeMetrics,
|
|
1636
|
+
initializeOtel: () => initializeOtel,
|
|
1637
|
+
initializeSecurityValkey: () => initializeSecurityValkey,
|
|
1638
|
+
mergeCostMap: () => mergeCostMap,
|
|
1639
|
+
resolveActor: () => resolveActor,
|
|
1640
|
+
resolveSecurityOptionsFromEnv: () => resolveSecurityOptionsFromEnv,
|
|
1641
|
+
resolveTiersFromEnv: () => resolveTiersFromEnv,
|
|
1642
|
+
scrapeMetrics: () => scrapeMetrics,
|
|
1643
|
+
shutdownOtel: () => shutdownOtel
|
|
1644
|
+
});
|
|
1645
|
+
|
|
1646
|
+
export { DEFAULT_COST_MAP as C, resolveTiersFromEnv as S, resolveActor as T, getSecurityValkey as _, createQueryComplexityPlugin as a, resolveSecurityOptionsFromEnv as b, shutdownOtel as c, __resetMetricsForTest as d, getMetrics as f, __setSecurityValkeyForTest as g, MemoryValkey as h, createRateLimitPlugin as i, createOperationTimeoutPlugin as l, scrapeMetrics as m, buildSecurityPlugins as n, createOtelPlugin as o, initializeMetrics as p, checkRateLimit as r, initializeOtel as s, security_exports as t, createArmorPlugins as u, initializeSecurityValkey as v, mergeCostMap as w, DEFAULT_TIERS as x, DEFAULT_ARMOR_CONFIG as y };
|
|
1647
|
+
//# sourceMappingURL=security-DIG-95Ic.js.map
|