@lensmcp/cluster 1.25.76 → 1.25.78
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/basic-ssl.js +1 -1
- package/build-host.js +1 -1
- package/build-scope-patterns.js +1 -1
- package/bundle-parent.js +1 -1
- package/checkout-cache.js +1 -1
- package/child-process-env.js +1 -1
- package/compile-retry.js +1 -1
- package/config-files.js +1 -1
- package/create-webpack-dev.js +1 -1
- package/create-webpack-prod.js +1 -1
- package/dev-devtool.js +1 -1
- package/devserver-host.js +1 -1
- package/devserver-notifier.js +1 -1
- package/devserver-transport.js +1 -1
- package/error-stack-release.js +1 -1
- package/executors/build/build.impl.js +1 -1
- package/executors/gateway/body-stall.d.ts +14 -1
- package/executors/gateway/body-stall.js +1 -1
- package/executors/gateway/canonical-path.js +1 -1
- package/executors/gateway/client-ip.d.ts +39 -15
- package/executors/gateway/client-ip.js +1 -1
- package/executors/gateway/gateway-errors.js +1 -1
- package/executors/gateway/gateway.impl.js +1 -1
- package/executors/gateway/gateway.lib.js +1 -1
- package/executors/gateway/health-check.js +1 -1
- package/executors/gateway/jwks-verify.js +1 -1
- package/executors/gateway/jwt-claims.d.ts +13 -0
- package/executors/gateway/jwt-claims.js +1 -1
- package/executors/gateway/main.prod-gateway.js +2 -2
- package/executors/gateway/main.rollout.js +4 -4
- package/executors/gateway/manifest.d.ts +72 -27
- package/executors/gateway/manifest.js +1 -1
- package/executors/gateway/metrics.js +1 -1
- package/executors/gateway/otel-tracing.js +1 -1
- package/executors/gateway/prod-config.d.ts +9 -1
- package/executors/gateway/prod-config.js +1 -1
- package/executors/gateway/prod-gateway.lib.js +1 -1
- package/executors/gateway/prod-runtime/access-log.js +1 -1
- package/executors/gateway/prod-runtime/app.d.ts +2 -0
- package/executors/gateway/prod-runtime/app.js +1 -1
- package/executors/gateway/prod-runtime/auth.js +1 -1
- package/executors/gateway/prod-runtime/body-stall.js +1 -1
- package/executors/gateway/prod-runtime/cors.js +1 -1
- package/executors/gateway/prod-runtime/edge.d.ts +13 -0
- package/executors/gateway/prod-runtime/edge.js +1 -1
- package/executors/gateway/prod-runtime/handler.d.ts +2 -0
- package/executors/gateway/prod-runtime/handler.js +1 -1
- package/executors/gateway/prod-runtime/hooks.js +1 -1
- package/executors/gateway/prod-runtime/observability.js +1 -1
- package/executors/gateway/prod-runtime/rollout.d.ts +7 -0
- package/executors/gateway/prod-runtime/rollout.js +1 -1
- package/executors/gateway/prod-runtime/route-limits.d.ts +30 -0
- package/executors/gateway/prod-runtime/route-limits.js +1 -0
- package/executors/gateway/prod-runtime/routing.js +1 -1
- package/executors/gateway/prod-runtime/server.js +1 -1
- package/executors/gateway/prod-runtime/trust.d.ts +45 -1
- package/executors/gateway/prod-runtime/trust.js +1 -1
- package/executors/gateway/prod-runtime/types.d.ts +33 -5
- package/executors/gateway/prod-runtime/upgrade.d.ts +2 -27
- package/executors/gateway/prod-runtime/upgrade.js +11 -9
- package/executors/gateway/prod-runtime/upstream-errors.d.ts +9 -0
- package/executors/gateway/prod-runtime/upstream-errors.js +1 -1
- package/executors/gateway/prod-runtime/upstream.js +1 -1
- package/executors/gateway/providers-prod.js +1 -1
- package/executors/gateway/rate-limit.js +2 -2
- package/executors/gateway/registry-source.d.ts +3 -2
- package/executors/gateway/registry-source.js +2 -1
- package/executors/gateway/rollout-ops.js +2 -2
- package/executors/gateway/runtime/act.js +1 -1
- package/executors/gateway/runtime/auth.js +1 -1
- package/executors/gateway/runtime/awake.js +1 -1
- package/executors/gateway/runtime/chooser.js +12 -12
- package/executors/gateway/runtime/control.js +2 -2
- package/executors/gateway/runtime/dev-auth.js +1 -1
- package/executors/gateway/runtime/discovery.js +1 -1
- package/executors/gateway/runtime/edge.js +1 -1
- package/executors/gateway/runtime/guest-graph.js +2 -2
- package/executors/gateway/runtime/guest-replay.js +2 -2
- package/executors/gateway/runtime/handler.js +1 -1
- package/executors/gateway/runtime/hmr-reload.js +1 -1
- package/executors/gateway/runtime/hooks.js +1 -1
- package/executors/gateway/runtime/hosted-dashboard.js +1 -1
- package/executors/gateway/runtime/instance.js +3 -3
- package/executors/gateway/runtime/internal-fetch.js +1 -1
- package/executors/gateway/runtime/lens-children.js +1 -1
- package/executors/gateway/runtime/lifecycle.js +4 -4
- package/executors/gateway/runtime/observability.js +3 -3
- package/executors/gateway/runtime/on-demand.js +7 -7
- package/executors/gateway/runtime/orphan-reaper.js +2 -2
- package/executors/gateway/runtime/own-log.js +6 -6
- package/executors/gateway/runtime/parked-dashboards.js +1 -1
- package/executors/gateway/runtime/pod-env.js +2 -2
- package/executors/gateway/runtime/pod-output.js +1 -1
- package/executors/gateway/runtime/pod-probe.js +1 -1
- package/executors/gateway/runtime/process-names.js +1 -1
- package/executors/gateway/runtime/project-graph-store.js +1 -1
- package/executors/gateway/runtime/proxy.js +1 -1
- package/executors/gateway/runtime/registration-guards.js +1 -1
- package/executors/gateway/runtime/route-registry.js +1 -1
- package/executors/gateway/runtime/scope.js +1 -1
- package/executors/gateway/runtime/serve-launch.js +3 -3
- package/executors/gateway/runtime/server.js +2 -2
- package/executors/gateway/runtime/service-keys.js +1 -1
- package/executors/gateway/runtime/shared-build.js +3 -3
- package/executors/gateway/runtime/source-poller.js +1 -1
- package/executors/gateway/runtime/types.js +1 -1
- package/executors/gateway/runtime/upgrade.js +1 -1
- package/executors/gateway/runtime/warm-start.js +1 -1
- package/executors/gateway/runtime/workspace-auth.js +1 -1
- package/executors/gateway/runtime/workspace-log.js +1 -1
- package/executors/gateway/runtime/workspace-middleware.js +1 -1
- package/executors/gateway/runtime/workspace-registry.js +1 -1
- package/executors/gateway/ssrf-guard.js +1 -1
- package/executors/gateway/workspace-auth.js +1 -1
- package/executors/serve/serve.impl.js +1 -1
- package/executors/serve/stop-on-signal.js +1 -1
- package/executors/trust/hostname.js +1 -1
- package/executors/trust/trust.impl.js +3 -3
- package/exit-reason.js +2 -2
- package/fork-ts-check-reporter.js +1 -1
- package/gateway.js +1 -1
- package/gc-notice.js +1 -1
- package/graph-snapshot.js +1 -1
- package/handoff-retire.js +1 -1
- package/heap-snapshot.js +1 -1
- package/hot-swap-registries.js +1 -1
- package/index.js +1 -1
- package/inspector-secret.js +1 -1
- package/main.devserver.js +11 -11
- package/notice-generation.js +1 -1
- package/package.json +4 -4
- package/perf/heavy-barrel-import.js +1 -1
- package/perf/perf-config.js +1 -1
- package/perf/perf-rule-events.js +2 -2
- package/perf/perf-rules-analysis.js +1 -1
- package/perf/perf-rules-plugin.js +1 -1
- package/perf/source-scan.js +5 -5
- package/perf/workspace-libraries.js +2 -2
- package/pod-memory-events.js +2 -2
- package/pod-memory.js +1 -1
- package/pod-sock.js +1 -1
- package/process-name.js +1 -1
- package/redis-disconnect-fix.js +1 -1
- package/schema-first-instance.js +1 -1
- package/serve-runner.js +1 -1
- package/service-build-events.js +2 -2
- package/shared-build/attach.js +2 -2
- package/shared-build/host.js +3 -3
- package/shared-build/protocol.js +1 -1
- package/shared-build/shared-compilation.js +3 -3
- package/shared-build/signature.js +1 -1
- package/stdio-guard.js +1 -1
- package/swap-mode.js +1 -1
- package/swap-recycle.js +1 -1
- package/tsgo-check-plugin.js +4 -4
- package/typecheck-bus.js +3 -3
- package/typecheck-queue.js +1 -1
- package/worker-guard.js +1 -1
- package/worker-retire.js +1 -1
- package/worker-supervisor.js +2 -2
- package/workspace-paths.js +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
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,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`;z?.maybeRotateEventFile(
|
|
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,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var p=Object.defineProperty;var l=(e,r)=>p(e,"name",{value:r,configurable:!0});var a=Object.defineProperty,i=l((e,r)=>a(e,"name",{value:r,configurable:!0}),"i");Object.defineProperty(exports,"__esModule",{value:!0}),exports.runRollout=runRollout;const node_fs_1=require("node:fs"),rollout_ops_1=require("./rollout-ops"),registry_source_1=require("./registry-source"),USAGE=`lensmcp rollout \u2014 edit the gateway rollout config (file or Redis registry)
|
|
2
2
|
|
|
3
3
|
Usage: <config.json> <command> [args]
|
|
4
4
|
--redis <url> [--prefix <p>] <command> [args]
|
|
@@ -16,9 +16,9 @@ Commands:
|
|
|
16
16
|
`)?e:e+`
|
|
17
17
|
`),"out"),err=i(e=>process.stderr.write(e.endsWith(`
|
|
18
18
|
`)?e:e+`
|
|
19
|
-
`),"err");function extractFlag(e,r){const o=e.indexOf(r);return o<0?{rest:e}:{value:e[o+1],rest:[...e.slice(0,o),...e.slice(o+2)]}}
|
|
19
|
+
`),"err");function extractFlag(e,r){const o=e.indexOf(r);return o<0?{rest:e}:{value:e[o+1],rest:[...e.slice(0,o),...e.slice(o+2)]}}l(extractFlag,"extractFlag"),i(extractFlag,"extractFlag");function runFile(e){const[r,...o]=e;if(!r||!o.length)return err(USAGE),2;let s;try{s=JSON.parse((0,node_fs_1.readFileSync)(r,"utf8"))}catch(t){return err(`cannot read ${r}: ${t.message}`),1}try{const t=(0,rollout_ops_1.parseRolloutCommand)(o);if(!t.op)return out((0,rollout_ops_1.summarizeRollout)(s,t.status)),0;const n=(0,rollout_ops_1.applyRolloutOp)(s,t.op);return(0,node_fs_1.writeFileSync)(`${r}.tmp`,JSON.stringify(n,null,2)+`
|
|
20
20
|
`),(0,node_fs_1.renameSync)(`${r}.tmp`,r),out(`\u2713 ${t.op.kind} ${t.op.service}
|
|
21
21
|
|
|
22
|
-
${(0,rollout_ops_1.summarizeRollout)(n,t.op.service)}`),0}catch(t){return err(`\u2717 ${t.message}`),1}}
|
|
22
|
+
${(0,rollout_ops_1.summarizeRollout)(n,t.op.service)}`),0}catch(t){return err(`\u2717 ${t.message}`),1}}l(runFile,"runFile"),i(runFile,"runFile");async function runRedis(e,r,o){if(!o.length)return err(USAGE),2;let s;try{const t=require("ioredis");s=new t(e)}catch{return err('--redis needs the "ioredis" package installed (peer dep of @lensmcp/cluster)'),1}try{const{endpoints:t}=await(0,registry_source_1.redisRegistrySource)(s,{prefix:r}).read(),n=(0,rollout_ops_1.parseRolloutCommand)(o);if(!n.op)return out((0,rollout_ops_1.summarizeRollout)(t,n.status)),0;const c=(0,rollout_ops_1.applyRolloutOp)(t,n.op),u=n.op.service,d=c[u];return d===void 0?await s.del((0,registry_source_1.rolloutKey)(r,u)):await s.set((0,registry_source_1.rolloutKey)(r,u),JSON.stringify(d)),await s.publish((0,registry_source_1.changeChannel)(r),u),out(`\u2713 ${n.op.kind} ${u} \u2192 redis ${r} (published)
|
|
23
23
|
|
|
24
|
-
${(0,rollout_ops_1.summarizeRollout)(
|
|
24
|
+
${(0,rollout_ops_1.summarizeRollout)(c,u)}`),0}catch(t){return err(`\u2717 ${t.message}`),1}finally{try{await s.quit()}catch{}}}l(runRedis,"runRedis"),i(runRedis,"runRedis");async function runRollout(e){const r=extractFlag(e,"--redis"),o=extractFlag(r.rest,"--prefix");return r.value?runRedis(r.value,o.value??registry_source_1.DEFAULT_REGISTRY_PREFIX,o.rest):runFile(o.rest)}l(runRollout,"runRollout"),i(runRollout,"runRollout"),require.main===module&&runRollout(process.argv.slice(2)).then(e=>process.exit(e));
|
|
@@ -1,23 +1,3 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Route manifests + the provider seams that make the gateway ONE library
|
|
3
|
-
* across dev and prod.
|
|
4
|
-
*
|
|
5
|
-
* The dev gateway and the production gateway share this routing core. A
|
|
6
|
-
* service DESCRIBES itself with a `RouteManifest` (in dev, synthesized from
|
|
7
|
-
* the project.json `cluster` field; in prod, published by the service to a
|
|
8
|
-
* registry / served at `/.well-known/lensmcp-routes`). The gateway builds a
|
|
9
|
-
* flat `Route[]` from the manifests and matches requests against it — the
|
|
10
|
-
* SAME `matchRoute` in both environments, so routing can never drift.
|
|
11
|
-
*
|
|
12
|
-
* What differs between dev and prod is supplied through two interfaces:
|
|
13
|
-
* - ManifestProvider — WHERE the manifests come from (workspace scan vs
|
|
14
|
-
* registry watch) and how changes arrive.
|
|
15
|
-
* - PodProvider — HOW a service name resolves to a concrete upstream
|
|
16
|
-
* (unix-socket pool with scale-from-zero vs a TCP endpoint).
|
|
17
|
-
*
|
|
18
|
-
* This module is PURE (no IO, no process, no http) so it is exhaustively
|
|
19
|
-
* unit-testable; the providers carry the environment-specific machinery.
|
|
20
|
-
*/
|
|
21
1
|
/** A host[+path] a service is mounted at (e.g. `api.tetros.ai` + `/crm`). */
|
|
22
2
|
export interface RouteMount {
|
|
23
3
|
host: string;
|
|
@@ -50,16 +30,24 @@ export interface AuthPolicy {
|
|
|
50
30
|
default?: AuthMode;
|
|
51
31
|
overrides?: AuthOverride[];
|
|
52
32
|
}
|
|
53
|
-
/**
|
|
54
|
-
*
|
|
33
|
+
/**
|
|
34
|
+
* Per-route rate limit, declared by the service and ENFORCED at the prod edge after auth (`prod-runtime/route-limits.ts`,
|
|
35
|
+
* issues/closed/prod-gateway-4-19). The field used to be carried and never read: a service that declared a limit on
|
|
36
|
+
* its login path got none and was told nothing.
|
|
37
|
+
*/
|
|
55
38
|
export interface RateLimit {
|
|
56
|
-
/** Path
|
|
39
|
+
/** Path this limit applies to (segment-prefix, like an auth override's); omit for the whole service. */
|
|
57
40
|
path?: string;
|
|
58
|
-
/** Bucket key dimension
|
|
41
|
+
/** Bucket key dimension: `ip` (the resolved client address), `tenant` (the verified `tid`) or `user` (the verified
|
|
42
|
+
* `sub`). A caller with no such identity is bucketed by address. */
|
|
59
43
|
key: string;
|
|
44
|
+
/** Requests allowed per window. */
|
|
60
45
|
points: number;
|
|
46
|
+
/** Window length in SECONDS. */
|
|
61
47
|
duration: number;
|
|
62
48
|
}
|
|
49
|
+
/** The dimensions a {@link RateLimit} may key on. */
|
|
50
|
+
export declare const RATE_LIMIT_KEYS: ReadonlySet<string>;
|
|
63
51
|
/**
|
|
64
52
|
* A service's self-description — the canonical thing the gateway routes from.
|
|
65
53
|
* In dev this is synthesized from project.json; in prod the service publishes
|
|
@@ -177,6 +165,8 @@ export interface Route {
|
|
|
177
165
|
* `buildRouteTable` always sets it (`{}` when the manifest declares none).
|
|
178
166
|
*/
|
|
179
167
|
policy?: AuthPolicy;
|
|
168
|
+
/** The manifest's per-route limits, carried like the policy (PG4-19). */
|
|
169
|
+
rateLimits?: RateLimit[];
|
|
180
170
|
}
|
|
181
171
|
/**
|
|
182
172
|
* Exact hostname or `*.suffix` wildcard (the bare suffix also matches).
|
|
@@ -278,6 +268,34 @@ export declare function authRuleForPath(manifest: RouteManifest, path: string, m
|
|
|
278
268
|
* specificity so `matchRoute` picks the most specific.
|
|
279
269
|
*/
|
|
280
270
|
export declare function buildRouteTable(manifests: readonly RouteManifest[]): Route[];
|
|
271
|
+
/**
|
|
272
|
+
* Everything wrong with ONE manifest's shape, or `[]` (PG4-05). The loaders used to check `service` and
|
|
273
|
+
* `Array.isArray(mounts)` and nothing else: `mounts:[{host:123}]` then made `hostMatches` throw for EVERY request on
|
|
274
|
+
* EVERY host, `mounts:[null]` and `auth.overrides:{}` threw out of `buildRouteTable` (a boot crash, and a route table
|
|
275
|
+
* that could never be rebuilt), and `mounts:[{}]` quietly became a second catch-all. A manifest is published by the
|
|
276
|
+
* service it describes; one service's malformed publish must cost that service its routes and nobody else theirs.
|
|
277
|
+
*/
|
|
278
|
+
export declare function manifestDefects(m: unknown): string[];
|
|
279
|
+
/**
|
|
280
|
+
* Who may mount which host — the operator's map, `{ hostPattern: [service, …] }` (PG4-06). A pattern is an exact
|
|
281
|
+
* host or `*.suffix`; the key `(default)` names the services that may be the catch-all. A host no pattern covers is
|
|
282
|
+
* free, so a deployment can pin just the hosts that matter (the IdP's, the API's).
|
|
283
|
+
*
|
|
284
|
+
* Without it any registry writer can mount `/login` on the IdP's host from its own key and be handed every caller's
|
|
285
|
+
* credentials: longest-prefix-match decides, and nothing in a manifest says whose host that is.
|
|
286
|
+
*/
|
|
287
|
+
export type HostOwners = Readonly<Record<string, readonly string[]>>;
|
|
288
|
+
/**
|
|
289
|
+
* Split a manifest set into what the edge will route and what it refuses, naming every refusal (PG4-05, PG4-06):
|
|
290
|
+
* - a manifest with a shape defect is dropped whole ({@link manifestDefects});
|
|
291
|
+
* - with `owners`, a mount on a host that belongs to other services is dropped (the manifest keeps its own hosts),
|
|
292
|
+
* as is a `default: true` from a service the map does not allow to be the catch-all.
|
|
293
|
+
* Never throws — whatever a provider hands in.
|
|
294
|
+
*/
|
|
295
|
+
export declare function admitManifests(manifests: readonly unknown[], owners?: HostOwners): {
|
|
296
|
+
ok: RouteManifest[];
|
|
297
|
+
problems: ManifestProblem[];
|
|
298
|
+
};
|
|
281
299
|
/** A configuration defect found in a manifest set — reported loudly at load, never served open. */
|
|
282
300
|
export interface ManifestProblem {
|
|
283
301
|
service: string;
|
|
@@ -340,6 +358,22 @@ export interface TargetRule {
|
|
|
340
358
|
}
|
|
341
359
|
/** Longest pattern, and longest attribute value, a `regex` condition runs on. Attributes are claims and headers. */
|
|
342
360
|
export declare const MAX_REGEX_LENGTH = 512;
|
|
361
|
+
/**
|
|
362
|
+
* Bound every rule regex in TIME (PG4-07). A lexical check cannot: `^(a|a)+$` — an alternation that overlaps under one
|
|
363
|
+
* quantifier — passed {@link unsafeRegex} and held the event loop 6.6 s on a 26-character path, and the 512-character
|
|
364
|
+
* value bound does not bound exponential cost at all.
|
|
365
|
+
*
|
|
366
|
+
* V8 ships a second, linear-time matcher. With `--enable-experimental-regexp-engine-on-excessive-backtracks` the
|
|
367
|
+
* ordinary engine hands a match over to it after 50 000 backtracks, so a pathological input costs about a millisecond
|
|
368
|
+
* instead of seconds; the result is the same. Both flags are settable at runtime, so this needs no launch flag and
|
|
369
|
+
* holds for a process that embeds the gateway. The linear engine cannot run lookaheads, backreferences or large
|
|
370
|
+
* counted repetitions; `--enable-experimental-regexp-engine` makes the `l` flag available, which is how
|
|
371
|
+
* {@link unsafeRegex} asks whether a given pattern HAS a linear fallback — one that has none is refused.
|
|
372
|
+
*
|
|
373
|
+
* Process-wide and idempotent; armed on the first regex rule. Returns false on a runtime without the engine, where
|
|
374
|
+
* the lexical check stands alone.
|
|
375
|
+
*/
|
|
376
|
+
export declare function armRegexGuard(): boolean;
|
|
343
377
|
/**
|
|
344
378
|
* Why a rule pattern is refused, or undefined when it is safe to run. A pattern-length bound alone let
|
|
345
379
|
* `^(\w+\s?)+$` hold the event loop for 8 s on a 27-byte client header (PG3-25): the cost of a backtracking match
|
|
@@ -347,11 +381,22 @@ export declare const MAX_REGEX_LENGTH = 512;
|
|
|
347
381
|
* - a quantified group that itself contains a repeating quantifier (star height > 1: `(a+)+`, `(\w+\s?)*`,
|
|
348
382
|
* `(a*b){2,}`) — the classic exponential shape, what `safe-regex` checks;
|
|
349
383
|
* - a backreference (`\1`, `\k<x>`), which no engine matches in linear time.
|
|
350
|
-
* A lexical check, not a proof: overlapping alternations under one quantifier (`(a|aa)+`) pass it
|
|
351
|
-
* the
|
|
384
|
+
* A lexical check, not a proof: overlapping alternations under one quantifier (`(a|aa)+`) pass it. What bounds
|
|
385
|
+
* those is {@link armRegexGuard} — and a pattern the linear engine cannot take over (a lookahead, a large counted
|
|
386
|
+
* repetition) is refused here, because for it there is no bound at all.
|
|
352
387
|
*/
|
|
353
388
|
export declare function unsafeRegex(src: string): string | undefined;
|
|
354
|
-
/**
|
|
389
|
+
/**
|
|
390
|
+
* An IPv6 address as a 128-bit integer, or null if it is not one. Accepts `::` compression, a zone id, brackets and
|
|
391
|
+
* an embedded IPv4 tail (`::ffff:1.2.3.4`) — every spelling of one address yields one number, which is what makes a
|
|
392
|
+
* prefix comparison (and a limiter key, `client-ip.ts`) independent of how a proxy chose to write it.
|
|
393
|
+
*/
|
|
394
|
+
export declare function ipv6ToBigInt(ip: string): bigint | null;
|
|
395
|
+
/**
|
|
396
|
+
* `ip ∈ cidr`, IPv4 and IPv6. An IPv4-mapped IPv6 address is judged by IPv4 rules; an IPv4 address never matches an
|
|
397
|
+
* IPv6 network and vice versa. False for anything malformed. (IPv6 networks used to be unmatchable — PG4-10 — so an
|
|
398
|
+
* `ip` rule or `internalPeers` could not name an IPv6 caller at all.)
|
|
399
|
+
*/
|
|
355
400
|
export declare function matchCidr(ip: string, cidr: string): boolean;
|
|
356
401
|
/** Evaluate a rule node (condition or all/any/not group) against attributes. Pure. A condition that cannot be
|
|
357
402
|
* evaluated safely makes the WHOLE rule false (deny / no targeting), wherever it sits. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var m=Object.defineProperty;var c=(e,r)=>m(e,"name",{value:r,configurable:!0});var p=Object.defineProperty,l=c((e,r)=>p(e,"name",{value:r,configurable:!0}),"l"),h=Object.defineProperty,a=l((e,r)=>h(e,"name",{value:r,configurable:!0}),"a");Object.defineProperty(exports,"__esModule",{value:!0}),exports.MAX_REGEX_LENGTH=void 0,exports.smoothWeightedSelector=smoothWeightedSelector,exports.hostMatches=hostMatches,exports.matchRoute=matchRoute,exports.pathUnderPrefix=pathUnderPrefix,exports.sortBySpecificity=sortBySpecificity,exports.authForPath=authForPath,exports.authPathMatches=authPathMatches,exports.authRuleFor=authRuleFor,exports.authRuleForPath=authRuleForPath,exports.buildRouteTable=buildRouteTable,exports.manifestProblems=manifestProblems,exports.regexSources=regexSources,exports.manifestFromClusterDecl=manifestFromClusterDecl,exports.claimAttrs=claimAttrs,exports.unsafeRegex=unsafeRegex,exports.matchCidr=matchCidr,exports.evalRule=evalRule,exports.pickTargetedVersion=pickTargetedVersion,exports.fnv1a=fnv1a,exports.bucketByWeight=bucketByWeight;function smoothWeightedSelector(e){const r=e.map(()=>0),t=e.reduce((n,o)=>n+Math.max(0,o),0);return()=>{if(t<=0||e.length===0)return 0;let n=0;for(let o=0;o<e.length;o++)r[o]+=Math.max(0,e[o]),r[o]>r[n]&&(n=o);return r[n]-=t,n}}c(smoothWeightedSelector,"smoothWeightedSelector"),l(smoothWeightedSelector,"smoothWeightedSelector"),a(smoothWeightedSelector,"smoothWeightedSelector");function hostMatches(e,r){const t=e.toLowerCase(),n=r.toLowerCase();return t.startsWith("*.")?n.endsWith(t.slice(1))||n===t.slice(2):n===t}c(hostMatches,"hostMatches"),l(hostMatches,"hostMatches"),a(hostMatches,"hostMatches");function matchRoute(e,r,t){const n=e.some(s=>s.host&&hostMatches(s.host,r));let o;if(n){o=e.filter(i=>i.host&&hostMatches(i.host,r));const s=r.toLowerCase();o.some(i=>i.host.toLowerCase()===s)?o=o.filter(i=>i.host.toLowerCase()===s):o.length>1&&(o=[...o].sort((i,u)=>u.host.length-i.host.length))}else{const s=e.filter(i=>!i.host);if(s.length<=1)o=s;else{const i=r.toLowerCase(),u=s.filter(f=>{const d=f.apex?.toLowerCase();return!!d&&(i===d||i.endsWith("."+d))}).sort((f,d)=>d.apex.length-f.apex.length);o=u.length>0?u:s.filter(f=>!f.apex)}}return o.find(s=>!s.prefix||pathUnderPrefix(t,s.prefix))}c(matchRoute,"matchRoute"),l(matchRoute,"matchRoute"),a(matchRoute,"matchRoute");function pathUnderPrefix(e,r){let t=r.length;for(;t>0&&r.charCodeAt(t-1)===47;)t-=1;if(t===0)return!0;if(e.length<t||e.slice(0,t).toLowerCase()!==r.slice(0,t).toLowerCase())return!1;const n=e.charCodeAt(t);return Number.isNaN(n)||n===47||n===63}c(pathUnderPrefix,"pathUnderPrefix"),l(pathUnderPrefix,"pathUnderPrefix"),a(pathUnderPrefix,"pathUnderPrefix");function sortBySpecificity(e){const r=a(t=>(t.host?2:0)+(t.prefix?1:0),"rank");return e.sort((t,n)=>r(n)-r(t)||(n.prefix?.length??0)-(t.prefix?.length??0)),e}c(sortBySpecificity,"sortBySpecificity"),l(sortBySpecificity,"sortBySpecificity"),a(sortBySpecificity,"sortBySpecificity");function authForPath(e,r,t){if(t)return"internal";const n=e.auth?.overrides??[];for(const o of n)if(r.startsWith(o.path))return o.mode;return e.auth?.default??"jwt"}c(authForPath,"authForPath"),l(authForPath,"authForPath"),a(authForPath,"authForPath");function authPathMatches(e,r){const t=e.split("/").filter(Boolean),n=r.split("/").filter(Boolean);if(n.length<t.length)return!1;for(let o=0;o<t.length;o++){const s=t[o];if(!(s==="*"||s.startsWith(":"))&&s.toLowerCase()!==n[o].toLowerCase())return!1}return!0}c(authPathMatches,"authPathMatches"),l(authPathMatches,"authPathMatches"),a(authPathMatches,"authPathMatches");function authRuleFor(e,r,t){const n=t.toUpperCase();for(const o of e?.overrides??[]){if(!authPathMatches(o.path,r)||o.methods&&!o.methods.some(i=>{const u=i.toUpperCase();return u===n||n==="HEAD"&&u==="GET"}))continue;const s=o.rule??(o.permission?{attr:"perms",op:"hastoken",value:o.permission}:void 0);return{mode:o.mode??e?.default??"jwt",...s?{rule:s}:{}}}return{mode:e?.default??"jwt"}}c(authRuleFor,"authRuleFor"),l(authRuleFor,"authRuleFor"),a(authRuleFor,"authRuleFor");function authRuleForPath(e,r,t,n){return n?{mode:"internal"}:authRuleFor(e.auth,r,t)}c(authRuleForPath,"authRuleForPath"),l(authRuleForPath,"authRuleForPath"),a(authRuleForPath,"authRuleForPath");function buildRouteTable(e){const r=[];for(const t of e){const n=t.auth?.default??"jwt",o=t.auth??{};for(const s of t.mounts){const i={service:t.service,...s.path?{prefix:s.path}:{},...t.prependPrefix?{prependPrefix:t.prependPrefix}:{},...t.upstream?{upstream:t.upstream}:{}};r.push({...i,host:s.host,auth:n,policy:o}),t.internal&&t.internalHost!==!1&&r.push({...i,host:typeof t.internalHost=="string"?t.internalHost:`internal.${s.host}`,internal:!0,auth:"internal"})}t.default&&r.push({service:t.service,...t.prependPrefix?{prependPrefix:t.prependPrefix}:{},...t.upstream?{upstream:t.upstream}:{},default:!0,auth:n,policy:o})}return sortBySpecificity(r)}c(buildRouteTable,"buildRouteTable"),l(buildRouteTable,"buildRouteTable"),a(buildRouteTable,"buildRouteTable");const HOST_ROUTE_MODES=new Set(["jwt","public"]);function manifestProblems(e){const r=[],t=new Map;for(const n of e){const o=n.mounts.map(u=>u.host+(u.path??"")),s=t.get(n.service);s&&r.push({service:n.service,problem:`the service name is declared by more than one manifest (${[...s,...o].join(", ")}) \u2014 each route keeps its own manifest's auth policy; give each manifest its own name`}),t.set(n.service,[...s??[],...o]);const i=n.auth?.default;i!==void 0&&!HOST_ROUTE_MODES.has(i)&&r.push({service:n.service,problem:`auth.default is \xAB${String(i)}\xBB \u2014 a host route is served as \`jwt\` or \`public\` only (\`internal\` is a route kind: set \`internal: true\` for an \`internal.<host>\` route); every request to it answers 401`});for(const u of n.auth?.overrides??[]){u.mode!==void 0&&!HOST_ROUTE_MODES.has(u.mode)&&r.push({service:n.service,problem:`the override for ${u.path} has mode \xAB${String(u.mode)}\xBB \u2014 only \`jwt\` and \`public\` are modes; requests under it answer 401`});for(const f of regexSources(u.rule)){const d=unsafeRegex(f);d&&r.push({service:n.service,problem:`the override for ${u.path} has a regex rule the edge will not run (${d}): ${f.slice(0,80)}`})}}}return r}c(manifestProblems,"manifestProblems"),l(manifestProblems,"manifestProblems"),a(manifestProblems,"manifestProblems");function regexSources(e){return e?isGroup(e)?[...(e.all??[]).flatMap(regexSources),...(e.any??[]).flatMap(regexSources),...regexSources(e.not)]:e.op==="regex"?[str(e.value)]:[]:[]}c(regexSources,"regexSources"),l(regexSources,"regexSources"),a(regexSources,"regexSources");function manifestFromClusterDecl(e,r){const t=r.upstream??(r.port?`http://localhost:${r.port}`:void 0);if(!(!r.service&&!t))return{service:r.service??e,mounts:r.host?[{host:r.host,...r.path?{path:r.path}:{}}]:[],internal:!!r.service,...r.internalHost!==void 0?{internalHost:r.internalHost}:{},...r.default?{default:!0}:{},...r.prependPrefix?{prependPrefix:r.prependPrefix}:{},...r.auth?{auth:r.auth}:{},...t?{upstream:t}:{}}}c(manifestFromClusterDecl,"manifestFromClusterDecl"),l(manifestFromClusterDecl,"manifestFromClusterDecl"),a(manifestFromClusterDecl,"manifestFromClusterDecl");const RESERVED_ATTRS=new Set(["ip","method","path","device"]);function claimAttrs(e){const r={...e??{}};for(const t of Object.keys(r))(RESERVED_ATTRS.has(t)||t.startsWith("header."))&&delete r[t];return r}c(claimAttrs,"claimAttrs"),l(claimAttrs,"claimAttrs"),a(claimAttrs,"claimAttrs");const isGroup=a(e=>"all"in e||"any"in e||"not"in e,"isGroup");exports.MAX_REGEX_LENGTH=512;function unsafeRegex(e){if(e.length>exports.MAX_REGEX_LENGTH)return`longer than ${exports.MAX_REGEX_LENGTH} characters`;if(/\\[1-9]|\\k</.test(e))return"a backreference";const r=[];let t;for(let n=0;n<e.length;){const o=e[n];if(o==="\\"){n+=2,t=!1;continue}if(o==="["){for(n+=1,e[n]==="^"&&(n+=1),e[n]==="]"&&(n+=1);n<e.length&&e[n]!=="]";)n+=e[n]==="\\"?2:1;n+=1,t=!1;continue}if(o==="("){if(r.push(!1),n+=1,t=void 0,e[n]==="?"){if(n+=1,e[n]==="<"&&e[n+1]!=="="&&e[n+1]!=="!")for(;n<e.length&&e[n]!==">";)n+=1;n+=1}continue}if(o===")"){const u=r.pop()??!1;n+=1,u&&r.length&&(r[r.length-1]=!0),t=u;continue}if(o==="|"){n+=1,t=void 0;continue}let s,i=1;if(o==="*"||o==="+")s=!0;else if(o==="?")s=!1;else if(o==="{"){const u=/^\{(\d+)(,(\d*))?\}/.exec(e.slice(n));if(u){i=u[0].length;const f=Number(u[1]);s=(u[2]===void 0?f:u[3]===""?1/0:Number(u[3]))>1}}if(s===void 0){n+=1,t=!1;continue}if(n+=i,e[n]==="?"&&(n+=1),t!==void 0){if(s&&t)return"nested quantifiers";s&&r.length&&(r[r.length-1]=!0),t=!1}}}c(unsafeRegex,"unsafeRegex"),l(unsafeRegex,"unsafeRegex"),a(unsafeRegex,"unsafeRegex");class Indeterminate extends Error{static{c(this,"Indeterminate")}static{l(this,"Indeterminate")}static{a(this,"Indeterminate")}}const reCache=new Map,compileRe=a(e=>{if(reCache.has(e))return reCache.get(e);let r=null;if(!unsafeRegex(e))try{r=new RegExp(e)}catch{r=null}return reCache.size>=1024&&reCache.clear(),reCache.set(e,r),r},"compileRe");function ipToInt(e){const r=(e.startsWith("::ffff:")?e.slice(7):e).split(".");if(r.length!==4)return null;let t=0;for(const n of r){const o=Number(n);if(!Number.isInteger(o)||o<0||o>255||n.length>1&&n[0]==="0")return null;t=t*256+o}return t>>>0}c(ipToInt,"ipToInt"),l(ipToInt,"ipToInt"),a(ipToInt,"ipToInt");function matchCidr(e,r){const t=r.indexOf("/");if(t<0)return!1;const n=Number(r.slice(t+1));if(!Number.isInteger(n)||n<0||n>32)return!1;const o=ipToInt(e),s=ipToInt(r.slice(0,t));if(o===null||s===null)return!1;if(n===0)return!0;const i=(n===32?4294967295:~((1<<32-n)-1))>>>0;return(o&i)>>>0===(s&i)>>>0}c(matchCidr,"matchCidr"),l(matchCidr,"matchCidr"),a(matchCidr,"matchCidr");const str=a(e=>e==null?"":String(e),"str"),eq=a((e,r)=>str(e)===str(r),"eq");function evalCondition(e,r){const t=r[e.attr],n=t!=null;switch(e.op){case"exists":return n;case"ne":return!n||!eq(t,e.value)}if(!n)return!1;switch(e.op){case"eq":return eq(t,e.value);case"in":return Array.isArray(e.value)&&e.value.some(o=>Array.isArray(t)?t.some(s=>eq(s,o)):eq(t,o));case"nin":return Array.isArray(e.value)&&!e.value.some(o=>Array.isArray(t)?t.some(s=>eq(s,o)):eq(t,o));case"prefix":return str(t).startsWith(str(e.value));case"suffix":return str(t).endsWith(str(e.value));case"domain":{const o=str(t).lastIndexOf("@"),s=(o===-1?str(t):str(t).slice(o+1)).toLowerCase().replace(/\.$/,""),i=str(e.value).toLowerCase().replace(/^\./,"").replace(/\.$/,"");return!!i&&(s===i||s.endsWith("."+i))}case"contains":return Array.isArray(t)?t.some(o=>eq(o,e.value)):str(t).includes(str(e.value));case"hastoken":{const o=str(e.value);return Array.isArray(t)?t.some(s=>eq(s,e.value)):str(t).split(/[\s,]+/).filter(Boolean).includes(o)}case"regex":{const o=compileRe(str(e.value)),s=str(t);if(!o||s.length>exports.MAX_REGEX_LENGTH)throw new Indeterminate;return o.test(s)}case"gt":return Number(t)>Number(e.value);case"lt":return Number(t)<Number(e.value);case"cidr":return matchCidr(str(t),str(e.value));default:return!1}}c(evalCondition,"evalCondition"),l(evalCondition,"evalCondition"),a(evalCondition,"evalCondition");function evalNode(e,r){if(!isGroup(e))return evalCondition(e,r);const t=Array.isArray(e.all)&&e.all.length?e.all:void 0,n=Array.isArray(e.any)&&e.any.length?e.any:void 0,o=e.not&&Object.keys(e.not).length?e.not:void 0;return o&&evalNode(o,r)||t&&!t.every(s=>evalNode(s,r))||n&&!n.some(s=>evalNode(s,r))?!1:!!(t||n||o)}c(evalNode,"evalNode"),l(evalNode,"evalNode"),a(evalNode,"evalNode");function evalRule(e,r){try{return evalNode(e,r)}catch(t){if(t instanceof Indeterminate)return!1;throw t}}c(evalRule,"evalRule"),l(evalRule,"evalRule"),a(evalRule,"evalRule");function pickTargetedVersion(e,r){for(const t of e)if(evalRule(t.when,r))return{version:t.version,...t.name?{rule:t.name}:{}}}c(pickTargetedVersion,"pickTargetedVersion"),l(pickTargetedVersion,"pickTargetedVersion"),a(pickTargetedVersion,"pickTargetedVersion");function fnv1a(e){let r=2166136261;for(let t=0;t<e.length;t++)r^=e.charCodeAt(t),r=Math.imul(r,16777619);return r>>>0}c(fnv1a,"fnv1a"),l(fnv1a,"fnv1a"),a(fnv1a,"fnv1a");function bucketByWeight(e,r){const t=r.reduce((s,i)=>s+Math.max(0,i),0);if(t<=0||r.length===0)return 0;const n=fnv1a(e)%1e4;let o=0;for(let s=0;s<r.length;s++)if(o+=Math.max(0,r[s])/t*1e4,n<o)return s;return r.length-1}c(bucketByWeight,"bucketByWeight"),l(bucketByWeight,"bucketByWeight"),a(bucketByWeight,"bucketByWeight");
|
|
1
|
+
"use strict";var v=Object.defineProperty;var c=(e,t)=>v(e,"name",{value:t,configurable:!0});var d=Object.defineProperty,u=c((e,t)=>d(e,"name",{value:t,configurable:!0}),"u");Object.defineProperty(exports,"__esModule",{value:!0}),exports.MAX_REGEX_LENGTH=exports.RATE_LIMIT_KEYS=void 0,exports.smoothWeightedSelector=smoothWeightedSelector,exports.hostMatches=hostMatches,exports.matchRoute=matchRoute,exports.pathUnderPrefix=pathUnderPrefix,exports.sortBySpecificity=sortBySpecificity,exports.authForPath=authForPath,exports.authPathMatches=authPathMatches,exports.authRuleFor=authRuleFor,exports.authRuleForPath=authRuleForPath,exports.buildRouteTable=buildRouteTable,exports.manifestDefects=manifestDefects,exports.admitManifests=admitManifests,exports.manifestProblems=manifestProblems,exports.regexSources=regexSources,exports.manifestFromClusterDecl=manifestFromClusterDecl,exports.claimAttrs=claimAttrs,exports.armRegexGuard=armRegexGuard,exports.unsafeRegex=unsafeRegex,exports.ipv6ToBigInt=ipv6ToBigInt,exports.matchCidr=matchCidr,exports.evalRule=evalRule,exports.pickTargetedVersion=pickTargetedVersion,exports.fnv1a=fnv1a,exports.bucketByWeight=bucketByWeight;const node_v8_1=require("node:v8");exports.RATE_LIMIT_KEYS=new Set(["ip","tenant","user"]);function smoothWeightedSelector(e){const t=e.map(()=>0),r=e.reduce((n,s)=>n+Math.max(0,s),0);return()=>{if(r<=0||e.length===0)return 0;let n=0;for(let s=0;s<e.length;s++)t[s]+=Math.max(0,e[s]),t[s]>t[n]&&(n=s);return t[n]-=r,n}}c(smoothWeightedSelector,"smoothWeightedSelector"),u(smoothWeightedSelector,"smoothWeightedSelector");function hostMatches(e,t){const r=e.toLowerCase(),n=t.toLowerCase();return r.startsWith("*.")?n.endsWith(r.slice(1))||n===r.slice(2):n===r}c(hostMatches,"hostMatches"),u(hostMatches,"hostMatches");function matchRoute(e,t,r){const n=e.some(o=>o.host&&hostMatches(o.host,t));let s;if(n){s=e.filter(i=>i.host&&hostMatches(i.host,t));const o=t.toLowerCase();s.some(i=>i.host.toLowerCase()===o)?s=s.filter(i=>i.host.toLowerCase()===o):s.length>1&&(s=[...s].sort((i,a)=>a.host.length-i.host.length))}else{const o=e.filter(i=>!i.host);if(o.length<=1)s=o;else{const i=t.toLowerCase(),a=o.filter(l=>{const h=l.apex?.toLowerCase();return!!h&&(i===h||i.endsWith("."+h))}).sort((l,h)=>h.apex.length-l.apex.length);s=a.length>0?a:o.filter(l=>!l.apex)}}return s.find(o=>!o.prefix||pathUnderPrefix(r,o.prefix))}c(matchRoute,"matchRoute"),u(matchRoute,"matchRoute");function pathUnderPrefix(e,t){let r=t.length;for(;r>0&&t.charCodeAt(r-1)===47;)r-=1;if(r===0)return!0;if(e.length<r||e.slice(0,r).toLowerCase()!==t.slice(0,r).toLowerCase())return!1;const n=e.charCodeAt(r);return Number.isNaN(n)||n===47||n===63}c(pathUnderPrefix,"pathUnderPrefix"),u(pathUnderPrefix,"pathUnderPrefix");function sortBySpecificity(e){const t=u(r=>(r.host?2:0)+(r.prefix?1:0),"rank");return e.sort((r,n)=>t(n)-t(r)||(n.prefix?.length??0)-(r.prefix?.length??0)),e}c(sortBySpecificity,"sortBySpecificity"),u(sortBySpecificity,"sortBySpecificity");function authForPath(e,t,r){if(r)return"internal";const n=e.auth?.overrides??[];for(const s of n)if(t.startsWith(s.path))return s.mode;return e.auth?.default??"jwt"}c(authForPath,"authForPath"),u(authForPath,"authForPath");function authPathMatches(e,t){const r=e.split("/").filter(Boolean),n=t.split("/").filter(Boolean);if(n.length<r.length)return!1;for(let s=0;s<r.length;s++){const o=r[s];if(!(o==="*"||o.startsWith(":"))&&o.toLowerCase()!==n[s].toLowerCase())return!1}return!0}c(authPathMatches,"authPathMatches"),u(authPathMatches,"authPathMatches");function authRuleFor(e,t,r){const n=r.toUpperCase();for(const s of e?.overrides??[]){if(!authPathMatches(s.path,t)||s.methods&&!s.methods.some(i=>{const a=i.toUpperCase();return a===n||n==="HEAD"&&a==="GET"}))continue;const o=s.rule??(s.permission?{attr:"perms",op:"hastoken",value:s.permission}:void 0);return{mode:s.mode??e?.default??"jwt",...o?{rule:o}:{}}}return{mode:e?.default??"jwt"}}c(authRuleFor,"authRuleFor"),u(authRuleFor,"authRuleFor");function authRuleForPath(e,t,r,n){return n?{mode:"internal"}:authRuleFor(e.auth,t,r)}c(authRuleForPath,"authRuleForPath"),u(authRuleForPath,"authRuleForPath");function buildRouteTable(e){const t=[];for(const r of e){const n=r.auth?.default??"jwt",s=r.auth??{};for(const o of r.mounts){const i={service:r.service,...o.path?{prefix:o.path}:{},...r.prependPrefix?{prependPrefix:r.prependPrefix}:{},...r.upstream?{upstream:r.upstream}:{},...Array.isArray(r.rateLimits)&&r.rateLimits.length?{rateLimits:r.rateLimits}:{}};t.push({...i,host:o.host,auth:n,policy:s}),r.internal&&r.internalHost!==!1&&t.push({...i,host:typeof r.internalHost=="string"?r.internalHost:`internal.${o.host}`,internal:!0,auth:"internal"})}r.default&&t.push({service:r.service,...r.prependPrefix?{prependPrefix:r.prependPrefix}:{},...r.upstream?{upstream:r.upstream}:{},...Array.isArray(r.rateLimits)&&r.rateLimits.length?{rateLimits:r.rateLimits}:{},default:!0,auth:n,policy:s})}return sortBySpecificity(t)}c(buildRouteTable,"buildRouteTable"),u(buildRouteTable,"buildRouteTable");const MOUNT_HOST=/^(\*\.)?[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]+)*\.?$/,isObj=u(e=>!!e&&typeof e=="object"&&!Array.isArray(e),"isObj"),isPath=u(e=>typeof e=="string"&&e.startsWith("/"),"isPath");function manifestDefects(e){if(!isObj(e))return["the manifest is not an object"];const t=[];(typeof e.service!="string"||e.service==="")&&t.push("`service` must be a non-empty string"),Array.isArray(e.mounts)?e.mounts.forEach((s,o)=>{if(!isObj(s)){t.push(`mounts[${o}] is not an object`);return}(typeof s.host!="string"||!MOUNT_HOST.test(s.host))&&t.push(`mounts[${o}].host must be a hostname (a catch-all is \`default: true\`, not a mount without a host)`),s.path!==void 0&&!isPath(s.path)&&t.push(`mounts[${o}].path must be a string starting with \xAB/\xBB`)}):t.push("`mounts` must be an array");const r=e.auth;if(r!==void 0)if(!isObj(r))t.push("`auth` must be an object");else{r.default!==void 0&&typeof r.default!="string"&&t.push("`auth.default` must be a string");const s=r.overrides;s!==void 0&&!Array.isArray(s)?t.push("`auth.overrides` must be an array"):s?.forEach((o,i)=>{if(!isObj(o)){t.push(`auth.overrides[${i}] is not an object`);return}isPath(o.path)||t.push(`auth.overrides[${i}].path must be a string starting with \xAB/\xBB`),o.mode!==void 0&&typeof o.mode!="string"&&t.push(`auth.overrides[${i}].mode must be a string`),o.methods!==void 0&&!(Array.isArray(o.methods)&&o.methods.every(a=>typeof a=="string"))&&t.push(`auth.overrides[${i}].methods must be an array of strings`),o.permission!==void 0&&typeof o.permission!="string"&&t.push(`auth.overrides[${i}].permission must be a string`),o.rule!==void 0&&!isObj(o.rule)&&t.push(`auth.overrides[${i}].rule must be an object`)})}if(e.upstream!==void 0&&e.upstream!==null&&e.upstream!==""){let s=!1;if(typeof e.upstream=="string")try{s=/^(https?|wss?):$/.test(new URL(e.upstream).protocol)}catch{s=!1}s||t.push("`upstream` must be an http(s) URL")}e.internalHost!==void 0&&e.internalHost!==!1&&!(typeof e.internalHost=="string"&&MOUNT_HOST.test(e.internalHost))&&t.push("`internalHost` must be a hostname or false"),e.prependPrefix!==void 0&&!isPath(e.prependPrefix)&&t.push("`prependPrefix` must be a string starting with \xAB/\xBB");const n=e.rateLimits;return n!==void 0&&(Array.isArray(n)?n.forEach((s,o)=>{if(!isObj(s)){t.push(`rateLimits[${o}] is not an object`);return}s.path!==void 0&&!isPath(s.path)&&t.push(`rateLimits[${o}].path must be a string starting with \xAB/\xBB`),(typeof s.key!="string"||!exports.RATE_LIMIT_KEYS.has(s.key))&&t.push(`rateLimits[${o}].key must be one of ${[...exports.RATE_LIMIT_KEYS].join(" | ")}`),typeof s.points=="number"&&Number.isFinite(s.points)&&s.points>=1||t.push(`rateLimits[${o}].points must be a number \u2265 1`),typeof s.duration=="number"&&Number.isFinite(s.duration)&&s.duration>0||t.push(`rateLimits[${o}].duration must be a number of seconds > 0`)}):t.push("`rateLimits` must be an array")),t}c(manifestDefects,"manifestDefects"),u(manifestDefects,"manifestDefects");function ownersOf(e,t){let r;for(const[n,s]of Object.entries(e)){if(n==="(default)")continue;const o=t.startsWith("*.")?t.slice(2):t;(n.toLowerCase()===t.toLowerCase()||hostMatches(n,o))&&(r??=[]).push(...s)}return r}c(ownersOf,"ownersOf"),u(ownersOf,"ownersOf");function admitManifests(e,t){const r=[],n=[];for(const s of Array.isArray(e)?e:[]){const o=isObj(s)&&typeof s.service=="string"&&s.service?s.service:"(unnamed)",i=manifestDefects(s);if(i.length){n.push({service:o,problem:`the manifest is malformed and was NOT loaded \u2014 ${i.slice(0,4).join("; ")}${i.length>4?`; and ${i.length-4} more`:""}`});continue}let a=s;if(t){const l=a.mounts.filter(p=>{const m=ownersOf(t,p.host);return m===void 0||m.includes(a.service)?!0:(n.push({service:a.service,problem:`mount ${p.host}${p.path??""} was NOT loaded \u2014 that host belongs to ${m.join(", ")||"no service"} (host owners)`}),!1)});let h=l.length===a.mounts.length?a:{...a,mounts:l};if(typeof h.internalHost=="string"){const p=ownersOf(t,h.internalHost);p!==void 0&&!p.includes(a.service)&&(n.push({service:a.service,problem:`internalHost ${h.internalHost} was NOT loaded \u2014 that host belongs to ${p.join(", ")||"no service"} (host owners)`}),h={...h,internalHost:!1})}const f=t["(default)"];h.default&&f!==void 0&&!f.includes(a.service)&&(n.push({service:a.service,problem:`\`default: true\` was NOT honoured \u2014 the catch-all belongs to ${f.join(", ")||"no service"} (host owners)`}),h={...h,default:!1}),a=h}r.push(a)}return{ok:r,problems:n}}c(admitManifests,"admitManifests"),u(admitManifests,"admitManifests");const HOST_ROUTE_MODES=new Set(["jwt","public"]);function manifestProblems(e){const t=[],r=new Map,n=new Map;for(const s of e)for(const o of s.mounts){const i=`${o.host.toLowerCase()}|${(o.path??"").replace(/\/+$/,"").toLowerCase()}`,a=n.get(i);a!==void 0&&a!==s.service?t.push({service:s.service,problem:`mounts ${o.host}${o.path??""}, which \xAB${a}\xBB already mounts \u2014 the first one listed serves it; set host owners to decide`}):n.set(i,s.service)}for(const s of e){const o=s.mounts.map(l=>l.host+(l.path??"")),i=r.get(s.service);i&&t.push({service:s.service,problem:`the service name is declared by more than one manifest (${[...i,...o].join(", ")}) \u2014 each route keeps its own manifest's auth policy; give each manifest its own name`}),r.set(s.service,[...i??[],...o]);const a=s.auth?.default;a!==void 0&&!HOST_ROUTE_MODES.has(a)&&t.push({service:s.service,problem:`auth.default is \xAB${String(a)}\xBB \u2014 a host route is served as \`jwt\` or \`public\` only (\`internal\` is a route kind: set \`internal: true\` for an \`internal.<host>\` route); every request to it answers 401`});for(const l of s.auth?.overrides??[]){l.mode!==void 0&&!HOST_ROUTE_MODES.has(l.mode)&&t.push({service:s.service,problem:`the override for ${l.path} has mode \xAB${String(l.mode)}\xBB \u2014 only \`jwt\` and \`public\` are modes; requests under it answer 401`});for(const h of regexSources(l.rule)){const f=unsafeRegex(h);f&&t.push({service:s.service,problem:`the override for ${l.path} has a regex rule the edge will not run (${f}): ${h.slice(0,80)}`})}}}return t}c(manifestProblems,"manifestProblems"),u(manifestProblems,"manifestProblems");function regexSources(e){return e?isGroup(e)?[...(e.all??[]).flatMap(regexSources),...(e.any??[]).flatMap(regexSources),...regexSources(e.not)]:e.op==="regex"?[str(e.value)]:[]:[]}c(regexSources,"regexSources"),u(regexSources,"regexSources");function manifestFromClusterDecl(e,t){const r=t.upstream??(t.port?`http://localhost:${t.port}`:void 0);if(!(!t.service&&!r))return{service:t.service??e,mounts:t.host?[{host:t.host,...t.path?{path:t.path}:{}}]:[],internal:!!t.service,...t.internalHost!==void 0?{internalHost:t.internalHost}:{},...t.default?{default:!0}:{},...t.prependPrefix?{prependPrefix:t.prependPrefix}:{},...t.auth?{auth:t.auth}:{},...r?{upstream:r}:{}}}c(manifestFromClusterDecl,"manifestFromClusterDecl"),u(manifestFromClusterDecl,"manifestFromClusterDecl");const RESERVED_ATTRS=new Set(["ip","method","path","device"]);function claimAttrs(e){const t={...e??{}};for(const r of Object.keys(t))(RESERVED_ATTRS.has(r)||r.startsWith("header."))&&delete t[r];return t}c(claimAttrs,"claimAttrs"),u(claimAttrs,"claimAttrs");const isGroup=u(e=>"all"in e||"any"in e||"not"in e,"isGroup");exports.MAX_REGEX_LENGTH=512;const LINEAR=["l"].join("");let linearGuard;function armRegexGuard(){if(linearGuard!==void 0)return linearGuard;try{(0,node_v8_1.setFlagsFromString)("--enable-experimental-regexp-engine-on-excessive-backtracks"),(0,node_v8_1.setFlagsFromString)("--enable-experimental-regexp-engine"),new RegExp("a",LINEAR),linearGuard=!0}catch{linearGuard=!1}return linearGuard}c(armRegexGuard,"armRegexGuard"),u(armRegexGuard,"armRegexGuard");function unsafeRegex(e){if(e.length>exports.MAX_REGEX_LENGTH)return`longer than ${exports.MAX_REGEX_LENGTH} characters`;if(/\\[1-9]|\\k</.test(e))return"a backreference";if(armRegexGuard()){let n=!0;try{new RegExp(e)}catch{n=!1}if(n)try{new RegExp(e,LINEAR)}catch{return"no linear-time fallback (a lookahead, or a counted repetition too large to expand)"}}const t=[];let r;for(let n=0;n<e.length;){const s=e[n];if(s==="\\"){n+=2,r=!1;continue}if(s==="["){for(n+=1,e[n]==="^"&&(n+=1),e[n]==="]"&&(n+=1);n<e.length&&e[n]!=="]";)n+=e[n]==="\\"?2:1;n+=1,r=!1;continue}if(s==="("){if(t.push(!1),n+=1,r=void 0,e[n]==="?"){if(n+=1,e[n]==="<"&&e[n+1]!=="="&&e[n+1]!=="!")for(;n<e.length&&e[n]!==">";)n+=1;n+=1}continue}if(s===")"){const a=t.pop()??!1;n+=1,a&&t.length&&(t[t.length-1]=!0),r=a;continue}if(s==="|"){n+=1,r=void 0;continue}let o,i=1;if(s==="*"||s==="+")o=!0;else if(s==="?")o=!1;else if(s==="{"){const a=/^\{(\d+)(,(\d*))?\}/.exec(e.slice(n));if(a){i=a[0].length;const l=Number(a[1]);o=(a[2]===void 0?l:a[3]===""?1/0:Number(a[3]))>1}}if(o===void 0){n+=1,r=!1;continue}if(n+=i,e[n]==="?"&&(n+=1),r!==void 0){if(o&&r)return"nested quantifiers";o&&t.length&&(t[t.length-1]=!0),r=!1}}}c(unsafeRegex,"unsafeRegex"),u(unsafeRegex,"unsafeRegex");class Indeterminate extends Error{static{c(this,"Indeterminate")}static{u(this,"Indeterminate")}}const reCache=new Map,compileRe=u(e=>{if(reCache.has(e))return reCache.get(e);let t=null;if(armRegexGuard(),!unsafeRegex(e))try{t=new RegExp(e)}catch{t=null}return reCache.size>=1024&&reCache.clear(),reCache.set(e,t),t},"compileRe");function ipToInt(e){const t=(e.startsWith("::ffff:")?e.slice(7):e).split(".");if(t.length!==4)return null;let r=0;for(const n of t){const s=Number(n);if(!Number.isInteger(s)||s<0||s>255||n.length>1&&n[0]==="0")return null;r=r*256+s}return r>>>0}c(ipToInt,"ipToInt"),u(ipToInt,"ipToInt");function ipv6ToBigInt(e){let t=e;const r=t.indexOf("%");if(r!==-1&&(t=t.slice(0,r)),t.startsWith("[")&&t.endsWith("]")&&(t=t.slice(1,-1)),!t.includes(":")||t.length>45)return null;const n=t.lastIndexOf(":"),s=t.slice(n+1);if(s.includes(".")){const l=ipToInt(s);if(l===null)return null;t=`${t.slice(0,n+1)}${(l>>>16).toString(16)}:${(l&65535).toString(16)}`}const o=t.indexOf("::");if(o!==t.lastIndexOf("::"))return null;let i;if(o===-1){if(i=t.split(":"),i.length!==8)return null}else{const l=t.slice(0,o)?t.slice(0,o).split(":"):[],h=t.slice(o+2)?t.slice(o+2).split(":"):[];if(l.length+h.length>7)return null;i=[...l,...new Array(8-l.length-h.length).fill("0"),...h]}let a=0n;for(const l of i){if(!/^[0-9a-fA-F]{1,4}$/.test(l))return null;a=a<<16n|BigInt(parseInt(l,16))}return a}c(ipv6ToBigInt,"ipv6ToBigInt"),u(ipv6ToBigInt,"ipv6ToBigInt");function matchCidr(e,t){const r=t.indexOf("/");if(r<0)return!1;const n=Number(t.slice(r+1)),s=t.slice(0,r);if(s.includes(":")){if(!Number.isInteger(n)||n<0||n>128||ipToInt(e)!==null)return!1;const l=ipv6ToBigInt(e),h=ipv6ToBigInt(s);if(l===null||h===null)return!1;if(n===0)return!0;const f=BigInt(128-n);return l>>f===h>>f}if(!Number.isInteger(n)||n<0||n>32)return!1;const o=ipToInt(e),i=ipToInt(s);if(o===null||i===null)return!1;if(n===0)return!0;const a=(n===32?4294967295:~((1<<32-n)-1))>>>0;return(o&a)>>>0===(i&a)>>>0}c(matchCidr,"matchCidr"),u(matchCidr,"matchCidr");const str=u(e=>e==null?"":String(e),"str"),eq=u((e,t)=>str(e)===str(t),"eq");function evalCondition(e,t){const r=t[e.attr],n=r!=null;switch(e.op){case"exists":return n;case"ne":return!n||!eq(r,e.value)}if(!n)return!1;switch(e.op){case"eq":return eq(r,e.value);case"in":return Array.isArray(e.value)&&e.value.some(s=>Array.isArray(r)?r.some(o=>eq(o,s)):eq(r,s));case"nin":return Array.isArray(e.value)&&!e.value.some(s=>Array.isArray(r)?r.some(o=>eq(o,s)):eq(r,s));case"prefix":return str(r).startsWith(str(e.value));case"suffix":return str(r).endsWith(str(e.value));case"domain":{const s=str(r).lastIndexOf("@"),o=(s===-1?str(r):str(r).slice(s+1)).toLowerCase().replace(/\.$/,""),i=str(e.value).toLowerCase().replace(/^\./,"").replace(/\.$/,"");return!!i&&(o===i||o.endsWith("."+i))}case"contains":return Array.isArray(r)?r.some(s=>eq(s,e.value)):str(r).includes(str(e.value));case"hastoken":{const s=str(e.value);return Array.isArray(r)?r.some(o=>eq(o,e.value)):str(r).split(/[\s,]+/).filter(Boolean).includes(s)}case"regex":{const s=compileRe(str(e.value)),o=str(r);if(!s||o.length>exports.MAX_REGEX_LENGTH)throw new Indeterminate;return s.test(o)}case"gt":return Number(r)>Number(e.value);case"lt":return Number(r)<Number(e.value);case"cidr":return matchCidr(str(r),str(e.value));default:return!1}}c(evalCondition,"evalCondition"),u(evalCondition,"evalCondition");function evalNode(e,t){if(!isGroup(e))return evalCondition(e,t);const r=Array.isArray(e.all)&&e.all.length?e.all:void 0,n=Array.isArray(e.any)&&e.any.length?e.any:void 0,s=e.not&&Object.keys(e.not).length?e.not:void 0;return s&&evalNode(s,t)||r&&!r.every(o=>evalNode(o,t))||n&&!n.some(o=>evalNode(o,t))?!1:!!(r||n||s)}c(evalNode,"evalNode"),u(evalNode,"evalNode");function evalRule(e,t){try{return evalNode(e,t)}catch(r){if(r instanceof Indeterminate)return!1;throw r}}c(evalRule,"evalRule"),u(evalRule,"evalRule");function pickTargetedVersion(e,t){for(const r of e)if(evalRule(r.when,t))return{version:r.version,...r.name?{rule:r.name}:{}}}c(pickTargetedVersion,"pickTargetedVersion"),u(pickTargetedVersion,"pickTargetedVersion");function fnv1a(e){let t=2166136261;for(let r=0;r<e.length;r++)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return t>>>0}c(fnv1a,"fnv1a"),u(fnv1a,"fnv1a");function bucketByWeight(e,t){const r=t.reduce((o,i)=>o+Math.max(0,i),0);if(r<=0||t.length===0)return 0;const n=fnv1a(e)%1e4;let s=0;for(let o=0;o<t.length;o++)if(s+=Math.max(0,t[o])/r*1e4,n<s)return o;return t.length-1}c(bucketByWeight,"bucketByWeight"),u(bucketByWeight,"bucketByWeight");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
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 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
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");
|
|
@@ -57,8 +57,16 @@ export interface GatewayEnvConfig {
|
|
|
57
57
|
mtlsFromRedis: boolean;
|
|
58
58
|
/** `LENSMCP_GW_INTERNAL_PEERS` — networks allowed to reach `internal.<host>` routes (PG3-12). */
|
|
59
59
|
internalPeers: string[];
|
|
60
|
-
/** `LENSMCP_GW_WS_MAX_PENDING_PER_IP` / `LENSMCP_GW_WS_MAX_TUNNELS_PER_SERVICE` (PG3-20)
|
|
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). */
|
|
61
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;
|
|
62
70
|
}
|
|
63
71
|
/** Parse everything the gateway can decide from the environment alone. Pure. */
|
|
64
72
|
export declare function parseGatewayEnv(env: NodeJS.ProcessEnv): GatewayEnvConfig;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
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 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
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 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
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;
|
|
@@ -8,6 +8,7 @@ import type * as http from 'node:http';
|
|
|
8
8
|
import type * as net from 'node:net';
|
|
9
9
|
import { type FastifyInstance, type FastifyReply, type FastifyRequest } from 'fastify';
|
|
10
10
|
import type { TraceSpan } from '../otel-tracing';
|
|
11
|
+
import type { RolloutLayer } from './rollout';
|
|
11
12
|
import type { ProdHookContext, ProdRuntime, ReqState } from './types';
|
|
12
13
|
import type { Observability } from './observability';
|
|
13
14
|
import type { CorsLayer } from './cors';
|
|
@@ -17,6 +18,7 @@ export interface AppDeps {
|
|
|
17
18
|
obs: Observability;
|
|
18
19
|
cors: CorsLayer;
|
|
19
20
|
hooks: HooksLayer;
|
|
21
|
+
rollout: RolloutLayer;
|
|
20
22
|
handler: (request: FastifyRequest, reply: FastifyReply) => Promise<unknown>;
|
|
21
23
|
upgrade: (req: http.IncomingMessage, socket: net.Socket, head: Buffer) => void;
|
|
22
24
|
reqState: WeakMap<FastifyRequest, ReqState>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
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 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
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 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
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 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
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");
|
|
@@ -3,6 +3,19 @@ import { type GatewayErrorReason } from '../gateway-errors';
|
|
|
3
3
|
import type { ReplyLike } from './types';
|
|
4
4
|
export declare const eid: () => string;
|
|
5
5
|
export declare const hdr: (v: string | string[] | undefined) => string | undefined;
|
|
6
|
+
/**
|
|
7
|
+
* The `Host` header as `{ name, port? }` — or undefined when it is anything but `name[:port]` (→ 400).
|
|
8
|
+
*
|
|
9
|
+
* The gateway routed on the part before the first `:` and forwarded the WHOLE header as `X-Forwarded-Host`, so
|
|
10
|
+
* `Host: app.x:@evil.example` reached the `app.x` service carrying a forwarded host that every URL parser reads as
|
|
11
|
+
* `evil.example` (`app.x:` is userinfo) — a password-reset link built from it points at the attacker
|
|
12
|
+
* (issues/closed/prod-gateway-4-08). A header that is exactly `name[:port]` is the only one whose forwarded form IS
|
|
13
|
+
* the host that was routed. An absent / empty header stays the empty name (HTTP/1.0: the catch-all, as before).
|
|
14
|
+
*/
|
|
15
|
+
export declare const parseHost: (raw: string | undefined) => {
|
|
16
|
+
name: string;
|
|
17
|
+
port?: string;
|
|
18
|
+
} | undefined;
|
|
6
19
|
/**
|
|
7
20
|
* Send a gateway-generated edge error as the JSON envelope `{ key, status, traceId, message? }` (NOT
|
|
8
21
|
* `text/plain`), stamping `x-request-id` so the trace id is on the response. The SAME `{ key, status }`
|