@lensmcp/cluster 1.25.79 → 1.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/build-scope-patterns.d.ts +1 -11
  2. package/build-scope-patterns.js +1 -1
  3. package/create-webpack-prod.d.ts +1 -27
  4. package/create-webpack-prod.js +1 -1
  5. package/executors/build/build.impl.js +1 -1
  6. package/executors/gateway/daemon.d.ts +43 -0
  7. package/executors/gateway/daemon.js +1 -0
  8. package/executors/gateway/gateway.lib.d.ts +1 -1
  9. package/executors/gateway/gateway.lib.js +1 -1
  10. package/executors/gateway/jwks-verify.d.ts +1 -79
  11. package/executors/gateway/jwks-verify.js +1 -1
  12. package/executors/gateway/main.rollout.d.ts +2 -1
  13. package/executors/gateway/main.rollout.js +1 -24
  14. package/executors/gateway/manifest.d.ts +1 -418
  15. package/executors/gateway/manifest.js +1 -1
  16. package/executors/gateway/prod-runtime/trust.d.ts +1 -80
  17. package/executors/gateway/prod-runtime/trust.js +1 -1
  18. package/executors/gateway/rate-limit.d.ts +1 -81
  19. package/executors/gateway/rate-limit.js +1 -18
  20. package/executors/gateway/runtime/auth.d.ts +1 -1
  21. package/executors/gateway/runtime/auth.js +1 -1
  22. package/executors/gateway/runtime/dev-auth.d.ts +3 -2
  23. package/executors/gateway/runtime/dev-auth.js +1 -1
  24. package/executors/gateway/runtime/discovery.js +1 -1
  25. package/executors/gateway/runtime/edge.d.ts +2 -2
  26. package/executors/gateway/runtime/edge.js +1 -1
  27. package/executors/gateway/runtime/handler.js +1 -1
  28. package/executors/gateway/runtime/internal-fetch.d.ts +1 -1
  29. package/executors/gateway/runtime/lens-children.js +1 -1
  30. package/executors/gateway/runtime/lens-modules.d.ts +13 -0
  31. package/executors/gateway/runtime/lens-modules.js +1 -0
  32. package/executors/gateway/runtime/lifecycle.js +1 -1
  33. package/executors/gateway/runtime/observability.js +1 -1
  34. package/executors/gateway/runtime/proxy.js +1 -1
  35. package/executors/gateway/runtime/route-registry.js +1 -1
  36. package/executors/gateway/runtime/serve-launch.d.ts +27 -0
  37. package/executors/gateway/runtime/serve-launch.js +3 -3
  38. package/executors/gateway/runtime/server.d.ts +1 -1
  39. package/executors/gateway/runtime/server.js +2 -2
  40. package/executors/gateway/runtime/services-decl.d.ts +24 -0
  41. package/executors/gateway/runtime/services-decl.js +1 -0
  42. package/executors/gateway/runtime/shared-build.d.ts +2 -2
  43. package/executors/gateway/runtime/shared-build.js +3 -3
  44. package/executors/gateway/runtime/types.d.ts +9 -3
  45. package/executors/gateway/runtime/upgrade.js +1 -1
  46. package/executors/gateway/runtime/workspace-auth.d.ts +1 -1
  47. package/executors/gateway/runtime/workspace-auth.js +1 -1
  48. package/executors/gateway/runtime/workspace-middleware.d.ts +2 -2
  49. package/executors/gateway/runtime/workspace-middleware.js +1 -1
  50. package/executors/serve/lens-run.d.ts +6 -0
  51. package/executors/serve/lens-run.js +1 -0
  52. package/executors/serve/schema.d.ts +2 -0
  53. package/executors/serve/schema.json +4 -0
  54. package/executors/serve/serve.impl.js +1 -1
  55. package/executors/trust/run.d.ts +19 -0
  56. package/executors/trust/run.js +1 -0
  57. package/executors/trust/trust.impl.js +5 -5
  58. package/gateway.d.ts +7 -19
  59. package/gateway.js +1 -1
  60. package/gc-notice.d.ts +3 -1
  61. package/gc-notice.js +1 -1
  62. package/main.devserver.js +7 -7
  63. package/package.json +6 -34
  64. package/pod-memory.d.ts +19 -2
  65. package/pod-memory.js +1 -1
  66. package/tsgo-check-plugin.d.ts +3 -2
  67. package/tsgo-check-plugin.js +3 -3
  68. package/typecheck-bus.d.ts +17 -0
  69. package/typecheck-bus.js +4 -3
  70. package/executors/gateway/body-stall.d.ts +0 -62
  71. package/executors/gateway/body-stall.js +0 -1
  72. package/executors/gateway/canonical-path.d.ts +0 -65
  73. package/executors/gateway/canonical-path.js +0 -1
  74. package/executors/gateway/client-ip.d.ts +0 -82
  75. package/executors/gateway/client-ip.js +0 -1
  76. package/executors/gateway/gateway-errors.d.ts +0 -43
  77. package/executors/gateway/gateway-errors.js +0 -1
  78. package/executors/gateway/health-check.d.ts +0 -52
  79. package/executors/gateway/health-check.js +0 -1
  80. package/executors/gateway/jwt-claims.d.ts +0 -51
  81. package/executors/gateway/jwt-claims.js +0 -1
  82. package/executors/gateway/main.prod-gateway.d.ts +0 -1
  83. package/executors/gateway/main.prod-gateway.js +0 -2
  84. package/executors/gateway/metrics.d.ts +0 -36
  85. package/executors/gateway/metrics.js +0 -1
  86. package/executors/gateway/otel-tracing.d.ts +0 -46
  87. package/executors/gateway/otel-tracing.js +0 -1
  88. package/executors/gateway/prod-config.d.ts +0 -130
  89. package/executors/gateway/prod-config.js +0 -1
  90. package/executors/gateway/prod-gateway.lib.d.ts +0 -19
  91. package/executors/gateway/prod-gateway.lib.js +0 -1
  92. package/executors/gateway/prod-runtime/access-log.d.ts +0 -8
  93. package/executors/gateway/prod-runtime/access-log.js +0 -1
  94. package/executors/gateway/prod-runtime/app.d.ts +0 -30
  95. package/executors/gateway/prod-runtime/app.js +0 -1
  96. package/executors/gateway/prod-runtime/auth.d.ts +0 -29
  97. package/executors/gateway/prod-runtime/auth.js +0 -1
  98. package/executors/gateway/prod-runtime/body-stall.d.ts +0 -5
  99. package/executors/gateway/prod-runtime/body-stall.js +0 -1
  100. package/executors/gateway/prod-runtime/cors.d.ts +0 -18
  101. package/executors/gateway/prod-runtime/cors.js +0 -1
  102. package/executors/gateway/prod-runtime/edge.d.ts +0 -44
  103. package/executors/gateway/prod-runtime/edge.js +0 -1
  104. package/executors/gateway/prod-runtime/handler.d.ts +0 -33
  105. package/executors/gateway/prod-runtime/handler.js +0 -1
  106. package/executors/gateway/prod-runtime/hooks.d.ts +0 -19
  107. package/executors/gateway/prod-runtime/hooks.js +0 -1
  108. package/executors/gateway/prod-runtime/observability.d.ts +0 -24
  109. package/executors/gateway/prod-runtime/observability.js +0 -1
  110. package/executors/gateway/prod-runtime/rollout.d.ts +0 -33
  111. package/executors/gateway/prod-runtime/rollout.js +0 -1
  112. package/executors/gateway/prod-runtime/route-limits.d.ts +0 -30
  113. package/executors/gateway/prod-runtime/route-limits.js +0 -1
  114. package/executors/gateway/prod-runtime/routing.d.ts +0 -3
  115. package/executors/gateway/prod-runtime/routing.js +0 -1
  116. package/executors/gateway/prod-runtime/server.d.ts +0 -17
  117. package/executors/gateway/prod-runtime/server.js +0 -1
  118. package/executors/gateway/prod-runtime/types.d.ts +0 -335
  119. package/executors/gateway/prod-runtime/types.js +0 -1
  120. package/executors/gateway/prod-runtime/upgrade.d.ts +0 -23
  121. package/executors/gateway/prod-runtime/upgrade.js +0 -16
  122. package/executors/gateway/prod-runtime/upstream-errors.d.ts +0 -33
  123. package/executors/gateway/prod-runtime/upstream-errors.js +0 -1
  124. package/executors/gateway/prod-runtime/upstream.d.ts +0 -14
  125. package/executors/gateway/prod-runtime/upstream.js +0 -1
  126. package/executors/gateway/providers-prod.d.ts +0 -54
  127. package/executors/gateway/providers-prod.js +0 -1
  128. package/executors/gateway/registry-source.d.ts +0 -68
  129. package/executors/gateway/registry-source.js +0 -2
  130. package/executors/gateway/rollout-ops.d.ts +0 -53
  131. package/executors/gateway/rollout-ops.js +0 -2
  132. package/executors/gateway/ssrf-guard.d.ts +0 -96
  133. package/executors/gateway/ssrf-guard.js +0 -1
  134. package/executors/gateway/workspace-auth.d.ts +0 -100
  135. package/executors/gateway/workspace-auth.js +0 -1
