@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 p=Object.defineProperty;var i=(e,r)=>p(e,"name",{value:r,configurable:!0});var c=Object.defineProperty,t=i((e,r)=>c(e,"name",{value:r,configurable:!0}),"t");Object.defineProperty(exports,"__esModule",{value:!0}),exports.safeUrl=exports.rememberRawTarget=exports.rawTargetOf=exports.RAW_TARGET=exports.canonicalPath=exports.canonicalize=exports.ENCODED_STRUCTURE=exports.addVary=exports.tokenMatches=exports.NO_STORE=exports.sendError=exports.parseHost=exports.hdr=exports.eid=void 0;const node_crypto_1=require("node:crypto"),gateway_errors_1=require("../gateway-errors"),eid=t(()=>Date.now().toString(36)+(0,node_crypto_1.randomBytes)(6).toString("hex"),"eid");exports.eid=eid;const hdr=t(e=>typeof e=="string"&&e!==""?e:Array.isArray(e)?e[0]:void 0,"hdr");exports.hdr=hdr;const HOST_GRAMMAR=/^(\[[0-9A-Fa-f:.]{2,45}\]|[A-Za-z0-9._-]{1,253})(?::(\d{1,5}))?$/,parseHost=t(e=>{if(e===void 0||e==="")return{name:""};const r=HOST_GRAMMAR.exec(e);return r?{name:r[1],...r[2]?{port:r[2]}:{}}:void 0},"parseHost");exports.parseHost=parseHost;const sendError=t((e,r,o,n,s)=>{const a=(0,gateway_errors_1.ensureRequestId)(r);return e.code(o).header("x-request-id",a).header("cache-control",exports.NO_STORE).type(gateway_errors_1.GATEWAY_ERROR_CONTENT_TYPE).send((0,gateway_errors_1.gatewayErrorBody)(o,n,a,s))},"sendError");exports.sendError=sendError,exports.NO_STORE="no-store";const tokenMatches=t((e,r)=>{if(!r)return!1;const o=Buffer.from(e??""),n=Buffer.from(r);return o.length===n.length&&(0,node_crypto_1.timingSafeEqual)(o,n)},"tokenMatches");exports.tokenMatches=tokenMatches;const addVary=t((e,r)=>{const o=e.vary,n=Array.isArray(o)?o.join(", "):typeof o=="string"?o:"";if(n.trim()==="*")return;const s=n.split(",").map(a=>a.trim()).filter(Boolean);s.some(a=>a.toLowerCase()===r.toLowerCase())||(e.vary=[...s,r].join(", "))},"addVary");exports.addVary=addVary;var canonical_path_1=require("../canonical-path");Object.defineProperty(exports,"ENCODED_STRUCTURE",{enumerable:!0,get:t(function(){return canonical_path_1.ENCODED_STRUCTURE},"get")}),Object.defineProperty(exports,"canonicalize",{enumerable:!0,get:t(function(){return canonical_path_1.canonicalize},"get")}),Object.defineProperty(exports,"canonicalPath",{enumerable:!0,get:t(function(){return canonical_path_1.canonicalPath},"get")}),Object.defineProperty(exports,"RAW_TARGET",{enumerable:!0,get:t(function(){return canonical_path_1.RAW_TARGET},"get")}),Object.defineProperty(exports,"rawTargetOf",{enumerable:!0,get:t(function(){return canonical_path_1.rawTargetOf},"get")}),Object.defineProperty(exports,"rememberRawTarget",{enumerable:!0,get:t(function(){return canonical_path_1.rememberRawTarget},"get")});const safeUrl=t(e=>{if(!e)return"(unset)";try{const r=new URL(e);return`${r.protocol}//${r.host}${r.pathname}`}catch{return"(set)"}},"safeUrl");exports.safeUrl=safeUrl;
|
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
*/
|
|
10
10
|
import type { FastifyReply, FastifyRequest } from 'fastify';
|
|
11
11
|
import type { TraceSpan } from '../otel-tracing';
|
|
12
|
+
import type { RouteLimits } from './route-limits';
|
|
12
13
|
import type { ProdHookContext, ProdRuntime, ReqState } from './types';
|
|
13
14
|
import type { Observability } from './observability';
|
|
14
15
|
import type { CorsLayer } from './cors';
|
|
@@ -24,6 +25,7 @@ export interface HandlerDeps {
|
|
|
24
25
|
upstream: UpstreamLayer;
|
|
25
26
|
rollout: RolloutLayer;
|
|
26
27
|
hooks: HooksLayer;
|
|
28
|
+
routeLimits: RouteLimits;
|
|
27
29
|
reqState: WeakMap<FastifyRequest, ReqState>;
|
|
28
30
|
spanByReq: WeakMap<FastifyRequest, TraceSpan>;
|
|
29
31
|
ctxByReq: WeakMap<FastifyRequest, ProdHookContext>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var ve=Object.defineProperty;var B=(k,n)=>ve(k,"name",{value:n,configurable:!0});var he=Object.defineProperty,m=B((k,n)=>he(k,"name",{value:n,configurable:!0}),"m");Object.defineProperty(exports,"__esModule",{value:!0}),exports.createHandler=createHandler;const manifest_1=require("../manifest"),gateway_errors_1=require("../gateway-errors"),client_ip_1=require("../client-ip"),upstream_errors_1=require("./upstream-errors"),trust_1=require("./trust"),edge_1=require("./edge");function createHandler(k){const{rt:n,obs:a,cors:j,auth:F,upstream:te,rollout:v,hooks:h,routeLimits:se,reqState:M,spanByReq:oe,ctxByReq:ae}=k,K=Math.max(0,Math.floor(n.opts.server?.maxInFlightPerClient??0)),q=new Map,ne=m(l=>t=>{a.emit("error",`gateway ${l} hook failed: ${t?.message??String(t)}`,`gateway-hook-error:${l}`,{kind:"gateway-hook-error",phase:l,error:t?.message??String(t)})},"hookFailed"),V=!!n.opts.pods?.resolveVersion,C=!!n.opts.cookie?.secret,W=!!n.opts.pods?.bucket&&(C||!!n.opts.uidHeader),ie=V||C||W,de=n.opts.upstreamRetries??1,ce=m(l=>(0,edge_1.tokenMatches)(l.query?.token??(0,edge_1.hdr)(l.raw.headers["x-status-token"]),n.opts.statusToken),"statusTokenMatches"),le=m((l,t,e,S,g,w)=>{const f=l.raw;if(j.setCors(t,f),t.header("cache-control",edge_1.NO_STORE),f.method==="OPTIONS"){t.code(204).header("access-control-allow-methods","GET,POST,PUT,PATCH,DELETE,HEAD,OPTIONS").header("access-control-allow-headers",String(f.headers["access-control-request-headers"]??"*")).send();return}const s=n.table.routes.filter(c=>c.host&&(0,manifest_1.hostMatches)(c.host,e)&&c.prefix),i=g;if(s.length>0&&(i==="/health"||i==="/healthz")){const c=w?{status:"ok",host:e,services:s.map(y=>({service:y.service,prefix:y.prefix}))}:{status:"ok"};t.code(200).type("application/json").send(JSON.stringify(c));return}if(i==="/.well-known/lensmcp-routes"){if(!w){(0,edge_1.sendError)(t,f,404,"not_found","No gateway route for this hostname.");return}t.code(200).type("application/json").send(JSON.stringify({host:e,routes:n.table.routes.filter(c=>!c.host||(0,manifest_1.hostMatches)(c.host,e)).map(c=>({host:c.host??"(default)",service:c.service,prefix:c.prefix,internal:!!c.internal,auth:c.auth}))}));return}(0,edge_1.sendError)(t,f,404,"not_found",w&&s.length>0?`No service mounted at ${S} on ${e}.`:"No gateway route for this hostname.")},"handleNoRoute");return async(l,t)=>{const e=l.raw,S=(0,edge_1.parseHost)(e.headers.host),g=S?.name??"",w=e.url??"/",f=ce(l);delete e.headers["x-status-token"];const s=a.beginTrace(e);(0,gateway_errors_1.ensureRequestId)(e),a.step(s,"received",{host:g,method:e.method,url:w});const i=h.any?h.httpContext(e,l,t,s):void 0;if(i&&ae.set(l,i),i&&h.has("onRequest")&&(await h.run("onRequest",i),i.responded()))return t;if(e.httpVersionMajor<1)return a.finish(s,"gateway",400),(0,edge_1.sendError)(t,e,400,"bad_request","Bad Request");if(e.method==="TRACE"||e.method==="TRACK")return a.finish(s,"gateway",405),t.header("allow","GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS"),(0,edge_1.sendError)(t,e,405,"bad_request","Method Not Allowed");if(!S)return a.step(s,"bad-host",{}),a.finish(s,"gateway",400),(0,edge_1.sendError)(t,e,400,"bad_request","Bad Request");const c=(0,edge_1.canonicalize)(w);if(c===void 0)return a.step(s,"bad-path",{}),a.finish(s,"gateway",400),(0,edge_1.sendError)(t,e,400,"bad_request","Bad Request");const y=c.policy,_=c.path+c.query;_!==w&&(0,edge_1.rememberRawTarget)(e,w),e.url=_;const A=e.socket?.remoteAddress??l.ip,x=v.clientIpOf(e,A),ue=v.proxyKind(e,A);v.dropProxySecret(e),(0,trust_1.stripProxyClaims)(e.headers,ue,v.proxyHeaders);const E=(0,client_ip_1.limiterKey)(x);if(n.opts.rateLimiter){const r=await n.opts.rateLimiter.check(E);if(!r.allowed)return t.header("retry-after",String(Math.ceil(r.retryAfterMs/1e3))),a.step(s,"rate-limited",{}),a.finish(s,"gateway",429),(0,edge_1.sendError)(t,e,429,"rate_limited","Too Many Requests")}const o=(0,manifest_1.matchRoute)(n.table.routes,g,y+c.query);if(!o)return le(l,t,g,_,y,f),t;if(i&&(i.route=o),a.step(s,"route-match",{project:o.service,...o.prefix?{prefix:o.prefix}:{},...o.internal?{internal:!0}:{}}),e.method==="OPTIONS")return j.setCors(t,e),t.code(204).header("access-control-allow-methods","GET,POST,PUT,PATCH,DELETE,HEAD,OPTIONS").header("access-control-allow-headers",String(e.headers["access-control-request-headers"]??"*")).send(),t;if(K){const r=q.get(E)??0;if(r>=K)return t.header("retry-after","1"),a.step(s,"in-flight-cap",{}),a.finish(s,o.service,429),(0,edge_1.sendError)(t,e,429,"rate_limited","Too Many Requests");q.set(E,r+1),t.raw.once("close",()=>{const d=(q.get(E)??1)-1;d>0?q.set(E,d):q.delete(E)})}const R=n.opts.tracing?.startSpan(e,`gateway ${o.service}`,{"http.request.method":e.method??"GET","url.path":_.split("?")[0],"server.address":g,"lensmcp.service":o.service,...o.internal?{"lensmcp.internal":!0}:{}});if(R&&oe.set(l,R),i&&h.has("beforeAuth")&&(await h.run("beforeAuth",i),i.responded()))return t;if(o.internal&&n.opts.internalPeers?.length&&!(0,client_ip_1.addressIn)(x,n.opts.internalPeers))return a.step(s,"internal-peer",{ok:!1}),a.finish(s,o.service,404),(0,edge_1.sendError)(t,e,404,"not_found","No gateway route for this hostname.");const N=o.internal?void 0:n.opts.identify?.(e),T=N instanceof Promise?await N:N;let L;if(o.internal){const r=F.internal(e,o,s);if(!r.ok)return a.finish(s,o.service,r.status),(0,edge_1.sendError)(t,e,r.status,r.reason,r.detail);L=r.caller,i&&(i.caller=L)}else{const r=F.public(e,o,y,T,x,s);if(!r.ok)return a.finish(s,o.service,r.status),(0,edge_1.sendError)(t,e,r.status,r.reason,r.detail);if(i&&(i.claims=T),i&&h.has("afterAuth")&&(await h.run("afterAuth",i),i.responded()))return t}const G=se.check(o,y,{ip:E,tenant:T?.tid,user:T?.sub}),P=G?await G:void 0;if(P)return t.header("retry-after",String(Math.max(1,Math.ceil(P.retryAfterMs/1e3)))),a.step(s,"route-limited",{key:P.limit.key,...P.limit.path?{path:P.limit.path}:{}}),a.finish(s,o.service,429),(0,edge_1.sendError)(t,e,429,"rate_limited","Too Many Requests");if((0,trust_1.countHop)(e)===void 0)return a.step(s,"loop",{}),a.finish(s,o.service,508),(0,edge_1.sendError)(t,e,508,"unavailable","Loop detected");e.headers["x-forwarded-for"]=v.forwardedFor(e,A),e.headers["x-forwarded-proto"]=v.forwardedProto(e,A,n.opts.tls?"https":"http"),e.headers["x-forwarded-host"]=e.headers.host??g,e.headers["x-real-ip"]=x;const z=n.serviceKeyOf(o.service);if(z&&(e.headers["x-internal-token"]=z),o.prependPrefix){const r=e.url??"/",d=o.prependPrefix;r!==d&&!r.startsWith(d+"/")&&(e.url=d+r)}const O=(0,edge_1.hdr)(e.headers[n.versionHeader]);let D=O,I=!1,H;if(ie&&!o.internal&&!O){const r=v.resolveStickyKey(e);r.mint&&(H=r.key);const d=V?n.opts.pods.resolveVersion(o.service,v.buildAttrs(e,x,T,r.key,y)):void 0;if(d)D=d.version,I=!0,a.step(s,"targeting",{rule:d.rule,version:d.version});else if(r.key){const b=n.opts.pods?.bucket?.(o.service,r.key);b&&(D=b.version,I=!0,a.step(s,"targeting",{mode:"sticky",version:b.version}))}}const p=await te.resolveUpstream(o,s,D,I);if(!p)return a.finish(s,o.service,503),(0,edge_1.sendError)(t,e,503,"unavailable",f?`Service ${o.service} has no available upstream.`:"Service unavailable.");if(!("url"in p))return a.finish(s,o.service,502),(0,edge_1.sendError)(t,e,502,"unavailable",f?`Service ${o.service}: socket upstreams are not supported by the prod gateway.`:"Upstream unavailable.");const J=new URL(p.url),pe=J.origin,Q=J.pathname.replace(/\/+$/,"");Q&&(e.url=Q+(e.url??"/"));const U=p.url,u={route:o,caller:L,startedAt:Date.now(),trace:s,version:p.version,upLabel:U};if(M.set(l,u),t.raw.once("close",()=>{if(t.raw.writableFinished||M.get(l)!==u)return;M.delete(l);const r=t.raw.headersSent,d=r?t.raw.statusCode:void 0;a.recordEdge(u.route,Date.now()-u.startedAt,d,u.caller,u.version),a.finish(u.trace,u.route.service,d,{aborted:r?"during-response":"before-response",error:r?"the caller went away before the response ended":"the caller went away before any response was sent",upstream:u.upLabel,...u.version?{version:u.version}:{},...u.caller?{caller:u.caller}:{}})}),i&&(i.version=p.version),a.step(s,p.version?"rollout":"upstream",{upstream:U,...p.version?{version:p.version,...O?{pinned:!0}:{}}:{}}),R&&n.opts.tracing.inject(R,e.headers),i&&h.has("beforeForward")&&(await h.run("beforeForward",i),i.responded()))return t;const X=(0,trust_1.unforwardableHeader)(e.headers);if(X)return a.step(s,"bad-header",{header:X}),(0,edge_1.sendError)(t,e,400,"bad_request","Bad Request");let Y=m(()=>{},"waitDone"),Z=!1;const ee=m(()=>{Z||(Y=n.upstreamWaits.begin())},"beginWait"),$=m(()=>{Z=!0,Y()},"endWait");return e.complete?ee():e.once("end",ee),t.raw.once("close",$),t.from(void 0,{getUpstream:m(()=>pe,"getUpstream"),retriesCount:de,rewriteHeaders:m(r=>{if(u.proxied=!0,$(),s&&f&&(r["x-lensmcp-upstream"]=U),r["x-request-id"]||(r["x-request-id"]=(0,gateway_errors_1.ensureRequestId)(e)),p.version&&(r["x-lensmcp-version"]=p.version),(O||p.version)&&(0,edge_1.addVary)(r,n.versionHeader),(H||W&&C)&&(0,edge_1.addVary)(r,"Cookie"),delete r["x-powered-by"],delete r.connection,delete r["keep-alive"],delete r["proxy-connection"],r.server="LensMCP",H){const d=r["set-cookie"],b=Array.isArray(d)?d:d?[d]:[];r["set-cookie"]=[...b,v.mintCookieHeader(H)]}return r},"rewriteHeaders"),onError:m((r,{error:d})=>{$();const b=d,re=(0,upstream_errors_1.refusedBeforeDispatch)(b),fe=(0,upstream_errors_1.clientWentAway)(e,t.raw);!re&&!fe&&(0,upstream_errors_1.upstreamTransportFailure)(b)&&n.opts.pods?.drop?.(o.service,p),i&&h.has("onError")&&(i.error=d,h.run("onError",i).catch(ne("onError"))),re?(0,edge_1.sendError)(r,e,400,"bad_request","Bad Request"):(0,edge_1.sendError)(r,e,502,"unavailable",f?`Upstream ${o.service} unavailable.`:"Upstream unavailable.")},"onError")})}}B(createHandler,"createHandler"),m(createHandler,"createHandler");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var f=Object.defineProperty;var i=(t,d)=>f(t,"name",{value:d,configurable:!0});var l=Object.defineProperty,n=i((t,d)=>l(t,"name",{value:d,configurable:!0}),"n");Object.defineProperty(exports,"__esModule",{value:!0}),exports.createHooks=createHooks;const edge_1=require("./edge"),TERMINAL_PHASES=new Set(["onResponse","onError"]);function createHooks(t){const d=n(async(e,o)=>{const r=t[e];if(!r||r.length===0)return;const s=TERMINAL_PHASES.has(e);for(const a of r){if(!s&&o.responded())return;await a(o)}},"run"),u=n(e=>(t[e]?.length??0)>0,"has");return{any:["onRequest","beforeAuth","afterAuth","beforeForward","onResponse","onError","onUpgrade"].some(e=>u(e)),run:d,has:u,httpContext:n((e,o,r,s)=>{let a=!1;return{req:e,request:o,reply:r,socket:void 0,trace:s,route:void 0,caller:void 0,claims:void 0,version:void 0,error:void 0,status:void 0,sendError:n((c,v,p)=>{(0,edge_1.sendError)(r,e,c,v,p),a=!0},"sendError"),responded:n(()=>a||r.raw.writableEnded,"responded")}},"httpContext"),upgradeContext:n((e,o,r)=>{let s=!1;return{req:e,request:void 0,reply:void 0,socket:o,trace:r,route:void 0,caller:void 0,claims:void 0,version:void 0,error:void 0,status:void 0,sendError:n(()=>{try{o.destroy()}catch{}s=!0},"sendError"),responded:n(()=>s||o.destroyed,"responded")}},"upgradeContext")}}i(createHooks,"createHooks"),n(createHooks,"createHooks");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var S=Object.defineProperty;var p=(a,c)=>S(a,"name",{value:c,configurable:!0});var y=Object.defineProperty,d=p((a,c)=>y(a,"name",{value:c,configurable:!0}),"d");Object.defineProperty(exports,"__esModule",{value:!0}),exports.createObservability=createObservability;const redact_1=require("@lensmcp/core/redact"),gateway_errors_1=require("../gateway-errors"),edge_1=require("./edge");function createObservability(a,c){const f=d((e,s,t,r,o)=>{if(a.emit)try{a.emit({id:(0,edge_1.eid)(),sessionId:"pending",timestamp:Date.now(),source:"gateway",category:"cluster",severity:e,context:(0,redact_1.redactDeep)({sessionId:"pending",...o}),fingerprint:t,title:(0,redact_1.safeTitle)(s),raw:r&&(0,redact_1.redactDeep)(r)})}catch{}},"emit"),h=new Map,q=d((e,s,t,r,o)=>{const i=e.host??"(default)",u=(r?r+"\u21D2":"")+i+"\u2192"+e.service+(o?"@"+o:""),n=h.get(u)??{host:i,service:e.service,caller:r,version:o,count:0,totalMs:0,errors:0};n.count+=1,n.totalMs+=s,t!==void 0&&(t>=500||t===0)&&(n.errors+=1),h.set(u,n)},"recordEdge"),m=Math.max(1,a.statusWindows??12),v=[],w=new Map,M=d(()=>[...new Set(c().map(e=>e.service))],"routeServices"),$=d(()=>{const e=new Map;for(const t of h.values()){const r=e.get(t.service)??{requests:0,errors:0,totalMs:0,versions:new Set};r.requests+=t.count,r.errors+=t.errors,r.totalMs+=t.totalMs,t.version&&r.versions.add(t.version),e.set(t.service,r)}const s=Date.now();for(const[t,r]of e)r.requests>0&&w.set(t,s);for(v.push(e);v.length>m;)v.shift()},"pushStatusWindow"),g=d(()=>{const e=new Map;for(const t of v)for(const[r,o]of t){const i=e.get(r)??{requests:0,errors:0,totalMs:0,versions:new Set};i.requests+=o.requests,i.errors+=o.errors,i.totalMs+=o.totalMs;for(const u of o.versions)i.versions.add(u);e.set(r,i)}const s=c();return M().map(t=>{const r=e.get(t)??{requests:0,errors:0,totalMs:0,versions:new Set},o=[...new Set(s.filter(n=>n.service===t).map(n=>n.host??"(default)"))],i=r.requests?r.errors/r.requests:0;let u=r.requests===0?"idle":i>=.5?"down":i>=.05?"degraded":"healthy";if(a.healthChecker){const n=s.filter(l=>l.service===t&&l.upstream).map(l=>l.upstream);n.length&&n.every(l=>!a.healthChecker.isHealthy(l))&&(u="down")}return{service:t,hosts:o,status:u,requests:r.requests,errorRate:+i.toFixed(4),avgMs:r.requests?Math.round(r.totalMs/r.requests):0,versions:[...r.versions],lastSeen:w.get(t)??null}})},"buildStatusSnapshot");return{emit:f,beginTrace:d(e=>{if(!a.emit)return;const s=(0,edge_1.hdr)(e.headers["x-lensmcp-flow-id"]);let t=(0,edge_1.hdr)(e.headers["x-request-id"]);if(t!==void 0&&!(0,gateway_errors_1.validRequestId)(t)&&(t=void 0,delete e.headers["x-request-id"]),!(!s&&!t&&!(0,edge_1.hdr)(e.headers.traceparent)))return t||(t=(0,edge_1.eid)(),e.headers["x-request-id"]=t),{startedAt:Date.now(),method:(e.method??"GET").toUpperCase(),host:(e.headers.host||"").split(":")[0],url:e.url??"/",steps:[],...s?{flowId:s}:{},...t?{requestId:t}:{}}},"beginTrace"),step:d((e,s,t)=>{e&&e.steps.push({step:s,atMs:Date.now()-e.startedAt,...t})},"step"),finish:d((e,s,t,r)=>{if(!e||e.done)return;e.done=!0;const o=Date.now()-e.startedAt;f(t===void 0?"warning":t>=500?"error":"info",t===void 0?`gateway ${e.method} ${e.host}${e.url} \u2192 no response: the caller went away after ${o}ms`:`gateway ${e.method} ${e.host}${e.url} \u2192 ${t} (${o}ms)`,`gateway-request:${s}`,{kind:"gateway-request",project:s,host:e.host,method:e.method,url:e.url,...t===void 0?{}:{status:t},durationMs:o,startedAt:e.startedAt,steps:e.steps,...r},{...e.flowId?{flowId:e.flowId}:{},...e.requestId?{requestId:e.requestId}:{}})},"finish"),recordEdge:q,buildStatusSnapshot:g,startFlusher:d(()=>{const e=setInterval(()=>{if($(),a.onStatus)try{a.onStatus(g())}catch{}if(a.emit)for(const s of h.values())f(s.errors?"warning":"info",`traffic ${s.host} \u2192 ${s.service}${s.version?"@"+s.version:""}: ${s.count} req`,`gateway-traffic:${s.host}->${s.service}${s.version?"@"+s.version:""}`,{kind:"gateway-traffic",host:s.host,project:s.service,caller:s.caller,version:s.version,count:s.count,avgMs:Math.round(s.totalMs/s.count),errors:s.errors});h.clear()},a.trafficFlushMs??5e3);return e.unref?.(),e},"startFlusher")}}p(createObservability,"createObservability"),d(createObservability,"createObservability");
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type * as http from 'node:http';
|
|
2
2
|
import { type Attrs } from '../manifest';
|
|
3
|
+
import { type ProxyKind } from '../client-ip';
|
|
3
4
|
import type { ProdGatewayOptions } from './types';
|
|
4
5
|
export interface RolloutLayer {
|
|
5
6
|
/** Resolve the client IP: the trusted front-proxy header if the peer is trusted, else the
|
|
@@ -15,6 +16,12 @@ export interface RolloutLayer {
|
|
|
15
16
|
buildAttrs(req: http.IncomingMessage, clientIp: string, principal: Record<string, unknown> | undefined, key: string | undefined, policyPath?: string): Attrs;
|
|
16
17
|
/** The `X-Forwarded-Proto` to send upstream — a trusted front proxy's, else the gateway's own scheme (PG3-04). */
|
|
17
18
|
forwardedProto(req: http.IncomingMessage, peer: string, ownScheme: 'http' | 'https'): 'http' | 'https';
|
|
19
|
+
/** What the request's peer is to the gateway — decides whose forwarding headers survive (`trust.stripProxyClaims`). */
|
|
20
|
+
proxyKind(req: http.IncomingMessage, peer: string): ProxyKind;
|
|
21
|
+
/** Remove the front proxy's shared secret from the request before it is forwarded (PG4-17). */
|
|
22
|
+
dropProxySecret(req: http.IncomingMessage): void;
|
|
23
|
+
/** Lower-cased headers that are the configured proxy's to assert: its client-address header. */
|
|
24
|
+
readonly proxyHeaders: readonly string[];
|
|
18
25
|
/** Resolve the sticky key: valid cookie → UID header → freshly minted (cookie clients). */
|
|
19
26
|
resolveStickyKey(req: http.IncomingMessage): {
|
|
20
27
|
key?: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var A=Object.defineProperty;var
|
|
1
|
+
"use strict";var A=Object.defineProperty;var l=(r,t)=>A(r,"name",{value:t,configurable:!0});var b=Object.defineProperty,n=l((r,t)=>b(r,"name",{value:t,configurable:!0}),"n");Object.defineProperty(exports,"__esModule",{value:!0}),exports.createRollout=createRollout;const node_crypto_1=require("node:crypto"),manifest_1=require("../manifest"),client_ip_1=require("../client-ip"),edge_1=require("./edge");function createRollout(r){const t=(0,client_ip_1.createClientIpResolver)({...r.clientIpHeader?{clientIpHeader:r.clientIpHeader}:{},...r.clientIpTrustedProxies?{clientIpTrustedProxies:r.clientIpTrustedProxies}:{},trustProxyHops:r.trustProxyIp?Math.max(1,Math.floor(r.trustProxyHops??1)):0,...r.clientIpProxySecret?.value?{proxySecret:r.clientIpProxySecret}:{},onIgnoredProxyHeader:n((e,o)=>console.warn(`[gateway] \xAB${o}\xBB arrived from ${e}, which is not a trusted proxy \u2014 the header is IGNORED and ${e} is treated as the client for every request it carries (one rate-limit bucket for all of them). If ${e} is your front proxy, list its network in clientIpTrustedProxies / LENSMCP_GW_CLIENT_IP_TRUSTED_PROXIES.`),"onIgnoredProxyHeader")}),h=t.clientIpOf,P=t.forwardedFor,g=t.forwardedProto,u=(r.attributeHeaders??[]).map(e=>e.toLowerCase()),p=r.uidHeader?.toLowerCase(),d=r.cookie?.secret,f=!!r.cookie&&!!d,y=r.cookie?.name??"lensmcp_did",m=r.cookie?.domain,S=r.cookie?.maxAge??31536e3;r.cookie&&!d&&console.warn("[gateway] device cookie has NO secret \u2014 sticky cookie bucketing is DISABLED (set cookie.secret / LENSMCP_GW_COOKIE_SECRET to enable it). An unsigned cookie is attacker-choosable.");const x=n(e=>(0,node_crypto_1.createHmac)("sha256",d).update(e).digest("base64url"),"signId"),_=n(e=>`${e}.${x(e)}`,"signedCookie"),v=n(e=>{if(!d)return;const o=e.lastIndexOf(".");if(o<0)return;const i=e.slice(0,o),s=Buffer.from(e.slice(o+1)),c=Buffer.from(x(i));return s.length===c.length&&(0,node_crypto_1.timingSafeEqual)(s,c)?i:void 0},"verifyCookie"),C=n((e,o)=>{if(e)for(const i of e.split(";")){const s=i.indexOf("=");if(s>0&&i.slice(0,s).trim()===o){const c=i.slice(s+1).trim();try{return decodeURIComponent(c)}catch{return}}}},"parseCookie"),H=n(e=>{let o=`${y}=${encodeURIComponent(_(e))}; Path=/; Max-Age=${S}; HttpOnly; SameSite=Lax; Secure`;return m&&(o+=`; Domain=${m}`),o},"mintCookieHeader"),w=n(e=>{if(f){const o=C(e.headers.cookie,y),i=o?v(o):void 0;if(i)return{key:i,mint:!1}}if(p){const o=(0,edge_1.hdr)(e.headers[p]);if(o)return{key:o,mint:!1}}return f?{key:"d_"+(0,node_crypto_1.randomBytes)(12).toString("base64url"),mint:!0}:{mint:!1}},"resolveStickyKey"),E=n((e,o,i,s,c)=>{const a=(0,manifest_1.claimAttrs)(i);if(a.ip=o,a.method=(e.method??"GET").toUpperCase(),a.path=c??(e.url??"/").split("?")[0],s&&(a.device=s),u.length&&t.peerAsserts(e.socket?.remoteAddress??void 0,e))for(const k of u){const I=(0,edge_1.hdr)(e.headers[k]);I!==void 0&&(a["header."+k]=I)}return a},"buildAttrs"),O=t.proxyHeaders;return{clientIpOf:h,forwardedFor:P,forwardedProto:g,buildAttrs:E,proxyKind:t.proxyKind,dropProxySecret:t.dropProxySecret,proxyHeaders:O,resolveStickyKey:w,mintCookieHeader:H}}l(createRollout,"createRollout"),n(createRollout,"createRollout");
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A manifest's `rateLimits`, enforced (issues/closed/prod-gateway-4-19).
|
|
3
|
+
*
|
|
4
|
+
* The field was declared on the manifest, shown in the design doc and never read: a service that declared a limit on
|
|
5
|
+
* its login path got none and was told nothing, and the only throttle at the edge was one bucket per client address —
|
|
6
|
+
* blind to identity, so a signed-in scraper was bounded per address and never per user or tenant, though the edge
|
|
7
|
+
* verifies both. This layer runs AFTER auth, so a limit may key on the verified `sub` or `tid`.
|
|
8
|
+
*
|
|
9
|
+
* One limiter per distinct `points` / `duration` (a limiter holds many keys); the key names the service, the limit's
|
|
10
|
+
* path and the caller's value in the limit's dimension. A caller with no such identity (anonymous on a public path)
|
|
11
|
+
* is bucketed by address. Built by `routeLimiter` when the host wires one (Redis: one budget for every replica), else
|
|
12
|
+
* the in-memory token bucket — per process, like the edge limiter.
|
|
13
|
+
*/
|
|
14
|
+
import { type RateLimit, type Route } from '../manifest';
|
|
15
|
+
import { type RateLimiter } from '../rate-limit';
|
|
16
|
+
export interface RouteLimitCaller {
|
|
17
|
+
ip: string;
|
|
18
|
+
tenant?: unknown;
|
|
19
|
+
user?: unknown;
|
|
20
|
+
}
|
|
21
|
+
export interface RouteLimits {
|
|
22
|
+
/** The first limit of `route` that covers `path` and is spent for this caller, or undefined. Resolves synchronously
|
|
23
|
+
* (no promise) when the route declares no limit, so an unlimited route pays nothing. */
|
|
24
|
+
check(route: Route, path: string, who: RouteLimitCaller): undefined | Promise<{
|
|
25
|
+
retryAfterMs: number;
|
|
26
|
+
limit: RateLimit;
|
|
27
|
+
} | undefined>;
|
|
28
|
+
stop(): void;
|
|
29
|
+
}
|
|
30
|
+
export declare function createRouteLimits(factory?: (limit: number, windowMs: number) => RateLimiter): RouteLimits;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var M=Object.defineProperty;var u=(s,r)=>M(s,"name",{value:r,configurable:!0});var h=Object.defineProperty,o=u((s,r)=>h(s,"name",{value:r,configurable:!0}),"o");Object.defineProperty(exports,"__esModule",{value:!0}),exports.createRouteLimits=createRouteLimits;const manifest_1=require("../manifest"),rate_limit_1=require("../rate-limit"),MAX_LIMITERS=256;function createRouteLimits(s=(r,c)=>(0,rate_limit_1.createRateLimiter)({limit:r,windowMs:c})){const r=new Map,c=o(e=>{const a=`${e.points}/${e.duration}`;let i=r.get(a);if(!i){if(r.size>=MAX_LIMITERS)return;i=s(Math.floor(e.points),Math.ceil(e.duration*1e3)),r.set(a,i)}return i},"limiterFor"),f=o(e=>typeof e=="string"&&e!==""?e:typeof e=="number"?String(e):void 0,"scalar"),m=o(async(e,a,i,n)=>{for(const t of a){if(!t||!manifest_1.RATE_LIMIT_KEYS.has(t.key)||!(t.points>=1)||!(t.duration>0)||t.path&&!(0,manifest_1.authPathMatches)(t.path,i))continue;const l=c(t);if(!l)continue;const d=t.key==="tenant"?f(n.tenant):t.key==="user"?f(n.user):void 0,y=`${e.service}|${t.path??""}|${t.key}|${d??`addr:${n.ip}`}`,p=await l.check(y);if(!p.allowed)return{retryAfterMs:p.retryAfterMs,limit:t}}},"run");return{check(e,a,i){const n=e.rateLimits;return n&&n.length?m(e,n,a,i):void 0},stop(){for(const e of r.values())e.stop();r.clear()}}}u(createRouteLimits,"createRouteLimits"),o(createRouteLimits,"createRouteLimits");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var y=Object.defineProperty;var u=(r,a)=>y(r,"name",{value:a,configurable:!0});var g=Object.defineProperty,n=u((r,a)=>g(r,"name",{value:a,configurable:!0}),"n");Object.defineProperty(exports,"__esModule",{value:!0}),exports.createRouteTable=createRouteTable;const manifest_1=require("../manifest");function createRouteTable(r,a){const o=[],c=new Map;let l=r.manifests.list(),f="";const p=n(t=>{const e=JSON.stringify(t);if(e!==f){f=e;for(const s of t)console.error(`[gateway] manifest ${s.service}: ${s.problem}`),a.emit("error",`gateway manifest ${s.service}: ${s.problem}`,`gateway-config-error:${s.service}`,{kind:"gateway-config-error",project:s.service,problem:s.problem})}},"report"),m=n(t=>{const{ok:e,problems:s}=(0,manifest_1.admitManifests)(t,r.hostOwners);let h;try{h=(0,manifest_1.buildRouteTable)(e)}catch(i){p([...s,{service:"(route table)",problem:`the manifest set could not be built and was NOT applied \u2014 the routes in use stay: ${i?.message??String(i)}`}]);return}l=e,o.length=0,o.push(...h),c.clear();for(const i of e)c.has(i.service)||c.set(i.service,i);p([...s,...(0,manifest_1.manifestProblems)(e)])},"apply"),b=n(()=>{if(!r.healthChecker)return;const t=new Set;for(const e of o)e.upstream&&t.add(e.upstream);for(const e of r.pods?.endpoints?.()??[])t.add(e);r.healthChecker.track([...t])},"trackUpstreams"),d=n(t=>{m(t),b(),a.emit("info",`gateway routes: ${o.length} on ${l.length} services`,"gateway-up",{kind:"gateway-up",routes:o.map(e=>({host:e.host??"(default)",service:e.service,internal:!!e.internal}))})},"rebuild");m(l);const v=r.manifests.watch?.(t=>d(t));return{routes:o,manifestByService:c,rebuild:d,trackUpstreams:b,manifests:n(()=>l,"manifests"),stop:n(()=>v?.(),"stop")}}u(createRouteTable,"createRouteTable"),n(createRouteTable,"createRouteTable");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var W=Object.defineProperty;var f=(e,t)=>W(e,"name",{value:t,configurable:!0});var R=Object.defineProperty,a=f((e,t)=>R(e,"name",{value:t,configurable:!0}),"a");Object.defineProperty(exports,"__esModule",{value:!0}),exports.indexServiceKeys=indexServiceKeys,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"),route_limits_1=require("./route-limits"),handler_1=require("./handler"),upgrade_1=require("./upgrade"),app_1=require("./app");function indexServiceKeys(e){const t=new Map,r=new Map;for(const[i,d]of Object.entries(e)){const y=(Array.isArray(d)?d:[d]).filter(c=>typeof c=="string"&&c.trim()!=="");if(y.length===0){console.warn(`[gateway] service key for "${i}" is empty \u2014 east-west auth for that service is DISABLED (all internal routes 401) until a key is set.`);continue}r.set(i,y[0]);for(const c of y){const u=t.get(c);if(u!==void 0&&u!==i)throw new Error(`[gateway] services "${u}" and "${i}" share a service key \u2014 every service needs its own (a shared key attributes one's calls to the other)`);t.set(c,i)}}return{keyToProject:t,stampKeys:r}}f(indexServiceKeys,"indexServiceKeys"),a(indexServiceKeys,"indexServiceKeys");function createUpstreamWaits(){const e=new Set;return{begin(){const t={at:Date.now()};return e.add(t),()=>{e.delete(t)}},oldestMs(){let t=1/0;for(const r of e)r.at<t&&(t=r.at);return t===1/0?0:Date.now()-t}}}f(createUpstreamWaits,"createUpstreamWaits"),a(createUpstreamWaits,"createUpstreamWaits");async function startProdGateway(e){const t=e.ports?.length?e.ports:[e.tls?8443:8080],r=e.host??"0.0.0.0";if(r!=="localhost"&&!(0,node_net_1.isIP)(r))throw new Error(`The gateway binds an IP address or localhost \u2014 not \xAB${r.slice(0,80)}\xBB (host)`);const i=e.authenticate??(s=>{if(s==="jwt")throw new Error("jwt route but no authenticator configured")}),d=(e.versionHeader??"x-lensmcp-version").toLowerCase(),y=!!e.accessLog,c=new Set((e.corsCredentialOrigins??[]).map(s=>s.toLowerCase())),u=new Map,m=new Map,q=a(s=>{const n=indexServiceKeys(s);u.clear();for(const[p,h]of n.keyToProject)u.set(p,h);m.clear();for(const[p,h]of n.stampKeys)m.set(p,h)},"applyServiceKeys");q(e.serviceKeys??{}),e.statusToken&&e.statusToken.length<16&&console.warn(`[gateway] the status token is ${e.statusToken.length} characters \u2014 use at least 16 random characters (it gates /statusz, /metricsz and the route view).`);const O=createUpstreamWaits(),_={},o=(0,observability_1.createObservability)(e,()=>_.current.routes),l=(0,routing_1.createRouteTable)(e,o);_.current=l;const w={opts:e,table:l,keyToProject:u,serviceKeyOf:a(s=>m.get(s),"serviceKeyOf"),upstreamWaits:O,versionHeader:d,accessLog:y,corsCredentialOrigins:c},g=(0,rollout_1.createRollout)(e),S=(0,upstream_1.createUpstream)(e,o),x=(0,auth_1.createEdgeAuth)(w,o,g,i),v=(0,hooks_1.createHooks)(e.hooks??{}),k=new WeakMap,P=new WeakMap,K=new WeakMap,L=(0,cors_1.createCors)(w,k),b=(0,route_limits_1.createRouteLimits)(e.routeLimiter),T=(0,handler_1.createHandler)({rt:w,obs:o,cors:L,auth:x,upstream:S,rollout:g,hooks:v,routeLimits:b,reqState:k,spanByReq:P,ctxByReq:K}),j=(0,upgrade_1.createUpgrade)({rt:w,obs:o,auth:x,upstream:S,hooks:v,rollout:g,routeLimits:b}),{buildApp:B}=(0,app_1.createApp)({rt:w,obs:o,cors:L,hooks:v,rollout:g,handler:T,upgrade:j,reqState:k,spanByReq:P,ctxByReq:K}),C=o.startFlusher();l.rebuild(l.manifests());const M=[],$=[],U=r.includes(":")?`[${r}]`:r;for(const s of t){const n=await B();await n.listen({port:s,host:r});const p=n.server.address(),h=typeof p=="object"&&p?p.port:s;$.push(h),console.log(`[gateway] listening on ${e.tls?"https":"http"}://${U}:${h}`),M.push(n)}e.healthChecker?.start();let A=!1;return{ports:$,host:r,routes:a(()=>l.routes,"routes"),status:o.buildStatusSnapshot,refreshUpstreams:l.trackUpstreams,setServiceKeys:q,stop:a(async()=>{if(A)return;A=!0,clearInterval(C),l.stop(),e.healthChecker?.stop(),e.rateLimiter?.stop(),b.stop(),e.metrics?.stop(),o.emit("info","gateway down","gateway-down",{kind:"gateway-down"});const s=Promise.all(M.map(n=>n.close()));j.closeAll(),await s},"stop")}}f(startProdGateway,"startProdGateway"),a(startProdGateway,"startProdGateway");
|
|
@@ -4,10 +4,51 @@
|
|
|
4
4
|
* originate from a verified token, then re-stamp on forward. Pure.
|
|
5
5
|
*/
|
|
6
6
|
import type * as http from 'node:http';
|
|
7
|
+
import type { ProxyKind } from '../client-ip';
|
|
7
8
|
export declare const TRUST_HEADERS: string[];
|
|
8
9
|
export declare const HOP_BY_HOP: string[];
|
|
9
10
|
export declare const METHOD_OVERRIDE_HEADERS: string[];
|
|
11
|
+
/** Forwarding headers the GATEWAY states on the way out — a client's copy is never what the upstream reads. */
|
|
12
|
+
export declare const FORWARDED_HEADERS: string[];
|
|
13
|
+
/** The hop counter (PG4-16): how many times this request has passed a LensMCP gateway. */
|
|
14
|
+
export declare const HOP_HEADER = "x-lensmcp-hops";
|
|
15
|
+
/** A request that has been through the gateway this often is a loop, not a chain of proxies. */
|
|
16
|
+
export declare const MAX_HOPS = 8;
|
|
17
|
+
/**
|
|
18
|
+
* Headers that name a DIFFERENT path, or restate the forwarding chain in a second dialect — dropped from every
|
|
19
|
+
* request (PG4-08). `X-Original-URL` / `X-Rewrite-URL` are honoured by IIS, Symfony and friends as THE request path:
|
|
20
|
+
* the edge authorises `/public` and the upstream serves `/admin`. `Forwarded` (RFC 7239) is preferred over
|
|
21
|
+
* `X-Forwarded-*` by Spring and Rack; the gateway rewrites the `X-Forwarded-*` family and never wrote this one, so a
|
|
22
|
+
* client's copy was the only statement an upstream that reads it ever got.
|
|
23
|
+
*/
|
|
24
|
+
export declare const ALWAYS_DROPPED: string[];
|
|
25
|
+
/**
|
|
26
|
+
* Client-address and forwarding headers a front proxy may assert and a caller may not (PG4-08). Kept from a counted
|
|
27
|
+
* `X-Forwarded-For` chain (a generic load balancer legitimately sets `X-Forwarded-Port`); dropped from everyone
|
|
28
|
+
* else — a proxy trusted for its OWN header (`cf-connecting-ip`) vouches for its own family, not for these, which
|
|
29
|
+
* Cloudflare passes through from the client untouched.
|
|
30
|
+
*/
|
|
31
|
+
export declare const PROXY_CLAIM_HEADERS: string[];
|
|
10
32
|
export declare const stripTrust: (req: http.IncomingMessage) => void;
|
|
33
|
+
/**
|
|
34
|
+
* Drop what a caller may not assert about itself, given what its peer is to the gateway (PG4-08):
|
|
35
|
+
* - `'chain'` (a counted X-Forwarded-For chain) — nothing more: a generic proxy's forwarding headers are its own;
|
|
36
|
+
* - `'header'` (trusted for `clientIpHeader`) — the generic claims go, its own header family stays;
|
|
37
|
+
* - `'none'` — the generic claims go, and so do the CONFIGURED proxy's headers: `configured` (its client-address
|
|
38
|
+
* header) and every header of the same vendor family (`cf-…` beside `cf-connecting-ip`). Rule attribute headers
|
|
39
|
+
* are NOT among them — they may be ordinary request headers an upstream needs from every caller. The gateway already ignored those for its own decisions; it used to forward them, so an
|
|
40
|
+
* upstream that reads `cf-connecting-ip` or `cf-access-authenticated-user-email` was told whatever a direct
|
|
41
|
+
* caller wrote. With no proxy configured the gateway has no proxy model, and only the generic claims are dropped.
|
|
42
|
+
* - `'peer'` (a trusted peer, no client-address header configured) — as `'header'`: the generic claims go.
|
|
43
|
+
*/
|
|
44
|
+
export declare const stripProxyClaims: (headers: http.IncomingHttpHeaders, kind: ProxyKind, configured: readonly string[]) => void;
|
|
45
|
+
/**
|
|
46
|
+
* Count this hop on the request, or return undefined when it has been through a LensMCP gateway {@link MAX_HOPS}
|
|
47
|
+
* times already (PG4-16). A route whose upstream resolves back to the gateway used to turn ONE request into 257 —
|
|
48
|
+
* the whole upstream pool — before a timeout ended it; nothing marked a request as having been here before. A
|
|
49
|
+
* client's own value is read as a number or not at all, and can only cut its own request short.
|
|
50
|
+
*/
|
|
51
|
+
export declare const countHop: (req: http.IncomingMessage) => number | undefined;
|
|
11
52
|
/**
|
|
12
53
|
* Request headers undici's `Request` constructor REFUSES, each with the error it would raise (PG3-17). Forwarded
|
|
13
54
|
* unchanged, a client's copy made the dispatch throw synchronously, and undici's pool read that `false` as
|
|
@@ -32,5 +73,8 @@ export declare const unforwardableHeader: (headers: http.IncomingHttpHeaders) =>
|
|
|
32
73
|
/**
|
|
33
74
|
* Stamp the verified identity onto the forwarded request — tenant from the `tid` CLAIM, never a client header. A
|
|
34
75
|
* workload's token (a composition's `preAuth`, `../workspace-auth`) is a service's: no `x-user-id`, no `x-user-roles`.
|
|
76
|
+
* Returns how many role / permission elements were refused, so the caller can say so.
|
|
35
77
|
*/
|
|
36
|
-
export declare const stampIdentity: (req: http.IncomingMessage, claims: Record<string, unknown>) =>
|
|
78
|
+
export declare const stampIdentity: (req: http.IncomingMessage, claims: Record<string, unknown>) => {
|
|
79
|
+
dropped: number;
|
|
80
|
+
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var E=Object.defineProperty;var a=(t,e)=>E(t,"name",{value:e,configurable:!0});var d=Object.defineProperty,n=a((t,e)=>d(t,"name",{value:e,configurable:!0}),"n");Object.defineProperty(exports,"__esModule",{value:!0}),exports.stampIdentity=exports.unforwardableHeader=exports.stripUnforwardable=exports.UNFORWARDABLE_HEADERS=exports.countHop=exports.stripProxyClaims=exports.stripTrust=exports.PROXY_CLAIM_HEADERS=exports.ALWAYS_DROPPED=exports.MAX_HOPS=exports.HOP_HEADER=exports.FORWARDED_HEADERS=exports.METHOD_OVERRIDE_HEADERS=exports.HOP_BY_HOP=exports.TRUST_HEADERS=void 0;const workspace_auth_1=require("../workspace-auth"),jwt_claims_1=require("../jwt-claims");exports.TRUST_HEADERS=["x-internal-token","x-api-key-id","x-user-id","x-tenant-id","x-user-roles","x-user-permissions"],exports.HOP_BY_HOP=["connection","proxy-connection","keep-alive"],exports.METHOD_OVERRIDE_HEADERS=["x-http-method-override","x-method-override","x-http-method"],exports.FORWARDED_HEADERS=["x-forwarded-for","x-forwarded-proto","x-forwarded-host","x-real-ip"],exports.HOP_HEADER="x-lensmcp-hops",exports.MAX_HOPS=8,exports.ALWAYS_DROPPED=["x-original-url","x-rewrite-url","x-original-uri","forwarded"],exports.PROXY_CLAIM_HEADERS=["x-client-ip","true-client-ip","x-cluster-client-ip","fastly-client-ip","x-forwarded-port","x-forwarded-scheme","x-forwarded-ssl","x-forwarded-prefix","x-forwarded-server","x-forwarded-protocol","x-forwarded-uri","x-forwarded-path","x-url-scheme","front-end-https","x-host","x-original-host"];const owned=n(t=>exports.TRUST_HEADERS.includes(t)||exports.FORWARDED_HEADERS.includes(t)||exports.METHOD_OVERRIDE_HEADERS.includes(t)||exports.ALWAYS_DROPPED.includes(t)||t===exports.HOP_HEADER,"owned"),stripTrust=n(t=>{const e=t.headers;for(const r of exports.TRUST_HEADERS)delete e[r];for(const r of exports.HOP_BY_HOP)delete e[r];for(const r of exports.METHOD_OVERRIDE_HEADERS)delete e[r];for(const r of exports.ALWAYS_DROPPED)delete e[r];for(const r in e)r.indexOf("_")!==-1&&owned(r.replace(/_/g,"-"))&&delete e[r]},"stripTrust");exports.stripTrust=stripTrust;const stripProxyClaims=n((t,e,r)=>{if(e==="chain")return;const s=e==="none"?r.map(o=>/^([a-z0-9]+-)/.exec(o)?.[1]).filter(o=>!!o&&o!=="x-"):[];for(const o in t){const i=o.indexOf("_")===-1?o:o.replace(/_/g,"-");(exports.PROXY_CLAIM_HEADERS.includes(i)||e==="none"&&(r.includes(i)||s.some(x=>i.startsWith(x))))&&delete t[o]}},"stripProxyClaims");exports.stripProxyClaims=stripProxyClaims;const countHop=n(t=>{const e=t.headers[exports.HOP_HEADER],r=Number(typeof e=="string"?e:0),s=Number.isInteger(r)&&r>0?r:0;if(!(s>=exports.MAX_HOPS))return t.headers[exports.HOP_HEADER]=String(s+1),s+1},"countHop");exports.countHop=countHop,exports.UNFORWARDABLE_HEADERS=["upgrade","expect"];const stripUnforwardable=n(t=>{for(const e of exports.UNFORWARDABLE_HEADERS)delete t.headers[e]},"stripUnforwardable");exports.stripUnforwardable=stripUnforwardable;const FIELD_VALUE=/^[\t\x20-\x7e\x80-\xff]*$/,unforwardableHeader=n(t=>{for(const[e,r]of Object.entries(t))if(r!==void 0){if(typeof r=="string"){if(!FIELD_VALUE.test(r))return e}else if(Array.isArray(r)){for(const s of r)if(!FIELD_VALUE.test(s))return e}}},"unforwardableHeader");exports.unforwardableHeader=unforwardableHeader;const stampIdentity=n((t,e)=>{const r=n((x,p)=>{(typeof p=="string"&&p!==""||typeof p=="number")&&(t.headers[x]=String(p))},"set"),s=(0,workspace_auth_1.workloadToken)(t);s||r("x-user-id",e.sub),r("x-tenant-id",e.tid);const o=(0,jwt_claims_1.identityList)(s?void 0:e.roles);o.values.length&&(t.headers["x-user-roles"]=o.values.join(","));const i=(0,jwt_claims_1.identityList)(e.perms);return i.values.length&&(t.headers["x-user-permissions"]=i.values.join(",")),{dropped:o.dropped+i.dropped}},"stampIdentity");exports.stampIdentity=stampIdentity;
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
*/
|
|
7
7
|
import type * as http from 'node:http';
|
|
8
8
|
import type { FastifyReply, FastifyRequest } from 'fastify';
|
|
9
|
-
import type { AuthMode, Attrs, ManifestProvider, PodProvider, Route, RouteManifest } from '../manifest';
|
|
9
|
+
import type { AuthMode, Attrs, HostOwners, ManifestProvider, PodProvider, Route, RouteManifest } from '../manifest';
|
|
10
10
|
import type { GatewayTracer } from '../otel-tracing';
|
|
11
11
|
import type { HealthChecker } from '../health-check';
|
|
12
12
|
import type { RateLimiter } from '../rate-limit';
|
|
@@ -44,12 +44,21 @@ export interface ProdGatewayOptions {
|
|
|
44
44
|
/** Networks (IPv4 CIDRs or exact addresses) allowed to reach an `internal.<host>` route. Unset ⇒ any caller with a
|
|
45
45
|
* valid key, as before. Set ⇒ a caller whose RESOLVED address is outside gets the no-route 404 (PG3-12). */
|
|
46
46
|
internalPeers?: string[];
|
|
47
|
+
/** Who may mount which host — `{ hostPattern: [service, …] }`, `(default)` for the catch-all (PG4-06). A mount on a
|
|
48
|
+
* host that belongs to other services is dropped and named at load. Unset ⇒ any manifest may mount any host, and
|
|
49
|
+
* the longer prefix wins whoever declared it — which is how one registry writer takes `/login` on another's host. */
|
|
50
|
+
hostOwners?: HostOwners;
|
|
47
51
|
/** WebSocket upgrade ceilings, enforced BEFORE any upstream dial (PG3-20). `maxPendingPerClient`: upgrades from
|
|
48
52
|
* one resolved client address still waiting for the upstream's 101 (default 32 → 429). `maxTunnelsPerService`:
|
|
49
|
-
* live tunnels per service (default 4096 → 503).
|
|
53
|
+
* live tunnels per service (default 4096 → 503). `maxTunnelsPerClient`: live tunnels one client address (an IPv6
|
|
54
|
+
* /64) may hold (default a quarter of the service ceiling → 429) — without it one client fills the service's
|
|
55
|
+
* ceiling alone (PG4-09). `idleMs`: a tunnel that carries no byte in either direction for this long is closed
|
|
56
|
+
* (default 600 000; 0 disables) — a WebSocket ping keeps a real one alive. */
|
|
50
57
|
upgrades?: {
|
|
51
58
|
maxPendingPerClient?: number;
|
|
52
59
|
maxTunnelsPerService?: number;
|
|
60
|
+
maxTunnelsPerClient?: number;
|
|
61
|
+
idleMs?: number;
|
|
53
62
|
};
|
|
54
63
|
/** Validate a `jwt`-mode request; THROW to reject (→ 401). Default: a
|
|
55
64
|
* pass-through with a one-time warning — wire a real JWKS validator in prod. */
|
|
@@ -92,6 +101,14 @@ export interface ProdGatewayOptions {
|
|
|
92
101
|
* X-Forwarded-For chain. Safe only when the origin is locked to that proxy —
|
|
93
102
|
* which Cloudflare Tunnel guarantees (there is no public origin to bypass). */
|
|
94
103
|
clientIpHeader?: string;
|
|
104
|
+
/** A secret the front proxy adds to every request, e.g. a Cloudflare Transform Rule setting
|
|
105
|
+
* `x-lensmcp-proxy-secret` (PG4-17). When set, a peer is the trusted proxy only if its address is trusted AND the
|
|
106
|
+
* request carries it — «the peer is loopback» alone is true of every process in the gateway's network namespace.
|
|
107
|
+
* The header never reaches an upstream. `header` defaults to `x-lensmcp-proxy-secret`. */
|
|
108
|
+
clientIpProxySecret?: {
|
|
109
|
+
header?: string;
|
|
110
|
+
value: string;
|
|
111
|
+
};
|
|
95
112
|
/** CIDRs of trusted front proxies. `clientIpHeader` is honored ONLY when the
|
|
96
113
|
* immediate peer (socket address) is in this set — otherwise the header is
|
|
97
114
|
* ignored and the socket IP is used (prevents spoofing the `ip` ABAC attribute
|
|
@@ -123,6 +140,9 @@ export interface ProdGatewayOptions {
|
|
|
123
140
|
* containers (`createRedisRateLimiter`). The check is `await`ed either way; it
|
|
124
141
|
* runs before routing/auth and applies only to proxied traffic (ops endpoints exempt). */
|
|
125
142
|
rateLimiter?: RateLimiter;
|
|
143
|
+
/** Builds the limiter behind a manifest's `rateLimits` entry (PG4-19) — one per distinct `points` / `duration`.
|
|
144
|
+
* Default: the in-memory token bucket (per process). Pass a Redis-backed factory for one budget across replicas. */
|
|
145
|
+
routeLimiter?: (limit: number, windowMs: number) => RateLimiter;
|
|
126
146
|
/** Process self-metrics (event-loop lag / rss / cpu / req rates) from `createProcessMetrics`;
|
|
127
147
|
* exposed at the token-gated `/metricsz` for load/stress tests + production monitoring. */
|
|
128
148
|
metrics?: ProcessMetrics;
|
|
@@ -139,12 +159,20 @@ export interface ProdGatewayOptions {
|
|
|
139
159
|
* `maxHeadersCount` / `maxConnections` are opt-in ceilings for a directly-exposed edge. */
|
|
140
160
|
/** `readyStallMs`: `/readyz` answers 503 while a proxied request has waited this long for an upstream's response
|
|
141
161
|
* head (a wedged pool, PG3-29). Default: the upstream headers timeout + 5 s; 0 disables the check. */
|
|
162
|
+
/** `bodyMinRateBps`: the rate a request BODY must average once `bodyRateGraceMs` (default 30 000) is spent — default
|
|
163
|
+
* 500 bytes/s, 0 disables. A stall bound calls one byte a minute progress; this is what stops a trickled upload
|
|
164
|
+
* from holding an upstream pool connection (PG4-04). `maxInFlightPerClient`: proxied requests one client address
|
|
165
|
+
* may have in flight (→ 429). OFF by default — it is only safe once the gateway resolves real client addresses
|
|
166
|
+
* (behind a proxy it does not trust, every caller is one address). */
|
|
142
167
|
server?: {
|
|
143
168
|
keepAliveTimeout?: number;
|
|
144
169
|
requestTimeout?: number;
|
|
145
170
|
connectionTimeout?: number;
|
|
146
171
|
headersTimeout?: number;
|
|
147
172
|
bodyStallMs?: number;
|
|
173
|
+
bodyMinRateBps?: number;
|
|
174
|
+
bodyRateGraceMs?: number;
|
|
175
|
+
maxInFlightPerClient?: number;
|
|
148
176
|
maxHeadersCount?: number;
|
|
149
177
|
maxConnections?: number;
|
|
150
178
|
connectionsCheckingInterval?: number;
|
|
@@ -289,11 +317,11 @@ export interface ProdGatewayHooks {
|
|
|
289
317
|
export interface ProdHookContext {
|
|
290
318
|
/** Raw node request (header mutation flows downstream to the upstream). */
|
|
291
319
|
readonly req: http.IncomingMessage;
|
|
292
|
-
/** The Fastify request (absent on
|
|
320
|
+
/** The Fastify request (absent on a WebSocket upgrade). */
|
|
293
321
|
readonly request?: FastifyRequest;
|
|
294
|
-
/** The Fastify reply (absent on
|
|
322
|
+
/** The Fastify reply (absent on a WebSocket upgrade). */
|
|
295
323
|
readonly reply?: FastifyReply;
|
|
296
|
-
/** The raw upgrade socket (present only on
|
|
324
|
+
/** The raw upgrade socket (present only on a WebSocket upgrade). */
|
|
297
325
|
readonly socket?: import('node:net').Socket;
|
|
298
326
|
route?: Route;
|
|
299
327
|
caller?: string;
|
|
@@ -1,32 +1,6 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Raw WebSocket upgrade proxy (same trust model; net-level pipe). The upgrade
|
|
3
|
-
* request is rebuilt from `req.rawHeaders` verbatim — minus the gateway-owned
|
|
4
|
-
* trust headers + the client's hop-by-hop control — plus the validated caller +
|
|
5
|
-
* target token + verified identity. Reuses the shared auth + upstream layers.
|
|
6
|
-
*
|
|
7
|
-
* Three properties this path has to supply for itself, because it does NOT go
|
|
8
|
-
* through undici/Fastify like the HTTP handler does:
|
|
9
|
-
*
|
|
10
|
-
* - **header-value validation.** We write the handshake to a raw socket, so a
|
|
11
|
-
* CR/LF anywhere in a forwarded value would inject headers the upstream reads
|
|
12
|
-
* as gateway-authoritative. `validHeaderValue` is undici's own field-value
|
|
13
|
-
* grammar; a violation destroys the socket rather than forwarding a
|
|
14
|
-
* half-trusted handshake.
|
|
15
|
-
* - **identity parity.** Identity is NEVER re-derived from claims here: it is
|
|
16
|
-
* read back from `req.headers`, where the shared `stampIdentity` put it (and
|
|
17
|
-
* only where the HTTP path would have — inside the `jwt` branch of
|
|
18
|
-
* `auth.public`). One stamp, one guard, no divergence to drift.
|
|
19
|
-
* - **TLS.** `https:`/`wss:` upstreams get `tls.connect` with the same connect
|
|
20
|
-
* options (CA / client cert / verification) the undici pool uses, so an mTLS
|
|
21
|
-
* deployment is not silently downgraded on this path.
|
|
22
|
-
*
|
|
23
|
-
* The upstream response head is parsed before anything is piped: a raw
|
|
24
|
-
* bidirectional pipe is only legitimate once the upstream has answered `101` and
|
|
25
|
-
* left HTTP semantics. Any other status is relayed to the client and the sockets
|
|
26
|
-
* are closed — never tunnelled.
|
|
27
|
-
*/
|
|
28
1
|
import * as net from 'node:net';
|
|
29
2
|
import type * as http from 'node:http';
|
|
3
|
+
import type { RouteLimits } from './route-limits';
|
|
30
4
|
import type { ProdRuntime } from './types';
|
|
31
5
|
import type { Observability } from './observability';
|
|
32
6
|
import type { EdgeAuth } from './auth';
|
|
@@ -40,6 +14,7 @@ export interface UpgradeDeps {
|
|
|
40
14
|
upstream: UpstreamLayer;
|
|
41
15
|
hooks: HooksLayer;
|
|
42
16
|
rollout: RolloutLayer;
|
|
17
|
+
routeLimits: RouteLimits;
|
|
43
18
|
}
|
|
44
19
|
export type UpgradeListener = ((req: http.IncomingMessage, socket: net.Socket, head: Buffer) => void) & {
|
|
45
20
|
/** Destroy every live tunnel and pending handshake — `stop()` calls it so a WebSocket cannot pin the drain. */
|
|
@@ -1,14 +1,16 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
${
|
|
1
|
+
"use strict";var be=Object.defineProperty;var V=(l,s)=>be(l,"name",{value:s,configurable:!0});var ve=Object.defineProperty,d=V((l,s)=>ve(l,"name",{value:s,configurable:!0}),"d");Object.defineProperty(exports,"__esModule",{value:!0}),exports.createUpgrade=createUpgrade;const tslib_1=require("tslib"),node_crypto_1=require("node:crypto"),net=tslib_1.__importStar(require("node:net")),tls=tslib_1.__importStar(require("node:tls")),manifest_1=require("../manifest"),client_ip_1=require("../client-ip"),gateway_errors_1=require("../gateway-errors"),edge_1=require("./edge"),trust_1=require("./trust"),validHeaderValue=d(l=>/^[\t\x20-\x7e\x80-\xff]*$/.test(l),"validHeaderValue"),validToken=d(l=>/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(l),"validToken"),WS_GUID="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",WS_KEY=/^[A-Za-z0-9+/]{22}==$/,acceptFor=d(l=>(0,node_crypto_1.createHash)("sha1").update(l+WS_GUID).digest("base64"),"acceptFor"),OWN_LINES=new Set(["host","connection"]),DEFAULT_TUNNEL_IDLE_MS=6e5,DEFAULT_MAX_PENDING_PER_CLIENT=32,DEFAULT_MAX_TUNNELS_PER_SERVICE=4096,MAX_HEAD_BYTES=64*1024,HANDSHAKE_TIMEOUT_MS=3e4;function createUpgrade(l){const{rt:s,obs:c,auth:X,upstream:ge,hooks:u,rollout:_,routeLimits:le}=l,fe=Math.max(1,s.opts.upgrades?.maxPendingPerClient??DEFAULT_MAX_PENDING_PER_CLIENT),Y=Math.max(1,s.opts.upgrades?.maxTunnelsPerService??DEFAULT_MAX_TUNNELS_PER_SERVICE),he=Math.max(1,Math.floor(s.opts.upgrades?.maxTunnelsPerClient??Math.max(1,Y/4))),Z=Math.max(0,s.opts.upgrades?.idleMs??DEFAULT_TUNNEL_IDLE_MS),H=new Map,U=new Map,L=new Map,v=new Set,x=d((e,t,i)=>{const p=(e.get(t)??0)+i;p>0?e.set(t,p):e.delete(t)},"bump"),h=d((e,t,i,p)=>{c.emit("warning",`gateway upgrade rejected (${t})${i?` for ${i}`:""}`,`gateway-upgrade:${i??"(none)"}:${t}`,{kind:"gateway-upgrade-rejected",reason:t,...i?{project:i}:{},...p}),e.destroy()},"reject"),w=d((e,t,i="")=>{try{e.end(`HTTP/1.1 ${t}\r
|
|
2
|
+
${i}Connection: close\r
|
|
3
3
|
Content-Length: 0\r
|
|
4
4
|
\r
|
|
5
|
-
`)}catch{e.destroy()}},"refuse"),
|
|
6
|
-
`);return}}if(
|
|
7
|
-
`);return}if((P.
|
|
8
|
-
`);return}
|
|
5
|
+
`)}catch{e.destroy()}},"refuse"),we=d(async(e,t,i)=>{const p={...e.headers};(0,trust_1.stripTrust)(e),delete e.headers["x-status-token"],(0,gateway_errors_1.ensureRequestId)(e);const o=u.any?u.upgradeContext(e,t,void 0):void 0;if(o&&u.has("onRequest")&&(await u.run("onRequest",o),o.responded()))return;if(e.method==="TRACE"||e.method==="TRACK"){w(t,"405 Method Not Allowed");return}const J=(0,edge_1.parseHost)(e.headers.host);if(!J){w(t,"400 Bad Request");return}const P=J.name,T=(0,edge_1.canonicalize)(e.url??"/");if(T===void 0){h(t,"bad-path");return}const N=T.policy;e.url=T.path+T.query;const r=(0,manifest_1.matchRoute)(s.table.routes,P,N+T.query);if(!r){h(t,"no-route",void 0,{host:P});return}o&&(o.route=r);const q=e.socket?.remoteAddress??"",R=_.clientIpOf(e,q),ye=_.proxyKind(e,q);_.dropProxySecret(e),(0,trust_1.stripProxyClaims)(e.headers,ye,_.proxyHeaders);const m=(0,client_ip_1.limiterKey)(R);if(s.opts.rateLimiter){const a=await s.opts.rateLimiter.check(m);if(!a.allowed){c.emit("warning",`gateway upgrade rate-limited for ${r.service}`,`gateway-upgrade:${r.service}:rate-limited`,{kind:"gateway-upgrade-rejected",reason:"rate-limited",project:r.service}),w(t,"429 Too Many Requests",`Retry-After: ${Math.ceil(a.retryAfterMs/1e3)}\r
|
|
6
|
+
`);return}}if(r.internal&&s.opts.internalPeers?.length&&!(0,client_ip_1.addressIn)(R,s.opts.internalPeers)){h(t,"no-route",void 0,{host:P});return}const Q=(0,edge_1.hdr)(e.headers["sec-websocket-key"])??"",me=e.headers["transfer-encoding"]!==void 0||e.headers["content-length"]!==void 0&&e.headers["content-length"]!=="0";if(e.method!=="GET"||String(e.headers.upgrade??"").toLowerCase()!=="websocket"||(0,edge_1.hdr)(e.headers["sec-websocket-version"])!=="13"||!WS_KEY.test(Q)||me){c.emit("warning",`gateway upgrade refused for ${r.service}: not a WebSocket handshake`,`gateway-upgrade:${r.service}:not-websocket`,{kind:"gateway-upgrade-rejected",reason:"not-websocket",project:r.service,upgrade:String(e.headers.upgrade??"").slice(0,40),method:e.method}),w(t,"400 Bad Request");return}if(o&&u.has("beforeAuth")&&(await u.run("beforeAuth",o),o.responded()))return;const I=r.internal?void 0:s.opts.identify?.(e),C=I instanceof Promise?await I:I;if(t.destroyed)return;let D;if(r.internal){const a=X.internal(e,r,void 0);if(!a.ok){h(t,"auth-failed",r.service);return}D=a.caller,o&&(o.caller=D)}else{if(!X.public(e,r,N,C,R,void 0).ok){h(t,"auth-failed",r.service);return}if(o&&(o.claims=C),o&&u.has("afterAuth")&&(await u.run("afterAuth",o),o.responded()))return}const ee=le.check(r,N,{ip:m,tenant:C?.tid,user:C?.sub}),re=ee?await ee:void 0;if(re){c.emit("warning",`gateway upgrade rate-limited for ${r.service} (route limit)`,`gateway-upgrade:${r.service}:route-limited`,{kind:"gateway-upgrade-rejected",reason:"route-limited",project:r.service}),w(t,"429 Too Many Requests",`Retry-After: ${Math.max(1,Math.ceil(re.retryAfterMs/1e3))}\r
|
|
7
|
+
`);return}if((0,trust_1.countHop)(e)===void 0){h(t,"loop",r.service);return}e.headers["x-forwarded-for"]=_.forwardedFor(e,q),e.headers["x-forwarded-proto"]=_.forwardedProto(e,q,s.opts.tls?"https":"http"),e.headers["x-forwarded-host"]=e.headers.host??P,e.headers["x-real-ip"]=R;const te=s.serviceKeyOf(r.service);if(te&&(e.headers["x-internal-token"]=te),r.prependPrefix){const a=e.url??"/",n=r.prependPrefix;a!==n&&!a.startsWith(n+"/")&&(e.url=n+a)}const $e=(0,edge_1.hdr)(e.headers[s.versionHeader]),M=await ge.resolveUpstream(r,void 0,$e);if(!M||!("url"in M)){h(t,"no-upstream",r.service);return}const y=new URL(M.url),ae=y.pathname.replace(/\/+$/,"");if(ae&&(e.url=ae+(e.url??"/")),o&&(o.version=M.version),o&&u.has("beforeForward")&&(await u.run("beforeForward",o),o.responded())||o&&u.has("onUpgrade")&&(await u.run("onUpgrade",o),o.responded())||t.destroyed)return;const oe=e.method??"GET",O=e.url??"/";if(!validToken(oe)||!validHeaderValue(O)||O.includes(" ")){h(t,"bad-request-line",r.service);return}const F=[`${oe} ${O} HTTP/1.1`,`Host: ${y.host}`,"Connection: Upgrade"];for(let a=0;a<e.rawHeaders.length;a+=2){const n=e.rawHeaders[a],f=e.rawHeaders[a+1]??"",k=n.toLowerCase();if(OWN_LINES.has(k))continue;const j=e.headers[k];if(!(j===void 0||j!==p[k])){if(!validToken(n)||!validHeaderValue(f)){h(t,"bad-header",r.service,{header:k});return}F.push(`${n}: ${f}`)}}for(const a of Object.keys(e.headers)){const n=e.headers[a];if(!(OWN_LINES.has(a)||n===void 0||n===p[a])){for(const f of Array.isArray(n)?n:[n])if(!(typeof f!="string"||f==="")){if(!validToken(a)||!validHeaderValue(f)){h(t,"bad-identity-value",r.service,{header:a});return}F.push(`${a}: ${f}`)}}}if((H.get(m)??0)>=fe){c.emit("warning",`gateway upgrade refused for ${r.service}: too many pending upgrades from one client`,`gateway-upgrade:${r.service}:pending-cap`,{kind:"gateway-upgrade-rejected",reason:"pending-cap",project:r.service}),w(t,"429 Too Many Requests",`Retry-After: 1\r
|
|
8
|
+
`);return}if((L.get(m)??0)>=he){c.emit("warning",`gateway upgrade refused for ${r.service}: one client holds its share of live tunnels`,`gateway-upgrade:${r.service}:client-tunnel-cap`,{kind:"gateway-upgrade-rejected",reason:"client-tunnel-cap",project:r.service}),w(t,"429 Too Many Requests",`Retry-After: 5\r
|
|
9
|
+
`);return}if((U.get(r.service)??0)>=Y){c.emit("warning",`gateway upgrade refused for ${r.service}: live tunnel ceiling reached`,`gateway-upgrade:${r.service}:tunnel-cap`,{kind:"gateway-upgrade-rejected",reason:"tunnel-cap",project:r.service}),w(t,"503 Service Unavailable",`Retry-After: 5\r
|
|
10
|
+
`);return}i?.length&&c.emit("warning",`gateway upgrade for ${r.service}: client sent ${i.length} byte(s) before the 101`,`gateway-upgrade:${r.service}:head-before-101`,{kind:"gateway-upgrade-anomaly",reason:"head-before-101",project:r.service,bytes:i.length});const B=y.protocol==="https:"||y.protocol==="wss:",se=Number(y.port)||(B?443:80),$=s.opts.undici,g=B?tls.connect({port:se,host:y.hostname,...net.isIP(y.hostname)?{}:{servername:y.hostname},rejectUnauthorized:$?.rejectUnauthorized??!1,...$?.cert?{cert:$.cert}:{},...$?.key?{key:$.key}:{},...$?.ca?{ca:$.ca}:{}}):net.connect(se,y.hostname);v.add(t),x(H,m,1);let ne=!0;const z=d(()=>{ne&&(ne=!1,x(H,m,-1))},"endPending");let E=!1,A=!1;const ie=d(()=>{z(),E&&(E=!1,x(U,r.service,-1),x(L,m,-1)),v.delete(t),g.destroy(),t.destroy()},"teardown"),b=d(a=>{if(A){ie();return}A=!0,clearTimeout(K),c.emit("warning",`gateway upgrade failed (${a}) for ${r.service}`,`gateway-upgrade:${r.service}:${a}`,{kind:"gateway-upgrade-rejected",reason:a,project:r.service}),ie()},"abort"),K=setTimeout(()=>b("handshake-timeout"),HANDSHAKE_TIMEOUT_MS);K.unref?.(),g.on("error",()=>b("upstream-error")),t.on("error",()=>b("client-error")),t.on("close",()=>{E||!A?b("client-closed"):(z(),v.delete(t))}),g.on(B?"secureConnect":"connect",()=>{g.write(F.join(`\r
|
|
9
11
|
`)+`\r
|
|
10
12
|
\r
|
|
11
|
-
`)});const
|
|
13
|
+
`)});const de=[];let ce=0;const ue=d(a=>{if(A)return;de.push(a),ce+=a.length;const n=Buffer.concat(de),f=n.indexOf(`\r
|
|
12
14
|
\r
|
|
13
|
-
`);if(
|
|
14
|
-
`))
|
|
15
|
+
`);if(f===-1){ce>MAX_HEAD_BYTES&&b("oversized-response-head");return}A=!0,clearTimeout(K),g.off("data",ue),z();const k=n.subarray(0,f).toString("latin1").split(`\r
|
|
16
|
+
`),j=Number(/^HTTP\/1\.[01] (\d{3})/.exec(k[0]??"")?.[1]);if(j!==101){c.emit("warning",`gateway upgrade refused upstream (${j||"malformed"}) for ${r.service}`,`gateway-upgrade:${r.service}:upstream-refused`,{kind:"gateway-upgrade-rejected",reason:"upstream-refused",project:r.service,status:j||0}),v.delete(t),t.end(n.subarray(0,f+4)),g.destroy();return}const S=new Map;for(const W of k.slice(1)){const G=W.indexOf(":");if(G>0){const pe=W.slice(0,G).trim().toLowerCase();S.has(pe)||S.set(pe,W.slice(G+1).trim())}}if((S.get("upgrade")??"").toLowerCase()!=="websocket"||S.get("sec-websocket-accept")!==acceptFor(Q)){c.emit("warning",`gateway upgrade for ${r.service}: the upstream's 101 does not answer the WebSocket handshake`,`gateway-upgrade:${r.service}:upstream-bad-101`,{kind:"gateway-upgrade-rejected",reason:"upstream-bad-101",project:r.service,upgrade:(S.get("upgrade")??"").slice(0,40)}),v.delete(t),w(t,"502 Bad Gateway"),g.destroy();return}c.recordEdge(r,0,101,D,M.version),E=!0,x(U,r.service,1),x(L,m,1),Z>0&&(t.setTimeout(Z),t.once("timeout",()=>b("idle"))),t.write(n),i?.length&&g.write(i),g.pipe(t),t.pipe(g)},"onHead");g.on("data",ue),g.on("close",()=>{(!A||E)&&b("upstream-closed")})},"run");return Object.assign(d((e,t,i)=>{t.on("error",()=>{}),we(e,t,i).catch(p=>{c.emit("error",`gateway upgrade error: ${p?.message??String(p)}`,"gateway-upgrade:(none):exception",{kind:"gateway-upgrade-rejected",reason:"exception",error:p?.message??String(p)});try{t.destroy()}catch{}})},"listener"),{closeAll(){for(const e of[...v])try{e.destroy()}catch{}v.clear()}})}V(createUpgrade,"createUpgrade"),d(createUpgrade,"createUpgrade");
|