@lensmcp/cluster 1.25.75 → 1.25.77
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/README.md +5 -4
- package/executors/gateway/client-ip.d.ts +14 -0
- package/executors/gateway/client-ip.js +1 -1
- package/executors/gateway/gateway-errors.d.ts +8 -0
- package/executors/gateway/gateway-errors.js +1 -1
- package/executors/gateway/health-check.js +1 -1
- package/executors/gateway/jwks-verify.d.ts +2 -0
- package/executors/gateway/jwks-verify.js +1 -1
- package/executors/gateway/jwt-claims.d.ts +6 -2
- package/executors/gateway/jwt-claims.js +1 -1
- package/executors/gateway/main.prod-gateway.js +2 -2
- package/executors/gateway/manifest.d.ts +48 -1
- package/executors/gateway/manifest.js +1 -1
- package/executors/gateway/prod-config.d.ts +19 -0
- package/executors/gateway/prod-config.js +1 -1
- package/executors/gateway/prod-runtime/app.js +1 -1
- package/executors/gateway/prod-runtime/auth.js +1 -1
- package/executors/gateway/prod-runtime/handler.js +1 -1
- package/executors/gateway/prod-runtime/observability.js +1 -1
- package/executors/gateway/prod-runtime/rollout.d.ts +4 -2
- package/executors/gateway/prod-runtime/rollout.js +1 -1
- package/executors/gateway/prod-runtime/routing.js +1 -1
- package/executors/gateway/prod-runtime/server.d.ts +15 -0
- package/executors/gateway/prod-runtime/server.js +1 -1
- package/executors/gateway/prod-runtime/trust.d.ts +22 -0
- package/executors/gateway/prod-runtime/trust.js +1 -1
- package/executors/gateway/prod-runtime/types.d.ts +31 -2
- package/executors/gateway/prod-runtime/upgrade.d.ts +4 -1
- package/executors/gateway/prod-runtime/upgrade.js +9 -7
- package/executors/gateway/prod-runtime/upstream-errors.d.ts +24 -0
- package/executors/gateway/prod-runtime/upstream-errors.js +1 -0
- package/executors/gateway/providers-prod.js +1 -1
- package/executors/gateway/runtime/auth.js +1 -1
- package/executors/gateway/runtime/dev-auth.js +1 -1
- package/executors/gateway/runtime/edge.js +1 -1
- package/executors/gateway/runtime/observability.js +3 -3
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
`@lensmcp/cluster` is the Nx plugin behind [LensMCP](https://github.com/kiwiapps-ltd/lensmcp), an observability lens for coding agents. It turns a monorepo of NestJS services and frontend apps into a cluster that behaves like production *on your laptop*: each backend service runs N hot-swappable child processes ("pods") on unix sockets with real NestJS HMR (20–100ms edit loop, in-memory state preserved), and a single HTTPS gateway routes traffic to them by hostname — `app.tetros.ai.local`, `api.tetros.ai.local`, and so on — over a locally-trusted CA so HTTPS *just works*.
|
|
6
6
|
|
|
7
|
-
The point is parity. The same gateway routing core (`matchRoute` / `buildRouteTable`) runs in dev and in production, so what you exercise locally — per-domain routing, path-mounted microservices, scale-from-zero, edge JWT verification + ABAC, and weighted / attribute-based rollout — is the same shape that ships. In dev the gateway runs on `node:http` + `http-proxy` (it owns the unix-socket pods and their lifecycle); in production the same routing brain is composed over a **Fastify + [@fastify/reply-from](https://github.com/fastify/fastify-reply-from) (undici)** transport, shipped as a **Node
|
|
7
|
+
The point is parity. The same gateway routing core (`matchRoute` / `buildRouteTable`) runs in dev and in production, so what you exercise locally — per-domain routing, path-mounted microservices, scale-from-zero, edge JWT verification + ABAC, and weighted / attribute-based rollout — is the same shape that ships. In dev the gateway runs on `node:http` + `http-proxy` (it owns the unix-socket pods and their lifecycle); in production the same routing brain is composed over a **Fastify + [@fastify/reply-from](https://github.com/fastify/fastify-reply-from) (undici)** transport, shipped as a **Node 24 distroless (nonroot)** image for the high-RPS edge. Throughout, the cluster publishes to the LensMCP event bus (service up/down, cold starts, autoscale, idle kills, request-derived traffic edges) so the dashboard can draw your live topology.
|
|
8
8
|
|
|
9
9
|
## Install
|
|
10
10
|
|
|
@@ -118,10 +118,11 @@ A declaration must route *somewhere*: either a pod `service` or a TCP `upstream`
|
|
|
118
118
|
|
|
119
119
|
One front door, two transports sharing one routing brain:
|
|
120
120
|
|
|
121
|
-
- **Routing** — every `cluster` declaration becomes a route; requests match by hostname (exact beats `*.suffix` wildcard) then by most-specific path prefix. A *claimed* host's unmatched root is served by the gateway itself (`/health` aggregate, `/.well-known/...`, CORS + preflights); an *unclaimed* host can only reach the `default` route or 404.
|
|
121
|
+
- **Routing** — every `cluster` declaration becomes a route; requests match by hostname (case-insensitive; exact beats `*.suffix` wildcard in any case spelling) then by most-specific path prefix. A *claimed* host's unmatched root is served by the gateway itself (`/health` aggregate, `/.well-known/...`, CORS + preflights); an *unclaimed* host can only reach the `default` route or 404.
|
|
122
122
|
- **Dev transport** — `node:http` + `http-proxy`. It owns the unix-socket pods: **scale-from-zero** on first request, autoscale while requests overlap, idle-kill, supervised reforks, and ghost-socket sweeping.
|
|
123
|
-
- **Prod transport** — the same `matchRoute` composed over **Fastify + @fastify/reply-from (undici)** (connection-reusing, HTTP/1.1 pipelined; benchmarks materially lower CPU/req than http-proxy), shipped as a **Node
|
|
124
|
-
- **Edge auth + identity** — for `jwt` routes the gateway verifies the end-user token (dev: HS256 shared secret; prod: RS256 via JWKS) and stamps trusted identity headers (`x-user-id`, `x-tenant-id`, roles, perms) onto the forwarded request; `internal.<host>` routes require the CALLER's own `x-api-key`, stamp `x-api-key-id` with the caller's project (or an identity it declares in `callerIds` and named itself), and once the key is validated the `x-tenant-id` and `x-user-id` the caller named are forwarded to the callee — production's service-to-service path is direct, so the callee reads them there too; roles, permissions and every other owned header stay the gateway's. Per-path **ABAC** rules (a `permission` or full predicate over verified claims + IP/headers, scoped by HTTP method) are enforced at the edge → 403.
|
|
123
|
+
- **Prod transport** — the same `matchRoute` composed over **Fastify + @fastify/reply-from (undici)** (connection-reusing, HTTP/1.1 pipelined; benchmarks materially lower CPU/req than http-proxy), shipped as a **Node 24 distroless `nonroot`** image whose runtime dependencies install from a committed lockfile pinned to the versions this repository's suites run (`docker/package-lock.json`). No process management — prod pods are always-on (k8s keeps them up).
|
|
124
|
+
- **Edge auth + identity** — for `jwt` routes the gateway verifies the end-user token (dev: HS256 shared secret; prod: RS256 via JWKS) and stamps trusted identity headers (`x-user-id`, `x-tenant-id`, roles, perms) onto the forwarded request; `internal.<host>` routes require the CALLER's own `x-api-key`, stamp `x-api-key-id` with the caller's project (or an identity it declares in `callerIds` and named itself), and once the key is validated the `x-tenant-id` and `x-user-id` the caller named are forwarded to the callee — production's service-to-service path is direct, so the callee reads them there too; roles, permissions and every other owned header stay the gateway's. Per-path **ABAC** rules (a `permission` or full predicate over verified claims + IP/headers, scoped by HTTP method — a `GET` scope also judges `HEAD`) are enforced at the edge → 403. Each route is judged by its own manifest's policy.
|
|
125
|
+
- **Route kinds vs auth modes** — `internal` is a route **kind** (`internal: true` → `internal.<host>`, x-api-key), never an auth **mode**: on a host route the mode is `jwt` or `public`, and a manifest that writes `internal` (or any unknown string) there gets **401** on that route — never an open route (the production gateway also names it at load, event kind `gateway-config-error`). `docs/lensmcp/concepts/prod-gateway-config.mdx` lists the rest of the edge contract (trusted-proxy `X-Forwarded-Proto`, attribute headers from trusted peers only, the decoded `path` attribute, regex limits, WebSocket handshake ordering and caps).
|
|
125
126
|
- **Rollout** — per-request upstream selection supports **weighted** cohorts (smooth nginx-style split for canary / blue-green) and **attribute-based targeting** (route by user / tenant / IP / header / sticky device key, consistent-hashed so a ramp moves a key across the boundary at most once). The serving version rides on `x-lensmcp-version` and the trace.
|
|
126
127
|
|
|
127
128
|
## Worktree instances
|
|
@@ -28,10 +28,24 @@ export interface ClientIpResolver {
|
|
|
28
28
|
forwardedFor(req: http.IncomingMessage, peer: string): string;
|
|
29
29
|
/** Is this peer address a trusted front proxy? */
|
|
30
30
|
peerTrusted(peer?: string): boolean;
|
|
31
|
+
/**
|
|
32
|
+
* Is a forwarding header from this peer evidence (PG3-05)? True behind a counted trusted hop chain, or when the
|
|
33
|
+
* peer itself is trusted (`clientIpTrustedProxies`, default loopback). Used for request headers a rule may read.
|
|
34
|
+
*/
|
|
35
|
+
peerAsserts(peer?: string): boolean;
|
|
36
|
+
/**
|
|
37
|
+
* The `X-Forwarded-Proto` to send upstream (PG3-04). A trusted front proxy terminated the user's TLS, so ITS
|
|
38
|
+
* statement of the scheme is kept (`X-Forwarded-Proto`, else Cloudflare's `CF-Visitor` when the client address
|
|
39
|
+
* comes from `cf-connecting-ip`); anyone else gets the gateway's own listener scheme. Trust is the forwarding
|
|
40
|
+
* chain's: the same condition {@link forwardedFor} appends to a chain under.
|
|
41
|
+
*/
|
|
42
|
+
forwardedProto(req: http.IncomingMessage, peer: string, ownScheme: 'http' | 'https'): 'http' | 'https';
|
|
31
43
|
readonly trustProxyHops: number;
|
|
32
44
|
}
|
|
33
45
|
/** An IPv4-mapped IPv6 peer (`::ffff:127.0.0.1`, what a dual-stack listener reports) → its IPv4 form. */
|
|
34
46
|
export declare const normalizePeer: (addr: string) => string;
|
|
47
|
+
/** Is `addr` in `list` — IPv4 CIDRs (`10.0.0.0/8`) or exact addresses (`::1`, `10.1.2.3`)? Mapped IPv6 folds first. */
|
|
48
|
+
export declare const addressIn: (addr: string, list: readonly string[]) => boolean;
|
|
35
49
|
/** `1.2.3.4:51234` (an X-Forwarded-For port suffix) → `1.2.3.4`. IPv6 keeps its colons unless bracketed. */
|
|
36
50
|
export declare const stripPort: (v: string) => string;
|
|
37
51
|
export declare function createClientIpResolver(opts?: ClientIpOptions): ClientIpResolver;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var h=Object.defineProperty;var f=(r,e)=>h(r,"name",{value:e,configurable:!0});var P=Object.defineProperty,o=f((r,e)=>P(r,"name",{value:e,configurable:!0}),"o");Object.defineProperty(exports,"__esModule",{value:!0}),exports.stripPort=exports.addressIn=exports.normalizePeer=void 0,exports.createClientIpResolver=createClientIpResolver,exports.clientIpOptionsFromEnv=clientIpOptionsFromEnv;const manifest_1=require("./manifest"),first=o(r=>{const e=Array.isArray(r)?r[0]:r;return typeof e=="string"&&e.length>0?e:void 0},"first"),normalizePeer=o(r=>r.startsWith("::ffff:")&&r.indexOf(":",7)===-1?r.slice(7):r,"normalizePeer");exports.normalizePeer=normalizePeer;const addressIn=o((r,e)=>{const i=(0,exports.normalizePeer)(r);return e.some(p=>p.includes("/")?(0,manifest_1.matchCidr)(i,p):(0,exports.normalizePeer)(p)===i)},"addressIn");exports.addressIn=addressIn;const stripPort=o(r=>{if(r.startsWith("[")){const i=r.indexOf("]");return i===-1?r:r.slice(1,i)}const e=r.indexOf(":");return e!==-1&&r.indexOf(":",e+1)===-1?r.slice(0,e):r},"stripPort");exports.stripPort=stripPort;function createClientIpResolver(r={}){const e=r.clientIpHeader?.toLowerCase(),i=r.clientIpTrustedProxies??[],p=Math.max(0,Math.floor(r.trustProxyHops??0)),c=o(t=>{if(!t)return!1;const a=t.startsWith("::ffff:")?t.slice(7):t;return i.length===0?a==="127.0.0.1"||t==="::1":i.some(s=>(0,manifest_1.matchCidr)(a,s))},"peerTrusted"),l=o(t=>String(t.headers["x-forwarded-for"]??"").split(",").map(a=>a.trim()).filter(Boolean),"forwardedChain"),x=o((t,a)=>{if(e&&c(t.socket?.remoteAddress??void 0)){const s=first(t.headers[e]);if(s){const n=(0,exports.stripPort)(s.split(",")[0].trim());if(n)return n}}if(p>0){const s=l(t),n=s.length-p;if(n>=0&&s[n])return(0,exports.stripPort)(s[n])}return(0,exports.normalizePeer)(a)},"clientIpOf"),u=o(t=>p>0||!!e&&c(t),"chainTrusted");return{clientIpOf:x,forwardedFor:o((t,a)=>{const s=(0,exports.normalizePeer)(a);if(u(a)){const n=l(t);return n.length?`${n.join(", ")}, ${s}`:s}return s},"forwardedFor"),peerTrusted:c,peerAsserts:o(t=>p>0||c(t),"peerAsserts"),forwardedProto:o((t,a,s)=>{if(!u(a))return s;const n=first(t.headers["x-forwarded-proto"])?.split(",")[0].trim().toLowerCase();if(n==="https"||n==="http")return n;if(e==="cf-connecting-ip"){const m=first(t.headers["cf-visitor"]);if(m)try{const d=JSON.parse(m).scheme;if(d==="https"||d==="http")return d}catch{}}return s},"forwardedProto"),trustProxyHops:p}}f(createClientIpResolver,"createClientIpResolver"),o(createClientIpResolver,"createClientIpResolver");function clientIpOptionsFromEnv(r=process.env){const e=Number(r.LENSMCP_TRUST_PROXY),i=String(r.LENSMCP_CLIENT_IP_TRUSTED_PROXIES??"").split(",").map(p=>p.trim()).filter(Boolean);return{...Number.isFinite(e)&&e>0?{trustProxyHops:Math.floor(e)}:{},...r.LENSMCP_CLIENT_IP_HEADER?{clientIpHeader:r.LENSMCP_CLIENT_IP_HEADER}:{},...i.length?{clientIpTrustedProxies:i}:{}}}f(clientIpOptionsFromEnv,"clientIpOptionsFromEnv"),o(clientIpOptionsFromEnv,"clientIpOptionsFromEnv");
|
|
@@ -27,6 +27,14 @@ export declare const GATEWAY_ERROR_KEY: Record<GatewayErrorReason, string>;
|
|
|
27
27
|
* `traceId`, and the gateway returns it on the response — one id, end-to-end, for ANY request.
|
|
28
28
|
*/
|
|
29
29
|
export declare function ensureRequestId(req: http.IncomingMessage): string;
|
|
30
|
+
/**
|
|
31
|
+
* The grammar a CLIENT's `x-request-id` must match to be adopted as the edge trace id: a short token. Anything else
|
|
32
|
+
* — 4 KB of markup, non-ASCII bytes, a CR the parser let through as obs-text — is replaced by a minted id (PG3-26):
|
|
33
|
+
* the id is forwarded to every upstream, echoed to the client and indexed by every log and trace store downstream,
|
|
34
|
+
* so adopting it verbatim was log/trace injection and a free 16 KB header per request.
|
|
35
|
+
*/
|
|
36
|
+
export declare const REQUEST_ID_GRAMMAR: RegExp;
|
|
37
|
+
export declare const validRequestId: (v: string) => boolean;
|
|
30
38
|
/**
|
|
31
39
|
* Build the JSON edge-error body `{ key, status, traceId, message? }`. `detail` becomes the dev-facing
|
|
32
40
|
* `message` (e.g. the old plain-text reason), never surfaced to end users.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var i=Object.defineProperty;var s=(e,t)=>i(e,"name",{value:t,configurable:!0});var o=Object.defineProperty,r=s((e,t)=>o(e,"name",{value:t,configurable:!0}),"r");Object.defineProperty(exports,"__esModule",{value:!0}),exports.GATEWAY_ERROR_CONTENT_TYPE=exports.validRequestId=exports.REQUEST_ID_GRAMMAR=exports.GATEWAY_ERROR_KEY=void 0,exports.ensureRequestId=ensureRequestId,exports.gatewayErrorBody=gatewayErrorBody,exports.GATEWAY_ERROR_KEY={bad_request:"gateway.badRequest",unauthorized:"gateway.unauthorized",forbidden:"gateway.forbidden",not_found:"gateway.notFound",rate_limited:"gateway.rateLimited",starting:"gateway.starting",unavailable:"gateway.unavailable",internal:"gateway.internal"};const headerValue=r(e=>typeof e=="string"&&e!==""?e:Array.isArray(e)?e[0]:void 0,"headerValue"),mintId=r(()=>Date.now().toString(36)+Math.random().toString(36).slice(2,12),"mintId");function ensureRequestId(e){const t=headerValue(e.headers["x-request-id"]);if(t&&(0,exports.validRequestId)(t))return t;const a=mintId();return e.headers["x-request-id"]=a,a}s(ensureRequestId,"ensureRequestId"),r(ensureRequestId,"ensureRequestId"),exports.REQUEST_ID_GRAMMAR=/^[A-Za-z0-9._-]{1,128}$/;const validRequestId=r(e=>exports.REQUEST_ID_GRAMMAR.test(e),"validRequestId");exports.validRequestId=validRequestId;function gatewayErrorBody(e,t,a,n,d){return JSON.stringify({...d??{},key:exports.GATEWAY_ERROR_KEY[t],status:e,traceId:a,...n?{message:n}:{}})}s(gatewayErrorBody,"gatewayErrorBody"),r(gatewayErrorBody,"gatewayErrorBody"),exports.GATEWAY_ERROR_CONTENT_TYPE="application/json; charset=utf-8";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var g=Object.defineProperty;var c=(a,
|
|
1
|
+
"use strict";var g=Object.defineProperty;var c=(a,r)=>g(a,"name",{value:r,configurable:!0});var C=Object.defineProperty,l=c((a,r)=>C(a,"name",{value:r,configurable:!0}),"l");Object.defineProperty(exports,"__esModule",{value:!0}),exports.createHealthChecker=createHealthChecker;function createHealthChecker(a={}){const r=a.path??"/healthz",y=a.intervalMs??5e3,f=a.timeoutMs??2e3,p=Math.max(1,a.unhealthyThreshold??2),d=Math.max(1,a.healthyThreshold??1),u=a.fetchImpl??globalThis.fetch,s=new Map;let n;const k=l(t=>t.replace(/\/+$/,"")+(r.startsWith("/")?r:"/"+r),"probeUrl"),m=l(async t=>{const e=s.get(t);if(!e)return;let h=!1;const i=new AbortController,b=setTimeout(()=>i.abort(),f);try{h=(await u(k(t),{method:"GET",signal:i.signal,redirect:"manual",headers:{"accept-encoding":"identity"}})).status<500}catch{}finally{clearTimeout(b)}e.lastCheckedAt=Date.now(),h?(e.oks+=1,e.fails=0,!e.healthy&&e.oks>=d&&(e.healthy=!0,a.onChange?.(t,!0))):(e.fails+=1,e.oks=0,e.healthy&&e.fails>=p&&(e.healthy=!1,a.onChange?.(t,!1)))},"probe"),o=l(()=>Promise.allSettled([...s.keys()].map(m)).then(()=>{}),"probeOnce");return{track(t){const e=new Set(t);for(const h of t)s.has(h)||s.set(h,{healthy:!0,fails:0,oks:0,lastCheckedAt:null});for(const h of[...s.keys()])e.has(h)||s.delete(h)},isHealthy:l(t=>s.get(t)?.healthy??!0,"isHealthy"),snapshot:l(()=>[...s.entries()].map(([t,e])=>({url:t,healthy:e.healthy,fails:e.fails,lastCheckedAt:e.lastCheckedAt})),"snapshot"),probeOnce:o,start(){n||(n=setInterval(()=>{o()},y),n.unref?.(),o())},stop(){n&&clearInterval(n),n=void 0}}}c(createHealthChecker,"createHealthChecker"),l(createHealthChecker,"createHealthChecker");
|
|
@@ -18,6 +18,8 @@ export interface JwksVerifierOptions {
|
|
|
18
18
|
fetchTimeoutMs?: number;
|
|
19
19
|
/** Clock skew tolerance for exp/nbf (seconds). Default 60. */
|
|
20
20
|
clockToleranceSec?: number;
|
|
21
|
+
/** Refuse tokens with no numeric `exp` (default true — see `checkStandardClaims`). */
|
|
22
|
+
requireExp?: boolean;
|
|
21
23
|
/** Injectable fetch (tests). Defaults to global fetch. */
|
|
22
24
|
fetchImpl?: typeof fetch;
|
|
23
25
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var D=Object.defineProperty;var w=(a,o)=>D(a,"name",{value:o,configurable:!0});var W=Object.defineProperty,i=w((a,o)=>W(a,"name",{value:o,configurable:!0}),"i");Object.defineProperty(exports,"__esModule",{value:!0}),exports.bearerIdentify=bearerIdentify,exports.createJwksVerifier=createJwksVerifier;const node_crypto_1=require("node:crypto"),jwt_claims_js_1=require("./jwt-claims.js");function bearerIdentify(a){return o=>{const d=String(o.headers.authorization??"");return d.startsWith("Bearer ")?a.verifyOrAwait(d.slice(7)):void 0}}w(bearerIdentify,"bearerIdentify"),i(bearerIdentify,"bearerIdentify");const ALG_TO_HASH={RS256:"sha256",RS384:"sha384",RS512:"sha512"},b64urlJsonSafe=i(a=>JSON.parse(Buffer.from(a,"base64url").toString("utf8")),"b64urlJsonSafe");function createJwksVerifier(a){const o=(a.algorithms??["RS256"]).filter(r=>r in ALG_TO_HASH),d=a.cacheMaxAgeMs??6e5,A=a.missRefreshMs??3e4,
|
|
1
|
+
"use strict";var D=Object.defineProperty;var w=(a,o)=>D(a,"name",{value:o,configurable:!0});var W=Object.defineProperty,i=w((a,o)=>W(a,"name",{value:o,configurable:!0}),"i");Object.defineProperty(exports,"__esModule",{value:!0}),exports.bearerIdentify=bearerIdentify,exports.createJwksVerifier=createJwksVerifier;const node_crypto_1=require("node:crypto"),jwt_claims_js_1=require("./jwt-claims.js");function bearerIdentify(a){return o=>{const d=String(o.headers.authorization??"");return d.startsWith("Bearer ")?a.verifyOrAwait(d.slice(7)):void 0}}w(bearerIdentify,"bearerIdentify"),i(bearerIdentify,"bearerIdentify");const ALG_TO_HASH={RS256:"sha256",RS384:"sha384",RS512:"sha512"},b64urlJsonSafe=i(a=>JSON.parse(Buffer.from(a,"base64url").toString("utf8")),"b64urlJsonSafe");function createJwksVerifier(a){const o=(a.algorithms??["RS256"]).filter(r=>r in ALG_TO_HASH),d=a.cacheMaxAgeMs??6e5,A=a.missRefreshMs??3e4,x=a.missWaitMs??2e3,S=a.fetchTimeoutMs??1e4,J=a.clockToleranceSec??60,O=a.fetchImpl??globalThis.fetch,b=a.audience===void 0?void 0:Array.isArray(a.audience)?a.audience:[a.audience];let c=new Map,u,f,M=0,m=!1;const h=new Map,P=i(async r=>{const e=await O(a.jwksUrl,{headers:{accept:"application/json","accept-encoding":"identity"},signal:r});if(!e.ok)throw new Error(`JWKS ${a.jwksUrl} \u2192 HTTP ${e.status}`);const t=await e.json(),n=new Map;for(const s of t.keys??[])if(!(s.kty!=="RSA"||!s.n||!s.e)&&!(s.use&&s.use!=="sig"))try{const k=(0,node_crypto_1.createPublicKey)({key:s,format:"jwk"});n.set(s.kid??"__single__",k)}catch{}n.size>0&&(c=n)},"load"),y=i(()=>{if(!u){const r=new AbortController;u=new Promise((e,t)=>{const n=setTimeout(()=>{r.abort(),t(new Error(`JWKS ${a.jwksUrl} \u2192 no answer in ${S} ms`))},S);n.unref?.(),P(r.signal).then(()=>{clearTimeout(n),e()},s=>{clearTimeout(n),t(s)})}).finally(()=>{u=void 0})}return u},"refresh"),p=i(()=>{if(f)return f;if(!(!u&&Date.now()<M))return f=y().catch(()=>{}).finally(()=>{f=void 0,M=Date.now()+A}),f},"refreshOnMiss"),T=setInterval(()=>{y().catch(()=>{})},d);T.unref?.();const v=i(r=>{const e=r.split(".");if(e.length!==3)return;let t;try{t=b64urlJsonSafe(e[0])}catch{return}if(!(!t.alg||!o.includes(t.alg)))return{parts:e,header:t}},"parse"),l=i(r=>r.kid!==void 0?c.get(r.kid):c.get("__single__")??(c.size===1?[...c.values()][0]:void 0),"keyFor"),g=i(({parts:r,header:e},t)=>{let n;try{n=(0,node_crypto_1.verify)(ALG_TO_HASH[e.alg],Buffer.from(`${r[0]}.${r[1]}`),t,Buffer.from(r[2],"base64url"))}catch{return}if(!n)return;let s;try{s=b64urlJsonSafe(r[1])}catch{return}if((0,jwt_claims_js_1.checkStandardClaims)(s,{...a.issuer?{issuer:a.issuer}:{},...b?{audience:b}:{},clockToleranceS:J,...a.requireExp===!1?{requireExp:!1}:{}}))return s},"verifyWith"),I=i(r=>{const e=v(r);if(!e)return;const t=l(e.header);if(!t){p();return}return g(e,t)},"verify"),j=i(async r=>{let e;await Promise.race([r,new Promise(t=>{e=setTimeout(t,x),e.unref?.()})]),clearTimeout(e)},"waitBounded"),R=i(async r=>{const e=v(r);if(!e)return!1;if(l(e.header))return!0;const t=p();return t?(await j(t),l(e.header)!==void 0):!1},"awaitKey"),$=i(r=>{const e=v(r);if(!e)return;const t=l(e.header);if(t)return g(e,t);const n=p();if(n)return j(n).then(()=>{const s=l(e.header);return s?g(e,s):void 0})},"verifyOrAwait"),B=i(r=>new Promise(e=>{const t=setTimeout(()=>{h.delete(t),e()},r);t.unref?.(),h.set(t,e)}),"sleep");return{verify:I,refresh:y,awaitKey:R,verifyOrAwait:$,warm:i(async(r={})=>{const e=Math.max(1,r.attempts??8),t=r.baseDelayMs??1e3,n=r.maxDelayMs??3e4;for(let s=1;!m;s++)try{return await y(),!0}catch(k){if(m)return!1;const _=s<e?Math.min(n,t*2**(s-1)):void 0;try{r.onError?.(k,s,_)}catch{}if(_===void 0)return!1;await B(_)}return!1},"warm"),stop:i(()=>{m=!0,clearInterval(T);for(const[r,e]of h)clearTimeout(r),e();h.clear()},"stop")}}w(createJwksVerifier,"createJwksVerifier"),i(createJwksVerifier,"createJwksVerifier");
|
|
@@ -20,6 +20,9 @@ export interface StandardClaimOptions {
|
|
|
20
20
|
audience?: readonly string[];
|
|
21
21
|
/** Clock skew allowance in seconds. Defaults to {@link DEFAULT_CLOCK_TOLERANCE_S}. */
|
|
22
22
|
clockToleranceS?: number;
|
|
23
|
+
/** Refuse a token with no numeric `exp`. Default TRUE: a token that never expires is valid forever once leaked
|
|
24
|
+
* (PG3-06). Pass `false` only for an issuer known to mint expiry-less tokens on purpose. */
|
|
25
|
+
requireExp?: boolean;
|
|
23
26
|
}
|
|
24
27
|
/**
|
|
25
28
|
* Are a verified token's registered claims acceptable?
|
|
@@ -28,7 +31,8 @@ export interface StandardClaimOptions {
|
|
|
28
31
|
* about whether an authentic token is one this gateway should accept.
|
|
29
32
|
*
|
|
30
33
|
* A configured restriction fails closed: with an `issuer` configured, a token carrying no `iss` is
|
|
31
|
-
* rejected rather than treated as unrestricted.
|
|
32
|
-
*
|
|
34
|
+
* rejected rather than treated as unrestricted. `iss`/`aud` the operator did not configure are not enforced here —
|
|
35
|
+
* the production entry refuses to BOOT a verifier without an audience instead (`jwtBootProblems`, PG3-06). A numeric
|
|
36
|
+
* `exp` is required unless `requireExp: false`.
|
|
33
37
|
*/
|
|
34
38
|
export declare function checkStandardClaims(payload: Record<string, unknown>, opts: StandardClaimOptions): boolean;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var c=Object.defineProperty;var t=(r,e)=>c(r,"name",{value:e,configurable:!0});var f=Object.defineProperty,u=t((r,e)=>f(r,"name",{value:e,configurable:!0}),"u");Object.defineProperty(exports,"__esModule",{value:!0}),exports.DEFAULT_CLOCK_TOLERANCE_S=void 0,exports.checkStandardClaims=checkStandardClaims,exports.DEFAULT_CLOCK_TOLERANCE_S=60;function checkStandardClaims(r,e){const s=e.clockToleranceS??exports.DEFAULT_CLOCK_TOLERANCE_S,i=Date.now()/1e3;if(typeof r.exp!="number"){if(e.requireExp!==!1)return!1}else if(i>r.exp+s)return!1;if(typeof r.nbf=="number"&&i<r.nbf-s||e.issuer&&r.iss!==e.issuer)return!1;if(e.audience&&e.audience.length>0){const n=r.aud;if(!(Array.isArray(n)?n:[n]).some(a=>typeof a=="string"&&e.audience.includes(a)))return!1}return!0}t(checkStandardClaims,"checkStandardClaims"),u(checkStandardClaims,"checkStandardClaims");
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`;
|
|
1
|
+
"use strict";var de=Object.defineProperty;var M=(e,r)=>de(e,"name",{value:r,configurable:!0});var le=Object.defineProperty,a=M((e,r)=>le(e,"name",{value:r,configurable:!0}),"a");Object.defineProperty(exports,"__esModule",{value:!0});const tslib_1=require("tslib"),node_fs_1=require("node:fs"),node_crypto_1=require("node:crypto"),node_path_1=require("node:path"),node_os_1=require("node:os"),node_cluster_1=tslib_1.__importDefault(require("node:cluster")),prod_gateway_lib_1=require("./prod-gateway.lib"),jwt_claims_1=require("./jwt-claims"),jwks_verify_1=require("./jwks-verify"),otel_tracing_1=require("./otel-tracing"),health_check_1=require("./health-check"),rate_limit_1=require("./rate-limit"),metrics_1=require("./metrics"),edge_1=require("./prod-runtime/edge"),registry_source_1=require("./registry-source"),providers_prod_1=require("./providers-prod"),prod_config_1=require("./prod-config");function readJson(e,r){if(!e)return r;try{return JSON.parse((0,node_fs_1.readFileSync)(e,"utf8"))}catch(n){return console.error(`[gateway] could not read ${e}:`,n.message),r}}M(readJson,"readJson"),a(readJson,"readJson");function watchJsonFile(e,r,n=1e3){let u=-1;const _=setInterval(a(()=>{if(!(0,node_fs_1.existsSync)(e))return;let w;try{w=(0,node_fs_1.statSync)(e).mtimeMs}catch{return}if(w===u)return;let p;try{p=JSON.parse((0,node_fs_1.readFileSync)(e,"utf8"))}catch(g){console.error("[gateway] endpoints reload:",g.message);return}u=w,r(p)},"tick"),n);return _.unref?.(),()=>clearInterval(_)}M(watchJsonFile,"watchJsonFile"),a(watchJsonFile,"watchJsonFile");async function main(){const e=process.env,r=(0,prod_config_1.parseGatewayEnv)(e),n=r.ports;process.on("uncaughtException",t=>console.error("[gateway] uncaughtException:",t)),process.on("unhandledRejection",t=>console.error("[gateway] unhandledRejection:",t));const u=[];let _=!1;const w=a(async t=>{if(!_){_=!0,console.log(`[gateway] ${t} \u2014 draining\u2026`);for(const s of u)try{await s()}catch{}process.exit(0)}},"shutdown");for(const t of["SIGTERM","SIGINT"])process.on(t,()=>{w(t)});const p=e.LENSMCP_GW_REDIS_URL;let g,y,O,j;const A={};let f;if(p){const t=require("ioredis"),s=new t(p);f=s;const o=(0,registry_source_1.createRegistryProviders)((0,registry_source_1.redisRegistrySource)(s,e.LENSMCP_GW_REDIS_PREFIX?{prefix:e.LENSMCP_GW_REDIS_PREFIX}:{}),{onError:a(i=>console.error("[gateway] registry:",i instanceof Error?i.message:i),"onError")});await o.start(),g=o.manifests,y=o.pods,j=o,console.log(`[gateway] registry: Redis-backed, live (${g.list().length} service(s))`)}else{const t=e.LENSMCP_GW_MANIFESTS;t?g=(0,providers_prod_1.fileManifestProvider)(t,{onError:a(o=>console.error("[gateway] manifest:",o instanceof Error?o.message:o),"onError")}):(console.warn("[gateway] no LENSMCP_GW_MANIFESTS / LENSMCP_GW_REDIS_URL \u2014 starting with an EMPTY route table (all requests 404 until manifests arrive)."),g=(0,providers_prod_1.staticManifestProvider)([]));const s=e.LENSMCP_GW_ENDPOINTS;if(s){const o=a(E=>console.error("[gateway] endpoints:",E instanceof Error?E.message:E),"onEpError"),i=readJson(s,{}),c=Object.keys(i).length,l=(0,providers_prod_1.isRolloutShape)(i);y=l?(0,providers_prod_1.rolloutPodProvider)(i,{onError:o}):(0,providers_prod_1.endpointsPodProvider)(i,{onError:o}),console.log(c?`[gateway] endpoints: ${l?"ROLLOUT (weighted cohorts)":"flat"} \u2014 ${c} service(s)`:`[gateway] endpoints: ${(0,node_fs_1.existsSync)(s)?"present but empty/unreadable":"file not there yet"} \u2014 watching ${s}`),O=watchJsonFile(s,E=>{try{y?.update?.(E),A.current?.refreshUpstreams(),console.log("[gateway] endpoints reloaded")}catch(ue){console.error("[gateway] endpoints reload failed:",ue.message)}})}}const I=e.LENSMCP_GW_KEYS,re=readJson(I,{}),D=e.LENSMCP_GW_TLS_KEY&&e.LENSMCP_GW_TLS_CERT?{key:(0,node_fs_1.readFileSync)(e.LENSMCP_GW_TLS_KEY),cert:(0,node_fs_1.readFileSync)(e.LENSMCP_GW_TLS_CERT)}:void 0,k=(0,prod_config_1.jwtBootProblems)(r.jwt);for(const t of k.warnings)console.warn(`[gateway] WARNING: ${t}`);if(k.errors.length)throw new Error(k.errors.join("; "));const te=r.jwt.presenceOnly,F=r.jwt.jwksUrl,P=r.jwt.secret,S=F?(0,jwks_verify_1.createJwksVerifier)({jwksUrl:F,...r.jwt.issuer?{issuer:r.jwt.issuer}:{},...r.jwt.audience?{audience:r.jwt.audience}:{}}):void 0,se=a(t=>{if(!P)return;const s=t.split(".");if(s.length===3)try{if(JSON.parse(Buffer.from(s[0],"base64url").toString()).alg!=="HS256")return;const o=(0,node_crypto_1.createHmac)("sha256",P).update(s[0]+"."+s[1]).digest("base64url"),i=Buffer.from(s[2]),c=Buffer.from(o);if(i.length!==c.length||!(0,node_crypto_1.timingSafeEqual)(i,c))return;const l=JSON.parse(Buffer.from(s[1],"base64url").toString());return(0,jwt_claims_1.checkStandardClaims)(l,{...r.jwt.issuer?{issuer:r.jwt.issuer}:{},...r.jwt.audience?.length?{audience:r.jwt.audience}:{}})?l:void 0}catch{return}},"hs256"),q=a(t=>{const s=String(t.headers.authorization??"");if(!s.startsWith("Bearer "))return;const o=s.slice(7);return S?S.verify(o):se(o)},"bearerClaims"),U=S?(0,jwks_verify_1.bearerIdentify)(S):P?q:void 0,oe=a((t,s)=>{if(t==="jwt"){if(S||P){if(!q(s))throw new Error("invalid or missing token");return}if(!te)throw new Error("jwt route but no verifier configured (set LENSMCP_GW_JWKS_URL or LENSMCP_GW_JWT_SECRET)");if(!String(s.headers.authorization??"").startsWith("Bearer "))throw new Error("missing bearer token")}},"authenticate"),{attributeHeaders:x,trustProxyHops:ie,trustProxyIp:J,uidHeader:H,cookie:K}=r,h=e.LENSMCP_EVENT_FILE,B=h?(()=>{try{return require("@lensmcp/node-instrumentation")}catch{return}})():void 0,z=B?.createEventFloodGuard({burst:30,perSec:5});let X=!1;const v=h?t=>{try{const s=z?z.admit(String(t.fingerprint??"")):{ok:!0,suppressed:0};if(!s.ok)return;X||((0,node_fs_1.mkdirSync)((0,node_path_1.dirname)(h),{recursive:!0}),X=!0);const o=t.raw,i=JSON.stringify(s.suppressed>0?{...t,raw:{...o,floodSuppressed:s.suppressed}}:t)+`
|
|
2
|
+
`;B?.maybeRotateEventFile(h,i.length),(0,node_fs_1.appendFileSync)(h,i)}catch{}}:void 0;if(S)try{await S.refresh(),console.log("[gateway] JWKS loaded")}catch(t){console.error("[gateway] initial JWKS load failed (will retry in background):",t.message)}const{accessLog:ne,clientIpHeader:Y,clientIpTrustedProxies:V,undici:d}=r;if(r.mtlsFromRedis&&f){const t=e.LENSMCP_GW_REDIS_PREFIX??"lensmcp:gw",[s,o,i]=await f.mget(`${t}:mtls:cert`,`${t}:mtls:key`,`${t}:mtls:ca`);s&&(d.cert=s),o&&(d.key=o),i&&(d.ca=i),(s||o)&&console.log("[gateway] mTLS materials loaded from Redis")}else e.LENSMCP_GW_MTLS_CERT&&(d.cert=(0,node_fs_1.readFileSync)(e.LENSMCP_GW_MTLS_CERT)),e.LENSMCP_GW_MTLS_KEY&&(d.key=(0,node_fs_1.readFileSync)(e.LENSMCP_GW_MTLS_KEY)),e.LENSMCP_GW_MTLS_CA&&(d.ca=(0,node_fs_1.readFileSync)(e.LENSMCP_GW_MTLS_CA));(0,prod_config_1.finalizeUpstreamTls)(d).autoEnabled&&console.log("[gateway] upstream TLS verification ENABLED (a CA is configured; set LENSMCP_GW_UPSTREAM_TLS_VERIFY=0 to opt out)"),(0,prod_config_1.finalizeUpstreamH2)(d,e)&&console.log(`[gateway] mTLS to upstreams ON over ${d.allowH2?"h2":"h1.1"} (server validation ${d.rejectUnauthorized?"enabled":"OFF"})`);const{upstreamRetries:C,server:Q}=r,T=(0,otel_tracing_1.setupTracing)({...e.OTEL_SERVICE_NAME?{serviceName:e.OTEL_SERVICE_NAME}:{},...e.LENSMCP_GW_OTEL_SAMPLE?{sampleRatio:Number(e.LENSMCP_GW_OTEL_SAMPLE)}:{}});T&&console.log(`[gateway] OTLP tracing on \u2192 ${(0,edge_1.safeUrl)(e.OTEL_EXPORTER_OTLP_ENDPOINT)}`);const{statusEnabled:N,statusToken:m}=r,Z=(0,node_os_1.hostname)(),ae=r.statusTtlSec,ee=f,G=N&&ee?t=>{for(const s of t)ee.set(`status:${s.service}:${Z}`,JSON.stringify({...s,instance:Z,at:Date.now()}),"EX",ae).catch(()=>{})}:void 0;N&&!m&&console.warn("[gateway] LENSMCP_GW_STATUS=1 but no LENSMCP_GW_STATUS_TOKEN \u2014 /statusz stays DISABLED (404) until a token is set (fail-closed). The Redis status:* fan-out still runs."),N&&console.log(`[gateway] status on \u2014 /statusz${m?"":" (endpoint disabled: no token)"}${G?" + Redis status:* fan-out":""}`);const W=r.health?(0,health_check_1.createHealthChecker)(r.health):void 0;W&&console.log(`[gateway] active health-checking on (path ${r.health?.path??"/healthz"})`);let L,b;if(r.rateLimit){const{limit:t,windowMs:s,wantRedis:o,failClosed:i}=r.rateLimit;if(o){const c=r.rateLimit.dedicatedUrl;let l;if(c){const E=require("ioredis");b=new E(c),l=b}else f&&(l=f);l?(L=(0,rate_limit_1.createRedisRateLimiter)(l,{limit:t,windowMs:s,prefix:`${e.LENSMCP_GW_REDIS_PREFIX??"lensmcp:gw"}:rl:`,...r.rateLimit.timeoutMs!==void 0?{timeoutMs:r.rateLimit.timeoutMs}:{},...i?{failOpen:!1}:{},onFailure:a(E=>console.error(`[gateway] RATE LIMITER DEGRADED \u2014 Redis unusable (${E}). Requests are being ${i?"DENIED":"ALLOWED"} without a limit check. Check the ACL covers ${e.LENSMCP_GW_REDIS_PREFIX??"lensmcp:gw"}:rl:*`),"onFailure")}),console.log(`[gateway] rate limit on \u2014 ${t} req / ${s}ms GLOBAL (Redis: ${c?"dedicated":"shared registry"}, fail-${i?"closed":"open"}) per client IP`)):console.warn("[gateway] LENSMCP_GW_RATE_LIMIT_REDIS set but no Redis configured (set LENSMCP_GW_REDIS_URL or LENSMCP_GW_RATE_LIMIT_REDIS_URL) \u2014 falling back to PER-INSTANCE in-memory limiting.")}if(!L){const c=(0,prod_config_1.workerCount)(e),l=(0,prod_config_1.perWorkerLimit)(t,c);L=(0,rate_limit_1.createRateLimiter)({limit:l,windowMs:s}),console.log(`[gateway] rate limit on \u2014 ${t} req / ${s}ms per client IP (in-memory`+(c>1?`, ${l}/worker \xD7 ${c} workers`:", per-instance")+")")}}const $=r.metricsEnabled?(0,metrics_1.createProcessMetrics)():void 0;$&&console.log(`[gateway] process metrics on \u2014 /metricsz${m?" (token-gated)":" (DISABLED: needs LENSMCP_GW_STATUS_TOKEN)"}`);const R=await(0,prod_gateway_lib_1.startProdGateway)({...n.length?{ports:n}:{},...r.host?{host:r.host}:{},manifests:g,...y?{pods:y}:{},serviceKeys:re,authenticate:oe,...D?{tls:D}:{},...v?{emit:v}:{},...U?{identify:U}:{},...x.length?{attributeHeaders:x}:{},...J?{trustProxyIp:J,trustProxyHops:ie}:{},...K?{cookie:K}:{},...H?{uidHeader:H}:{},...ne?{accessLog:!0}:{},...Y?{clientIpHeader:Y}:{},...V.length?{clientIpTrustedProxies:V}:{},...T?{tracing:T}:{},...N?{statusEndpoint:!0}:{},...m?{statusToken:m}:{},...G?{onStatus:G}:{},...W?{healthChecker:W}:{},...L?{rateLimiter:L}:{},...$?{metrics:$}:{},...r.trafficFlushMs!==void 0?{trafficFlushMs:r.trafficFlushMs}:{},...C!==void 0&&Number.isFinite(C)?{upstreamRetries:C}:{},...Object.keys(d).length?{undici:d}:{},...Object.keys(Q).length?{server:Q}:{},...r.internalPeers.length?{internalPeers:r.internalPeers}:{},...Object.keys(r.upgrades).length?{upgrades:r.upgrades}:{}});A.current=R;const ce=I?watchJsonFile(I,t=>{try{R.setServiceKeys(t),console.log(`[gateway] service keys reloaded (${Object.keys(t).length} service(s))`)}catch(s){console.error("[gateway] service keys reload refused \u2014 keeping the keys in use:",s.message)}}):void 0;console.log(`[gateway] production gateway up on ${R.ports.join(", ")} (${R.routes().length} routes${v?", lens ON":""})`),u.push(()=>g.stop?.(),()=>O?.(),()=>ce?.(),()=>j?.stop(),()=>b?.quit(),()=>S?.stop(),()=>R.stop(),()=>T?.shutdown())}M(main,"main"),a(main,"main");const WORKERS=(0,prod_config_1.workerCount)(process.env);if(WORKERS>1&&node_cluster_1.default.isPrimary){if(console.log(`[gateway] primary ${process.pid}: forking ${WORKERS} workers (one per core)\u2026`),process.env.LENSMCP_GW_RATE_LIMIT&&!(0,prod_config_1.redisLimiterConfigured)(process.env)){const n=process.env.LENSMCP_GW_RATE_LIMIT_REDIS==="1",u=Number(process.env.LENSMCP_GW_RATE_LIMIT),_=(0,prod_config_1.perWorkerLimit)(u,WORKERS);console.warn(`[gateway] WARNING: ${n?"LENSMCP_GW_RATE_LIMIT_REDIS=1 is set but no Redis URL is \u2014 each worker will fall back to":"using"} the in-memory rate limiter with ${WORKERS} workers. Each worker now enforces ${_} req/window so the total stays \u2248 ${u}; a single client's burst can still land unevenly across workers. Set ${n?"LENSMCP_GW_REDIS_URL (or LENSMCP_GW_RATE_LIMIT_REDIS_URL)":"LENSMCP_GW_RATE_LIMIT_REDIS=1 and a Redis URL"} for one shared global budget.`)}let e=!1;for(let n=0;n<WORKERS;n++)node_cluster_1.default.fork();node_cluster_1.default.on("exit",(n,u,_)=>{e||(console.warn(`[gateway] worker ${n.process.pid} exited (code=${u} sig=${_??""}) \u2014 respawning.`),node_cluster_1.default.fork())});const r=a(n=>{if(!e){e=!0,console.log(`[gateway] primary: ${n} \u2014 stopping ${Object.keys(node_cluster_1.default.workers??{}).length} workers\u2026`);for(const u of Object.values(node_cluster_1.default.workers??{}))try{u?.kill(n)}catch{}setTimeout(()=>process.exit(0),12e3).unref()}},"stopAll");process.on("SIGTERM",()=>r("SIGTERM")),process.on("SIGINT",()=>r("SIGINT"))}else main().catch(e=>{console.error("[gateway] FATAL: could not start \u2014",e instanceof Error?e.stack??e.message:e),process.exit(1)});
|
|
@@ -169,6 +169,14 @@ export interface Route {
|
|
|
169
169
|
upstream?: string;
|
|
170
170
|
/** Resolved auth for the route root (overrides refine per-path at match). */
|
|
171
171
|
auth: AuthMode;
|
|
172
|
+
/**
|
|
173
|
+
* The auth policy of the manifest THIS route was built from — carried on the route so the edge never
|
|
174
|
+
* re-resolves it by service NAME at request time. Resolving by name let a second manifest that reused a
|
|
175
|
+
* service name judge the first one's host with its own policy (a `jwt` host served under a `public` twin's
|
|
176
|
+
* policy, PG3-28), and let a registry reload during a JWKS wait drop a route's overrides (PG3-15).
|
|
177
|
+
* `buildRouteTable` always sets it (`{}` when the manifest declares none).
|
|
178
|
+
*/
|
|
179
|
+
policy?: AuthPolicy;
|
|
172
180
|
}
|
|
173
181
|
/**
|
|
174
182
|
* Exact hostname or `*.suffix` wildcard (the bare suffix also matches).
|
|
@@ -270,6 +278,24 @@ export declare function authRuleForPath(manifest: RouteManifest, path: string, m
|
|
|
270
278
|
* specificity so `matchRoute` picks the most specific.
|
|
271
279
|
*/
|
|
272
280
|
export declare function buildRouteTable(manifests: readonly RouteManifest[]): Route[];
|
|
281
|
+
/** A configuration defect found in a manifest set — reported loudly at load, never served open. */
|
|
282
|
+
export interface ManifestProblem {
|
|
283
|
+
service: string;
|
|
284
|
+
problem: string;
|
|
285
|
+
}
|
|
286
|
+
/**
|
|
287
|
+
* Name every configuration defect in a manifest set that the edge would otherwise have to guess about. The
|
|
288
|
+
* gateway still FAILS CLOSED on each at request time (an `internal`/unknown mode answers 401, an unsafe regex
|
|
289
|
+
* never matches, a duplicated service keeps each route's own policy); this is the loud half, so an operator sees
|
|
290
|
+
* at boot and on every reload what a manifest asked for and did not get.
|
|
291
|
+
*
|
|
292
|
+
* - `internal` (or any string that is not `jwt`/`public`) as `auth.default` or an override `mode` (PG3-01);
|
|
293
|
+
* - two manifests with the same `service` name (PG3-28);
|
|
294
|
+
* - a `regex` rule the engine refuses to run ({@link unsafeRegex}, PG3-25).
|
|
295
|
+
*/
|
|
296
|
+
export declare function manifestProblems(manifests: readonly RouteManifest[]): ManifestProblem[];
|
|
297
|
+
/** Every `regex` pattern in a rule tree. */
|
|
298
|
+
export declare function regexSources(node: RuleNode | undefined): string[];
|
|
273
299
|
/** Synthesize a manifest from a dev project.json `cluster` declaration —
|
|
274
300
|
* the dev ManifestProvider's adapter, and the seed for `lensmcp`-generated
|
|
275
301
|
* prod manifests (same fields, prod adds version/rateLimits). */
|
|
@@ -287,6 +313,13 @@ export declare function manifestFromClusterDecl(project: string, decl: {
|
|
|
287
313
|
/** A flat, read-only attribute bag assembled per request: verified JWT claims,
|
|
288
314
|
* `ip`, `header.<name>`, `device` (sticky key), `path`, `method`. */
|
|
289
315
|
export type Attrs = Record<string, unknown>;
|
|
316
|
+
/**
|
|
317
|
+
* The verified claims as the first layer of an attribute bag, minus every name the gateway owns (`ip`, `method`,
|
|
318
|
+
* `path`, `device`, `header.*`). A claim named `header.cf-ipcountry` (or `device`) used to survive whenever the
|
|
319
|
+
* gateway left that attribute unset and satisfied its rule (PG3-27); built-ins are set AFTER this by the caller.
|
|
320
|
+
* Spread-then-delete, never `a[k] = v` per claim, which would run the `__proto__` setter.
|
|
321
|
+
*/
|
|
322
|
+
export declare function claimAttrs(claims: Record<string, unknown> | undefined): Attrs;
|
|
290
323
|
export type RuleOp = 'eq' | 'ne' | 'in' | 'nin' | 'prefix' | 'suffix' | 'contains' | 'domain' | 'hastoken' | 'regex' | 'exists' | 'gt' | 'lt' | 'cidr';
|
|
291
324
|
export interface Condition {
|
|
292
325
|
attr: string;
|
|
@@ -305,9 +338,23 @@ export interface TargetRule {
|
|
|
305
338
|
when: RuleNode;
|
|
306
339
|
version: string;
|
|
307
340
|
}
|
|
341
|
+
/** Longest pattern, and longest attribute value, a `regex` condition runs on. Attributes are claims and headers. */
|
|
342
|
+
export declare const MAX_REGEX_LENGTH = 512;
|
|
343
|
+
/**
|
|
344
|
+
* Why a rule pattern is refused, or undefined when it is safe to run. A pattern-length bound alone let
|
|
345
|
+
* `^(\w+\s?)+$` hold the event loop for 8 s on a 27-byte client header (PG3-25): the cost of a backtracking match
|
|
346
|
+
* is set by the pattern's SHAPE. Refused here:
|
|
347
|
+
* - a quantified group that itself contains a repeating quantifier (star height > 1: `(a+)+`, `(\w+\s?)*`,
|
|
348
|
+
* `(a*b){2,}`) — the classic exponential shape, what `safe-regex` checks;
|
|
349
|
+
* - a backreference (`\1`, `\k<x>`), which no engine matches in linear time.
|
|
350
|
+
* A lexical check, not a proof: overlapping alternations under one quantifier (`(a|aa)+`) pass it, which is why
|
|
351
|
+
* the matched VALUE is bounded too ({@link MAX_REGEX_LENGTH}).
|
|
352
|
+
*/
|
|
353
|
+
export declare function unsafeRegex(src: string): string | undefined;
|
|
308
354
|
/** `ip ∈ cidr` for IPv4 (handles IPv4-mapped IPv6). False for IPv6/malformed. */
|
|
309
355
|
export declare function matchCidr(ip: string, cidr: string): boolean;
|
|
310
|
-
/** Evaluate a rule node (condition or all/any/not group) against attributes. Pure.
|
|
356
|
+
/** Evaluate a rule node (condition or all/any/not group) against attributes. Pure. A condition that cannot be
|
|
357
|
+
* evaluated safely makes the WHOLE rule false (deny / no targeting), wherever it sits. */
|
|
311
358
|
export declare function evalRule(node: RuleNode, attrs: Attrs): boolean;
|
|
312
359
|
/** First matching rule's version (top-to-bottom), or undefined. */
|
|
313
360
|
export declare function pickTargetedVersion(rules: readonly TargetRule[], attrs: Attrs): {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var h=Object.defineProperty;var i=(t,r)=>h(t,"name",{value:r,configurable:!0});var f=Object.defineProperty,o=i((t,r)=>f(t,"name",{value:r,configurable:!0}),"o");Object.defineProperty(exports,"__esModule",{value:!0}),exports.smoothWeightedSelector=smoothWeightedSelector,exports.hostMatches=hostMatches,exports.matchRoute=matchRoute,exports.pathUnderPrefix=pathUnderPrefix,exports.sortBySpecificity=sortBySpecificity,exports.authForPath=authForPath,exports.authPathMatches=authPathMatches,exports.authRuleFor=authRuleFor,exports.authRuleForPath=authRuleForPath,exports.buildRouteTable=buildRouteTable,exports.manifestFromClusterDecl=manifestFromClusterDecl,exports.matchCidr=matchCidr,exports.evalRule=evalRule,exports.pickTargetedVersion=pickTargetedVersion,exports.fnv1a=fnv1a,exports.bucketByWeight=bucketByWeight;function smoothWeightedSelector(t){const r=t.map(()=>0),e=t.reduce((s,n)=>s+Math.max(0,n),0);return()=>{if(e<=0||t.length===0)return 0;let s=0;for(let n=0;n<t.length;n++)r[n]+=Math.max(0,t[n]),r[n]>r[s]&&(s=n);return r[s]-=e,s}}i(smoothWeightedSelector,"smoothWeightedSelector"),o(smoothWeightedSelector,"smoothWeightedSelector");function hostMatches(t,r){const e=t.toLowerCase(),s=r.toLowerCase();return e.startsWith("*.")?s.endsWith(e.slice(1))||s===e.slice(2):s===e}i(hostMatches,"hostMatches"),o(hostMatches,"hostMatches");function matchRoute(t,r,e){const s=t.some(a=>a.host&&hostMatches(a.host,r));let n;if(s)n=t.filter(a=>a.host&&hostMatches(a.host,r)),n.some(a=>a.host===r)?n=n.filter(a=>a.host===r):n.length>1&&(n=[...n].sort((a,u)=>u.host.length-a.host.length));else{const a=t.filter(u=>!u.host);if(a.length<=1)n=a;else{const u=a.filter(l=>l.apex&&(r===l.apex||r.endsWith("."+l.apex))).sort((l,c)=>c.apex.length-l.apex.length);n=u.length>0?u:a.filter(l=>!l.apex)}}return n.find(a=>!a.prefix||pathUnderPrefix(e,a.prefix))}i(matchRoute,"matchRoute"),o(matchRoute,"matchRoute");function pathUnderPrefix(t,r){let e=r.length;for(;e>0&&r.charCodeAt(e-1)===47;)e-=1;if(e===0)return!0;if(t.length<e||t.slice(0,e).toLowerCase()!==r.slice(0,e).toLowerCase())return!1;const s=t.charCodeAt(e);return Number.isNaN(s)||s===47||s===63}i(pathUnderPrefix,"pathUnderPrefix"),o(pathUnderPrefix,"pathUnderPrefix");function sortBySpecificity(t){const r=o(e=>(e.host?2:0)+(e.prefix?1:0),"rank");return t.sort((e,s)=>r(s)-r(e)||(s.prefix?.length??0)-(e.prefix?.length??0)),t}i(sortBySpecificity,"sortBySpecificity"),o(sortBySpecificity,"sortBySpecificity");function authForPath(t,r,e){if(e)return"internal";const s=t.auth?.overrides??[];for(const n of s)if(r.startsWith(n.path))return n.mode;return t.auth?.default??"jwt"}i(authForPath,"authForPath"),o(authForPath,"authForPath");function authPathMatches(t,r){const e=t.split("/").filter(Boolean),s=(r.split("?")[0]??"").split("/").filter(Boolean);if(s.length<e.length)return!1;for(let n=0;n<e.length;n++){const a=e[n];if(!(a==="*"||a.startsWith(":"))&&a.toLowerCase()!==s[n].toLowerCase())return!1}return!0}i(authPathMatches,"authPathMatches"),o(authPathMatches,"authPathMatches");function authRuleFor(t,r,e){const s=e.toUpperCase();for(const n of t?.overrides??[]){if(!authPathMatches(n.path,r)||n.methods&&!n.methods.some(u=>u.toUpperCase()===s))continue;const a=n.rule??(n.permission?{attr:"perms",op:"hastoken",value:n.permission}:void 0);return{mode:n.mode??t?.default??"jwt",...a?{rule:a}:{}}}return{mode:t?.default??"jwt"}}i(authRuleFor,"authRuleFor"),o(authRuleFor,"authRuleFor");function authRuleForPath(t,r,e,s){return s?{mode:"internal"}:authRuleFor(t.auth,r,e)}i(authRuleForPath,"authRuleForPath"),o(authRuleForPath,"authRuleForPath");function buildRouteTable(t){const r=[];for(const e of t){const s=e.auth?.default??"jwt";for(const n of e.mounts){const a={service:e.service,...n.path?{prefix:n.path}:{},...e.prependPrefix?{prependPrefix:e.prependPrefix}:{},...e.upstream?{upstream:e.upstream}:{}};r.push({...a,host:n.host,auth:s}),e.internal&&e.internalHost!==!1&&r.push({...a,host:typeof e.internalHost=="string"?e.internalHost:`internal.${n.host}`,internal:!0,auth:"internal"})}e.default&&r.push({service:e.service,...e.prependPrefix?{prependPrefix:e.prependPrefix}:{},...e.upstream?{upstream:e.upstream}:{},default:!0,auth:s})}return sortBySpecificity(r)}i(buildRouteTable,"buildRouteTable"),o(buildRouteTable,"buildRouteTable");function manifestFromClusterDecl(t,r){const e=r.upstream??(r.port?`http://localhost:${r.port}`:void 0);if(!(!r.service&&!e))return{service:r.service??t,mounts:r.host?[{host:r.host,...r.path?{path:r.path}:{}}]:[],internal:!!r.service,...r.internalHost!==void 0?{internalHost:r.internalHost}:{},...r.default?{default:!0}:{},...r.prependPrefix?{prependPrefix:r.prependPrefix}:{},...r.auth?{auth:r.auth}:{},...e?{upstream:e}:{}}}i(manifestFromClusterDecl,"manifestFromClusterDecl"),o(manifestFromClusterDecl,"manifestFromClusterDecl");const isGroup=o(t=>"all"in t||"any"in t||"not"in t,"isGroup"),reCache=new Map,compileRe=o(t=>{if(t.length>512)return null;if(reCache.has(t))return reCache.get(t);let r;try{r=new RegExp(t)}catch{r=null}return reCache.set(t,r),r},"compileRe");function ipToInt(t){const r=(t.startsWith("::ffff:")?t.slice(7):t).split(".");if(r.length!==4)return null;let e=0;for(const s of r){const n=Number(s);if(!Number.isInteger(n)||n<0||n>255||s.length>1&&s[0]==="0")return null;e=e*256+n}return e>>>0}i(ipToInt,"ipToInt"),o(ipToInt,"ipToInt");function matchCidr(t,r){const e=r.indexOf("/");if(e<0)return!1;const s=Number(r.slice(e+1));if(!Number.isInteger(s)||s<0||s>32)return!1;const n=ipToInt(t),a=ipToInt(r.slice(0,e));if(n===null||a===null)return!1;if(s===0)return!0;const u=(s===32?4294967295:~((1<<32-s)-1))>>>0;return(n&u)>>>0===(a&u)>>>0}i(matchCidr,"matchCidr"),o(matchCidr,"matchCidr");const str=o(t=>t==null?"":String(t),"str"),eq=o((t,r)=>str(t)===str(r),"eq");function evalCondition(t,r){const e=r[t.attr],s=e!=null;switch(t.op){case"exists":return s;case"ne":return!s||!eq(e,t.value)}if(!s)return!1;switch(t.op){case"eq":return eq(e,t.value);case"in":return Array.isArray(t.value)&&t.value.some(n=>Array.isArray(e)?e.some(a=>eq(a,n)):eq(e,n));case"nin":return Array.isArray(t.value)&&!t.value.some(n=>Array.isArray(e)?e.some(a=>eq(a,n)):eq(e,n));case"prefix":return str(e).startsWith(str(t.value));case"suffix":return str(e).endsWith(str(t.value));case"domain":{const n=str(e).lastIndexOf("@"),a=(n===-1?str(e):str(e).slice(n+1)).toLowerCase().replace(/\.$/,""),u=str(t.value).toLowerCase().replace(/^\./,"").replace(/\.$/,"");return!!u&&(a===u||a.endsWith("."+u))}case"contains":return Array.isArray(e)?e.some(n=>eq(n,t.value)):str(e).includes(str(t.value));case"hastoken":{const n=str(t.value);return Array.isArray(e)?e.some(a=>eq(a,t.value)):str(e).split(/[\s,]+/).filter(Boolean).includes(n)}case"regex":{const n=compileRe(str(t.value));return n?n.test(str(e)):!1}case"gt":return Number(e)>Number(t.value);case"lt":return Number(e)<Number(t.value);case"cidr":return matchCidr(str(e),str(t.value));default:return!1}}i(evalCondition,"evalCondition"),o(evalCondition,"evalCondition");function evalRule(t,r){if(!isGroup(t))return evalCondition(t,r);const e=Array.isArray(t.all)&&t.all.length?t.all:void 0,s=Array.isArray(t.any)&&t.any.length?t.any:void 0,n=t.not&&Object.keys(t.not).length?t.not:void 0;return n&&evalRule(n,r)||e&&!e.every(a=>evalRule(a,r))||s&&!s.some(a=>evalRule(a,r))?!1:!!(e||s||n)}i(evalRule,"evalRule"),o(evalRule,"evalRule");function pickTargetedVersion(t,r){for(const e of t)if(evalRule(e.when,r))return{version:e.version,...e.name?{rule:e.name}:{}}}i(pickTargetedVersion,"pickTargetedVersion"),o(pickTargetedVersion,"pickTargetedVersion");function fnv1a(t){let r=2166136261;for(let e=0;e<t.length;e++)r^=t.charCodeAt(e),r=Math.imul(r,16777619);return r>>>0}i(fnv1a,"fnv1a"),o(fnv1a,"fnv1a");function bucketByWeight(t,r){const e=r.reduce((a,u)=>a+Math.max(0,u),0);if(e<=0||r.length===0)return 0;const s=fnv1a(t)%1e4;let n=0;for(let a=0;a<r.length;a++)if(n+=Math.max(0,r[a])/e*1e4,s<n)return a;return r.length-1}i(bucketByWeight,"bucketByWeight"),o(bucketByWeight,"bucketByWeight");
|
|
1
|
+
"use strict";var p=Object.defineProperty;var l=(e,r)=>p(e,"name",{value:r,configurable:!0});var h=Object.defineProperty,a=l((e,r)=>h(e,"name",{value:r,configurable:!0}),"a");Object.defineProperty(exports,"__esModule",{value:!0}),exports.MAX_REGEX_LENGTH=void 0,exports.smoothWeightedSelector=smoothWeightedSelector,exports.hostMatches=hostMatches,exports.matchRoute=matchRoute,exports.pathUnderPrefix=pathUnderPrefix,exports.sortBySpecificity=sortBySpecificity,exports.authForPath=authForPath,exports.authPathMatches=authPathMatches,exports.authRuleFor=authRuleFor,exports.authRuleForPath=authRuleForPath,exports.buildRouteTable=buildRouteTable,exports.manifestProblems=manifestProblems,exports.regexSources=regexSources,exports.manifestFromClusterDecl=manifestFromClusterDecl,exports.claimAttrs=claimAttrs,exports.unsafeRegex=unsafeRegex,exports.matchCidr=matchCidr,exports.evalRule=evalRule,exports.pickTargetedVersion=pickTargetedVersion,exports.fnv1a=fnv1a,exports.bucketByWeight=bucketByWeight;function smoothWeightedSelector(e){const r=e.map(()=>0),t=e.reduce((n,o)=>n+Math.max(0,o),0);return()=>{if(t<=0||e.length===0)return 0;let n=0;for(let o=0;o<e.length;o++)r[o]+=Math.max(0,e[o]),r[o]>r[n]&&(n=o);return r[n]-=t,n}}l(smoothWeightedSelector,"smoothWeightedSelector"),a(smoothWeightedSelector,"smoothWeightedSelector");function hostMatches(e,r){const t=e.toLowerCase(),n=r.toLowerCase();return t.startsWith("*.")?n.endsWith(t.slice(1))||n===t.slice(2):n===t}l(hostMatches,"hostMatches"),a(hostMatches,"hostMatches");function matchRoute(e,r,t){const n=e.some(s=>s.host&&hostMatches(s.host,r));let o;if(n){o=e.filter(i=>i.host&&hostMatches(i.host,r));const s=r.toLowerCase();o.some(i=>i.host.toLowerCase()===s)?o=o.filter(i=>i.host.toLowerCase()===s):o.length>1&&(o=[...o].sort((i,u)=>u.host.length-i.host.length))}else{const s=e.filter(i=>!i.host);if(s.length<=1)o=s;else{const i=r.toLowerCase(),u=s.filter(c=>{const f=c.apex?.toLowerCase();return!!f&&(i===f||i.endsWith("."+f))}).sort((c,f)=>f.apex.length-c.apex.length);o=u.length>0?u:s.filter(c=>!c.apex)}}return o.find(s=>!s.prefix||pathUnderPrefix(t,s.prefix))}l(matchRoute,"matchRoute"),a(matchRoute,"matchRoute");function pathUnderPrefix(e,r){let t=r.length;for(;t>0&&r.charCodeAt(t-1)===47;)t-=1;if(t===0)return!0;if(e.length<t||e.slice(0,t).toLowerCase()!==r.slice(0,t).toLowerCase())return!1;const n=e.charCodeAt(t);return Number.isNaN(n)||n===47||n===63}l(pathUnderPrefix,"pathUnderPrefix"),a(pathUnderPrefix,"pathUnderPrefix");function sortBySpecificity(e){const r=a(t=>(t.host?2:0)+(t.prefix?1:0),"rank");return e.sort((t,n)=>r(n)-r(t)||(n.prefix?.length??0)-(t.prefix?.length??0)),e}l(sortBySpecificity,"sortBySpecificity"),a(sortBySpecificity,"sortBySpecificity");function authForPath(e,r,t){if(t)return"internal";const n=e.auth?.overrides??[];for(const o of n)if(r.startsWith(o.path))return o.mode;return e.auth?.default??"jwt"}l(authForPath,"authForPath"),a(authForPath,"authForPath");function authPathMatches(e,r){const t=e.split("/").filter(Boolean),n=r.split("/").filter(Boolean);if(n.length<t.length)return!1;for(let o=0;o<t.length;o++){const s=t[o];if(!(s==="*"||s.startsWith(":"))&&s.toLowerCase()!==n[o].toLowerCase())return!1}return!0}l(authPathMatches,"authPathMatches"),a(authPathMatches,"authPathMatches");function authRuleFor(e,r,t){const n=t.toUpperCase();for(const o of e?.overrides??[]){if(!authPathMatches(o.path,r)||o.methods&&!o.methods.some(i=>{const u=i.toUpperCase();return u===n||n==="HEAD"&&u==="GET"}))continue;const s=o.rule??(o.permission?{attr:"perms",op:"hastoken",value:o.permission}:void 0);return{mode:o.mode??e?.default??"jwt",...s?{rule:s}:{}}}return{mode:e?.default??"jwt"}}l(authRuleFor,"authRuleFor"),a(authRuleFor,"authRuleFor");function authRuleForPath(e,r,t,n){return n?{mode:"internal"}:authRuleFor(e.auth,r,t)}l(authRuleForPath,"authRuleForPath"),a(authRuleForPath,"authRuleForPath");function buildRouteTable(e){const r=[];for(const t of e){const n=t.auth?.default??"jwt",o=t.auth??{};for(const s of t.mounts){const i={service:t.service,...s.path?{prefix:s.path}:{},...t.prependPrefix?{prependPrefix:t.prependPrefix}:{},...t.upstream?{upstream:t.upstream}:{}};r.push({...i,host:s.host,auth:n,policy:o}),t.internal&&t.internalHost!==!1&&r.push({...i,host:typeof t.internalHost=="string"?t.internalHost:`internal.${s.host}`,internal:!0,auth:"internal"})}t.default&&r.push({service:t.service,...t.prependPrefix?{prependPrefix:t.prependPrefix}:{},...t.upstream?{upstream:t.upstream}:{},default:!0,auth:n,policy:o})}return sortBySpecificity(r)}l(buildRouteTable,"buildRouteTable"),a(buildRouteTable,"buildRouteTable");const HOST_ROUTE_MODES=new Set(["jwt","public"]);function manifestProblems(e){const r=[],t=new Map;for(const n of e){const o=n.mounts.map(u=>u.host+(u.path??"")),s=t.get(n.service);s&&r.push({service:n.service,problem:`the service name is declared by more than one manifest (${[...s,...o].join(", ")}) \u2014 each route keeps its own manifest's auth policy; give each manifest its own name`}),t.set(n.service,[...s??[],...o]);const i=n.auth?.default;i!==void 0&&!HOST_ROUTE_MODES.has(i)&&r.push({service:n.service,problem:`auth.default is \xAB${String(i)}\xBB \u2014 a host route is served as \`jwt\` or \`public\` only (\`internal\` is a route kind: set \`internal: true\` for an \`internal.<host>\` route); every request to it answers 401`});for(const u of n.auth?.overrides??[]){u.mode!==void 0&&!HOST_ROUTE_MODES.has(u.mode)&&r.push({service:n.service,problem:`the override for ${u.path} has mode \xAB${String(u.mode)}\xBB \u2014 only \`jwt\` and \`public\` are modes; requests under it answer 401`});for(const c of regexSources(u.rule)){const f=unsafeRegex(c);f&&r.push({service:n.service,problem:`the override for ${u.path} has a regex rule the edge will not run (${f}): ${c.slice(0,80)}`})}}}return r}l(manifestProblems,"manifestProblems"),a(manifestProblems,"manifestProblems");function regexSources(e){return e?isGroup(e)?[...(e.all??[]).flatMap(regexSources),...(e.any??[]).flatMap(regexSources),...regexSources(e.not)]:e.op==="regex"?[str(e.value)]:[]:[]}l(regexSources,"regexSources"),a(regexSources,"regexSources");function manifestFromClusterDecl(e,r){const t=r.upstream??(r.port?`http://localhost:${r.port}`:void 0);if(!(!r.service&&!t))return{service:r.service??e,mounts:r.host?[{host:r.host,...r.path?{path:r.path}:{}}]:[],internal:!!r.service,...r.internalHost!==void 0?{internalHost:r.internalHost}:{},...r.default?{default:!0}:{},...r.prependPrefix?{prependPrefix:r.prependPrefix}:{},...r.auth?{auth:r.auth}:{},...t?{upstream:t}:{}}}l(manifestFromClusterDecl,"manifestFromClusterDecl"),a(manifestFromClusterDecl,"manifestFromClusterDecl");const RESERVED_ATTRS=new Set(["ip","method","path","device"]);function claimAttrs(e){const r={...e??{}};for(const t of Object.keys(r))(RESERVED_ATTRS.has(t)||t.startsWith("header."))&&delete r[t];return r}l(claimAttrs,"claimAttrs"),a(claimAttrs,"claimAttrs");const isGroup=a(e=>"all"in e||"any"in e||"not"in e,"isGroup");exports.MAX_REGEX_LENGTH=512;function unsafeRegex(e){if(e.length>exports.MAX_REGEX_LENGTH)return`longer than ${exports.MAX_REGEX_LENGTH} characters`;if(/\\[1-9]|\\k</.test(e))return"a backreference";const r=[];let t;for(let n=0;n<e.length;){const o=e[n];if(o==="\\"){n+=2,t=!1;continue}if(o==="["){for(n+=1,e[n]==="^"&&(n+=1),e[n]==="]"&&(n+=1);n<e.length&&e[n]!=="]";)n+=e[n]==="\\"?2:1;n+=1,t=!1;continue}if(o==="("){if(r.push(!1),n+=1,t=void 0,e[n]==="?"){if(n+=1,e[n]==="<"&&e[n+1]!=="="&&e[n+1]!=="!")for(;n<e.length&&e[n]!==">";)n+=1;n+=1}continue}if(o===")"){const u=r.pop()??!1;n+=1,u&&r.length&&(r[r.length-1]=!0),t=u;continue}if(o==="|"){n+=1,t=void 0;continue}let s,i=1;if(o==="*"||o==="+")s=!0;else if(o==="?")s=!1;else if(o==="{"){const u=/^\{(\d+)(,(\d*))?\}/.exec(e.slice(n));if(u){i=u[0].length;const c=Number(u[1]);s=(u[2]===void 0?c:u[3]===""?1/0:Number(u[3]))>1}}if(s===void 0){n+=1,t=!1;continue}if(n+=i,e[n]==="?"&&(n+=1),t!==void 0){if(s&&t)return"nested quantifiers";s&&r.length&&(r[r.length-1]=!0),t=!1}}}l(unsafeRegex,"unsafeRegex"),a(unsafeRegex,"unsafeRegex");class Indeterminate extends Error{static{l(this,"Indeterminate")}static{a(this,"Indeterminate")}}const reCache=new Map,compileRe=a(e=>{if(reCache.has(e))return reCache.get(e);let r=null;if(!unsafeRegex(e))try{r=new RegExp(e)}catch{r=null}return reCache.size>=1024&&reCache.clear(),reCache.set(e,r),r},"compileRe");function ipToInt(e){const r=(e.startsWith("::ffff:")?e.slice(7):e).split(".");if(r.length!==4)return null;let t=0;for(const n of r){const o=Number(n);if(!Number.isInteger(o)||o<0||o>255||n.length>1&&n[0]==="0")return null;t=t*256+o}return t>>>0}l(ipToInt,"ipToInt"),a(ipToInt,"ipToInt");function matchCidr(e,r){const t=r.indexOf("/");if(t<0)return!1;const n=Number(r.slice(t+1));if(!Number.isInteger(n)||n<0||n>32)return!1;const o=ipToInt(e),s=ipToInt(r.slice(0,t));if(o===null||s===null)return!1;if(n===0)return!0;const i=(n===32?4294967295:~((1<<32-n)-1))>>>0;return(o&i)>>>0===(s&i)>>>0}l(matchCidr,"matchCidr"),a(matchCidr,"matchCidr");const str=a(e=>e==null?"":String(e),"str"),eq=a((e,r)=>str(e)===str(r),"eq");function evalCondition(e,r){const t=r[e.attr],n=t!=null;switch(e.op){case"exists":return n;case"ne":return!n||!eq(t,e.value)}if(!n)return!1;switch(e.op){case"eq":return eq(t,e.value);case"in":return Array.isArray(e.value)&&e.value.some(o=>Array.isArray(t)?t.some(s=>eq(s,o)):eq(t,o));case"nin":return Array.isArray(e.value)&&!e.value.some(o=>Array.isArray(t)?t.some(s=>eq(s,o)):eq(t,o));case"prefix":return str(t).startsWith(str(e.value));case"suffix":return str(t).endsWith(str(e.value));case"domain":{const o=str(t).lastIndexOf("@"),s=(o===-1?str(t):str(t).slice(o+1)).toLowerCase().replace(/\.$/,""),i=str(e.value).toLowerCase().replace(/^\./,"").replace(/\.$/,"");return!!i&&(s===i||s.endsWith("."+i))}case"contains":return Array.isArray(t)?t.some(o=>eq(o,e.value)):str(t).includes(str(e.value));case"hastoken":{const o=str(e.value);return Array.isArray(t)?t.some(s=>eq(s,e.value)):str(t).split(/[\s,]+/).filter(Boolean).includes(o)}case"regex":{const o=compileRe(str(e.value)),s=str(t);if(!o||s.length>exports.MAX_REGEX_LENGTH)throw new Indeterminate;return o.test(s)}case"gt":return Number(t)>Number(e.value);case"lt":return Number(t)<Number(e.value);case"cidr":return matchCidr(str(t),str(e.value));default:return!1}}l(evalCondition,"evalCondition"),a(evalCondition,"evalCondition");function evalNode(e,r){if(!isGroup(e))return evalCondition(e,r);const t=Array.isArray(e.all)&&e.all.length?e.all:void 0,n=Array.isArray(e.any)&&e.any.length?e.any:void 0,o=e.not&&Object.keys(e.not).length?e.not:void 0;return o&&evalNode(o,r)||t&&!t.every(s=>evalNode(s,r))||n&&!n.some(s=>evalNode(s,r))?!1:!!(t||n||o)}l(evalNode,"evalNode"),a(evalNode,"evalNode");function evalRule(e,r){try{return evalNode(e,r)}catch(t){if(t instanceof Indeterminate)return!1;throw t}}l(evalRule,"evalRule"),a(evalRule,"evalRule");function pickTargetedVersion(e,r){for(const t of e)if(evalRule(t.when,r))return{version:t.version,...t.name?{rule:t.name}:{}}}l(pickTargetedVersion,"pickTargetedVersion"),a(pickTargetedVersion,"pickTargetedVersion");function fnv1a(e){let r=2166136261;for(let t=0;t<e.length;t++)r^=e.charCodeAt(t),r=Math.imul(r,16777619);return r>>>0}l(fnv1a,"fnv1a"),a(fnv1a,"fnv1a");function bucketByWeight(e,r){const t=r.reduce((s,i)=>s+Math.max(0,i),0);if(t<=0||r.length===0)return 0;const n=fnv1a(e)%1e4;let o=0;for(let s=0;s<r.length;s++)if(o+=Math.max(0,r[s])/t*1e4,n<o)return s;return r.length-1}l(bucketByWeight,"bucketByWeight"),a(bucketByWeight,"bucketByWeight");
|
|
@@ -18,6 +18,9 @@ export interface JwtConfig {
|
|
|
18
18
|
audience?: string[];
|
|
19
19
|
/** Accept any `Bearer <anything>` on a `jwt` route when no verifier is wired. Opt-in, weak. */
|
|
20
20
|
presenceOnly: boolean;
|
|
21
|
+
/** `LENSMCP_GW_JWT_ALLOW_ANY_AUD=1`: run a verifier with no audience — tokens minted for ANY application of the
|
|
22
|
+
* IdP pass the edge. An explicit, named waiver; without it such a verifier refuses to boot (PG3-06). */
|
|
23
|
+
allowAnyAudience: boolean;
|
|
21
24
|
}
|
|
22
25
|
export interface GatewayEnvConfig {
|
|
23
26
|
/** Bind ports: explicit `LENSMCP_GW_PORTS`, else the platform `PORT` contract, else []. */
|
|
@@ -52,9 +55,25 @@ export interface GatewayEnvConfig {
|
|
|
52
55
|
healthCheckEnabled: boolean;
|
|
53
56
|
jwt: JwtConfig;
|
|
54
57
|
mtlsFromRedis: boolean;
|
|
58
|
+
/** `LENSMCP_GW_INTERNAL_PEERS` — networks allowed to reach `internal.<host>` routes (PG3-12). */
|
|
59
|
+
internalPeers: string[];
|
|
60
|
+
/** `LENSMCP_GW_WS_MAX_PENDING_PER_IP` / `LENSMCP_GW_WS_MAX_TUNNELS_PER_SERVICE` (PG3-20). */
|
|
61
|
+
upgrades: NonNullable<ProdGatewayOptions['upgrades']>;
|
|
55
62
|
}
|
|
56
63
|
/** Parse everything the gateway can decide from the environment alone. Pure. */
|
|
57
64
|
export declare function parseGatewayEnv(env: NodeJS.ProcessEnv): GatewayEnvConfig;
|
|
65
|
+
/**
|
|
66
|
+
* What the identity edge is missing to bind a token to THIS API (PG3-06). `errors` refuse boot; `warnings` print.
|
|
67
|
+
*
|
|
68
|
+
* Signature verification alone answers "signed by this IdP", not "issued for this API": against a multi-application
|
|
69
|
+
* IdP tenant (a Frontegg environment, an Auth0 tenant, Entra) any token the JWKS signs — another app's, a
|
|
70
|
+
* client-credentials token for a different API — passed a `jwt` route, and the shipped example env left both
|
|
71
|
+
* restrictions commented out. A verifier without an audience now needs the named waiver.
|
|
72
|
+
*/
|
|
73
|
+
export declare function jwtBootProblems(jwt: JwtConfig): {
|
|
74
|
+
errors: string[];
|
|
75
|
+
warnings: string[];
|
|
76
|
+
};
|
|
58
77
|
/**
|
|
59
78
|
* Worker processes for multi-core. `auto`/`max`/`0` ⇒ one per core; anything unparseable or
|
|
60
79
|
* non-positive ⇒ 1, so a typo runs a single healthy gateway rather than none.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var x=Object.defineProperty;var e=(_,t)=>x(_,"name",{value:t,configurable:!0});var y=Object.defineProperty,i=e((_,t)=>y(_,"name",{value:t,configurable:!0}),"i");Object.defineProperty(exports,"__esModule",{value:!0}),exports.parseGatewayEnv=parseGatewayEnv,exports.jwtBootProblems=jwtBootProblems,exports.redisLimiterConfigured=redisLimiterConfigured,exports.perWorkerLimit=perWorkerLimit,exports.workerCount=workerCount,exports.finalizeUpstreamTls=finalizeUpstreamTls,exports.finalizeUpstreamH2=finalizeUpstreamH2;const node_os_1=require("node:os"),num=i(_=>{if(_===void 0||_.trim()==="")return;const t=Number(_);return Number.isFinite(t)?t:void 0},"num"),csv=i(_=>(_??"").split(",").map(t=>t.trim()).filter(Boolean),"csv"),flag=i(_=>_==="1","flag");function parseGatewayEnv(_){const t=csv(_.LENSMCP_GW_PORTS??_.PORT).map(Number).filter(N=>Number.isFinite(N)&&N>=0&&N<=65535),E=Math.max(0,Math.floor(num(_.LENSMCP_GW_TRUST_PROXY)??0)),r={},a=_.LENSMCP_GW_UPSTREAM_TLS_VERIFY;a==="1"?r.rejectUnauthorized=!0:a==="0"&&(r.rejectUnauthorized=!1),flag(_.LENSMCP_GW_UPSTREAM_H2)&&(r.allowH2=!0);const C=num(_.LENSMCP_GW_UNDICI_CONNECTIONS);C!==void 0&&(r.connections=C);const P=num(_.LENSMCP_GW_UNDICI_BODY_TIMEOUT_MS);P!==void 0&&(r.bodyTimeout=P);const T=num(_.LENSMCP_GW_UNDICI_PIPELINING);T!==void 0&&(r.pipelining=T);const W=num(_.LENSMCP_GW_UNDICI_HEADERS_TIMEOUT_MS);W!==void 0&&(r.headersTimeout=W);const u=num(_.LENSMCP_GW_UNDICI_KEEPALIVE_MS);u!==void 0&&(r.keepAliveTimeout=u);const o={},I=num(_.LENSMCP_GW_KEEPALIVE_MS);I!==void 0&&(o.keepAliveTimeout=I);const d=num(_.LENSMCP_GW_REQUEST_TIMEOUT_MS);d!==void 0&&(o.requestTimeout=d);const c=num(_.LENSMCP_GW_HEADERS_TIMEOUT_MS);c!==void 0&&(o.headersTimeout=c);const G=num(_.LENSMCP_GW_MAX_HEADERS);G!==void 0&&(o.maxHeadersCount=G);const l=num(_.LENSMCP_GW_CONN_CHECK_MS);l!==void 0&&(o.connectionsCheckingInterval=l);const A=num(_.LENSMCP_GW_MAX_CONNECTIONS);A!==void 0&&(o.maxConnections=A);const R=num(_.LENSMCP_GW_BODY_STALL_MS);R!==void 0&&(o.bodyStallMs=R);const S=_.LENSMCP_GW_COOKIE_SECRET,n=_.LENSMCP_GW_COOKIE_NAME,s=_.LENSMCP_GW_COOKIE_DOMAIN,m=num(_.LENSMCP_GW_COOKIE_MAXAGE),U=S||n||s?{...n?{name:n}:{},...S?{secret:S}:{},...s?{domain:s}:{},...m!==void 0?{maxAge:m}:{}}:void 0,p=num(_.LENSMCP_GW_RATE_LIMIT),M=_.LENSMCP_GW_RATE_LIMIT_REDIS_URL,v=num(_.LENSMCP_GW_RATE_LIMIT_TIMEOUT_MS),O=p===void 0?void 0:{limit:p,windowMs:num(_.LENSMCP_GW_RATE_WINDOW_MS)??6e4,wantRedis:flag(_.LENSMCP_GW_RATE_LIMIT_REDIS)||!!M,...M?{dedicatedUrl:M}:{},...v!==void 0?{timeoutMs:v}:{},failClosed:flag(_.LENSMCP_GW_RATE_LIMIT_FAIL_CLOSED)},f=_.LENSMCP_GW_HEALTH_PATH,h=num(_.LENSMCP_GW_HEALTH_INTERVAL_MS),D=num(_.LENSMCP_GW_HEALTH_TIMEOUT_MS),H=flag(_.LENSMCP_GW_HEALTH_CHECK),w=H?{...f?{path:f}:{},...h!==void 0?{intervalMs:h}:{},...D!==void 0?{timeoutMs:D}:{}}:void 0,L=num(_.LENSMCP_GW_TRAFFIC_FLUSH_MS),b=csv(_.LENSMCP_GW_JWT_AUD),k=_.LENSMCP_GW_HOST?.trim();return{ports:t,...k?{host:k}:{},workers:workerCount(_),undici:r,server:o,...num(_.LENSMCP_GW_UPSTREAM_RETRIES)!==void 0?{upstreamRetries:num(_.LENSMCP_GW_UPSTREAM_RETRIES)}:{},trustProxyIp:E>0,trustProxyHops:E,...U?{cookie:U}:{},attributeHeaders:csv(_.LENSMCP_GW_ATTR_HEADERS),..._.LENSMCP_GW_CLIENT_IP_HEADER?{clientIpHeader:_.LENSMCP_GW_CLIENT_IP_HEADER}:{},clientIpTrustedProxies:csv(_.LENSMCP_GW_CLIENT_IP_TRUSTED_PROXIES),..._.LENSMCP_GW_UID_HEADER?{uidHeader:_.LENSMCP_GW_UID_HEADER}:{},accessLog:flag(_.LENSMCP_GW_ACCESS_LOG),statusEnabled:flag(_.LENSMCP_GW_STATUS),..._.LENSMCP_GW_STATUS_TOKEN?{statusToken:_.LENSMCP_GW_STATUS_TOKEN}:{},metricsEnabled:flag(_.LENSMCP_GW_METRICS),statusTtlSec:Math.max(3,Math.ceil((L??5e3)/1e3*3)),...L!==void 0?{trafficFlushMs:L}:{},...O?{rateLimit:O}:{},...w?{health:w}:{},healthCheckEnabled:H,jwt:{..._.LENSMCP_GW_JWKS_URL?{jwksUrl:_.LENSMCP_GW_JWKS_URL}:{},..._.LENSMCP_GW_JWT_SECRET?{secret:_.LENSMCP_GW_JWT_SECRET}:{},..._.LENSMCP_GW_JWT_ISS?{issuer:_.LENSMCP_GW_JWT_ISS}:{},...b.length?{audience:b}:{},presenceOnly:flag(_.LENSMCP_GW_JWT_PRESENCE_ONLY),allowAnyAudience:flag(_.LENSMCP_GW_JWT_ALLOW_ANY_AUD)},mtlsFromRedis:flag(_.LENSMCP_GW_MTLS_FROM_REDIS),internalPeers:csv(_.LENSMCP_GW_INTERNAL_PEERS),upgrades:{...num(_.LENSMCP_GW_WS_MAX_PENDING_PER_IP)!==void 0?{maxPendingPerClient:num(_.LENSMCP_GW_WS_MAX_PENDING_PER_IP)}:{},...num(_.LENSMCP_GW_WS_MAX_TUNNELS_PER_SERVICE)!==void 0?{maxTunnelsPerService:num(_.LENSMCP_GW_WS_MAX_TUNNELS_PER_SERVICE)}:{}}}}e(parseGatewayEnv,"parseGatewayEnv"),i(parseGatewayEnv,"parseGatewayEnv");function jwtBootProblems(_){const t=[],E=[];return _.jwksUrl||_.secret?(_.audience?.length||(_.allowAnyAudience?E.push("LENSMCP_GW_JWT_ALLOW_ANY_AUD=1 \u2014 tokens minted for ANY application of this IdP are accepted on jwt routes"):t.push("a JWT verifier is configured without LENSMCP_GW_JWT_AUD \u2014 set the audience this API's tokens carry (or LENSMCP_GW_JWT_ALLOW_ANY_AUD=1 to accept tokens minted for any application)")),_.issuer||E.push("LENSMCP_GW_JWT_ISS is not set \u2014 tokens from any issuer the verifier's keys sign are accepted"),{errors:t,warnings:E}):{errors:t,warnings:E}}e(jwtBootProblems,"jwtBootProblems"),i(jwtBootProblems,"jwtBootProblems");function redisLimiterConfigured(_){return _.LENSMCP_GW_RATE_LIMIT_REDIS_URL?!0:flag(_.LENSMCP_GW_RATE_LIMIT_REDIS)&&!!_.LENSMCP_GW_REDIS_URL}e(redisLimiterConfigured,"redisLimiterConfigured"),i(redisLimiterConfigured,"redisLimiterConfigured");function perWorkerLimit(_,t){if(!Number.isFinite(_)||_<=0)return _;const E=Number.isFinite(t)&&t>1?Math.floor(t):1;return Math.max(1,Math.floor(_/E))}e(perWorkerLimit,"perWorkerLimit"),i(perWorkerLimit,"perWorkerLimit");function workerCount(_){const t=(_.LENSMCP_GW_WORKERS??"1").trim().toLowerCase();if(t==="auto"||t==="max"||t==="0")return Math.max(1,(0,node_os_1.cpus)().length);const E=Math.floor(Number(t));return Number.isFinite(E)&&E>0?E:1}e(workerCount,"workerCount"),i(workerCount,"workerCount");function finalizeUpstreamTls(_){return _.ca&&_.rejectUnauthorized===void 0?(_.rejectUnauthorized=!0,{autoEnabled:!0}):{autoEnabled:!1}}e(finalizeUpstreamTls,"finalizeUpstreamTls"),i(finalizeUpstreamTls,"finalizeUpstreamTls");function finalizeUpstreamH2(_,t){return _.cert&&_.key?(t.LENSMCP_GW_UPSTREAM_H2!=="0"&&(_.allowH2=!0),!0):!1}e(finalizeUpstreamH2,"finalizeUpstreamH2"),i(finalizeUpstreamH2,"finalizeUpstreamH2");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var q=Object.defineProperty;var h=(d,a)=>q(d,"name",{value:a,configurable:!0});var b=Object.defineProperty,u=h((d,a)=>b(d,"name",{value:a,configurable:!0}),"u");Object.defineProperty(exports,"__esModule",{value:!0}),exports.createApp=createApp;const tslib_1=require("tslib"),fastify_1=tslib_1.__importDefault(require("fastify")),reply_from_1=tslib_1.__importDefault(require("@fastify/reply-from")),edge_1=require("./edge"),trust_1=require("./trust"),body_stall_1=require("./body-stall"),access_log_1=require("./access-log");function createApp(d){const{rt:a,obs:l,cors:C,hooks:y,handler:m,upgrade:x,reqState:v,spanByReq:g,ctxByReq:T}=d,e=a.opts;return{buildApp:u(async()=>{const O=e.server?.keepAliveTimeout??62e4,s=(0,fastify_1.default)({logger:!1,keepAliveTimeout:O,requestTimeout:e.server?.requestTimeout??0,...e.server?.connectionTimeout!==void 0?{connectionTimeout:e.server.connectionTimeout}:{},...e.trustProxyIp?{trustProxy:Math.max(1,Math.floor(e.trustProxyHops??1))}:{},...e.tls?{https:{key:e.tls.key,cert:e.tls.cert}}:{}});s.server.headersTimeout=e.server?.headersTimeout??6e4,e.server?.connectionsCheckingInterval!==void 0&&(s.server.connectionsCheckingInterval=e.server.connectionsCheckingInterval),e.server?.maxHeadersCount!==void 0&&(s.server.maxHeadersCount=e.server.maxHeadersCount),e.server?.maxConnections!==void 0&&(s.server.maxConnections=e.server.maxConnections),s.removeAllContentTypeParsers(),s.addContentTypeParser("*",(o,t,n)=>n(null,t)),await s.register(reply_from_1.default,{disableRequestLogging:!0,undici:{connections:e.undici?.connections??256,pipelining:e.undici?.pipelining??1,keepAliveTimeout:e.undici?.keepAliveTimeout??6e4,bodyTimeout:e.undici?.bodyTimeout??0,headersTimeout:e.undici?.headersTimeout??6e4,...e.undici?.allowH2?{allowH2:!0}:{},connect:{rejectUnauthorized:e.undici?.rejectUnauthorized??!1,...e.undici?.cert?{cert:e.undici.cert}:{},...e.undici?.key?{key:e.undici.key}:{},...e.undici?.ca?{ca:e.undici.ca}:{}}}}),s.get("/livez",(o,t)=>{t.header("cache-control",edge_1.NO_STORE).type("text/plain").send("ok")});const f=e.undici?.headersTimeout??6e4,k=e.server?.readyStallMs??(f>0?f+5e3:0);s.get("/readyz",(o,t)=>{const n=a.table.routes.length>0,r=n&&k>0&&a.upstreamWaits.oldestMs()>k,i=n&&!r;t.code(i?200:503).header("cache-control",edge_1.NO_STORE).type("text/plain").send(i?"ready":n?"upstream pool stalled":"no routes loaded")});const _=u(o=>(0,edge_1.tokenMatches)(o.query?.token??(0,edge_1.hdr)(o.raw.headers["x-status-token"]),e.statusToken),"opToken");s.get("/statusz",(o,t)=>{if(!e.statusEndpoint||!e.statusToken){t.code(404).header("cache-control",edge_1.NO_STORE).type("text/plain").send("not found");return}if(!_(o)){t.code(401).header("cache-control",edge_1.NO_STORE).type("text/plain").send("unauthorized");return}t.header("cache-control",edge_1.NO_STORE).type("application/json").send(JSON.stringify({generatedAt:Date.now(),services:l.buildStatusSnapshot(),endpoints:e.healthChecker?.snapshot()??[]}))}),s.get("/metricsz",(o,t)=>{if(!e.metrics||!e.statusToken){t.code(404).header("cache-control",edge_1.NO_STORE).type("text/plain").send("not found");return}if(!_(o)){t.code(401).header("cache-control",edge_1.NO_STORE).type("text/plain").send("unauthorized");return}t.header("cache-control",edge_1.NO_STORE).type("application/json").send(JSON.stringify(e.metrics.snapshot()))});const p=(0,body_stall_1.createBodyStallGuard)(e.server?.bodyStallMs??6e4);return s.addHook("onClose",(o,t)=>{p.stop(),t()}),s.addHook("onRequest",(o,t,n)=>{(0,trust_1.stripTrust)(o.raw),(0,trust_1.stripUnforwardable)(o.raw),p.arm(o.raw),p.armResponse(t.raw),n()}),s.addHook("onSend",(o,t,n,r)=>{C.applyResponseCors(o,t),r(null,n)}),s.addHook("onResponse",(o,t,n)=>{const r=v.get(o);r&&(l.recordEdge(r.route,Date.now()-r.startedAt,t.statusCode??0,r.caller,r.version),l.finish(r.trace,r.route.service,t.statusCode??0,{upstream:r.upLabel,...r.version?{version:r.version}:{},...r.caller?{caller:r.caller}:{}}),v.delete(o));const i=g.get(o);i&&(e.tracing.end(i,t.statusCode??0,{...r?.upLabel?{"upstream.url":r.upLabel}:{},...r?.version?{"lensmcp.version":r.version}:{}}),g.delete(o)),e.metrics?.recordRequest(t.statusCode??0),a.accessLog&&(0,access_log_1.logAccess)(o,t,r);const c=T.get(o);c&&(c.status=t.statusCode??0,y.has("onResponse")&&y.run("onResponse",c),T.delete(o)),n()}),s.setErrorHandler((o,t,n)=>{const r=o,i=r.message??String(o);l.emit("error",`gateway request error: ${i}`,`gateway-error:${r.code??"exception"}`,{kind:"gateway-request-error",error:i,...r.code?{code:r.code}:{}});const c=typeof r.statusCode=="number"&&r.statusCode>=400&&r.statusCode<600?r.statusCode:500;(0,edge_1.sendError)(n,t.raw,c,c===400?"bad_request":"internal")}),s.setNotFoundHandler((o,t)=>{(0,edge_1.sendError)(t,o.raw,404,"not_found","No gateway route for this hostname.")}),s.all("/",m),s.all("/*",m),s.server.on("upgrade",x),s},"buildApp")}}h(createApp,"createApp"),u(createApp,"createApp");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var f=Object.defineProperty;var l=(
|
|
1
|
+
"use strict";var f=Object.defineProperty;var l=(a,e)=>f(a,"name",{value:e,configurable:!0});var m=Object.defineProperty,d=l((a,e)=>m(a,"name",{value:e,configurable:!0}),"d");Object.defineProperty(exports,"__esModule",{value:!0}),exports.createEdgeAuth=createEdgeAuth;const manifest_1=require("../manifest"),trust_1=require("./trust");function createEdgeAuth(a,e,c,k){return{internal:d((o,i,u)=>{const r=o.headers["x-api-key"],n=typeof r=="string"?r:Array.isArray(r)?r[0]:void 0,t=n?a.keyToProject.get(n):void 0;return t?(o.headers["x-api-key-id"]=t,delete o.headers["x-api-key"],e.step(u,"auth",{mode:"x-api-key",ok:!0,caller:t}),{ok:!0,caller:t}):(e.step(u,"auth",{mode:"x-api-key",ok:!1}),{ok:!1,status:401,reason:"unauthorized",detail:"Invalid or missing x-api-key for internal route."})},"internal"),public:d((o,i,u,r,n,t)=>{const h=i.policy?void 0:a.table.manifestByService.get(i.service),p=o.method??"GET",s=i.policy?(0,manifest_1.authRuleFor)(i.policy,u,p):h?(0,manifest_1.authRuleForPath)(h,u,p,!1):{mode:i.auth};if(s.mode==="public")return e.step(t,"auth",{mode:"public"}),{ok:!0};if(s.mode!=="jwt")return e.step(t,"auth",{mode:String(s.mode),ok:!1,reason:"unsupported-mode"}),{ok:!1,status:401,reason:"unauthorized",detail:"Unauthorized: this route's auth mode is not served at the edge"};if(a.opts.identify){if(!r)return e.step(t,"auth",{mode:"jwt",ok:!1}),{ok:!1,status:401,reason:"unauthorized",detail:"Unauthorized: invalid or missing token"}}else try{k("jwt",o)}catch(y){return e.step(t,"auth",{mode:"jwt",ok:!1,reason:y.message}),{ok:!1,status:401,reason:"unauthorized",detail:"Unauthorized: invalid or missing token"}}return s.rule&&(!r||!(0,manifest_1.evalRule)(s.rule,c.buildAttrs(o,n,r,void 0,u)))?(e.step(t,"authz",{ok:!1}),{ok:!1,status:403,reason:"forbidden",detail:"Forbidden: insufficient permission"}):(e.step(t,"auth",{mode:"jwt",ok:!0}),r&&(0,trust_1.stampIdentity)(o,r),{ok:!0})},"publicAuth")}}l(createEdgeAuth,"createEdgeAuth"),d(createEdgeAuth,"createEdgeAuth");
|