@@ -1,43 +0,0 @@
1
- import type * as http from 'node:http';
2
- /**
3
- * The gateway's EDGE error contract — shared by the dev (`gateway.lib.ts`) and prod
4
- * (`prod-gateway.lib.ts`) gateways so an error the gateway generates ITSELF (before/instead of an
5
- * upstream) has the SAME shape as an error a service returns.
6
- *
7
- * Two properties the gateway guarantees for every request:
8
- * 1. **JSON, not `text/plain`.** A gateway-generated 4xx/5xx is the JSON envelope
9
- * `{ key, status, traceId, message? }` — the same `{ key, status }` localized contract the house
10
- * `ApiError` uses, so a browser app renders `t(key)` (a localized message) AND can read the trace id.
11
- * `key` is a framework-NEUTRAL `gateway.*` slug; the consumer ships the `gateway.*` translations.
12
- * `message` is a developer-facing hint (never shown to users), preserving the old plain-text detail.
13
- * 2. **A trace id on EVERY request.** {@link ensureRequestId} mints `x-request-id` at the edge if the
14
- * client didn't send one, so the SAME id is forwarded to the upstream (the pod adopts it as its
15
- * trace id) AND returned to the client — making any request traceable end-to-end, not just lensmcp
16
- * flow-traced ones.
17
- *
18
- * This keeps the gateway generic (no consumer-specific keys baked in beyond the neutral `gateway.*`
19
- * namespace) while integrating cleanly with a localized-error system.
20
- */
21
- export type GatewayErrorReason = 'bad_request' | 'unauthorized' | 'forbidden' | 'not_found' | 'rate_limited' | 'starting' | 'unavailable' | 'internal';
22
- /** Reason → stable, neutral localized key (the consumer translates the `gateway.*` namespace). */
23
- export declare const GATEWAY_ERROR_KEY: Record<GatewayErrorReason, string>;
24
- /**
25
- * Ensure the request carries an `x-request-id` (mint one at the edge if absent) and return it. Because
26
- * the gateway forwards `req.headers` to the upstream, the pod's request-context adopts THIS id as its
27
- * `traceId`, and the gateway returns it on the response — one id, end-to-end, for ANY request.
28
- */
29
- export declare function ensureRequestId(req: http.IncomingMessage): string;
30
- /**
31
- * The grammar a CLIENT's `x-request-id` must match to be adopted as the edge trace id: a short token. Anything else
32
- * — 4 KB of markup, non-ASCII bytes, a CR the parser let through as obs-text — is replaced by a minted id (PG3-26):
33
- * the id is forwarded to every upstream, echoed to the client and indexed by every log and trace store downstream,
34
- * so adopting it verbatim was log/trace injection and a free 16 KB header per request.
35
- */
36
- export declare const REQUEST_ID_GRAMMAR: RegExp;
37
- export declare const validRequestId: (v: string) => boolean;
38
- /**
39
- * Build the JSON edge-error body `{ key, status, traceId, message? }`. `detail` becomes the dev-facing
40
- * `message` (e.g. the old plain-text reason), never surfaced to end users.
41
- */
42
- export declare function gatewayErrorBody(status: number, reason: GatewayErrorReason, traceId: string, detail?: string, metadata?: Readonly<Record<string, unknown>>): string;
43
- export declare const GATEWAY_ERROR_CONTENT_TYPE = "application/json; charset=utf-8";
@@ -1 +0,0 @@
1
- "use strict";var i=Object.defineProperty;var s=(e,t)=>i(e,"name",{value:t,configurable:!0});var o=Object.defineProperty,r=s((e,t)=>o(e,"name",{value:t,configurable:!0}),"r");Object.defineProperty(exports,"__esModule",{value:!0}),exports.GATEWAY_ERROR_CONTENT_TYPE=exports.validRequestId=exports.REQUEST_ID_GRAMMAR=exports.GATEWAY_ERROR_KEY=void 0,exports.ensureRequestId=ensureRequestId,exports.gatewayErrorBody=gatewayErrorBody,exports.GATEWAY_ERROR_KEY={bad_request:"gateway.badRequest",unauthorized:"gateway.unauthorized",forbidden:"gateway.forbidden",not_found:"gateway.notFound",rate_limited:"gateway.rateLimited",starting:"gateway.starting",unavailable:"gateway.unavailable",internal:"gateway.internal"};const headerValue=r(e=>typeof e=="string"&&e!==""?e:Array.isArray(e)?e[0]:void 0,"headerValue"),mintId=r(()=>Date.now().toString(36)+Math.random().toString(36).slice(2,12),"mintId");function ensureRequestId(e){const t=headerValue(e.headers["x-request-id"]);if(t&&(0,exports.validRequestId)(t))return t;const a=mintId();return e.headers["x-request-id"]=a,a}s(ensureRequestId,"ensureRequestId"),r(ensureRequestId,"ensureRequestId"),exports.REQUEST_ID_GRAMMAR=/^[A-Za-z0-9._-]{1,128}$/;const validRequestId=r(e=>exports.REQUEST_ID_GRAMMAR.test(e),"validRequestId");exports.validRequestId=validRequestId;function gatewayErrorBody(e,t,a,n,d){return JSON.stringify({...d??{},key:exports.GATEWAY_ERROR_KEY[t],status:e,traceId:a,...n?{message:n}:{}})}s(gatewayErrorBody,"gatewayErrorBody"),r(gatewayErrorBody,"gatewayErrorBody"),exports.GATEWAY_ERROR_CONTENT_TYPE="application/json; charset=utf-8";
@@ -1,52 +0,0 @@
1
- /**
2
- * Active upstream health-checking — opt-in. Periodically probes every known
3
- * upstream URL and tracks healthy/unhealthy per endpoint, so the gateway routes
4
- * a pooled service AROUND dead endpoints (instead of only discovering death
5
- * passively, one failed request at a time) and the /statusz rollup reflects true
6
- * liveness even with zero traffic.
7
- *
8
- * Liveness, not readiness: a probe is "healthy" when the endpoint ANSWERS with
9
- * status < 500 — so a service without the health path still reads up on a 404;
10
- * only a 5xx or a connection failure/timeout is down. New endpoints start
11
- * optimistically healthy, so a not-yet-probed endpoint is never black-holed.
12
- *
13
- * Fail-open by design (see providers-prod `pick`): only multi-endpoint POOLS are
14
- * health-filtered, and even then the gateway falls back to an unhealthy endpoint
15
- * rather than 503 if a whole pool looks down — a checker false-positive must
16
- * never take a service fully offline.
17
- */
18
- export interface HealthCheckerOptions {
19
- /** Probe path appended to each upstream URL. Default `/healthz`. */
20
- path?: string;
21
- /** Probe period (ms). Default 5000. */
22
- intervalMs?: number;
23
- /** Per-probe timeout (ms). Default 2000. */
24
- timeoutMs?: number;
25
- /** Consecutive failures before an endpoint is marked unhealthy. Default 2. */
26
- unhealthyThreshold?: number;
27
- /** Consecutive successes before a down endpoint is marked healthy again. Default 1. */
28
- healthyThreshold?: number;
29
- /** Injectable fetch (tests). Defaults to global fetch. */
30
- fetchImpl?: typeof fetch;
31
- /** Notified when an endpoint flips health. */
32
- onChange?: (url: string, healthy: boolean) => void;
33
- }
34
- export interface EndpointHealth {
35
- url: string;
36
- healthy: boolean;
37
- fails: number;
38
- lastCheckedAt: number | null;
39
- }
40
- export interface HealthChecker {
41
- /** Set the current URL set to monitor (called on every route rebuild). */
42
- track(urls: string[]): void;
43
- /** Current health (default true for an untracked / not-yet-probed URL). */
44
- isHealthy(url: string): boolean;
45
- /** Per-endpoint health for the status page. */
46
- snapshot(): EndpointHealth[];
47
- /** Probe every tracked URL once (used by start()'s loop and by tests). */
48
- probeOnce(): Promise<void>;
49
- start(): void;
50
- stop(): void;
51
- }
52
- export declare function createHealthChecker(opts?: HealthCheckerOptions): HealthChecker;
@@ -1 +0,0 @@
1
- "use strict";var g=Object.defineProperty;var c=(a,r)=>g(a,"name",{value:r,configurable:!0});var C=Object.defineProperty,l=c((a,r)=>C(a,"name",{value:r,configurable:!0}),"l");Object.defineProperty(exports,"__esModule",{value:!0}),exports.createHealthChecker=createHealthChecker;function createHealthChecker(a={}){const r=a.path??"/healthz",y=a.intervalMs??5e3,f=a.timeoutMs??2e3,p=Math.max(1,a.unhealthyThreshold??2),d=Math.max(1,a.healthyThreshold??1),u=a.fetchImpl??globalThis.fetch,s=new Map;let n;const k=l(t=>t.replace(/\/+$/,"")+(r.startsWith("/")?r:"/"+r),"probeUrl"),m=l(async t=>{const e=s.get(t);if(!e)return;let h=!1;const i=new AbortController,b=setTimeout(()=>i.abort(),f);try{h=(await u(k(t),{method:"GET",signal:i.signal,redirect:"manual",headers:{"accept-encoding":"identity"}})).status<500}catch{}finally{clearTimeout(b)}e.lastCheckedAt=Date.now(),h?(e.oks+=1,e.fails=0,!e.healthy&&e.oks>=d&&(e.healthy=!0,a.onChange?.(t,!0))):(e.fails+=1,e.oks=0,e.healthy&&e.fails>=p&&(e.healthy=!1,a.onChange?.(t,!1)))},"probe"),o=l(()=>Promise.allSettled([...s.keys()].map(m)).then(()=>{}),"probeOnce");return{track(t){const e=new Set(t);for(const h of t)s.has(h)||s.set(h,{healthy:!0,fails:0,oks:0,lastCheckedAt:null});for(const h of[...s.keys()])e.has(h)||s.delete(h)},isHealthy:l(t=>s.get(t)?.healthy??!0,"isHealthy"),snapshot:l(()=>[...s.entries()].map(([t,e])=>({url:t,healthy:e.healthy,fails:e.fails,lastCheckedAt:e.lastCheckedAt})),"snapshot"),probeOnce:o,start(){n||(n=setInterval(()=>{o()},y),n.unref?.(),o())},stop(){n&&clearInterval(n),n=void 0}}}c(createHealthChecker,"createHealthChecker"),l(createHealthChecker,"createHealthChecker");
@@ -1,51 +0,0 @@
1
- /**
2
- * The standard JWT claim checks, in ONE place, for BOTH verifiers.
3
- *
4
- * They used to exist only in `jwks-verify.ts`. The HS256 fallback in `main.prod-gateway.ts` checked
5
- * the HMAC and `exp` and nothing else — no `nbf`, no `iss`, no `aud` — while
6
- * `docs/lensmcp/concepts/prod-gateway-config.mdx` documents `LENSMCP_GW_JWT_ISS` and
7
- * `LENSMCP_GW_JWT_AUD` as the required restrictions for the fallback it also documents. An operator
8
- * following that table configured an identity control that did not exist, and a token signed with
9
- * the same shared key by another issuer or for another audience was accepted, satisfied edge ABAC,
10
- * and was stamped into gateway-owned `x-user-*` headers (issues/closed/codex-security-01).
11
- *
12
- * Two verifiers that must agree about identity should not each carry their own copy of the rules.
13
- */
14
- /** Seconds of clock skew tolerated on `exp` and `nbf`. */
15
- export declare const DEFAULT_CLOCK_TOLERANCE_S = 60;
16
- export interface StandardClaimOptions {
17
- /** Required `iss`. Unset ⇒ not enforced. */
18
- issuer?: string;
19
- /** Allowed `aud` values; a token matching ANY of them passes. Unset ⇒ not enforced. */
20
- audience?: readonly string[];
21
- /** Clock skew allowance in seconds. Defaults to {@link DEFAULT_CLOCK_TOLERANCE_S}. */
22
- clockToleranceS?: number;
23
- /** Refuse a token with no numeric `exp`. Default TRUE: a token that never expires is valid forever once leaked
24
- * (PG3-06). Pass `false` only for an issuer known to mint expiry-less tokens on purpose. */
25
- requireExp?: boolean;
26
- }
27
- /**
28
- * Are a verified token's registered claims acceptable?
29
- *
30
- * Call this only AFTER the signature has been verified — it says nothing about authenticity, only
31
- * about whether an authentic token is one this gateway should accept.
32
- *
33
- * A configured restriction fails closed: with an `issuer` configured, a token carrying no `iss` is
34
- * rejected rather than treated as unrestricted. `iss`/`aud` the operator did not configure are not enforced here —
35
- * the production entry refuses to BOOT a verifier without an audience instead (`jwtBootProblems`, PG3-06). A numeric
36
- * `exp` is required unless `requireExp: false`.
37
- */
38
- export declare function checkStandardClaims(payload: Record<string, unknown>, opts: StandardClaimOptions): boolean;
39
- /**
40
- * The elements of a `roles` / `perms` claim that may be stamped, and how many were refused (issues/closed/prod-gateway-4-12).
41
- *
42
- * The edge used to write `claim.map(String).join(',')`. One element `"viewer,admin"` then reached the service as TWO
43
- * roles, a nested `["viewer","admin"]` did the same, and an object became `[object Object]` — while the edge's own
44
- * permission check compared whole elements and saw none of that. An upstream that splits the header on `,` and the
45
- * edge that judged the request disagreed about what the caller holds. An element that is not a plain token is
46
- * dropped, never rewritten: dropping can only take a privilege away.
47
- */
48
- export declare function identityList(claim: unknown): {
49
- values: string[];
50
- dropped: number;
51
- };
@@ -1 +0,0 @@
1
- "use strict";var u=Object.defineProperty;var o=(t,e)=>u(t,"name",{value:e,configurable:!0});var f=Object.defineProperty,i=o((t,e)=>f(t,"name",{value:e,configurable:!0}),"i");Object.defineProperty(exports,"__esModule",{value:!0}),exports.DEFAULT_CLOCK_TOLERANCE_S=void 0,exports.checkStandardClaims=checkStandardClaims,exports.identityList=identityList,exports.DEFAULT_CLOCK_TOLERANCE_S=60;function checkStandardClaims(t,e){const s=e.clockToleranceS??exports.DEFAULT_CLOCK_TOLERANCE_S,r=Date.now()/1e3;if(typeof t.exp!="number"){if(e.requireExp!==!1)return!1}else if(r>t.exp+s)return!1;if(typeof t.nbf=="number"&&r<t.nbf-s||e.issuer&&t.iss!==e.issuer)return!1;if(e.audience&&e.audience.length>0){const n=t.aud;if(!(Array.isArray(n)?n:[n]).some(a=>typeof a=="string"&&e.audience.includes(a)))return!1}return!0}o(checkStandardClaims,"checkStandardClaims"),i(checkStandardClaims,"checkStandardClaims");const IDENTITY_TOKEN=/^[A-Za-z0-9._:@*/+=-]+(?: [A-Za-z0-9._:@*/+=-]+)*$/,MAX_IDENTITY_TOKEN=256;function identityList(t){if(!Array.isArray(t))return{values:[],dropped:0};const e=[];let s=0;for(const r of t){const n=typeof r=="string"?r:typeof r=="number"&&Number.isFinite(r)?String(r):void 0;n!==void 0&&n.length<=MAX_IDENTITY_TOKEN&&IDENTITY_TOKEN.test(n)?e.push(n):s+=1}return{values:e,dropped:s}}o(identityList,"identityList"),i(identityList,"identityList");
@@ -1 +0,0 @@
1
- export {};
@@ -1,2 +0,0 @@
1
- "use strict";var Ee=Object.defineProperty;var M=(t,e)=>Ee(t,"name",{value:e,configurable:!0});var ue=Object.defineProperty,a=M((t,e)=>ue(t,"name",{value:e,configurable:!0}),"a");Object.defineProperty(exports,"__esModule",{value:!0});const tslib_1=require("tslib"),node_fs_1=require("node:fs"),node_crypto_1=require("node:crypto"),node_path_1=require("node:path"),node_os_1=require("node:os"),node_cluster_1=tslib_1.__importDefault(require("node:cluster")),prod_gateway_lib_1=require("./prod-gateway.lib"),jwt_claims_1=require("./jwt-claims"),jwks_verify_1=require("./jwks-verify"),otel_tracing_1=require("./otel-tracing"),health_check_1=require("./health-check"),rate_limit_1=require("./rate-limit"),metrics_1=require("./metrics"),edge_1=require("./prod-runtime/edge"),registry_source_1=require("./registry-source"),providers_prod_1=require("./providers-prod"),prod_config_1=require("./prod-config");function readJson(t,e){if(!t)return e;try{return JSON.parse((0,node_fs_1.readFileSync)(t,"utf8"))}catch(n){return console.error(`[gateway] could not read ${t}:`,n.message),e}}M(readJson,"readJson"),a(readJson,"readJson");function watchJsonFile(t,e,n=1e3){let u=-1;const _=setInterval(a(()=>{if(!(0,node_fs_1.existsSync)(t))return;let p;try{p=(0,node_fs_1.statSync)(t).mtimeMs}catch{return}if(p===u)return;let f;try{f=JSON.parse((0,node_fs_1.readFileSync)(t,"utf8"))}catch(g){console.error("[gateway] endpoints reload:",g.message);return}u=p,e(f)},"tick"),n);return _.unref?.(),()=>clearInterval(_)}M(watchJsonFile,"watchJsonFile"),a(watchJsonFile,"watchJsonFile");async function main(){const t=process.env,e=(0,prod_config_1.parseGatewayEnv)(t),n=e.ports;process.on("uncaughtException",r=>console.error("[gateway] uncaughtException:",r)),process.on("unhandledRejection",r=>console.error("[gateway] unhandledRejection:",r));const u=[];let _=!1;const p=a(async r=>{if(!_){_=!0,console.log(`[gateway] ${r} \u2014 draining\u2026`);for(const s of u)try{await s()}catch{}process.exit(0)}},"shutdown");for(const r of["SIGTERM","SIGINT"])process.on(r,()=>{p(r)});const f=t.LENSMCP_GW_REDIS_URL;let g,y,A,j;const F={};let w;if(f){const r=require("ioredis"),s=new r(f);w=s;const o=(0,registry_source_1.createRegistryProviders)((0,registry_source_1.redisRegistrySource)(s,t.LENSMCP_GW_REDIS_PREFIX?{prefix:t.LENSMCP_GW_REDIS_PREFIX}:{}),{onError:a(i=>console.error("[gateway] registry:",i instanceof Error?i.message:i),"onError")});await o.start(),g=o.manifests,y=o.pods,j=o,console.log(`[gateway] registry: Redis-backed, live (${g.list().length} service(s))`)}else{const r=t.LENSMCP_GW_MANIFESTS;r?g=(0,providers_prod_1.fileManifestProvider)(r,{onError:a(o=>console.error("[gateway] manifest:",o instanceof Error?o.message:o),"onError")}):(console.warn("[gateway] no LENSMCP_GW_MANIFESTS / LENSMCP_GW_REDIS_URL \u2014 starting with an EMPTY route table (all requests 404 until manifests arrive)."),g=(0,providers_prod_1.staticManifestProvider)([]));const s=t.LENSMCP_GW_ENDPOINTS;if(s){const o=a(E=>console.error("[gateway] endpoints:",E instanceof Error?E.message:E),"onEpError"),i=readJson(s,{}),c=Object.keys(i).length,l=(0,providers_prod_1.isRolloutShape)(i);y=l?(0,providers_prod_1.rolloutPodProvider)(i,{onError:o}):(0,providers_prod_1.endpointsPodProvider)(i,{onError:o}),console.log(c?`[gateway] endpoints: ${l?"ROLLOUT (weighted cohorts)":"flat"} \u2014 ${c} service(s)`:`[gateway] endpoints: ${(0,node_fs_1.existsSync)(s)?"present but empty/unreadable":"file not there yet"} \u2014 watching ${s}`),A=watchJsonFile(s,E=>{try{y?.update?.(E),F.current?.refreshUpstreams(),console.log("[gateway] endpoints reloaded")}catch(_e){console.error("[gateway] endpoints reload failed:",_e.message)}})}}const k=t.LENSMCP_GW_KEYS,se=readJson(k,{}),D=t.LENSMCP_GW_TLS_KEY&&t.LENSMCP_GW_TLS_CERT?{key:(0,node_fs_1.readFileSync)(t.LENSMCP_GW_TLS_KEY),cert:(0,node_fs_1.readFileSync)(t.LENSMCP_GW_TLS_CERT)}:void 0,C=(0,prod_config_1.jwtBootProblems)(e.jwt);for(const r of C.warnings)console.warn(`[gateway] WARNING: ${r}`);if(C.errors.length)throw new Error(C.errors.join("; "));const oe=e.jwt.presenceOnly,q=e.jwt.jwksUrl,P=e.jwt.secret,S=q?(0,jwks_verify_1.createJwksVerifier)({jwksUrl:q,...e.jwt.issuer?{issuer:e.jwt.issuer}:{},...e.jwt.audience?{audience:e.jwt.audience}:{}}):void 0,ie=a(r=>{if(!P)return;const s=r.split(".");if(s.length===3)try{if(JSON.parse(Buffer.from(s[0],"base64url").toString()).alg!=="HS256")return;const o=(0,node_crypto_1.createHmac)("sha256",P).update(s[0]+"."+s[1]).digest("base64url"),i=Buffer.from(s[2]),c=Buffer.from(o);if(i.length!==c.length||!(0,node_crypto_1.timingSafeEqual)(i,c))return;const l=JSON.parse(Buffer.from(s[1],"base64url").toString());return(0,jwt_claims_1.checkStandardClaims)(l,{...e.jwt.issuer?{issuer:e.jwt.issuer}:{},...e.jwt.audience?.length?{audience:e.jwt.audience}:{}})?l:void 0}catch{return}},"hs256"),x=a(r=>{const s=String(r.headers.authorization??"");if(!s.startsWith("Bearer "))return;const o=s.slice(7);return S?S.verify(o):ie(o)},"bearerClaims"),U=S?(0,jwks_verify_1.bearerIdentify)(S):P?x:void 0,ne=a((r,s)=>{if(r==="jwt"){if(S||P){if(!x(s))throw new Error("invalid or missing token");return}if(!oe)throw new Error("jwt route but no verifier configured (set LENSMCP_GW_JWKS_URL or LENSMCP_GW_JWT_SECRET)");if(!String(s.headers.authorization??"").startsWith("Bearer "))throw new Error("missing bearer token")}},"authenticate"),{attributeHeaders:J,trustProxyHops:ae,trustProxyIp:H,uidHeader:K,cookie:B}=e,m=t.LENSMCP_EVENT_FILE,z=m?(()=>{try{return require("@lensmcp/node-instrumentation")}catch{return}})():void 0,X=z?.createEventFloodGuard({burst:30,perSec:5});let Y=!1;const b=m?r=>{try{const s=X?X.admit(String(r.fingerprint??"")):{ok:!0,suppressed:0};if(!s.ok)return;Y||((0,node_fs_1.mkdirSync)((0,node_path_1.dirname)(m),{recursive:!0}),Y=!0);const o=r.raw,i=JSON.stringify(s.suppressed>0?{...r,raw:{...o,floodSuppressed:s.suppressed}}:r)+`
2
- `;z?.maybeRotateEventFile(m,i.length),(0,node_fs_1.appendFileSync)(m,i)}catch{}}:void 0;if(S)try{await S.refresh(),console.log("[gateway] JWKS loaded")}catch(r){console.error("[gateway] initial JWKS load failed (will retry in background):",r.message)}const{accessLog:ce,clientIpHeader:V,clientIpTrustedProxies:Q,undici:d}=e;if(e.mtlsFromRedis&&w){const r=t.LENSMCP_GW_REDIS_PREFIX??"lensmcp:gw",[s,o,i]=await w.mget(`${r}:mtls:cert`,`${r}:mtls:key`,`${r}:mtls:ca`);s&&(d.cert=s),o&&(d.key=o),i&&(d.ca=i),(s||o)&&console.log("[gateway] mTLS materials loaded from Redis")}else t.LENSMCP_GW_MTLS_CERT&&(d.cert=(0,node_fs_1.readFileSync)(t.LENSMCP_GW_MTLS_CERT)),t.LENSMCP_GW_MTLS_KEY&&(d.key=(0,node_fs_1.readFileSync)(t.LENSMCP_GW_MTLS_KEY)),t.LENSMCP_GW_MTLS_CA&&(d.ca=(0,node_fs_1.readFileSync)(t.LENSMCP_GW_MTLS_CA));(0,prod_config_1.finalizeUpstreamTls)(d).autoEnabled&&console.log("[gateway] upstream TLS verification ENABLED (a CA is configured; set LENSMCP_GW_UPSTREAM_TLS_VERIFY=0 to opt out)"),(0,prod_config_1.finalizeUpstreamH2)(d,t)&&console.log(`[gateway] mTLS to upstreams ON over ${d.allowH2?"h2":"h1.1"} (server validation ${d.rejectUnauthorized?"enabled":"OFF"})`);const{upstreamRetries:G,server:Z}=e,T=(0,otel_tracing_1.setupTracing)({...t.OTEL_SERVICE_NAME?{serviceName:t.OTEL_SERVICE_NAME}:{},...t.LENSMCP_GW_OTEL_SAMPLE?{sampleRatio:Number(t.LENSMCP_GW_OTEL_SAMPLE)}:{}});T&&console.log(`[gateway] OTLP tracing on \u2192 ${(0,edge_1.safeUrl)(t.OTEL_EXPORTER_OTLP_ENDPOINT)}`);const{statusEnabled:N,statusToken:h}=e,ee=(0,node_os_1.hostname)(),le=e.statusTtlSec,te=w,W=N&&te?r=>{for(const s of r)te.set(`status:${s.service}:${ee}`,JSON.stringify({...s,instance:ee,at:Date.now()}),"EX",le).catch(()=>{})}:void 0;N&&!h&&console.warn("[gateway] LENSMCP_GW_STATUS=1 but no LENSMCP_GW_STATUS_TOKEN \u2014 /statusz stays DISABLED (404) until a token is set (fail-closed). The Redis status:* fan-out still runs."),N&&console.log(`[gateway] status on \u2014 /statusz${h?"":" (endpoint disabled: no token)"}${W?" + Redis status:* fan-out":""}`);const $=e.health?(0,health_check_1.createHealthChecker)(e.health):void 0;$&&console.log(`[gateway] active health-checking on (path ${e.health?.path??"/healthz"})`);let L,I;if(e.rateLimit){const{limit:r,windowMs:s,wantRedis:o,failClosed:i}=e.rateLimit;if(o){const c=e.rateLimit.dedicatedUrl;let l;if(c){const E=require("ioredis");I=new E(c),l=I}else w&&(l=w);l?(L=(0,rate_limit_1.createRedisRateLimiter)(l,{limit:r,windowMs:s,prefix:`${t.LENSMCP_GW_REDIS_PREFIX??"lensmcp:gw"}:rl:`,...e.rateLimit.timeoutMs!==void 0?{timeoutMs:e.rateLimit.timeoutMs}:{},...i?{failOpen:!1}:{},onFailure:a(E=>console.error(`[gateway] RATE LIMITER DEGRADED \u2014 Redis unusable (${E}). Requests are being ${i?"DENIED":"ALLOWED"} without a limit check. Check the ACL covers ${t.LENSMCP_GW_REDIS_PREFIX??"lensmcp:gw"}:rl:*`),"onFailure")}),console.log(`[gateway] rate limit on \u2014 ${r} req / ${s}ms GLOBAL (Redis: ${c?"dedicated":"shared registry"}, fail-${i?"closed":"open"}) per client IP`)):console.warn("[gateway] LENSMCP_GW_RATE_LIMIT_REDIS set but no Redis configured (set LENSMCP_GW_REDIS_URL or LENSMCP_GW_RATE_LIMIT_REDIS_URL) \u2014 falling back to PER-INSTANCE in-memory limiting.")}if(!L){const c=(0,prod_config_1.workerCount)(t),l=(0,prod_config_1.perWorkerLimit)(r,c);L=(0,rate_limit_1.createRateLimiter)({limit:l,windowMs:s}),console.log(`[gateway] rate limit on \u2014 ${r} req / ${s}ms per client IP (in-memory`+(c>1?`, ${l}/worker \xD7 ${c} workers`:", per-instance")+")")}}let v;if(e.hostOwnersFile){const r=JSON.parse((0,node_fs_1.readFileSync)(e.hostOwnersFile,"utf8"));if(!r||typeof r!="object"||Array.isArray(r)||!Object.values(r).every(s=>Array.isArray(s)&&s.every(o=>typeof o=="string")))throw new Error(`LENSMCP_GW_HOST_OWNERS (${e.hostOwnersFile}) must be { "<host pattern>": ["<service>", \u2026] }`);v=r,console.log(`[gateway] host owners: ${Object.keys(v).length} pattern(s) \u2014 a mount on an owned host by another service is dropped`)}const re=e.rateLimit?.wantRedis?I??w:void 0,O=e.metricsEnabled?(0,metrics_1.createProcessMetrics)():void 0;O&&console.log(`[gateway] process metrics on \u2014 /metricsz${h?" (token-gated)":" (DISABLED: needs LENSMCP_GW_STATUS_TOKEN)"}`);const R=await(0,prod_gateway_lib_1.startProdGateway)({...n.length?{ports:n}:{},...e.host?{host:e.host}:{},manifests:g,...y?{pods:y}:{},serviceKeys:se,authenticate:ne,...D?{tls:D}:{},...b?{emit:b}:{},...U?{identify:U}:{},...J.length?{attributeHeaders:J}:{},...H?{trustProxyIp:H,trustProxyHops:ae}:{},...B?{cookie:B}:{},...K?{uidHeader:K}:{},...ce?{accessLog:!0}:{},...V?{clientIpHeader:V}:{},...Q.length?{clientIpTrustedProxies:Q}:{},...T?{tracing:T}:{},...N?{statusEndpoint:!0}:{},...h?{statusToken:h}:{},...W?{onStatus:W}:{},...$?{healthChecker:$}:{},...L?{rateLimiter:L}:{},...O?{metrics:O}:{},...e.trafficFlushMs!==void 0?{trafficFlushMs:e.trafficFlushMs}:{},...G!==void 0&&Number.isFinite(G)?{upstreamRetries:G}:{},...Object.keys(d).length?{undici:d}:{},...Object.keys(Z).length?{server:Z}:{},...e.internalPeers.length?{internalPeers:e.internalPeers}:{},...Object.keys(e.upgrades).length?{upgrades:e.upgrades}:{},...e.proxySecret?{clientIpProxySecret:e.proxySecret}:{},...v?{hostOwners:v}:{},...re?{routeLimiter:a((r,s)=>(0,rate_limit_1.createRedisRateLimiter)(re,{limit:r,windowMs:s,prefix:`${t.LENSMCP_GW_REDIS_PREFIX??"lensmcp:gw"}:rl:route:`,...e.rateLimit?.timeoutMs!==void 0?{timeoutMs:e.rateLimit.timeoutMs}:{},...e.rateLimit?.failClosed?{failOpen:!1}:{}}),"routeLimiter")}:{}});F.current=R;const de=k?watchJsonFile(k,r=>{try{R.setServiceKeys(r),console.log(`[gateway] service keys reloaded (${Object.keys(r).length} service(s))`)}catch(s){console.error("[gateway] service keys reload refused \u2014 keeping the keys in use:",s.message)}}):void 0;console.log(`[gateway] production gateway up on ${R.ports.join(", ")} (${R.routes().length} routes${b?", lens ON":""})`),u.push(()=>g.stop?.(),()=>A?.(),()=>de?.(),()=>j?.stop(),()=>I?.quit(),()=>S?.stop(),()=>R.stop(),()=>T?.shutdown())}M(main,"main"),a(main,"main");const WORKERS=(0,prod_config_1.workerCount)(process.env);if(WORKERS>1&&node_cluster_1.default.isPrimary){if(console.log(`[gateway] primary ${process.pid}: forking ${WORKERS} workers (one per core)\u2026`),process.env.LENSMCP_GW_RATE_LIMIT&&!(0,prod_config_1.redisLimiterConfigured)(process.env)){const n=process.env.LENSMCP_GW_RATE_LIMIT_REDIS==="1",u=Number(process.env.LENSMCP_GW_RATE_LIMIT),_=(0,prod_config_1.perWorkerLimit)(u,WORKERS);console.warn(`[gateway] WARNING: ${n?"LENSMCP_GW_RATE_LIMIT_REDIS=1 is set but no Redis URL is \u2014 each worker will fall back to":"using"} the in-memory rate limiter with ${WORKERS} workers. Each worker now enforces ${_} req/window so the total stays \u2248 ${u}; a single client's burst can still land unevenly across workers. Set ${n?"LENSMCP_GW_REDIS_URL (or LENSMCP_GW_RATE_LIMIT_REDIS_URL)":"LENSMCP_GW_RATE_LIMIT_REDIS=1 and a Redis URL"} for one shared global budget.`)}let t=!1;for(let n=0;n<WORKERS;n++)node_cluster_1.default.fork();node_cluster_1.default.on("exit",(n,u,_)=>{t||(console.warn(`[gateway] worker ${n.process.pid} exited (code=${u} sig=${_??""}) \u2014 respawning.`),node_cluster_1.default.fork())});const e=a(n=>{if(!t){t=!0,console.log(`[gateway] primary: ${n} \u2014 stopping ${Object.keys(node_cluster_1.default.workers??{}).length} workers\u2026`);for(const u of Object.values(node_cluster_1.default.workers??{}))try{u?.kill(n)}catch{}setTimeout(()=>process.exit(0),12e3).unref()}},"stopAll");process.on("SIGTERM",()=>e("SIGTERM")),process.on("SIGINT",()=>e("SIGINT"))}else main().catch(t=>{console.error("[gateway] FATAL: could not start \u2014",t instanceof Error?t.stack??t.message:t),process.exit(1)});
@@ -1,36 +0,0 @@
1
- export interface MetricsSnapshot {
2
- uptimeSec: number;
3
- rssMB: number;
4
- heapUsedMB: number;
5
- heapTotalMB: number;
6
- externalMB: number;
7
- /** CPU consumed in the interval since the previous snapshot. `percent` is of one core (single-threaded gateway). */
8
- cpu: {
9
- userMs: number;
10
- systemMs: number;
11
- percent: number;
12
- };
13
- /** Event-loop delay over the interval (ms). p99/max are the latency-killers to watch. */
14
- loopLagMs: {
15
- mean: number;
16
- p50: number;
17
- p90: number;
18
- p99: number;
19
- max: number;
20
- };
21
- requests: {
22
- total: number;
23
- sinceLast: number;
24
- perSec: number;
25
- s2xx: number;
26
- s4xx: number;
27
- s5xx: number;
28
- };
29
- }
30
- export interface ProcessMetrics {
31
- recordRequest(status: number): void;
32
- /** Read-and-reset: returns interval deltas and resets the CPU/req/loop-lag windows. */
33
- snapshot(): MetricsSnapshot;
34
- stop(): void;
35
- }
36
- export declare function createProcessMetrics(): ProcessMetrics;
@@ -1 +0,0 @@
1
- "use strict";var y=Object.defineProperty;var l=(r,e)=>y(r,"name",{value:e,configurable:!0});var f=Object.defineProperty,p=l((r,e)=>f(r,"name",{value:e,configurable:!0}),"p");Object.defineProperty(exports,"__esModule",{value:!0}),exports.createProcessMetrics=createProcessMetrics;const node_perf_hooks_1=require("node:perf_hooks"),MB=1024*1024,round=p((r,e=1)=>{const t=10**e;return Math.round(r*t)/t},"round");function createProcessMetrics(){const r=Date.now(),e=(0,node_perf_hooks_1.monitorEventLoopDelay)({resolution:10});e.enable();let t=process.cpuUsage(),i=Date.now(),o=0,M=0,d=0,m=0,u=0;const a=p(s=>round(s/1e6,2),"lagMs");return{recordRequest(s){o+=1,s>=500||s===0?m+=1:s>=400?d+=1:s>=200&&(M+=1)},snapshot(){const s=Date.now(),x=Math.max(1,s-i),n=process.cpuUsage(t),c=process.memoryUsage(),h=(n.user+n.system)/1e3,g={uptimeSec:Math.round((s-r)/1e3),rssMB:round(c.rss/MB),heapUsedMB:round(c.heapUsed/MB),heapTotalMB:round(c.heapTotal/MB),externalMB:round(c.external/MB),cpu:{userMs:round(n.user/1e3),systemMs:round(n.system/1e3),percent:round(h/x*100)},loopLagMs:{mean:a(e.mean),p50:a(e.percentile(50)),p90:a(e.percentile(90)),p99:a(e.percentile(99)),max:a(e.max)},requests:{total:o,sinceLast:o-u,perSec:Math.round((o-u)/x*1e3),s2xx:M,s4xx:d,s5xx:m}};return t=process.cpuUsage(),i=s,u=o,e.reset(),g},stop(){e.disable()}}}l(createProcessMetrics,"createProcessMetrics"),p(createProcessMetrics,"createProcessMetrics");
@@ -1,46 +0,0 @@
1
- /**
2
- * OpenTelemetry tracing for the production gateway — OPT-IN, cloud-neutral.
3
- *
4
- * Makes the gateway a first-class span in a distributed trace: it continues the
5
- * incoming W3C `traceparent`, emits one SERVER span per request, and INJECTS its
6
- * context into the forwarded headers so the downstream service's spans parent to
7
- * the gateway hop. Spans export over OTLP/HTTP — point `OTEL_EXPORTER_OTLP_ENDPOINT`
8
- * at Cloud Trace (GCP), the OTel Collector / X-Ray (AWS), Tempo, Jaeger, etc. The
9
- * SAME image traces on any cloud; only the endpoint env changes.
10
- *
11
- * All OpenTelemetry imports live HERE. The gateway lib takes a `GatewayTracer`
12
- * (type-only) and calls these helpers, so it never pulls OTel unless tracing is
13
- * wired — and when no endpoint is set, `setupTracing` returns undefined and the
14
- * hot path does zero span work.
15
- *
16
- * No global context manager (`provider.register()` is intentionally NOT called):
17
- * context is threaded explicitly via extract/inject, keeping the proxy hot path
18
- * synchronous and free of async-hooks overhead.
19
- */
20
- import { type Span } from '@opentelemetry/api';
21
- import type { IncomingHttpHeaders, IncomingMessage } from 'node:http';
22
- /** A started span — opaque to the gateway lib (no OTel types leak into it). */
23
- export type TraceSpan = Span;
24
- export interface GatewayTracer {
25
- /** Start a SERVER span, continuing the incoming W3C trace context (traceparent). */
26
- startSpan(req: IncomingMessage, name: string, attrs: Record<string, string | number | boolean>): TraceSpan;
27
- /** Inject the span's context into outgoing headers — the downstream parents to it. */
28
- inject(span: TraceSpan, headers: IncomingHttpHeaders): void;
29
- /** Finish the span with the response status (+ optional extra attributes). */
30
- end(span: TraceSpan, statusCode: number, attrs?: Record<string, string | number | boolean>): void;
31
- /** Flush + shut the exporter down (drained on SIGTERM). */
32
- shutdown(): Promise<void>;
33
- }
34
- export interface TracingOptions {
35
- /** OTLP/HTTP endpoint; falls back to `OTEL_EXPORTER_OTLP_ENDPOINT`. `/v1/traces` appended if absent. */
36
- endpoint?: string;
37
- /** Resource `service.name`; falls back to `OTEL_SERVICE_NAME`, then `lensmcp-gateway`. */
38
- serviceName?: string;
39
- /** Head-based sample ratio 0..1 for root spans (default 1 = all). */
40
- sampleRatio?: number;
41
- /** Extra OTLP exporter headers (auth). The exporter also reads OTEL_EXPORTER_OTLP_HEADERS. */
42
- headers?: Record<string, string>;
43
- }
44
- /** Build the gateway tracer, or undefined when no OTLP endpoint is configured
45
- * (default-off → the lib skips all span work, zero hot-path overhead). */
46
- export declare function setupTracing(opts?: TracingOptions): GatewayTracer | undefined;
@@ -1 +0,0 @@
1
- "use strict";var O=Object.defineProperty;var c=(e,r)=>O(e,"name",{value:r,configurable:!0});var T=Object.defineProperty,o=c((e,r)=>T(e,"name",{value:r,configurable:!0}),"o");Object.defineProperty(exports,"__esModule",{value:!0}),exports.setupTracing=setupTracing;const api_1=require("@opentelemetry/api"),core_1=require("@opentelemetry/core"),sdk_trace_base_1=require("@opentelemetry/sdk-trace-base"),resources_1=require("@opentelemetry/resources"),exporter_trace_otlp_http_1=require("@opentelemetry/exporter-trace-otlp-http"),firstHeader=o((e,r)=>{const t=e[r.toLowerCase()];return Array.isArray(t)?t[0]:t},"firstHeader"),getter={keys:o(e=>Object.keys(e),"keys"),get:o((e,r)=>firstHeader(e,r),"get")},setter={set:o((e,r,t)=>{e[r.toLowerCase()]=t},"set")};function setupTracing(e={}){const r=e.endpoint??process.env.OTEL_EXPORTER_OTLP_ENDPOINT;if(!r)return;const t=r.replace(/\/+$/,""),u=/\/v1\/traces$/.test(t)?t:`${t}/v1/traces`,d=new exporter_trace_otlp_http_1.OTLPTraceExporter({url:u,...e.headers?{headers:e.headers}:{}}),p=new sdk_trace_base_1.BasicTracerProvider({resource:(0,resources_1.resourceFromAttributes)({"service.name":e.serviceName??process.env.OTEL_SERVICE_NAME??"lensmcp-gateway"}),sampler:new sdk_trace_base_1.ParentBasedSampler({root:new sdk_trace_base_1.TraceIdRatioBasedSampler(e.sampleRatio??1)}),spanProcessors:[new sdk_trace_base_1.BatchSpanProcessor(d)]}),_=p.getTracer("lensmcp-gateway"),i=new core_1.W3CTraceContextPropagator;return{startSpan(s,a,n){const l=i.extract(api_1.ROOT_CONTEXT,s.headers,getter);return _.startSpan(a,{kind:api_1.SpanKind.SERVER,attributes:n},l)},inject(s,a){i.inject(api_1.trace.setSpan(api_1.ROOT_CONTEXT,s),a,setter)},end(s,a,n){n&&s.setAttributes(n),s.setAttribute("http.response.status_code",a),(a>=500||a===0)&&s.setStatus({code:api_1.SpanStatusCode.ERROR}),s.end()},shutdown:o(()=>p.shutdown(),"shutdown")}}c(setupTracing,"setupTracing"),o(setupTracing,"setupTracing");
@@ -1,130 +0,0 @@
1
- import type { ProdGatewayOptions } from './prod-runtime/types';
2
- export interface RateLimitConfig {
3
- limit: number;
4
- windowMs: number;
5
- /** Use the shared/dedicated Redis budget rather than per-instance memory. */
6
- wantRedis: boolean;
7
- /** A Redis URL just for the limiter; otherwise the registry client is reused. */
8
- dedicatedUrl?: string;
9
- timeoutMs?: number;
10
- /** Deny on a Redis error/timeout. Default false — the limiter is defence in depth, and a
11
- * Redis blip must not 429 every request. */
12
- failClosed: boolean;
13
- }
14
- export interface JwtConfig {
15
- jwksUrl?: string;
16
- secret?: string;
17
- issuer?: string;
18
- audience?: string[];
19
- /** Accept any `Bearer <anything>` on a `jwt` route when no verifier is wired. Opt-in, weak. */
20
- presenceOnly: boolean;
21
- /** `LENSMCP_GW_JWT_ALLOW_ANY_AUD=1`: run a verifier with no audience — tokens minted for ANY application of the
22
- * IdP pass the edge. An explicit, named waiver; without it such a verifier refuses to boot (PG3-06). */
23
- allowAnyAudience: boolean;
24
- }
25
- export interface GatewayEnvConfig {
26
- /** Bind ports: explicit `LENSMCP_GW_PORTS`, else the platform `PORT` contract, else []. */
27
- ports: number[];
28
- /** Bind address: `LENSMCP_GW_HOST` — absent for every interface, the default (foodguard-264). */
29
- host?: string;
30
- /** Cluster worker processes; `auto`/`max`/`0` ⇒ one per core. Always ≥ 1. */
31
- workers: number;
32
- undici: NonNullable<ProdGatewayOptions['undici']>;
33
- server: NonNullable<ProdGatewayOptions['server']>;
34
- upstreamRetries?: number;
35
- trustProxyIp: boolean;
36
- trustProxyHops: number;
37
- cookie?: NonNullable<ProdGatewayOptions['cookie']>;
38
- attributeHeaders: string[];
39
- clientIpHeader?: string;
40
- clientIpTrustedProxies: string[];
41
- uidHeader?: string;
42
- accessLog: boolean;
43
- statusEnabled: boolean;
44
- statusToken?: string;
45
- metricsEnabled: boolean;
46
- /** TTL for the Redis `status:*` fan-out — three flush windows, never under 3s. */
47
- statusTtlSec: number;
48
- trafficFlushMs?: number;
49
- rateLimit?: RateLimitConfig;
50
- health?: {
51
- path?: string;
52
- intervalMs?: number;
53
- timeoutMs?: number;
54
- };
55
- healthCheckEnabled: boolean;
56
- jwt: JwtConfig;
57
- mtlsFromRedis: boolean;
58
- /** `LENSMCP_GW_INTERNAL_PEERS` — networks allowed to reach `internal.<host>` routes (PG3-12). */
59
- internalPeers: string[];
60
- /** `LENSMCP_GW_WS_MAX_PENDING_PER_IP` / `LENSMCP_GW_WS_MAX_TUNNELS_PER_SERVICE` (PG3-20), and
61
- * `LENSMCP_GW_WS_MAX_TUNNELS_PER_IP` / `LENSMCP_GW_WS_IDLE_MS` (PG4-09). */
62
- upgrades: NonNullable<ProdGatewayOptions['upgrades']>;
63
- /** `LENSMCP_GW_PROXY_SECRET` (+ `LENSMCP_GW_PROXY_SECRET_HEADER`) — the front proxy's shared secret (PG4-17). */
64
- proxySecret?: {
65
- header?: string;
66
- value: string;
67
- };
68
- /** `LENSMCP_GW_HOST_OWNERS` — path of a `{ hostPattern: [service, …] }` JSON file (PG4-06). */
69
- hostOwnersFile?: string;
70
- }
71
- /** Parse everything the gateway can decide from the environment alone. Pure. */
72
- export declare function parseGatewayEnv(env: NodeJS.ProcessEnv): GatewayEnvConfig;
73
- /**
74
- * What the identity edge is missing to bind a token to THIS API (PG3-06). `errors` refuse boot; `warnings` print.
75
- *
76
- * Signature verification alone answers "signed by this IdP", not "issued for this API": against a multi-application
77
- * IdP tenant (a Frontegg environment, an Auth0 tenant, Entra) any token the JWKS signs — another app's, a
78
- * client-credentials token for a different API — passed a `jwt` route, and the shipped example env left both
79
- * restrictions commented out. A verifier without an audience now needs the named waiver.
80
- */
81
- export declare function jwtBootProblems(jwt: JwtConfig): {
82
- errors: string[];
83
- warnings: string[];
84
- };
85
- /**
86
- * Worker processes for multi-core. `auto`/`max`/`0` ⇒ one per core; anything unparseable or
87
- * non-positive ⇒ 1, so a typo runs a single healthy gateway rather than none.
88
- */
89
- /**
90
- * Will the Redis-backed rate limiter actually be used — as opposed to merely asked for?
91
- *
92
- * issues/closed/codex-security-31: the primary's multi-worker warning tested the DECLARED INTENT
93
- * (`LENSMCP_GW_RATE_LIMIT_REDIS=1` or a dedicated URL) and suppressed itself whenever either was
94
- * present. Whether Redis is reachable at all is decided later, per worker, where the limiter falls
95
- * back to the per-process in-memory one and logs a line that says nothing about multiplication. So
96
- * the configuration that most needs the warning — *"I asked for Redis and did not get it"* — is
97
- * exactly the one that did not print it, and the operator instead saw N copies of a fallback notice
98
- * that reads like a detail.
99
- *
100
- * The primary can settle this before forking, because the answer is entirely in the environment: a
101
- * dedicated limiter URL, or the shared registry URL that `main()` builds its client from. It cannot
102
- * know whether that Redis will ANSWER — the limiter's own `onFailure` covers a live outage — but
103
- * "configured" is the half the warning got wrong.
104
- */
105
- export declare function redisLimiterConfigured(env: NodeJS.ProcessEnv): boolean;
106
- /**
107
- * The per-process budget for the in-memory limiter, so the CONFIGURED limit is the ENFORCED one.
108
- *
109
- * With N workers each owning its own bucket map, Node's cluster scheduler spreads one client's
110
- * connections across processes and `LENSMCP_GW_RATE_LIMIT` became roughly `N ×` itself. Warning
111
- * about that is documentation; dividing is the fix. Floors at 1 — a budget of zero would deny every
112
- * request, which is a worse failure than a slightly generous limit, and `Math.floor` on a limit
113
- * smaller than the worker count would otherwise reach it.
114
- */
115
- export declare function perWorkerLimit(limit: number, workers: number): number;
116
- export declare function workerCount(env: NodeJS.ProcessEnv): number;
117
- /**
118
- * The last word on upstream TLS, applied AFTER the mTLS materials are loaded (which is
119
- * effectful, so it cannot live in `parseGatewayEnv`).
120
- *
121
- * A configured CA that is never checked against is inert: `rejectUnauthorized:false` skips
122
- * verification entirely, so an operator who mounted their private CA to pin east-west TLS got no
123
- * pinning at all and no warning. A CA is an explicit statement of who to trust — honour it
124
- * unless verification was explicitly turned off. Returns what changed, for the boot log.
125
- */
126
- export declare function finalizeUpstreamTls(undici: NonNullable<ProdGatewayOptions['undici']>): {
127
- autoEnabled: boolean;
128
- };
129
- /** mTLS rides on HTTP/2 unless explicitly disabled. Returns whether a client cert is in play. */
130
- export declare function finalizeUpstreamH2(undici: NonNullable<ProdGatewayOptions['undici']>, env: NodeJS.ProcessEnv): boolean;
@@ -1 +0,0 @@
1
- "use strict";var X=Object.defineProperty;var S=(e,E)=>X(e,"name",{value:E,configurable:!0});var w=Object.defineProperty,i=S((e,E)=>w(e,"name",{value:E,configurable:!0}),"i");Object.defineProperty(exports,"__esModule",{value:!0}),exports.parseGatewayEnv=parseGatewayEnv,exports.jwtBootProblems=jwtBootProblems,exports.redisLimiterConfigured=redisLimiterConfigured,exports.perWorkerLimit=perWorkerLimit,exports.workerCount=workerCount,exports.finalizeUpstreamTls=finalizeUpstreamTls,exports.finalizeUpstreamH2=finalizeUpstreamH2;const node_os_1=require("node:os"),num=i(e=>{if(e===void 0||e.trim()==="")return;const E=Number(e);return Number.isFinite(E)?E:void 0},"num"),csv=i(e=>(e??"").split(",").map(E=>E.trim()).filter(Boolean),"csv"),flag=i(e=>e==="1","flag");function parseGatewayEnv(e){const E=csv(e.LENSMCP_GW_PORTS??e.PORT).map(Number).filter(N=>Number.isFinite(N)&&N>=0&&N<=65535),_=Math.max(0,Math.floor(num(e.LENSMCP_GW_TRUST_PROXY)??0)),o={},P=e.LENSMCP_GW_UPSTREAM_TLS_VERIFY;P==="1"?o.rejectUnauthorized=!0:P==="0"&&(o.rejectUnauthorized=!1),flag(e.LENSMCP_GW_UPSTREAM_H2)&&(o.allowH2=!0);const C=num(e.LENSMCP_GW_UNDICI_CONNECTIONS);C!==void 0&&(o.connections=C);const a=num(e.LENSMCP_GW_UNDICI_BODY_TIMEOUT_MS);a!==void 0&&(o.bodyTimeout=a);const W=num(e.LENSMCP_GW_UNDICI_PIPELINING);W!==void 0&&(o.pipelining=W);const T=num(e.LENSMCP_GW_UNDICI_HEADERS_TIMEOUT_MS);T!==void 0&&(o.headersTimeout=T);const G=num(e.LENSMCP_GW_UNDICI_KEEPALIVE_MS);G!==void 0&&(o.keepAliveTimeout=G);const t={},u=num(e.LENSMCP_GW_KEEPALIVE_MS);u!==void 0&&(t.keepAliveTimeout=u);const I=num(e.LENSMCP_GW_REQUEST_TIMEOUT_MS);I!==void 0&&(t.requestTimeout=I);const d=num(e.LENSMCP_GW_HEADERS_TIMEOUT_MS);d!==void 0&&(t.headersTimeout=d);const R=num(e.LENSMCP_GW_MAX_HEADERS);R!==void 0&&(t.maxHeadersCount=R);const c=num(e.LENSMCP_GW_CONN_CHECK_MS);c!==void 0&&(t.connectionsCheckingInterval=c);const l=num(e.LENSMCP_GW_MAX_CONNECTIONS);l!==void 0&&(t.maxConnections=l);const A=num(e.LENSMCP_GW_BODY_STALL_MS);A!==void 0&&(t.bodyStallMs=A);const m=num(e.LENSMCP_GW_BODY_MIN_RATE);m!==void 0&&(t.bodyMinRateBps=m);const O=num(e.LENSMCP_GW_BODY_RATE_GRACE_MS);O!==void 0&&(t.bodyRateGraceMs=O);const U=num(e.LENSMCP_GW_MAX_IN_FLIGHT_PER_IP);U!==void 0&&(t.maxInFlightPerClient=U);const r=e.LENSMCP_GW_COOKIE_SECRET,n=e.LENSMCP_GW_COOKIE_NAME,M=e.LENSMCP_GW_COOKIE_DOMAIN,p=num(e.LENSMCP_GW_COOKIE_MAXAGE),v=r||n||M?{...n?{name:n}:{},...r?{secret:r}:{},...M?{domain:M}:{},...p!==void 0?{maxAge:p}:{}}:void 0,f=num(e.LENSMCP_GW_RATE_LIMIT),s=e.LENSMCP_GW_RATE_LIMIT_REDIS_URL,D=num(e.LENSMCP_GW_RATE_LIMIT_TIMEOUT_MS),h=f===void 0?void 0:{limit:f,windowMs:num(e.LENSMCP_GW_RATE_WINDOW_MS)??6e4,wantRedis:flag(e.LENSMCP_GW_RATE_LIMIT_REDIS)||!!s,...s?{dedicatedUrl:s}:{},...D!==void 0?{timeoutMs:D}:{},failClosed:flag(e.LENSMCP_GW_RATE_LIMIT_FAIL_CLOSED)},H=e.LENSMCP_GW_HEALTH_PATH,b=num(e.LENSMCP_GW_HEALTH_INTERVAL_MS),x=num(e.LENSMCP_GW_HEALTH_TIMEOUT_MS),k=flag(e.LENSMCP_GW_HEALTH_CHECK),g=k?{...H?{path:H}:{},...b!==void 0?{intervalMs:b}:{},...x!==void 0?{timeoutMs:x}:{}}:void 0,L=num(e.LENSMCP_GW_TRAFFIC_FLUSH_MS),y=csv(e.LENSMCP_GW_JWT_AUD),F=e.LENSMCP_GW_HOST?.trim();return{ports:E,...F?{host:F}:{},workers:workerCount(e),undici:o,server:t,...num(e.LENSMCP_GW_UPSTREAM_RETRIES)!==void 0?{upstreamRetries:num(e.LENSMCP_GW_UPSTREAM_RETRIES)}:{},trustProxyIp:_>0,trustProxyHops:_,...v?{cookie:v}:{},attributeHeaders:csv(e.LENSMCP_GW_ATTR_HEADERS),...e.LENSMCP_GW_CLIENT_IP_HEADER?{clientIpHeader:e.LENSMCP_GW_CLIENT_IP_HEADER}:{},clientIpTrustedProxies:csv(e.LENSMCP_GW_CLIENT_IP_TRUSTED_PROXIES),...e.LENSMCP_GW_UID_HEADER?{uidHeader:e.LENSMCP_GW_UID_HEADER}:{},accessLog:flag(e.LENSMCP_GW_ACCESS_LOG),statusEnabled:flag(e.LENSMCP_GW_STATUS),...e.LENSMCP_GW_STATUS_TOKEN?{statusToken:e.LENSMCP_GW_STATUS_TOKEN}:{},metricsEnabled:flag(e.LENSMCP_GW_METRICS),statusTtlSec:Math.max(3,Math.ceil((L??5e3)/1e3*3)),...L!==void 0?{trafficFlushMs:L}:{},...h?{rateLimit:h}:{},...g?{health:g}:{},healthCheckEnabled:k,jwt:{...e.LENSMCP_GW_JWKS_URL?{jwksUrl:e.LENSMCP_GW_JWKS_URL}:{},...e.LENSMCP_GW_JWT_SECRET?{secret:e.LENSMCP_GW_JWT_SECRET}:{},...e.LENSMCP_GW_JWT_ISS?{issuer:e.LENSMCP_GW_JWT_ISS}:{},...y.length?{audience:y}:{},presenceOnly:flag(e.LENSMCP_GW_JWT_PRESENCE_ONLY),allowAnyAudience:flag(e.LENSMCP_GW_JWT_ALLOW_ANY_AUD)},mtlsFromRedis:flag(e.LENSMCP_GW_MTLS_FROM_REDIS),internalPeers:csv(e.LENSMCP_GW_INTERNAL_PEERS),upgrades:{...num(e.LENSMCP_GW_WS_MAX_PENDING_PER_IP)!==void 0?{maxPendingPerClient:num(e.LENSMCP_GW_WS_MAX_PENDING_PER_IP)}:{},...num(e.LENSMCP_GW_WS_MAX_TUNNELS_PER_SERVICE)!==void 0?{maxTunnelsPerService:num(e.LENSMCP_GW_WS_MAX_TUNNELS_PER_SERVICE)}:{},...num(e.LENSMCP_GW_WS_MAX_TUNNELS_PER_IP)!==void 0?{maxTunnelsPerClient:num(e.LENSMCP_GW_WS_MAX_TUNNELS_PER_IP)}:{},...num(e.LENSMCP_GW_WS_IDLE_MS)!==void 0?{idleMs:num(e.LENSMCP_GW_WS_IDLE_MS)}:{}},...e.LENSMCP_GW_PROXY_SECRET?{proxySecret:{value:e.LENSMCP_GW_PROXY_SECRET,...e.LENSMCP_GW_PROXY_SECRET_HEADER?{header:e.LENSMCP_GW_PROXY_SECRET_HEADER}:{}}}:{},...e.LENSMCP_GW_HOST_OWNERS?{hostOwnersFile:e.LENSMCP_GW_HOST_OWNERS}:{}}}S(parseGatewayEnv,"parseGatewayEnv"),i(parseGatewayEnv,"parseGatewayEnv");function jwtBootProblems(e){const E=[],_=[];return e.jwksUrl||e.secret?(e.audience?.length||(e.allowAnyAudience?_.push("LENSMCP_GW_JWT_ALLOW_ANY_AUD=1 \u2014 tokens minted for ANY application of this IdP are accepted on jwt routes"):E.push("a JWT verifier is configured without LENSMCP_GW_JWT_AUD \u2014 set the audience this API's tokens carry (or LENSMCP_GW_JWT_ALLOW_ANY_AUD=1 to accept tokens minted for any application)")),e.issuer||_.push("LENSMCP_GW_JWT_ISS is not set \u2014 tokens from any issuer the verifier's keys sign are accepted"),{errors:E,warnings:_}):{errors:E,warnings:_}}S(jwtBootProblems,"jwtBootProblems"),i(jwtBootProblems,"jwtBootProblems");function redisLimiterConfigured(e){return e.LENSMCP_GW_RATE_LIMIT_REDIS_URL?!0:flag(e.LENSMCP_GW_RATE_LIMIT_REDIS)&&!!e.LENSMCP_GW_REDIS_URL}S(redisLimiterConfigured,"redisLimiterConfigured"),i(redisLimiterConfigured,"redisLimiterConfigured");function perWorkerLimit(e,E){if(!Number.isFinite(e)||e<=0)return e;const _=Number.isFinite(E)&&E>1?Math.floor(E):1;return Math.max(1,Math.floor(e/_))}S(perWorkerLimit,"perWorkerLimit"),i(perWorkerLimit,"perWorkerLimit");function workerCount(e){const E=(e.LENSMCP_GW_WORKERS??"1").trim().toLowerCase();if(E==="auto"||E==="max"||E==="0")return Math.max(1,(0,node_os_1.cpus)().length);const _=Math.floor(Number(E));return Number.isFinite(_)&&_>0?_:1}S(workerCount,"workerCount"),i(workerCount,"workerCount");function finalizeUpstreamTls(e){return e.ca&&e.rejectUnauthorized===void 0?(e.rejectUnauthorized=!0,{autoEnabled:!0}):{autoEnabled:!1}}S(finalizeUpstreamTls,"finalizeUpstreamTls"),i(finalizeUpstreamTls,"finalizeUpstreamTls");function finalizeUpstreamH2(e,E){return e.cert&&e.key?(E.LENSMCP_GW_UPSTREAM_H2!=="0"&&(e.allowH2=!0),!0):!1}S(finalizeUpstreamH2,"finalizeUpstreamH2"),i(finalizeUpstreamH2,"finalizeUpstreamH2");
@@ -1,19 +0,0 @@
1
- /**
2
- * Public facade for the PRODUCTION gateway runtime (Fastify + @fastify/reply-from).
3
- *
4
- * The implementation now lives in `./prod-runtime/*` as composable LAYERS,
5
- * mirroring the dev gateway's `./runtime/*` — see `prod-runtime/server.ts` for the
6
- * composition root (`startProdGateway`), `prod-runtime/types.ts` for the shared
7
- * types + the customer **hooks** API, and the sibling modules for each layer
8
- * (routing, observability, rollout, upstream, auth, cors, trust, handler, upgrade,
9
- * app, access-log, hooks). This barrel preserves the original module's public
10
- * surface so the entry (`main.prod-gateway.ts`), the `@lensmcp/cluster` re-export
11
- * (`gateway.ts`), the e2e suite, and the pentest/perf suites import from one stable
12
- * path, and additionally exposes the hooks types for customer-authored layers.
13
- *
14
- * The same routing brain as dev (shared `matchRoute` / `buildRouteTable` / manifest
15
- * schema); the HTTP transport differs on purpose (dev: node:http + http-proxy over
16
- * unix-socket pods; prod: Fastify + reply-from's undici pool for the high-RPS edge).
17
- */
18
- export { startProdGateway } from './prod-runtime/server';
19
- export type { ServiceStatus, ProdGatewayOptions, ProdGatewayHandle, ProdGatewayHooks, ProdGatewayPhase, ProdHookHandler, ProdHookContext, } from './prod-runtime/types';
@@ -1 +0,0 @@
1
- "use strict";var s=Object.defineProperty;var o=(r,t)=>s(r,"name",{value:t,configurable:!0});var a=Object.defineProperty,e=o((r,t)=>a(r,"name",{value:t,configurable:!0}),"e");Object.defineProperty(exports,"__esModule",{value:!0}),exports.startProdGateway=void 0;var server_1=require("./prod-runtime/server");Object.defineProperty(exports,"startProdGateway",{enumerable:!0,get:e(function(){return server_1.startProdGateway},"get")});
@@ -1,8 +0,0 @@
1
- /**
2
- * Opt-in one-JSON-line-per-request access log to stdout, shaped for Cloud
3
- * Logging (severity + time + message). Covers EVERY response (incl. 401/404/503
4
- * that never reached an upstream); `reply.elapsedTime` gives latency for free.
5
- */
6
- import type { FastifyReply, FastifyRequest } from 'fastify';
7
- import type { ReqState } from './types';
8
- export declare const logAccess: (request: FastifyRequest, reply: FastifyReply, st: ReqState | undefined) => void;
@@ -1 +0,0 @@
1
- "use strict";var g=Object.defineProperty;var u=(t,r)=>g(t,"name",{value:r,configurable:!0});var d=Object.defineProperty,n=u((t,r)=>d(t,"name",{value:r,configurable:!0}),"n");Object.defineProperty(exports,"__esModule",{value:!0}),exports.logAccess=void 0;const edge_1=require("./edge"),logAccess=n((t,r,e)=>{const s=t.raw,o=r.statusCode??0,a=(s.headers.host||"").split(":")[0],i=(s.url||"/").split("?")[0],c=(0,edge_1.rawTargetOf)(s),l=Math.round(r.elapsedTime);try{console.log(JSON.stringify({severity:o>=500?"ERROR":o>=400?"WARNING":"INFO",time:new Date().toISOString(),message:`${s.method} ${a}${i} ${o} ${l}ms`,method:s.method,host:a,path:i,status:o,ms:l,...c?{rawPath:c.split("?")[0]}:{},...e?{service:e.route.service,upstream:e.upLabel}:{},...e?.version?{version:e.version}:{},...e?.caller?{caller:e.caller}:{},...s.headers["x-request-id"]?{requestId:String(s.headers["x-request-id"])}:{}}))}catch{}},"logAccess");exports.logAccess=logAccess;
@@ -1,30 +0,0 @@
1
- /**
2
- * Builds one Fastify app per port (shared route table + providers). Streams
3
- * every body straight through (never parses/buffers — this is a proxy), wires
4
- * reply-from's undici pool, the operational probes (/livez /readyz /statusz
5
- * /metricsz), and the trust / CORS / edge-finish hooks.
6
- */
7
- import type * as http from 'node:http';
8
- import type * as net from 'node:net';
9
- import { type FastifyInstance, type FastifyReply, type FastifyRequest } from 'fastify';
10
- import type { TraceSpan } from '../otel-tracing';
11
- import type { RolloutLayer } from './rollout';
12
- import type { ProdHookContext, ProdRuntime, ReqState } from './types';
13
- import type { Observability } from './observability';
14
- import type { CorsLayer } from './cors';
15
- import type { HooksLayer } from './hooks';
16
- export interface AppDeps {
17
- rt: ProdRuntime;
18
- obs: Observability;
19
- cors: CorsLayer;
20
- hooks: HooksLayer;
21
- rollout: RolloutLayer;
22
- handler: (request: FastifyRequest, reply: FastifyReply) => Promise<unknown>;
23
- upgrade: (req: http.IncomingMessage, socket: net.Socket, head: Buffer) => void;
24
- reqState: WeakMap<FastifyRequest, ReqState>;
25
- spanByReq: WeakMap<FastifyRequest, TraceSpan>;
26
- ctxByReq: WeakMap<FastifyRequest, ProdHookContext>;
27
- }
28
- export declare function createApp(deps: AppDeps): {
29
- buildApp: () => Promise<FastifyInstance>;
30
- };
@@ -1 +0,0 @@
1
- "use strict";var P=Object.defineProperty;var g=(p,a)=>P(p,"name",{value:a,configurable:!0});var H=Object.defineProperty,i=g((p,a)=>H(p,"name",{value:a,configurable:!0}),"i");Object.defineProperty(exports,"__esModule",{value:!0}),exports.createApp=createApp;const tslib_1=require("tslib"),fastify_1=tslib_1.__importDefault(require("fastify")),reply_from_1=tslib_1.__importDefault(require("@fastify/reply-from")),edge_1=require("./edge"),trust_1=require("./trust"),body_stall_1=require("./body-stall"),access_log_1=require("./access-log"),client_ip_1=require("../client-ip");function createApp(p){const{rt:a,obs:y,cors:R,hooks:f,rollout:q,handler:k,upgrade:S,reqState:T,spanByReq:_,ctxByReq:w}=p,e=a.opts,x=10,O=6e4,E=1e4,m=new Map,A=i(c=>(0,client_ip_1.limiterKey)(q.clientIpOf(c.raw,c.raw.socket?.remoteAddress??"")),"guesser"),M=i(c=>{const s=m.get(c);return!!s&&Date.now()<s.until&&s.n>=x},"guessesSpent"),N=i(c=>{const s=Date.now(),u=m.get(c);if(u&&s<u.until){u.n+=1;return}m.size>=E&&m.clear(),m.set(c,{n:1,until:s+O})},"noteGuess");return{buildApp:i(async()=>{const c=e.server?.keepAliveTimeout??62e4,s=(0,fastify_1.default)({logger:!1,keepAliveTimeout:c,requestTimeout:e.server?.requestTimeout??0,...e.server?.connectionTimeout!==void 0?{connectionTimeout:e.server.connectionTimeout}:{},...e.trustProxyIp?{trustProxy:Math.max(1,Math.floor(e.trustProxyHops??1))}:{},...e.tls?{https:{key:e.tls.key,cert:e.tls.cert}}:{},frameworkErrors:i((t,r,n)=>{const o=t.statusCode&&t.statusCode>=400&&t.statusCode<600?t.statusCode:400;(0,edge_1.sendError)(n,r.raw,o,o>=500?"internal":"bad_request",o>=500?void 0:"Bad Request"),e.metrics?.recordRequest(o),a.accessLog&&(0,access_log_1.logAccess)(r,n,void 0)},"frameworkErrors")});s.server.headersTimeout=e.server?.headersTimeout??6e4,e.server?.connectionsCheckingInterval!==void 0&&(s.server.connectionsCheckingInterval=e.server.connectionsCheckingInterval),e.server?.maxHeadersCount!==void 0&&(s.server.maxHeadersCount=e.server.maxHeadersCount),e.server?.maxConnections!==void 0&&(s.server.maxConnections=e.server.maxConnections),s.removeAllContentTypeParsers(),s.addContentTypeParser("*",(t,r,n)=>n(null,r)),await s.register(reply_from_1.default,{disableRequestLogging:!0,undici:{connections:e.undici?.connections??256,pipelining:e.undici?.pipelining??1,keepAliveTimeout:e.undici?.keepAliveTimeout??6e4,bodyTimeout:e.undici?.bodyTimeout??0,headersTimeout:e.undici?.headersTimeout??6e4,...e.undici?.allowH2?{allowH2:!0}:{},connect:{rejectUnauthorized:e.undici?.rejectUnauthorized??!1,...e.undici?.cert?{cert:e.undici.cert}:{},...e.undici?.key?{key:e.undici.key}:{},...e.undici?.ca?{ca:e.undici.ca}:{}}}}),s.get("/livez",(t,r)=>{r.header("cache-control",edge_1.NO_STORE).type("text/plain").send("ok")});const u=e.undici?.headersTimeout??6e4,C=e.server?.readyStallMs??(u>0?u+5e3:0);s.get("/readyz",(t,r)=>{const n=a.table.routes.length>0,o=n&&C>0&&a.upstreamWaits.oldestMs()>C,d=n&&!o;r.code(d?200:503).header("cache-control",edge_1.NO_STORE).type("text/plain").send(d?"ready":n?"upstream pool stalled":"no routes loaded")});const z=i(t=>(0,edge_1.tokenMatches)(t.query?.token??(0,edge_1.hdr)(t.raw.headers["x-status-token"]),e.statusToken),"opToken"),b=i((t,r)=>{const n=A(t);return M(n)?(r.code(429).header("cache-control",edge_1.NO_STORE).header("retry-after","60").type("text/plain").send("too many attempts"),!1):z(t)?!0:(N(n),r.code(401).header("cache-control",edge_1.NO_STORE).type("text/plain").send("unauthorized"),!1)},"opGate");s.get("/statusz",(t,r)=>{if(!e.statusEndpoint||!e.statusToken){r.code(404).header("cache-control",edge_1.NO_STORE).type("text/plain").send("not found");return}b(t,r)&&r.header("cache-control",edge_1.NO_STORE).type("application/json").send(JSON.stringify({generatedAt:Date.now(),services:y.buildStatusSnapshot(),endpoints:e.healthChecker?.snapshot()??[]}))}),s.get("/metricsz",(t,r)=>{if(!e.metrics||!e.statusToken){r.code(404).header("cache-control",edge_1.NO_STORE).type("text/plain").send("not found");return}b(t,r)&&r.header("cache-control",edge_1.NO_STORE).type("application/json").send(JSON.stringify(e.metrics.snapshot()))});const v=(0,body_stall_1.createBodyStallGuard)(e.server?.bodyStallMs??6e4,{minBytesPerSec:e.server?.bodyMinRateBps??500,...e.server?.bodyRateGraceMs!==void 0?{graceMs:e.server.bodyRateGraceMs}:{}});return s.addHook("onClose",(t,r)=>{v.stop(),r()}),s.addHook("onRequest",(t,r,n)=>{(0,trust_1.stripTrust)(t.raw),(0,trust_1.stripUnforwardable)(t.raw),v.arm(t.raw),v.armResponse(r.raw),n()}),s.addHook("onSend",(t,r,n,o)=>{R.applyResponseCors(t,r),o(null,n)}),s.addHook("onResponse",(t,r,n)=>{const o=T.get(t);o&&(y.recordEdge(o.route,Date.now()-o.startedAt,r.statusCode??0,o.caller,o.version),y.finish(o.trace,o.route.service,r.statusCode??0,{upstream:o.upLabel,...o.version?{version:o.version}:{},...o.caller?{caller:o.caller}:{}}),T.delete(t));const d=_.get(t);d&&(e.tracing.end(d,r.statusCode??0,{...o?.upLabel?{"upstream.url":o.upLabel}:{},...o?.version?{"lensmcp.version":o.version}:{}}),_.delete(t)),e.metrics?.recordRequest(r.statusCode??0),a.accessLog&&(0,access_log_1.logAccess)(t,r,o);const l=w.get(t);l&&(l.status=r.statusCode??0,f.has("onResponse")&&f.run("onResponse",l).catch(h=>y.emit("error",`gateway onResponse hook failed: ${h?.message??String(h)}`,"gateway-hook-error:onResponse",{kind:"gateway-hook-error",phase:"onResponse",error:h?.message??String(h)})),w.delete(t)),n()}),s.setErrorHandler((t,r,n)=>{const o=t,d=o.message??String(t);y.emit("error",`gateway request error: ${d}`,`gateway-error:${o.code??"exception"}`,{kind:"gateway-request-error",error:d,...o.code?{code:o.code}:{}});const l=typeof o.statusCode=="number"&&o.statusCode>=400&&o.statusCode<600?o.statusCode:500;(0,edge_1.sendError)(n,r.raw,l,l===400?"bad_request":"internal")}),s.setNotFoundHandler((t,r)=>{(0,edge_1.sendError)(r,t.raw,404,"not_found","No gateway route for this hostname.")}),s.all("/",k),s.all("/*",k),s.server.on("upgrade",S),s},"buildApp")}}g(createApp,"createApp"),i(createApp,"createApp");
@@ -1,29 +0,0 @@
1
- /**
2
- * The edge-auth layer — ONE source for the HTTP handler and the WS upgrade so
3
- * they can't drift. `internal(...)` validates the caller's `x-api-key` on an
4
- * `internal.<host>` route; `public(...)` runs the JWT/authz seam (verify →
5
- * fail-closed ABAC → stamp identity). Each returns a verdict; the caller turns a
6
- * denial into its own rejection (handler → `finish`+`sendError`; upgrade → `socket.destroy()`).
7
- *
8
- * NOTE: `public()` calls `stampIdentity` and `internal()` mutates `req.headers`;
9
- * the upgrade path rebuilds its request from `req.rawHeaders` (re-adding identity
10
- * explicitly), so those header mutations are simply ignored there — no divergence.
11
- */
12
- import * as http from 'node:http';
13
- import { type AuthMode, type Route } from '../manifest';
14
- import type { GatewayErrorReason } from '../gateway-errors';
15
- import type { GwTrace, ProdRuntime } from './types';
16
- import type { Observability } from './observability';
17
- import type { RolloutLayer } from './rollout';
18
- export interface AuthVerdict {
19
- ok: boolean;
20
- caller?: string;
21
- status?: number;
22
- reason?: GatewayErrorReason;
23
- detail?: string;
24
- }
25
- export interface EdgeAuth {
26
- internal(req: http.IncomingMessage, route: Route, trace: GwTrace | undefined): AuthVerdict;
27
- public(req: http.IncomingMessage, route: Route, cpath: string, claims: Record<string, unknown> | undefined, clientIp: string, trace: GwTrace | undefined): AuthVerdict;
28
- }
29
- export declare function createEdgeAuth(rt: ProdRuntime, obs: Observability, rollout: RolloutLayer, authenticate: (mode: AuthMode, req: http.IncomingMessage) => void): EdgeAuth;
@@ -1 +0,0 @@
1
- "use strict";var f=Object.defineProperty;var p=(a,e)=>f(a,"name",{value:e,configurable:!0});var y=Object.defineProperty,l=p((a,e)=>y(a,"name",{value:e,configurable:!0}),"l");Object.defineProperty(exports,"__esModule",{value:!0}),exports.createEdgeAuth=createEdgeAuth;const manifest_1=require("../manifest"),trust_1=require("./trust");function createEdgeAuth(a,e,m,k){return{internal:l((i,o,d)=>{const r=i.headers["x-api-key"],u=typeof r=="string"?r:Array.isArray(r)?r[0]:void 0,t=u?a.keyToProject.get(u):void 0;return t?(i.headers["x-api-key-id"]=t,delete i.headers["x-api-key"],e.step(d,"auth",{mode:"x-api-key",ok:!0,caller:t}),{ok:!0,caller:t}):(e.step(d,"auth",{mode:"x-api-key",ok:!1}),{ok:!1,status:401,reason:"unauthorized",detail:"Invalid or missing x-api-key for internal route."})},"internal"),public:l((i,o,d,r,u,t)=>{const c=o.policy?void 0:a.table.manifestByService.get(o.service),h=i.method??"GET",n=o.policy?(0,manifest_1.authRuleFor)(o.policy,d,h):c?(0,manifest_1.authRuleForPath)(c,d,h,!1):{mode:o.auth};if(n.mode==="public")return e.step(t,"auth",{mode:"public"}),{ok:!0};if(n.mode!=="jwt")return e.step(t,"auth",{mode:String(n.mode),ok:!1,reason:"unsupported-mode"}),{ok:!1,status:401,reason:"unauthorized",detail:"Unauthorized: this route's auth mode is not served at the edge"};if(a.opts.identify){if(!r)return e.step(t,"auth",{mode:"jwt",ok:!1}),{ok:!1,status:401,reason:"unauthorized",detail:"Unauthorized: invalid or missing token"}}else try{k("jwt",i)}catch(s){return e.step(t,"auth",{mode:"jwt",ok:!1,reason:s.message}),{ok:!1,status:401,reason:"unauthorized",detail:"Unauthorized: invalid or missing token"}}if(n.rule&&(!r||!(0,manifest_1.evalRule)(n.rule,m.buildAttrs(i,u,r,void 0,d))))return e.step(t,"authz",{ok:!1}),{ok:!1,status:403,reason:"forbidden",detail:"Forbidden: insufficient permission"};if(e.step(t,"auth",{mode:"jwt",ok:!0}),r){const{dropped:s}=(0,trust_1.stampIdentity)(i,r);s>0&&(e.step(t,"identity",{dropped:s}),e.emit("warning",`gateway identity for ${o.service}: ${s} role/permission value(s) are not plain tokens and were not stamped`,`gateway-identity:${o.service}:dropped`,{kind:"gateway-identity-dropped",project:o.service,dropped:s}))}return{ok:!0}},"publicAuth")}}p(createEdgeAuth,"createEdgeAuth"),l(createEdgeAuth,"createEdgeAuth");
@@ -1,5 +0,0 @@
1
- /**
2
- * The stall guard lives in `../body-stall` — SHARED with the dev gateway (issues/closed/dev-gateway-12) so the
3
- * two proxies bound a stalled transfer the same way. Re-exported so every prod import keeps its address.
4
- */
5
- export { createBodyStallGuard, type BodyStallGuard } from '../body-stall';
@@ -1 +0,0 @@
1
- "use strict";var o=Object.defineProperty;var l=(r,t)=>o(r,"name",{value:t,configurable:!0});var a=Object.defineProperty,e=l((r,t)=>a(r,"name",{value:t,configurable:!0}),"e");Object.defineProperty(exports,"__esModule",{value:!0}),exports.createBodyStallGuard=void 0;var body_stall_1=require("../body-stall");Object.defineProperty(exports,"createBodyStallGuard",{enumerable:!0,get:e(function(){return body_stall_1.createBodyStallGuard},"get")});
@@ -1,18 +0,0 @@
1
- /**
2
- * The edge CORS authority. The gateway is the CORS authority for its OWN
3
- * responses (no-route / errors / preflights) and for credentialed first-party
4
- * origins, but must NEVER bless a proxied upstream success cross-origin (the
5
- * upstream owns CORS on its own app data — CWE-942).
6
- */
7
- import type * as http from 'node:http';
8
- import type { FastifyReply, FastifyRequest } from 'fastify';
9
- import type { ProdRuntime, ReqState } from './types';
10
- export interface CorsLayer {
11
- /** Stamp CORS on a gateway-generated reply (no-route / preflight): exact origin +
12
- * credentials for an allowlisted origin, else a reflected origin WITHOUT credentials. */
13
- setCors(reply: FastifyReply, req: http.IncomingMessage): void;
14
- /** onSend: add CORS to any response that lacks it — a credentialed-allowlist origin always
15
- * (proxied or generated); a non-allowlisted origin ONLY on a gateway-GENERATED reply. */
16
- applyResponseCors(request: FastifyRequest, reply: FastifyReply): void;
17
- }
18
- export declare function createCors(rt: ProdRuntime, reqState: WeakMap<FastifyRequest, ReqState>): CorsLayer;
@@ -1 +0,0 @@
1
- "use strict";var i=Object.defineProperty;var n=(s,a)=>i(s,"name",{value:a,configurable:!0});var c=Object.defineProperty,t=n((s,a)=>c(s,"name",{value:a,configurable:!0}),"t");Object.defineProperty(exports,"__esModule",{value:!0}),exports.createCors=createCors;const addVaryOrigin=t(s=>{const a=s.getHeader("vary"),e=Array.isArray(a)?a.join(", "):typeof a=="string"?a:"";if(e.trim()==="*")return;const o=e.split(",").map(r=>r.trim()).filter(Boolean);o.some(r=>r.toLowerCase()==="origin")||s.header("vary",[...o,"Origin"].join(", "))},"addVaryOrigin");function createCors(s,a){return{setCors:t((e,o)=>{const r=o.headers.origin;if(r&&s.corsCredentialOrigins.has(r.toLowerCase())){e.header("access-control-allow-origin",r),e.header("access-control-allow-credentials","true"),addVaryOrigin(e);return}e.header("access-control-allow-origin",String(r??"*")),addVaryOrigin(e)},"setCors"),applyResponseCors:t((e,o)=>{const r=e.headers.origin;r&&!o.getHeader("access-control-allow-origin")&&(s.corsCredentialOrigins.has(r.toLowerCase())?(o.header("access-control-allow-origin",r),o.header("access-control-allow-credentials","true"),addVaryOrigin(o)):a.get(e)?.proxied||(o.header("access-control-allow-origin",String(r)),addVaryOrigin(o)))},"applyResponseCors")}}n(createCors,"createCors"),t(createCors,"createCors");