@lensmcp/cluster 1.25.67 → 1.25.70
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/executors/gateway/main.prod-gateway.js +2 -2
- package/executors/gateway/prod-config.d.ts +2 -0
- package/executors/gateway/prod-config.js +1 -1
- package/executors/gateway/prod-runtime/server.js +1 -1
- package/executors/gateway/prod-runtime/types.d.ts +7 -0
- package/executors/gateway/runtime/service-keys.d.ts +4 -1
- package/package.json +4 -4
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var ce=Object.defineProperty;var R=(e,
|
|
2
|
-
`;H?.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(s){console.error("[gateway] initial JWKS load failed (will retry in background):",s.message)}const{accessLog:oe,clientIpHeader:z,clientIpTrustedProxies:X,undici:d}=
|
|
1
|
+
"use strict";var ce=Object.defineProperty;var R=(e,t)=>ce(e,"name",{value:t,configurable:!0});var ie=Object.defineProperty,a=R((e,t)=>ie(e,"name",{value:t,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(e,t){if(!e)return t;try{return JSON.parse((0,node_fs_1.readFileSync)(e,"utf8"))}catch(n){return console.error(`[gateway] could not read ${e}:`,n.message),t}}R(readJson,"readJson"),a(readJson,"readJson");function watchJsonFile(e,t,n=1e3){let u=-1;const _=setInterval(a(()=>{if(!(0,node_fs_1.existsSync)(e))return;let p;try{p=(0,node_fs_1.statSync)(e).mtimeMs}catch{return}if(p===u)return;let w;try{w=JSON.parse((0,node_fs_1.readFileSync)(e,"utf8"))}catch(g){console.error("[gateway] endpoints reload:",g.message);return}u=p,t(w)},"tick"),n);return _.unref?.(),()=>clearInterval(_)}R(watchJsonFile,"watchJsonFile"),a(watchJsonFile,"watchJsonFile");async function main(){const e=process.env,t=(0,prod_config_1.parseGatewayEnv)(e),n=t.ports;process.on("uncaughtException",s=>console.error("[gateway] uncaughtException:",s)),process.on("unhandledRejection",s=>console.error("[gateway] unhandledRejection:",s));const u=[];let _=!1;const p=a(async s=>{if(!_){_=!0,console.log(`[gateway] ${s} \u2014 draining\u2026`);for(const r of u)try{await r()}catch{}process.exit(0)}},"shutdown");for(const s of["SIGTERM","SIGINT"])process.on(s,()=>{p(s)});const w=e.LENSMCP_GW_REDIS_URL;let g,y,b,$;const O={};let f;if(w){const s=require("ioredis"),r=new s(w);f=r;const o=(0,registry_source_1.createRegistryProviders)((0,registry_source_1.redisRegistrySource)(r,e.LENSMCP_GW_REDIS_PREFIX?{prefix:e.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,$=o,console.log(`[gateway] registry: Redis-backed, live (${g.list().length} service(s))`)}else{const s=e.LENSMCP_GW_MANIFESTS;s?g=(0,providers_prod_1.fileManifestProvider)(s,{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 r=e.LENSMCP_GW_ENDPOINTS;if(r){const o=a(E=>console.error("[gateway] endpoints:",E instanceof Error?E.message:E),"onEpError"),i=readJson(r,{}),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)(r)?"present but empty/unreadable":"file not there yet"} \u2014 watching ${r}`),b=watchJsonFile(r,E=>{try{y?.update?.(E),O.current?.refreshUpstreams(),console.log("[gateway] endpoints reloaded")}catch(ae){console.error("[gateway] endpoints reload failed:",ae.message)}})}}const Z=readJson(e.LENSMCP_GW_KEYS,{}),A=e.LENSMCP_GW_TLS_KEY&&e.LENSMCP_GW_TLS_CERT?{key:(0,node_fs_1.readFileSync)(e.LENSMCP_GW_TLS_KEY),cert:(0,node_fs_1.readFileSync)(e.LENSMCP_GW_TLS_CERT)}:void 0,ee=t.jwt.presenceOnly,D=t.jwt.jwksUrl,M=t.jwt.secret,S=D?(0,jwks_verify_1.createJwksVerifier)({jwksUrl:D,...t.jwt.issuer?{issuer:t.jwt.issuer}:{},...t.jwt.audience?{audience:t.jwt.audience}:{}}):void 0,te=a(s=>{if(!M)return;const r=s.split(".");if(r.length===3)try{if(JSON.parse(Buffer.from(r[0],"base64url").toString()).alg!=="HS256")return;const o=(0,node_crypto_1.createHmac)("sha256",M).update(r[0]+"."+r[1]).digest("base64url"),i=Buffer.from(r[2]),c=Buffer.from(o);if(i.length!==c.length||!(0,node_crypto_1.timingSafeEqual)(i,c))return;const l=JSON.parse(Buffer.from(r[1],"base64url").toString());return(0,jwt_claims_1.checkStandardClaims)(l,{...t.jwt.issuer?{issuer:t.jwt.issuer}:{},...t.jwt.audience?.length?{audience:t.jwt.audience}:{}})?l:void 0}catch{return}},"hs256"),F=a(s=>{const r=String(s.headers.authorization??"");if(!r.startsWith("Bearer "))return;const o=r.slice(7);return S?S.verify(o):te(o)},"bearerClaims"),j=S?(0,jwks_verify_1.bearerIdentify)(S):M?F:void 0,re=a((s,r)=>{if(s==="jwt"){if(S||M){if(!F(r))throw new Error("invalid or missing token");return}if(!ee)throw new Error("jwt route but no verifier configured (set LENSMCP_GW_JWKS_URL or LENSMCP_GW_JWT_SECRET)");if(!String(r.headers.authorization??"").startsWith("Bearer "))throw new Error("missing bearer token")}},"authenticate"),{attributeHeaders:q,trustProxyHops:se,trustProxyIp:U,uidHeader:x,cookie:J}=t,m=e.LENSMCP_EVENT_FILE,H=m?(()=>{try{return require("@lensmcp/node-instrumentation")}catch{return}})():void 0,K=H?.createEventFloodGuard({burst:30,perSec:5});let B=!1;const I=m?s=>{try{const r=K?K.admit(String(s.fingerprint??"")):{ok:!0,suppressed:0};if(!r.ok)return;B||((0,node_fs_1.mkdirSync)((0,node_path_1.dirname)(m),{recursive:!0}),B=!0);const o=s.raw,i=JSON.stringify(r.suppressed>0?{...s,raw:{...o,floodSuppressed:r.suppressed}}:s)+`
|
|
2
|
+
`;H?.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(s){console.error("[gateway] initial JWKS load failed (will retry in background):",s.message)}const{accessLog:oe,clientIpHeader:z,clientIpTrustedProxies:X,undici:d}=t;if(t.mtlsFromRedis&&f){const s=e.LENSMCP_GW_REDIS_PREFIX??"lensmcp:gw",[r,o,i]=await f.mget(`${s}:mtls:cert`,`${s}:mtls:key`,`${s}:mtls:ca`);r&&(d.cert=r),o&&(d.key=o),i&&(d.ca=i),(r||o)&&console.log("[gateway] mTLS materials loaded from Redis")}else e.LENSMCP_GW_MTLS_CERT&&(d.cert=(0,node_fs_1.readFileSync)(e.LENSMCP_GW_MTLS_CERT)),e.LENSMCP_GW_MTLS_KEY&&(d.key=(0,node_fs_1.readFileSync)(e.LENSMCP_GW_MTLS_KEY)),e.LENSMCP_GW_MTLS_CA&&(d.ca=(0,node_fs_1.readFileSync)(e.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,e)&&console.log(`[gateway] mTLS to upstreams ON over ${d.allowH2?"h2":"h1.1"} (server validation ${d.rejectUnauthorized?"enabled":"OFF"})`);const{upstreamRetries:C,server:Y}=t,T=(0,otel_tracing_1.setupTracing)({...e.OTEL_SERVICE_NAME?{serviceName:e.OTEL_SERVICE_NAME}:{},...e.LENSMCP_GW_OTEL_SAMPLE?{sampleRatio:Number(e.LENSMCP_GW_OTEL_SAMPLE)}:{}});T&&console.log(`[gateway] OTLP tracing on \u2192 ${(0,edge_1.safeUrl)(e.OTEL_EXPORTER_OTLP_ENDPOINT)}`);const{statusEnabled:P,statusToken:h}=t,V=(0,node_os_1.hostname)(),ne=t.statusTtlSec,Q=f,k=P&&Q?s=>{for(const r of s)Q.set(`status:${r.service}:${V}`,JSON.stringify({...r,instance:V,at:Date.now()}),"EX",ne).catch(()=>{})}:void 0;P&&!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."),P&&console.log(`[gateway] status on \u2014 /statusz${h?"":" (endpoint disabled: no token)"}${k?" + Redis status:* fan-out":""}`);const v=t.health?(0,health_check_1.createHealthChecker)(t.health):void 0;v&&console.log(`[gateway] active health-checking on (path ${t.health?.path??"/healthz"})`);let L,G;if(t.rateLimit){const{limit:s,windowMs:r,wantRedis:o,failClosed:i}=t.rateLimit;if(o){const c=t.rateLimit.dedicatedUrl;let l;if(c){const E=require("ioredis");G=new E(c),l=G}else f&&(l=f);l?(L=(0,rate_limit_1.createRedisRateLimiter)(l,{limit:s,windowMs:r,prefix:`${e.LENSMCP_GW_REDIS_PREFIX??"lensmcp:gw"}:rl:`,...t.rateLimit.timeoutMs!==void 0?{timeoutMs:t.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 ${e.LENSMCP_GW_REDIS_PREFIX??"lensmcp:gw"}:rl:*`),"onFailure")}),console.log(`[gateway] rate limit on \u2014 ${s} req / ${r}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)(e),l=(0,prod_config_1.perWorkerLimit)(s,c);L=(0,rate_limit_1.createRateLimiter)({limit:l,windowMs:r}),console.log(`[gateway] rate limit on \u2014 ${s} req / ${r}ms per client IP (in-memory`+(c>1?`, ${l}/worker \xD7 ${c} workers`:", per-instance")+")")}}const W=t.metricsEnabled?(0,metrics_1.createProcessMetrics)():void 0;W&&console.log(`[gateway] process metrics on \u2014 /metricsz${h?" (token-gated)":" (DISABLED: needs LENSMCP_GW_STATUS_TOKEN)"}`);const N=await(0,prod_gateway_lib_1.startProdGateway)({...n.length?{ports:n}:{},...t.host?{host:t.host}:{},manifests:g,...y?{pods:y}:{},serviceKeys:Z,authenticate:re,...A?{tls:A}:{},...I?{emit:I}:{},...j?{identify:j}:{},...q.length?{attributeHeaders:q}:{},...U?{trustProxyIp:U,trustProxyHops:se}:{},...J?{cookie:J}:{},...x?{uidHeader:x}:{},...oe?{accessLog:!0}:{},...z?{clientIpHeader:z}:{},...X.length?{clientIpTrustedProxies:X}:{},...T?{tracing:T}:{},...P?{statusEndpoint:!0}:{},...h?{statusToken:h}:{},...k?{onStatus:k}:{},...v?{healthChecker:v}:{},...L?{rateLimiter:L}:{},...W?{metrics:W}:{},...t.trafficFlushMs!==void 0?{trafficFlushMs:t.trafficFlushMs}:{},...C!==void 0&&Number.isFinite(C)?{upstreamRetries:C}:{},...Object.keys(d).length?{undici:d}:{},...Object.keys(Y).length?{server:Y}:{}});O.current=N,console.log(`[gateway] production gateway up on ${N.ports.join(", ")} (${N.routes().length} routes${I?", lens ON":""})`),u.push(()=>g.stop?.(),()=>b?.(),()=>$?.stop(),()=>G?.quit(),()=>S?.stop(),()=>N.stop(),()=>T?.shutdown())}R(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 e=!1;for(let n=0;n<WORKERS;n++)node_cluster_1.default.fork();node_cluster_1.default.on("exit",(n,u,_)=>{e||(console.warn(`[gateway] worker ${n.process.pid} exited (code=${u} sig=${_??""}) \u2014 respawning.`),node_cluster_1.default.fork())});const t=a(n=>{if(!e){e=!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",()=>t("SIGTERM")),process.on("SIGINT",()=>t("SIGINT"))}else main().catch(e=>{console.error("[gateway] FATAL: could not start \u2014",e instanceof Error?e.stack??e.message:e),process.exit(1)});
|
|
@@ -22,6 +22,8 @@ export interface JwtConfig {
|
|
|
22
22
|
export interface GatewayEnvConfig {
|
|
23
23
|
/** Bind ports: explicit `LENSMCP_GW_PORTS`, else the platform `PORT` contract, else []. */
|
|
24
24
|
ports: number[];
|
|
25
|
+
/** Bind address: `LENSMCP_GW_HOST` — absent for every interface, the default (foodguard-264). */
|
|
26
|
+
host?: string;
|
|
25
27
|
/** Cluster worker processes; `auto`/`max`/`0` ⇒ one per core. Always ≥ 1. */
|
|
26
28
|
workers: number;
|
|
27
29
|
undici: NonNullable<ProdGatewayOptions['undici']>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var w=Object.defineProperty;var S=(_,E)=>w(_,"name",{value:E,configurable:!0});var
|
|
1
|
+
"use strict";var w=Object.defineProperty;var S=(_,E)=>w(_,"name",{value:E,configurable:!0});var K=Object.defineProperty,t=S((_,E)=>K(_,"name",{value:E,configurable:!0}),"t");Object.defineProperty(exports,"__esModule",{value:!0}),exports.parseGatewayEnv=parseGatewayEnv,exports.redisLimiterConfigured=redisLimiterConfigured,exports.perWorkerLimit=perWorkerLimit,exports.workerCount=workerCount,exports.finalizeUpstreamTls=finalizeUpstreamTls,exports.finalizeUpstreamH2=finalizeUpstreamH2;const node_os_1=require("node:os"),num=t(_=>{if(_===void 0||_.trim()==="")return;const E=Number(_);return Number.isFinite(E)?E:void 0},"num"),csv=t(_=>(_??"").split(",").map(E=>E.trim()).filter(Boolean),"csv"),flag=t(_=>_==="1","flag");function parseGatewayEnv(_){const E=csv(_.LENSMCP_GW_PORTS??_.PORT).map(Number).filter(L=>Number.isFinite(L)&&L>=0&&L<=65535),r=Math.max(0,Math.floor(num(_.LENSMCP_GW_TRUST_PROXY)??0)),i={},N=_.LENSMCP_GW_UPSTREAM_TLS_VERIFY;N==="1"?i.rejectUnauthorized=!0:N==="0"&&(i.rejectUnauthorized=!1),flag(_.LENSMCP_GW_UPSTREAM_H2)&&(i.allowH2=!0);const a=num(_.LENSMCP_GW_UNDICI_CONNECTIONS);a!==void 0&&(i.connections=a);const T=num(_.LENSMCP_GW_UNDICI_BODY_TIMEOUT_MS);T!==void 0&&(i.bodyTimeout=T);const P=num(_.LENSMCP_GW_UNDICI_PIPELINING);P!==void 0&&(i.pipelining=P);const W=num(_.LENSMCP_GW_UNDICI_HEADERS_TIMEOUT_MS);W!==void 0&&(i.headersTimeout=W);const I=num(_.LENSMCP_GW_UNDICI_KEEPALIVE_MS);I!==void 0&&(i.keepAliveTimeout=I);const o={},u=num(_.LENSMCP_GW_KEEPALIVE_MS);u!==void 0&&(o.keepAliveTimeout=u);const d=num(_.LENSMCP_GW_REQUEST_TIMEOUT_MS);d!==void 0&&(o.requestTimeout=d);const G=num(_.LENSMCP_GW_HEADERS_TIMEOUT_MS);G!==void 0&&(o.headersTimeout=G);const c=num(_.LENSMCP_GW_MAX_HEADERS);c!==void 0&&(o.maxHeadersCount=c);const R=num(_.LENSMCP_GW_CONN_CHECK_MS);R!==void 0&&(o.connectionsCheckingInterval=R);const l=num(_.LENSMCP_GW_MAX_CONNECTIONS);l!==void 0&&(o.maxConnections=l);const m=num(_.LENSMCP_GW_BODY_STALL_MS);m!==void 0&&(o.bodyStallMs=m);const e=_.LENSMCP_GW_COOKIE_SECRET,M=_.LENSMCP_GW_COOKIE_NAME,n=_.LENSMCP_GW_COOKIE_DOMAIN,A=num(_.LENSMCP_GW_COOKIE_MAXAGE),U=e||M||n?{...M?{name:M}:{},...e?{secret:e}:{},...n?{domain:n}:{},...A!==void 0?{maxAge:A}:{}}:void 0,v=num(_.LENSMCP_GW_RATE_LIMIT),s=_.LENSMCP_GW_RATE_LIMIT_REDIS_URL,O=num(_.LENSMCP_GW_RATE_LIMIT_TIMEOUT_MS),p=v===void 0?void 0:{limit:v,windowMs:num(_.LENSMCP_GW_RATE_WINDOW_MS)??6e4,wantRedis:flag(_.LENSMCP_GW_RATE_LIMIT_REDIS)||!!s,...s?{dedicatedUrl:s}:{},...O!==void 0?{timeoutMs:O}:{},failClosed:flag(_.LENSMCP_GW_RATE_LIMIT_FAIL_CLOSED)},H=_.LENSMCP_GW_HEALTH_PATH,f=num(_.LENSMCP_GW_HEALTH_INTERVAL_MS),D=num(_.LENSMCP_GW_HEALTH_TIMEOUT_MS),h=flag(_.LENSMCP_GW_HEALTH_CHECK),b=h?{...H?{path:H}:{},...f!==void 0?{intervalMs:f}:{},...D!==void 0?{timeoutMs:D}:{}}:void 0,C=num(_.LENSMCP_GW_TRAFFIC_FLUSH_MS),x=csv(_.LENSMCP_GW_JWT_AUD),k=_.LENSMCP_GW_HOST?.trim();return{ports:E,...k?{host:k}:{},workers:workerCount(_),undici:i,server:o,...num(_.LENSMCP_GW_UPSTREAM_RETRIES)!==void 0?{upstreamRetries:num(_.LENSMCP_GW_UPSTREAM_RETRIES)}:{},trustProxyIp:r>0,trustProxyHops:r,...U?{cookie:U}:{},attributeHeaders:csv(_.LENSMCP_GW_ATTR_HEADERS),..._.LENSMCP_GW_CLIENT_IP_HEADER?{clientIpHeader:_.LENSMCP_GW_CLIENT_IP_HEADER}:{},clientIpTrustedProxies:csv(_.LENSMCP_GW_CLIENT_IP_TRUSTED_PROXIES),..._.LENSMCP_GW_UID_HEADER?{uidHeader:_.LENSMCP_GW_UID_HEADER}:{},accessLog:flag(_.LENSMCP_GW_ACCESS_LOG),statusEnabled:flag(_.LENSMCP_GW_STATUS),..._.LENSMCP_GW_STATUS_TOKEN?{statusToken:_.LENSMCP_GW_STATUS_TOKEN}:{},metricsEnabled:flag(_.LENSMCP_GW_METRICS),statusTtlSec:Math.max(3,Math.ceil((C??5e3)/1e3*3)),...C!==void 0?{trafficFlushMs:C}:{},...p?{rateLimit:p}:{},...b?{health:b}:{},healthCheckEnabled:h,jwt:{..._.LENSMCP_GW_JWKS_URL?{jwksUrl:_.LENSMCP_GW_JWKS_URL}:{},..._.LENSMCP_GW_JWT_SECRET?{secret:_.LENSMCP_GW_JWT_SECRET}:{},..._.LENSMCP_GW_JWT_ISS?{issuer:_.LENSMCP_GW_JWT_ISS}:{},...x.length?{audience:x}:{},presenceOnly:flag(_.LENSMCP_GW_JWT_PRESENCE_ONLY)},mtlsFromRedis:flag(_.LENSMCP_GW_MTLS_FROM_REDIS)}}S(parseGatewayEnv,"parseGatewayEnv"),t(parseGatewayEnv,"parseGatewayEnv");function redisLimiterConfigured(_){return _.LENSMCP_GW_RATE_LIMIT_REDIS_URL?!0:flag(_.LENSMCP_GW_RATE_LIMIT_REDIS)&&!!_.LENSMCP_GW_REDIS_URL}S(redisLimiterConfigured,"redisLimiterConfigured"),t(redisLimiterConfigured,"redisLimiterConfigured");function perWorkerLimit(_,E){if(!Number.isFinite(_)||_<=0)return _;const r=Number.isFinite(E)&&E>1?Math.floor(E):1;return Math.max(1,Math.floor(_/r))}S(perWorkerLimit,"perWorkerLimit"),t(perWorkerLimit,"perWorkerLimit");function workerCount(_){const 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 r=Math.floor(Number(E));return Number.isFinite(r)&&r>0?r:1}S(workerCount,"workerCount"),t(workerCount,"workerCount");function finalizeUpstreamTls(_){return _.ca&&_.rejectUnauthorized===void 0?(_.rejectUnauthorized=!0,{autoEnabled:!0}):{autoEnabled:!1}}S(finalizeUpstreamTls,"finalizeUpstreamTls"),t(finalizeUpstreamTls,"finalizeUpstreamTls");function finalizeUpstreamH2(_,E){return _.cert&&_.key?(E.LENSMCP_GW_UPSTREAM_H2!=="0"&&(_.allowH2=!0),!0):!1}S(finalizeUpstreamH2,"finalizeUpstreamH2"),t(finalizeUpstreamH2,"finalizeUpstreamH2");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var M=Object.defineProperty;var d=(e,n)=>M(e,"name",{value:n,configurable:!0});var S=Object.defineProperty,c=d((e,n)=>S(e,"name",{value:n,configurable:!0}),"c");Object.defineProperty(exports,"__esModule",{value:!0}),exports.startProdGateway=startProdGateway;const node_net_1=require("node:net"),observability_1=require("./observability"),routing_1=require("./routing"),rollout_1=require("./rollout"),upstream_1=require("./upstream"),auth_1=require("./auth"),hooks_1=require("./hooks"),cors_1=require("./cors"),handler_1=require("./handler"),upgrade_1=require("./upgrade"),app_1=require("./app");async function startProdGateway(e){const n=e.ports?.length?e.ports:[e.tls?8443:8080],o=e.host??"0.0.0.0";if(o!=="localhost"&&!(0,node_net_1.isIP)(o))throw new Error(`The gateway binds an IP address or localhost \u2014 not \xAB${o.slice(0,80)}\xBB (host)`);const j=e.authenticate??(t=>{if(t==="jwt")throw new Error("jwt route but no authenticator configured")}),B=(e.versionHeader??"x-lensmcp-version").toLowerCase(),C=!!e.accessLog,x=new Set((e.corsCredentialOrigins??[]).map(t=>t.toLowerCase())),w=new Map;for(const[t,a]of Object.entries(e.serviceKeys??{}))typeof a=="string"&&a.trim()!==""?w.set(a,t):console.warn(`[gateway] service key for "${t}" is empty \u2014 east-west auth for that service is DISABLED (all internal routes 401) until a key is set.`);const y={},r=(0,observability_1.createObservability)(e,()=>y.current.routes),s=(0,routing_1.createRouteTable)(e,r);y.current=s;const i={opts:e,table:s,keyToProject:w,versionHeader:B,accessLog:C,corsCredentialOrigins:x},u=(0,rollout_1.createRollout)(e),g=(0,upstream_1.createUpstream)(e,r),b=(0,auth_1.createEdgeAuth)(i,r,u,j),l=(0,hooks_1.createHooks)(e.hooks??{}),p=new WeakMap,f=new WeakMap,m=new WeakMap,k=(0,cors_1.createCors)(i,p),L=(0,handler_1.createHandler)({rt:i,obs:r,cors:k,auth:b,upstream:g,rollout:u,hooks:l,reqState:p,spanByReq:f,ctxByReq:m}),O=(0,upgrade_1.createUpgrade)({rt:i,obs:r,auth:b,upstream:g,hooks:l,rollout:u}),{buildApp:R}=(0,app_1.createApp)({rt:i,obs:r,cors:k,hooks:l,handler:L,upgrade:O,reqState:p,spanByReq:f,ctxByReq:m}),$=r.startFlusher();s.rebuild(s.manifests());const q=[],v=[],A=o.includes(":")?`[${o}]`:o;for(const t of n){const a=await R();await a.listen({port:t,host:o});const h=a.server.address(),P=typeof h=="object"&&h?h.port:t;v.push(P),console.log(`[gateway] listening on ${e.tls?"https":"http"}://${A}:${P}`),q.push(a)}e.healthChecker?.start();let _=!1;return{ports:v,host:o,routes:c(()=>s.routes,"routes"),status:r.buildStatusSnapshot,refreshUpstreams:s.trackUpstreams,stop:c(async()=>{_||(_=!0,clearInterval($),s.stop(),e.healthChecker?.stop(),e.rateLimiter?.stop(),e.metrics?.stop(),r.emit("info","gateway down","gateway-down",{kind:"gateway-down"}),await Promise.all(q.map(t=>t.close())))},"stop")}}d(startProdGateway,"startProdGateway"),c(startProdGateway,"startProdGateway");
|
|
@@ -29,6 +29,11 @@ export interface ProdGatewayOptions {
|
|
|
29
29
|
/** Ports to bind. Default `[8080]` (or `[8443]` with TLS). One Fastify
|
|
30
30
|
* instance per port; all share the route table + providers. */
|
|
31
31
|
ports?: number[];
|
|
32
|
+
/** The address every listener binds (issues/closed/foodguard-264). Default `0.0.0.0`, every interface: the
|
|
33
|
+
* production contract. `127.0.0.1` or `::1` keeps an owned local fixture loopback-only — FoodGuard's QA had to run
|
|
34
|
+
* the real export against its real manifest and could only bind the wildcard. An IP literal or `localhost`;
|
|
35
|
+
* anything else is refused before any port is bound. */
|
|
36
|
+
host?: string;
|
|
32
37
|
manifests: ManifestProvider;
|
|
33
38
|
/** Resolves a service → upstream when a route has no direct `upstream`. */
|
|
34
39
|
pods?: PodProvider;
|
|
@@ -179,6 +184,8 @@ export interface ProdGatewayOptions {
|
|
|
179
184
|
}
|
|
180
185
|
export interface ProdGatewayHandle {
|
|
181
186
|
ports: number[];
|
|
187
|
+
/** The address the listeners bound — `0.0.0.0` unless {@link ProdGatewayOptions.host} said otherwise. */
|
|
188
|
+
host: string;
|
|
182
189
|
routes: () => Route[];
|
|
183
190
|
status: () => ServiceStatus[];
|
|
184
191
|
/** Re-derive the health-checked upstream set. Call after an ENDPOINTS reload (a rollout
|
|
@@ -26,7 +26,10 @@ export declare function serviceKeyId(wsKey: string | undefined, project: string)
|
|
|
26
26
|
* `taken` names key VALUES another workspace already holds: those are replaced with fresh ones and persisted
|
|
27
27
|
* (`regenerated`). A copy of a checkout — `cp -R`, or a copy-on-write clone of `node_modules` with its `.cache` —
|
|
28
28
|
* carries the original's key file, and two workspaces with one key value cannot be told apart: adopting it
|
|
29
|
-
* re-attributed the original's internal calls to the copy, which the gateway then refused as cross-workspace.
|
|
29
|
+
* re-attributed the original's internal calls to the copy, which the gateway then refused as cross-workspace.
|
|
30
|
+
*
|
|
31
|
+
* apps/agent's `materialiseServiceKeys` (candidate-runtime.ts, issues/closed/foodguard-251) writes this file the same
|
|
32
|
+
* way before a candidate runtime registers, so its preparation can read the keys adopted here: keep the two in step. */
|
|
30
33
|
export declare function loadServiceKeys(root: string, services: ServiceCtl[], wsKey?: string, taken?: (key: string) => boolean): {
|
|
31
34
|
serviceKeys: Record<string, string>;
|
|
32
35
|
keyToProject: Map<string, string>;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lensmcp/cluster",
|
|
3
|
-
"version": "1.25.
|
|
3
|
+
"version": "1.25.70",
|
|
4
4
|
"description": "Run your Nx workspace as a local production cluster: pods on unix sockets with true HMR, one https gateway with per-project domains, scale-from-zero, autoscale, idle-kill, local-CA TLS — observed by the LensMCP lens.",
|
|
5
5
|
"main": "./index.js",
|
|
6
6
|
"types": "./index.d.ts",
|
|
@@ -58,9 +58,9 @@
|
|
|
58
58
|
}
|
|
59
59
|
},
|
|
60
60
|
"dependencies": {
|
|
61
|
-
"@lensmcp/core": "1.25.
|
|
62
|
-
"@lensmcp/node-instrumentation": "1.25.
|
|
63
|
-
"@lensmcp/nx-plugin": "1.25.
|
|
61
|
+
"@lensmcp/core": "1.25.70",
|
|
62
|
+
"@lensmcp/node-instrumentation": "1.25.70",
|
|
63
|
+
"@lensmcp/nx-plugin": "1.25.70",
|
|
64
64
|
"fastify": "^5.8.5",
|
|
65
65
|
"@fastify/reply-from": "^12.6.2",
|
|
66
66
|
"@typescript/native-preview": "^7.0.0-dev.20260707.2",
|