@lensmcp/cluster 1.25.79 → 1.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build-scope-patterns.d.ts +1 -11
- package/build-scope-patterns.js +1 -1
- package/create-webpack-prod.d.ts +1 -27
- package/create-webpack-prod.js +1 -1
- package/executors/build/build.impl.js +1 -1
- package/executors/gateway/daemon.d.ts +43 -0
- package/executors/gateway/daemon.js +1 -0
- package/executors/gateway/gateway.lib.d.ts +1 -1
- package/executors/gateway/gateway.lib.js +1 -1
- package/executors/gateway/jwks-verify.d.ts +1 -79
- package/executors/gateway/jwks-verify.js +1 -1
- package/executors/gateway/main.rollout.d.ts +2 -1
- package/executors/gateway/main.rollout.js +1 -24
- package/executors/gateway/manifest.d.ts +1 -418
- package/executors/gateway/manifest.js +1 -1
- package/executors/gateway/prod-runtime/trust.d.ts +1 -80
- package/executors/gateway/prod-runtime/trust.js +1 -1
- package/executors/gateway/rate-limit.d.ts +1 -81
- package/executors/gateway/rate-limit.js +1 -18
- package/executors/gateway/runtime/auth.d.ts +1 -1
- package/executors/gateway/runtime/auth.js +1 -1
- package/executors/gateway/runtime/dev-auth.d.ts +3 -2
- package/executors/gateway/runtime/dev-auth.js +1 -1
- package/executors/gateway/runtime/discovery.js +1 -1
- package/executors/gateway/runtime/edge.d.ts +2 -2
- package/executors/gateway/runtime/edge.js +1 -1
- package/executors/gateway/runtime/handler.js +1 -1
- package/executors/gateway/runtime/internal-fetch.d.ts +1 -1
- package/executors/gateway/runtime/lens-children.js +1 -1
- package/executors/gateway/runtime/lens-modules.d.ts +13 -0
- package/executors/gateway/runtime/lens-modules.js +1 -0
- package/executors/gateway/runtime/lifecycle.js +1 -1
- package/executors/gateway/runtime/observability.js +1 -1
- package/executors/gateway/runtime/proxy.js +1 -1
- package/executors/gateway/runtime/route-registry.js +1 -1
- package/executors/gateway/runtime/serve-launch.d.ts +27 -0
- package/executors/gateway/runtime/serve-launch.js +3 -3
- package/executors/gateway/runtime/server.d.ts +1 -1
- package/executors/gateway/runtime/server.js +2 -2
- package/executors/gateway/runtime/services-decl.d.ts +24 -0
- package/executors/gateway/runtime/services-decl.js +1 -0
- package/executors/gateway/runtime/shared-build.d.ts +2 -2
- package/executors/gateway/runtime/shared-build.js +3 -3
- package/executors/gateway/runtime/types.d.ts +9 -3
- package/executors/gateway/runtime/upgrade.js +1 -1
- package/executors/gateway/runtime/workspace-auth.d.ts +1 -1
- package/executors/gateway/runtime/workspace-auth.js +1 -1
- package/executors/gateway/runtime/workspace-middleware.d.ts +2 -2
- package/executors/gateway/runtime/workspace-middleware.js +1 -1
- package/executors/serve/lens-run.d.ts +6 -0
- package/executors/serve/lens-run.js +1 -0
- package/executors/serve/schema.d.ts +2 -0
- package/executors/serve/schema.json +4 -0
- package/executors/serve/serve.impl.js +1 -1
- package/executors/trust/run.d.ts +19 -0
- package/executors/trust/run.js +1 -0
- package/executors/trust/trust.impl.js +5 -5
- package/gateway.d.ts +7 -19
- package/gateway.js +1 -1
- package/gc-notice.d.ts +3 -1
- package/gc-notice.js +1 -1
- package/main.devserver.js +7 -7
- package/package.json +6 -34
- package/pod-memory.d.ts +19 -2
- package/pod-memory.js +1 -1
- package/tsgo-check-plugin.d.ts +3 -2
- package/tsgo-check-plugin.js +3 -3
- package/typecheck-bus.d.ts +17 -0
- package/typecheck-bus.js +4 -3
- package/executors/gateway/body-stall.d.ts +0 -62
- package/executors/gateway/body-stall.js +0 -1
- package/executors/gateway/canonical-path.d.ts +0 -65
- package/executors/gateway/canonical-path.js +0 -1
- package/executors/gateway/client-ip.d.ts +0 -82
- package/executors/gateway/client-ip.js +0 -1
- package/executors/gateway/gateway-errors.d.ts +0 -43
- package/executors/gateway/gateway-errors.js +0 -1
- package/executors/gateway/health-check.d.ts +0 -52
- package/executors/gateway/health-check.js +0 -1
- package/executors/gateway/jwt-claims.d.ts +0 -51
- package/executors/gateway/jwt-claims.js +0 -1
- package/executors/gateway/main.prod-gateway.d.ts +0 -1
- package/executors/gateway/main.prod-gateway.js +0 -2
- package/executors/gateway/metrics.d.ts +0 -36
- package/executors/gateway/metrics.js +0 -1
- package/executors/gateway/otel-tracing.d.ts +0 -46
- package/executors/gateway/otel-tracing.js +0 -1
- package/executors/gateway/prod-config.d.ts +0 -130
- package/executors/gateway/prod-config.js +0 -1
- package/executors/gateway/prod-gateway.lib.d.ts +0 -19
- package/executors/gateway/prod-gateway.lib.js +0 -1
- package/executors/gateway/prod-runtime/access-log.d.ts +0 -8
- package/executors/gateway/prod-runtime/access-log.js +0 -1
- package/executors/gateway/prod-runtime/app.d.ts +0 -30
- package/executors/gateway/prod-runtime/app.js +0 -1
- package/executors/gateway/prod-runtime/auth.d.ts +0 -29
- package/executors/gateway/prod-runtime/auth.js +0 -1
- package/executors/gateway/prod-runtime/body-stall.d.ts +0 -5
- package/executors/gateway/prod-runtime/body-stall.js +0 -1
- package/executors/gateway/prod-runtime/cors.d.ts +0 -18
- package/executors/gateway/prod-runtime/cors.js +0 -1
- package/executors/gateway/prod-runtime/edge.d.ts +0 -44
- package/executors/gateway/prod-runtime/edge.js +0 -1
- package/executors/gateway/prod-runtime/handler.d.ts +0 -33
- package/executors/gateway/prod-runtime/handler.js +0 -1
- package/executors/gateway/prod-runtime/hooks.d.ts +0 -19
- package/executors/gateway/prod-runtime/hooks.js +0 -1
- package/executors/gateway/prod-runtime/observability.d.ts +0 -24
- package/executors/gateway/prod-runtime/observability.js +0 -1
- package/executors/gateway/prod-runtime/rollout.d.ts +0 -33
- package/executors/gateway/prod-runtime/rollout.js +0 -1
- package/executors/gateway/prod-runtime/route-limits.d.ts +0 -30
- package/executors/gateway/prod-runtime/route-limits.js +0 -1
- package/executors/gateway/prod-runtime/routing.d.ts +0 -3
- package/executors/gateway/prod-runtime/routing.js +0 -1
- package/executors/gateway/prod-runtime/server.d.ts +0 -17
- package/executors/gateway/prod-runtime/server.js +0 -1
- package/executors/gateway/prod-runtime/types.d.ts +0 -335
- package/executors/gateway/prod-runtime/types.js +0 -1
- package/executors/gateway/prod-runtime/upgrade.d.ts +0 -23
- package/executors/gateway/prod-runtime/upgrade.js +0 -16
- package/executors/gateway/prod-runtime/upstream-errors.d.ts +0 -33
- package/executors/gateway/prod-runtime/upstream-errors.js +0 -1
- package/executors/gateway/prod-runtime/upstream.d.ts +0 -14
- package/executors/gateway/prod-runtime/upstream.js +0 -1
- package/executors/gateway/providers-prod.d.ts +0 -54
- package/executors/gateway/providers-prod.js +0 -1
- package/executors/gateway/registry-source.d.ts +0 -68
- package/executors/gateway/registry-source.js +0 -2
- package/executors/gateway/rollout-ops.d.ts +0 -53
- package/executors/gateway/rollout-ops.js +0 -2
- package/executors/gateway/ssrf-guard.d.ts +0 -96
- package/executors/gateway/ssrf-guard.js +0 -1
- package/executors/gateway/workspace-auth.d.ts +0 -100
- package/executors/gateway/workspace-auth.js +0 -1
|
@@ -1,44 +0,0 @@
|
|
|
1
|
-
import type * as http from 'node:http';
|
|
2
|
-
import { type GatewayErrorReason } from '../gateway-errors';
|
|
3
|
-
import type { ReplyLike } from './types';
|
|
4
|
-
export declare const eid: () => string;
|
|
5
|
-
export declare const hdr: (v: string | string[] | undefined) => string | undefined;
|
|
6
|
-
/**
|
|
7
|
-
* The `Host` header as `{ name, port? }` — or undefined when it is anything but `name[:port]` (→ 400).
|
|
8
|
-
*
|
|
9
|
-
* The gateway routed on the part before the first `:` and forwarded the WHOLE header as `X-Forwarded-Host`, so
|
|
10
|
-
* `Host: app.x:@evil.example` reached the `app.x` service carrying a forwarded host that every URL parser reads as
|
|
11
|
-
* `evil.example` (`app.x:` is userinfo) — a password-reset link built from it points at the attacker
|
|
12
|
-
* (issues/closed/prod-gateway-4-08). A header that is exactly `name[:port]` is the only one whose forwarded form IS
|
|
13
|
-
* the host that was routed. An absent / empty header stays the empty name (HTTP/1.0: the catch-all, as before).
|
|
14
|
-
*/
|
|
15
|
-
export declare const parseHost: (raw: string | undefined) => {
|
|
16
|
-
name: string;
|
|
17
|
-
port?: string;
|
|
18
|
-
} | undefined;
|
|
19
|
-
/**
|
|
20
|
-
* Send a gateway-generated edge error as the JSON envelope `{ key, status, traceId, message? }` (NOT
|
|
21
|
-
* `text/plain`), stamping `x-request-id` so the trace id is on the response. The SAME `{ key, status }`
|
|
22
|
-
* localized contract a service returns, so a browser app renders `t(key)` and surfaces the trace id.
|
|
23
|
-
* `detail` is the dev-facing hint (the old plain-text reason), never shown to end users.
|
|
24
|
-
*/
|
|
25
|
-
export declare const sendError: (reply: ReplyLike, req: http.IncomingMessage, status: number, reason: GatewayErrorReason, detail?: string) => ReplyLike;
|
|
26
|
-
/** Cache directive for everything the gateway answers itself (errors, probes, discovery). */
|
|
27
|
-
export declare const NO_STORE = "no-store";
|
|
28
|
-
/**
|
|
29
|
-
* Constant-time compare of a presented operator token against the configured one. Shared by
|
|
30
|
-
* `/statusz`, `/metricsz` and the route-discovery view so all three fail closed identically:
|
|
31
|
-
* no token configured ⇒ never a match, whatever the caller sends.
|
|
32
|
-
*/
|
|
33
|
-
export declare const tokenMatches: (presented: string | undefined, expected: string | undefined) => boolean;
|
|
34
|
-
/**
|
|
35
|
-
* Append a token to a raw response `Vary` header without destroying what the upstream set.
|
|
36
|
-
* `Vary: *` already varies on everything; an existing token is not duplicated.
|
|
37
|
-
*/
|
|
38
|
-
export declare const addVary: (headers: Record<string, unknown>, token: string) => void;
|
|
39
|
-
export { ENCODED_STRUCTURE, canonicalize, canonicalPath, RAW_TARGET, rawTargetOf, rememberRawTarget, type CanonicalTarget, } from '../canonical-path';
|
|
40
|
-
/** Render an operator-supplied URL for a LOG: origin + path only. Vendor OTLP endpoints
|
|
41
|
-
* routinely carry the token in userinfo (`https://<token>@otlp.vendor.io/v1/traces`) or a
|
|
42
|
-
* query string, and boot logs are widely readable precisely because they are not expected
|
|
43
|
-
* to hold secrets. */
|
|
44
|
-
export declare const safeUrl: (raw: string | undefined) => string;
|
|
@@ -1 +0,0 @@
|
|
|
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;
|
|
@@ -1,33 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* The prod HTTP request pipeline: route → trust → auth → forward, with the
|
|
3
|
-
* security guards (HTTP/0.9 reject, path-canonicalization, rate-limit) BEFORE
|
|
4
|
-
* routing and the rollout/sticky version selection before the undici hop.
|
|
5
|
-
*
|
|
6
|
-
* Customer hook phases slot in at the analogous points, but EVERY hook call is
|
|
7
|
-
* guarded by `ctx` (built only when hooks are configured) — so with no hooks the
|
|
8
|
-
* pipeline is byte-for-byte the original (zero overhead; the pentest/perf path).
|
|
9
|
-
*/
|
|
10
|
-
import type { FastifyReply, FastifyRequest } from 'fastify';
|
|
11
|
-
import type { TraceSpan } from '../otel-tracing';
|
|
12
|
-
import type { RouteLimits } from './route-limits';
|
|
13
|
-
import type { ProdHookContext, ProdRuntime, ReqState } from './types';
|
|
14
|
-
import type { Observability } from './observability';
|
|
15
|
-
import type { CorsLayer } from './cors';
|
|
16
|
-
import type { EdgeAuth } from './auth';
|
|
17
|
-
import type { UpstreamLayer } from './upstream';
|
|
18
|
-
import type { RolloutLayer } from './rollout';
|
|
19
|
-
import type { HooksLayer } from './hooks';
|
|
20
|
-
export interface HandlerDeps {
|
|
21
|
-
rt: ProdRuntime;
|
|
22
|
-
obs: Observability;
|
|
23
|
-
cors: CorsLayer;
|
|
24
|
-
auth: EdgeAuth;
|
|
25
|
-
upstream: UpstreamLayer;
|
|
26
|
-
rollout: RolloutLayer;
|
|
27
|
-
hooks: HooksLayer;
|
|
28
|
-
routeLimits: RouteLimits;
|
|
29
|
-
reqState: WeakMap<FastifyRequest, ReqState>;
|
|
30
|
-
spanByReq: WeakMap<FastifyRequest, TraceSpan>;
|
|
31
|
-
ctxByReq: WeakMap<FastifyRequest, ProdHookContext>;
|
|
32
|
-
}
|
|
33
|
-
export declare function createHandler(deps: HandlerDeps): (request: FastifyRequest, reply: FastifyReply) => Promise<unknown>;
|
|
@@ -1 +0,0 @@
|
|
|
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,19 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Customer extensibility for the prod gateway: phase-named hooks (mirrors dev).
|
|
3
|
-
* Request-flow phases (`onRequest`/`beforeAuth`/`afterAuth`/`beforeForward`/
|
|
4
|
-
* `onUpgrade`) short-circuit the moment a handler responds; the terminal phases
|
|
5
|
-
* (`onResponse`/`onError`) observe a finished request and always run all handlers.
|
|
6
|
-
*/
|
|
7
|
-
import type * as http from 'node:http';
|
|
8
|
-
import type * as net from 'node:net';
|
|
9
|
-
import type { FastifyReply, FastifyRequest } from 'fastify';
|
|
10
|
-
import type { GwTrace, ProdGatewayHooks, ProdGatewayPhase, ProdHookContext } from './types';
|
|
11
|
-
export interface HooksLayer {
|
|
12
|
-
/** True if ANY phase has a registered handler — lets the hot path skip all hook machinery. */
|
|
13
|
-
readonly any: boolean;
|
|
14
|
-
run(phase: ProdGatewayPhase, ctx: ProdHookContext): Promise<void>;
|
|
15
|
-
has(phase: ProdGatewayPhase): boolean;
|
|
16
|
-
httpContext(req: http.IncomingMessage, request: FastifyRequest, reply: FastifyReply, trace: GwTrace | undefined): ProdHookContext;
|
|
17
|
-
upgradeContext(req: http.IncomingMessage, socket: net.Socket, trace: GwTrace | undefined): ProdHookContext;
|
|
18
|
-
}
|
|
19
|
-
export declare function createHooks(hooks: ProdGatewayHooks): HooksLayer;
|
|
@@ -1 +0,0 @@
|
|
|
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,24 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Observability for the prod gateway: the lens bus (`emit`, OPT-IN), the
|
|
3
|
-
* header-gated per-request flow trace (`beginTrace`/`step`/`finish`), the
|
|
4
|
-
* aggregated traffic edges (`recordEdge`), and the per-service health rollup
|
|
5
|
-
* (`buildStatusSnapshot`) fed from those edges + the periodic flusher. Merged
|
|
6
|
-
* because health + edges + trace all derive from the same observed traffic and
|
|
7
|
-
* all write to the same bus.
|
|
8
|
-
*/
|
|
9
|
-
import type * as http from 'node:http';
|
|
10
|
-
import type { Route } from '../manifest';
|
|
11
|
-
import type { GwTrace, ProdGatewayOptions, ServiceStatus } from './types';
|
|
12
|
-
export interface Observability {
|
|
13
|
-
emit(severity: string, title: string, fingerprint: string, raw?: Record<string, unknown>, ctx?: Record<string, unknown>): void;
|
|
14
|
-
beginTrace(req: http.IncomingMessage): GwTrace | undefined;
|
|
15
|
-
step(t: GwTrace | undefined, name: string, info?: Record<string, unknown>): void;
|
|
16
|
-
/** `status` `undefined`: the caller went away before any response head — the span reads «no response» (foodguard-118). */
|
|
17
|
-
finish(t: GwTrace | undefined, service: string, status: number | undefined, extra?: Record<string, unknown>): void;
|
|
18
|
-
/** `status` `undefined`: the caller went away before any response — timed, but not an upstream error. */
|
|
19
|
-
recordEdge(route: Route, ms: number, status: number | undefined, caller?: string, version?: string): void;
|
|
20
|
-
buildStatusSnapshot(): ServiceStatus[];
|
|
21
|
-
/** Start the periodic edge-flush + health-window roll; returns the interval (`.unref()`'d). */
|
|
22
|
-
startFlusher(): NodeJS.Timeout;
|
|
23
|
-
}
|
|
24
|
-
export declare function createObservability(opts: ProdGatewayOptions, getRoutes: () => Route[]): Observability;
|
|
@@ -1 +0,0 @@
|
|
|
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,33 +0,0 @@
|
|
|
1
|
-
import type * as http from 'node:http';
|
|
2
|
-
import { type Attrs } from '../manifest';
|
|
3
|
-
import { type ProxyKind } from '../client-ip';
|
|
4
|
-
import type { ProdGatewayOptions } from './types';
|
|
5
|
-
export interface RolloutLayer {
|
|
6
|
-
/** Resolve the client IP: the trusted front-proxy header if the peer is trusted, else the
|
|
7
|
-
* configured number of trusted `X-Forwarded-For` hops, else the socket address. */
|
|
8
|
-
clientIpOf(req: http.IncomingMessage, fallback: string): string;
|
|
9
|
-
/** The `X-Forwarded-For` value to send upstream: the trusted chain plus this hop, or just
|
|
10
|
-
* this hop when no proxy is trusted (the client's own chain is then fiction). */
|
|
11
|
-
forwardedFor(req: http.IncomingMessage, peer: string): string;
|
|
12
|
-
/** Assemble the flat attribute bag a rule evaluates against. `clientIp` is the address the
|
|
13
|
-
* caller ALREADY resolved with {@link clientIpOf} — re-resolving here would re-read
|
|
14
|
-
* `X-Forwarded-For`, which the gateway rewrites before forwarding, so a rule would see the
|
|
15
|
-
* gateway's own appended hop instead of the client. */
|
|
16
|
-
buildAttrs(req: http.IncomingMessage, clientIp: string, principal: Record<string, unknown> | undefined, key: string | undefined, policyPath?: string): Attrs;
|
|
17
|
-
/** The `X-Forwarded-Proto` to send upstream — a trusted front proxy's, else the gateway's own scheme (PG3-04). */
|
|
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[];
|
|
25
|
-
/** Resolve the sticky key: valid cookie → UID header → freshly minted (cookie clients). */
|
|
26
|
-
resolveStickyKey(req: http.IncomingMessage): {
|
|
27
|
-
key?: string;
|
|
28
|
-
mint: boolean;
|
|
29
|
-
};
|
|
30
|
-
/** Build the `Set-Cookie` header value for a freshly minted device id. */
|
|
31
|
-
mintCookieHeader(id: string): string;
|
|
32
|
-
}
|
|
33
|
-
export declare function createRollout(opts: ProdGatewayOptions): RolloutLayer;
|
|
@@ -1 +0,0 @@
|
|
|
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");
|
|
@@ -1,30 +0,0 @@
|
|
|
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;
|
|
@@ -1 +0,0 @@
|
|
|
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 +0,0 @@
|
|
|
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,17 +0,0 @@
|
|
|
1
|
-
import type { ProdGatewayHandle, ProdGatewayOptions } from './types';
|
|
2
|
-
/**
|
|
3
|
-
* Index the service-key registry: presented key → service, and service → the key the gateway stamps.
|
|
4
|
-
*
|
|
5
|
-
* Empty keys are DROPPED, loudly. `auth.internal` coerces a missing `x-api-key` to '', so an empty entry would make
|
|
6
|
-
* an anonymous caller authenticate as that service — and be attributed to it in the access log and traffic edges. A
|
|
7
|
-
* key that never got generated is a deploy bug; it must read as a broken service, not as an open one.
|
|
8
|
-
*
|
|
9
|
-
* A key value shared by two services is REFUSED, naming both (PG3-22): the map silently attributed the caller to
|
|
10
|
-
* whichever came last, so service A's calls arrived upstream as `x-api-key-id: B`. A list per service is rotation —
|
|
11
|
-
* the first entry is stamped on forwards, every entry is accepted inbound.
|
|
12
|
-
*/
|
|
13
|
-
export declare function indexServiceKeys(keys: Record<string, string | string[]>): {
|
|
14
|
-
keyToProject: Map<string, string>;
|
|
15
|
-
stampKeys: Map<string, string>;
|
|
16
|
-
};
|
|
17
|
-
export declare function startProdGateway(opts: ProdGatewayOptions): Promise<ProdGatewayHandle>;
|
|
@@ -1 +0,0 @@
|
|
|
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");
|