@lensmcp/cluster 1.25.78 → 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.
Files changed (135) hide show
  1. package/build-scope-patterns.d.ts +1 -11
  2. package/build-scope-patterns.js +1 -1
  3. package/create-webpack-prod.d.ts +1 -27
  4. package/create-webpack-prod.js +1 -1
  5. package/executors/build/build.impl.js +1 -1
  6. package/executors/gateway/daemon.d.ts +43 -0
  7. package/executors/gateway/daemon.js +1 -0
  8. package/executors/gateway/gateway.lib.d.ts +1 -1
  9. package/executors/gateway/gateway.lib.js +1 -1
  10. package/executors/gateway/jwks-verify.d.ts +1 -79
  11. package/executors/gateway/jwks-verify.js +1 -1
  12. package/executors/gateway/main.rollout.d.ts +2 -1
  13. package/executors/gateway/main.rollout.js +1 -24
  14. package/executors/gateway/manifest.d.ts +1 -418
  15. package/executors/gateway/manifest.js +1 -1
  16. package/executors/gateway/prod-runtime/trust.d.ts +1 -80
  17. package/executors/gateway/prod-runtime/trust.js +1 -1
  18. package/executors/gateway/rate-limit.d.ts +1 -81
  19. package/executors/gateway/rate-limit.js +1 -18
  20. package/executors/gateway/runtime/auth.d.ts +1 -1
  21. package/executors/gateway/runtime/auth.js +1 -1
  22. package/executors/gateway/runtime/dev-auth.d.ts +3 -2
  23. package/executors/gateway/runtime/dev-auth.js +1 -1
  24. package/executors/gateway/runtime/discovery.js +1 -1
  25. package/executors/gateway/runtime/edge.d.ts +2 -2
  26. package/executors/gateway/runtime/edge.js +1 -1
  27. package/executors/gateway/runtime/handler.js +1 -1
  28. package/executors/gateway/runtime/internal-fetch.d.ts +1 -1
  29. package/executors/gateway/runtime/lens-children.js +1 -1
  30. package/executors/gateway/runtime/lens-modules.d.ts +13 -0
  31. package/executors/gateway/runtime/lens-modules.js +1 -0
  32. package/executors/gateway/runtime/lifecycle.js +1 -1
  33. package/executors/gateway/runtime/observability.js +1 -1
  34. package/executors/gateway/runtime/proxy.js +1 -1
  35. package/executors/gateway/runtime/route-registry.js +1 -1
  36. package/executors/gateway/runtime/serve-launch.d.ts +27 -0
  37. package/executors/gateway/runtime/serve-launch.js +3 -3
  38. package/executors/gateway/runtime/server.d.ts +1 -1
  39. package/executors/gateway/runtime/server.js +2 -2
  40. package/executors/gateway/runtime/services-decl.d.ts +24 -0
  41. package/executors/gateway/runtime/services-decl.js +1 -0
  42. package/executors/gateway/runtime/shared-build.d.ts +2 -2
  43. package/executors/gateway/runtime/shared-build.js +3 -3
  44. package/executors/gateway/runtime/types.d.ts +9 -3
  45. package/executors/gateway/runtime/upgrade.js +1 -1
  46. package/executors/gateway/runtime/workspace-auth.d.ts +1 -1
  47. package/executors/gateway/runtime/workspace-auth.js +1 -1
  48. package/executors/gateway/runtime/workspace-middleware.d.ts +2 -2
  49. package/executors/gateway/runtime/workspace-middleware.js +1 -1
  50. package/executors/serve/lens-run.d.ts +6 -0
  51. package/executors/serve/lens-run.js +1 -0
  52. package/executors/serve/schema.d.ts +2 -0
  53. package/executors/serve/schema.json +4 -0
  54. package/executors/serve/serve.impl.js +1 -1
  55. package/executors/trust/run.d.ts +19 -0
  56. package/executors/trust/run.js +1 -0
  57. package/executors/trust/trust.impl.js +5 -5
  58. package/gateway.d.ts +7 -19
  59. package/gateway.js +1 -1
  60. package/gc-notice.d.ts +3 -1
  61. package/gc-notice.js +1 -1
  62. package/main.devserver.js +7 -7
  63. package/package.json +6 -34
  64. package/pod-memory.d.ts +19 -2
  65. package/pod-memory.js +1 -1
  66. package/tsgo-check-plugin.d.ts +3 -2
  67. package/tsgo-check-plugin.js +3 -3
  68. package/typecheck-bus.d.ts +17 -0
  69. package/typecheck-bus.js +4 -3
  70. package/executors/gateway/body-stall.d.ts +0 -62
  71. package/executors/gateway/body-stall.js +0 -1
  72. package/executors/gateway/canonical-path.d.ts +0 -65
  73. package/executors/gateway/canonical-path.js +0 -1
  74. package/executors/gateway/client-ip.d.ts +0 -82
  75. package/executors/gateway/client-ip.js +0 -1
  76. package/executors/gateway/gateway-errors.d.ts +0 -43
  77. package/executors/gateway/gateway-errors.js +0 -1
  78. package/executors/gateway/health-check.d.ts +0 -52
  79. package/executors/gateway/health-check.js +0 -1
  80. package/executors/gateway/jwt-claims.d.ts +0 -51
  81. package/executors/gateway/jwt-claims.js +0 -1
  82. package/executors/gateway/main.prod-gateway.d.ts +0 -1
  83. package/executors/gateway/main.prod-gateway.js +0 -2
  84. package/executors/gateway/metrics.d.ts +0 -36
  85. package/executors/gateway/metrics.js +0 -1
  86. package/executors/gateway/otel-tracing.d.ts +0 -46
  87. package/executors/gateway/otel-tracing.js +0 -1
  88. package/executors/gateway/prod-config.d.ts +0 -130
  89. package/executors/gateway/prod-config.js +0 -1
  90. package/executors/gateway/prod-gateway.lib.d.ts +0 -19
  91. package/executors/gateway/prod-gateway.lib.js +0 -1
  92. package/executors/gateway/prod-runtime/access-log.d.ts +0 -8
  93. package/executors/gateway/prod-runtime/access-log.js +0 -1
  94. package/executors/gateway/prod-runtime/app.d.ts +0 -30
  95. package/executors/gateway/prod-runtime/app.js +0 -1
  96. package/executors/gateway/prod-runtime/auth.d.ts +0 -29
  97. package/executors/gateway/prod-runtime/auth.js +0 -1
  98. package/executors/gateway/prod-runtime/body-stall.d.ts +0 -5
  99. package/executors/gateway/prod-runtime/body-stall.js +0 -1
  100. package/executors/gateway/prod-runtime/cors.d.ts +0 -18
  101. package/executors/gateway/prod-runtime/cors.js +0 -1
  102. package/executors/gateway/prod-runtime/edge.d.ts +0 -44
  103. package/executors/gateway/prod-runtime/edge.js +0 -1
  104. package/executors/gateway/prod-runtime/handler.d.ts +0 -33
  105. package/executors/gateway/prod-runtime/handler.js +0 -1
  106. package/executors/gateway/prod-runtime/hooks.d.ts +0 -19
  107. package/executors/gateway/prod-runtime/hooks.js +0 -1
  108. package/executors/gateway/prod-runtime/observability.d.ts +0 -24
  109. package/executors/gateway/prod-runtime/observability.js +0 -1
  110. package/executors/gateway/prod-runtime/rollout.d.ts +0 -33
  111. package/executors/gateway/prod-runtime/rollout.js +0 -1
  112. package/executors/gateway/prod-runtime/route-limits.d.ts +0 -30
  113. package/executors/gateway/prod-runtime/route-limits.js +0 -1
  114. package/executors/gateway/prod-runtime/routing.d.ts +0 -3
  115. package/executors/gateway/prod-runtime/routing.js +0 -1
  116. package/executors/gateway/prod-runtime/server.d.ts +0 -17
  117. package/executors/gateway/prod-runtime/server.js +0 -1
  118. package/executors/gateway/prod-runtime/types.d.ts +0 -335
  119. package/executors/gateway/prod-runtime/types.js +0 -1
  120. package/executors/gateway/prod-runtime/upgrade.d.ts +0 -23
  121. package/executors/gateway/prod-runtime/upgrade.js +0 -16
  122. package/executors/gateway/prod-runtime/upstream-errors.d.ts +0 -33
  123. package/executors/gateway/prod-runtime/upstream-errors.js +0 -1
  124. package/executors/gateway/prod-runtime/upstream.d.ts +0 -14
  125. package/executors/gateway/prod-runtime/upstream.js +0 -1
  126. package/executors/gateway/providers-prod.d.ts +0 -54
  127. package/executors/gateway/providers-prod.js +0 -1
  128. package/executors/gateway/registry-source.d.ts +0 -68
  129. package/executors/gateway/registry-source.js +0 -2
  130. package/executors/gateway/rollout-ops.d.ts +0 -53
  131. package/executors/gateway/rollout-ops.js +0 -2
  132. package/executors/gateway/ssrf-guard.d.ts +0 -96
  133. package/executors/gateway/ssrf-guard.js +0 -1
  134. package/executors/gateway/workspace-auth.d.ts +0 -100
  135. package/executors/gateway/workspace-auth.js +0 -1
@@ -1,53 +0,0 @@
1
- /**
2
- * Rollout config operations — the brain behind `lensmcp rollout` (the CD helper).
3
- * PURE: each op takes the rollout table and returns a NEW one, validating and
4
- * throwing on bad input. The CLI (`main.rollout.ts`) wraps these with file IO +
5
- * atomic write so pipelines never hand-edit JSON (and never write a half file).
6
- *
7
- * Works on the targeted/cohort shape (`{svc:{rules?,cohorts}}` or `{svc:[cohorts]}`);
8
- * a flat endpoint list (`{svc:[url,…]}`) is rejected with a clear message — convert
9
- * it to cohorts first. See docs/design/targeted-rollout.md.
10
- */
11
- import type { RolloutTable } from './providers-prod';
12
- import type { TargetRule } from './manifest';
13
- export type RolloutOp = {
14
- kind: 'add-cohort';
15
- service: string;
16
- version: string;
17
- weight: number;
18
- urls: string[];
19
- } | {
20
- kind: 'set-weight';
21
- service: string;
22
- version: string;
23
- weight: number;
24
- } | {
25
- kind: 'remove-cohort';
26
- service: string;
27
- version: string;
28
- } | {
29
- kind: 'promote';
30
- service: string;
31
- version: string;
32
- } | {
33
- kind: 'abort';
34
- service: string;
35
- version: string;
36
- } | {
37
- kind: 'add-rule';
38
- service: string;
39
- rule: TargetRule;
40
- } | {
41
- kind: 'remove-rule';
42
- service: string;
43
- name: string;
44
- };
45
- /** Apply one operation to the rollout table; returns a NEW table. Throws on invalid input. */
46
- export declare function applyRolloutOp(config: RolloutTable, op: RolloutOp): RolloutTable;
47
- /** Human-readable status for one service (or all). Read-only. */
48
- export declare function summarizeRollout(config: RolloutTable, service?: string): string;
49
- /** Parse CLI argv (after the config-file path) into an op, a status request, or throw a usage error. */
50
- export declare function parseRolloutCommand(argv: string[]): {
51
- op?: RolloutOp;
52
- status?: string | undefined;
53
- };
@@ -1,2 +0,0 @@
1
- "use strict";var d=Object.defineProperty;var c=(n,r)=>d(n,"name",{value:r,configurable:!0});var h=Object.defineProperty,i=c((n,r)=>h(n,"name",{value:r,configurable:!0}),"i");Object.defineProperty(exports,"__esModule",{value:!0}),exports.applyRolloutOp=applyRolloutOp,exports.summarizeRollout=summarizeRollout,exports.parseRolloutCommand=parseRolloutCommand;const RULE_OPS=new Set(["eq","ne","in","nin","prefix","suffix","contains","regex","exists","gt","lt","cidr"]),clone=i(n=>JSON.parse(JSON.stringify(n)),"clone");function asSpec(n,r){if(r===void 0)return{rules:[],cohorts:[]};if(Array.isArray(r)){if(r.length&&typeof r[0]=="string")throw new Error(`service "${n}" is a flat endpoint list; convert it to cohorts first (e.g. add-cohort)`);return{rules:[],cohorts:r}}return{rules:r.rules??[],cohorts:r.cohorts??[]}}c(asSpec,"asSpec"),i(asSpec,"asSpec");const findCohort=i((n,r)=>n.cohorts.find(o=>o.version===r),"findCohort");function reqWeight(n){if(!Number.isFinite(n)||n<0)throw new Error(`weight must be a number \u2265 0 (got ${n})`);return n}c(reqWeight,"reqWeight"),i(reqWeight,"reqWeight");function applyRolloutOp(n,r){const o=clone(n),e=asSpec(r.service,o[r.service]);switch(r.kind){case"add-cohort":{if(findCohort(e,r.version))throw new Error(`cohort "${r.version}" already exists on "${r.service}" \u2014 use set-weight`);if(!r.urls.length)throw new Error("add-cohort needs at least one upstream url");e.cohorts.push({version:r.version,weight:reqWeight(r.weight),urls:r.urls.slice()});break}case"set-weight":{const t=findCohort(e,r.version);if(!t)throw new Error(`no cohort "${r.version}" on "${r.service}"`);t.weight=reqWeight(r.weight);break}case"remove-cohort":{if(!findCohort(e,r.version))throw new Error(`no cohort "${r.version}" on "${r.service}"`);e.cohorts=e.cohorts.filter(t=>t.version!==r.version);break}case"promote":{if(!findCohort(e,r.version))throw new Error(`no cohort "${r.version}" on "${r.service}"`);for(const t of e.cohorts)t.weight=t.version===r.version?100:0;break}case"abort":{const t=findCohort(e,r.version);if(!t)throw new Error(`no cohort "${r.version}" on "${r.service}"`);t.weight=0;break}case"add-rule":{validateRule(r.rule),e.rules=[...(e.rules??[]).filter(t=>!r.rule.name||t.name!==r.rule.name),r.rule];break}case"remove-rule":{const t=(e.rules??[]).length;if(e.rules=(e.rules??[]).filter(s=>s.name!==r.name),e.rules.length===t)throw new Error(`no rule named "${r.name}" on "${r.service}"`);break}}return o[r.service]=e.rules&&e.rules.length?{rules:e.rules,cohorts:e.cohorts}:e.cohorts,o}c(applyRolloutOp,"applyRolloutOp"),i(applyRolloutOp,"applyRolloutOp");function validateRule(n){if(!n||typeof n.version!="string"||!n.version)throw new Error("rule needs a non-empty version");if(!n.when||typeof n.when!="object")throw new Error("rule needs a `when` condition");const r=i(o=>{const e=o;if("all"in e||"any"in e||"not"in e){for(const t of["all","any"])Array.isArray(e[t])&&e[t].forEach(r);e.not&&r(e.not);return}if(typeof e.attr!="string"||!RULE_OPS.has(e.op))throw new Error(`invalid rule condition (attr/op): ${JSON.stringify(e)}`)},"walk");r(n.when)}c(validateRule,"validateRule"),i(validateRule,"validateRule");function summarizeRollout(n,r){const o=r?[r]:Object.keys(n);if(!o.length)return"(no services in rollout config)";const e=[];for(const t of o){const s=n[t];if(s===void 0){e.push(`${t}: (not present)`);continue}if(Array.isArray(s)&&s.length&&typeof s[0]=="string"){e.push(`${t}: flat LB \u2192 ${s.join(", ")}`);continue}const u=asSpec(t,s),l=u.cohorts.reduce((a,v)=>a+Math.max(0,v.weight),0)||1;e.push(`${t}:`);for(const a of u.cohorts)e.push(` \u2022 ${a.version.padEnd(16)} weight ${String(a.weight).padStart(3)} (${(Math.max(0,a.weight)/l*100).toFixed(0)}%) ${a.urls.length} url(s)`);for(const a of u.rules??[])e.push(` \u25B8 rule ${(a.name??"(unnamed)").padEnd(16)} \u2192 ${a.version} ${ruleSummary(a.when)}`)}return e.join(`
2
- `)}c(summarizeRollout,"summarizeRollout"),i(summarizeRollout,"summarizeRollout");function ruleSummary(n){const r=n;return"all"in r?"("+r.all.map(ruleSummary).join(" AND ")+")":"any"in r?"("+r.any.map(ruleSummary).join(" OR ")+")":"not"in r?"NOT "+ruleSummary(r.not):`${r.attr} ${r.op}${r.value!==void 0?" "+JSON.stringify(r.value):""}`}c(ruleSummary,"ruleSummary"),i(ruleSummary,"ruleSummary");function parseRolloutCommand(n){const[r,...o]=n,e=i((t,s)=>{if(o.length<t)throw new Error(`usage: ${r} ${s}`)},"need");switch(r){case"status":return{status:o[0]};case"add-cohort":return e(4,"<service> <version> <weight> <url> [url...]"),{op:{kind:"add-cohort",service:o[0],version:o[1],weight:Number(o[2]),urls:o.slice(3)}};case"set-weight":return e(3,"<service> <version> <weight>"),{op:{kind:"set-weight",service:o[0],version:o[1],weight:Number(o[2])}};case"remove-cohort":return e(2,"<service> <version>"),{op:{kind:"remove-cohort",service:o[0],version:o[1]}};case"promote":return e(2,"<service> <version>"),{op:{kind:"promote",service:o[0],version:o[1]}};case"abort":return e(2,"<service> <version>"),{op:{kind:"abort",service:o[0],version:o[1]}};case"add-rule":{e(6,"<service> <name> <attr> <op> <value> <version>");const t=o[3],s=o[4]??"",u=t==="in"||t==="nin"?s.split(",").map(l=>l.trim()).filter(Boolean):s;return{op:{kind:"add-rule",service:o[0],rule:{name:o[1],when:{attr:o[2],op:t,value:u},version:o[5]}}}}case"remove-rule":return e(2,"<service> <name>"),{op:{kind:"remove-rule",service:o[0],name:o[1]}};default:throw new Error(`unknown command "${r??""}". commands: status, add-cohort, set-weight, remove-cohort, promote, abort, add-rule, remove-rule`)}}c(parseRolloutCommand,"parseRolloutCommand"),i(parseRolloutCommand,"parseRolloutCommand");
@@ -1,96 +0,0 @@
1
- /**
2
- * SSRF guard for OUTBOUND fetches of a request- or config-supplied URL.
3
- *
4
- * The prod gateway today never fetches an attacker-controlled URL — upstreams
5
- * are pinned in the manifest, the JWKS URL is operator env, and reply-from /
6
- * undici do not chase redirects. This module exists so that the MOMENT a sink
7
- * IS added (a remote-MCP / OpenAPI schema import, a webhook callback, a
8
- * dynamically-discovered upstream — anything that fetches a URL it did not
9
- * author) there is a ready, tested guard to wrap it with, instead of a naive
10
- * `if (host === '127.0.0.1')` string check that the classic bypasses defeat.
11
- *
12
- * It defends the three canonical bypasses:
13
- * 1. DNS name that RESOLVES to an internal IP (`127.0.0.1.nip.io`, rebinding)
14
- * → we resolve the host and check the RESOLVED addresses, not the string.
15
- * 2. Redirect chase (`/redirect` 3xx → loopback) → `safeFetch` re-validates
16
- * EVERY hop with `redirect:'manual'`; it never blindly follows a Location.
17
- * 3. IPv4-mapped IPv6 loopback (`[::ffff:127.0.0.1]`, `[::ffff:7f00:1]`) →
18
- * `net.BlockList` normalizes mapped forms against the IPv4 rules.
19
- *
20
- * Residual TOCTOU: between the resolve-and-check and the socket connect, a
21
- * rebinding resolver could flip the record. Close it by pinning the connection
22
- * to the validated address(es) with `pinnedLookup()` (pass to
23
- * `new http.Agent({ lookup })` or an undici `connect:{ lookup }` dispatcher).
24
- *
25
- * Defaults are operator-overridable but FAIL CLOSED: anything unparseable, any
26
- * non-http(s) scheme, embedded credentials, an empty host, or a host that
27
- * resolves to no records is rejected.
28
- */
29
- import { BlockList } from 'node:net';
30
- import type { LookupAddress } from 'node:dns';
31
- /** Thrown for every blocked URL — carries a machine-readable `reason` and, when
32
- * the block was an address, the offending `address` (the resolved IP, not the
33
- * hostname, so logs show what the name actually pointed at). */
34
- export declare class SsrfBlockedError extends Error {
35
- readonly reason: string;
36
- readonly url?: string;
37
- readonly address?: string;
38
- constructor(reason: string, url?: string, address?: string, cause?: unknown);
39
- }
40
- /** True if `ip` (a literal address) falls in a blocked range. Mapped IPv6 is
41
- * normalized by BlockList; an unparseable string is treated as blocked. */
42
- export declare function isBlockedAddress(ip: string, blockList?: BlockList): boolean;
43
- export interface FetchableUrlOptions {
44
- /** Allowed URL schemes. Default `['http:', 'https:']`. */
45
- allowedProtocols?: string[];
46
- /** DNS resolver (injectable for tests). Default `dns.lookup(host, {all:true})`. */
47
- resolve?: (host: string) => Promise<string[]>;
48
- /** Override the blocked-range set. Default = the internal/non-routable set. */
49
- blockList?: BlockList;
50
- /** Escape hatch: skip all internal-range checks (e.g. a trusted-loopback dev
51
- * sink). Off by default — opt in explicitly, never from request input. */
52
- allowPrivate?: boolean;
53
- }
54
- export interface FetchableUrl {
55
- /** The parsed, validated URL. */
56
- url: URL;
57
- /** The host (brackets stripped for IPv6 literals). */
58
- hostname: string;
59
- /** Validated addresses: the literal IP, or every resolved DNS record. Feed to
60
- * `pinnedLookup()` to pin the connection and close the rebinding TOCTOU. */
61
- addresses: string[];
62
- }
63
- /**
64
- * Validate that `rawUrl` is safe to fetch. Rejects (throws `SsrfBlockedError`)
65
- * a malformed URL, a disallowed scheme, embedded credentials, a missing host,
66
- * a literal internal IP, or a host that resolves to ANY internal address.
67
- * Returns the parsed URL and the validated address set on success.
68
- */
69
- export declare function assertFetchableUrl(rawUrl: string | URL, opts?: FetchableUrlOptions): Promise<FetchableUrl>;
70
- export interface SafeFetchOptions extends FetchableUrlOptions {
71
- /** Max redirect hops before giving up. Default 5. */
72
- maxRedirects?: number;
73
- /** Injectable fetch (tests). Default global `fetch`. */
74
- fetchImpl?: typeof fetch;
75
- }
76
- /**
77
- * A `fetch` that validates the target — and re-validates every redirect hop —
78
- * with the SSRF guard. Redirects are handled manually (`redirect:'manual'`) so
79
- * a 3xx Location to an internal host is checked BEFORE it is followed, never
80
- * chased blindly. Returns the final non-redirect `Response`.
81
- *
82
- * Note: each hop re-issues with the original `init` (method + body preserved —
83
- * the security-relevant worst case for 307/308). A streamed request body cannot
84
- * be replayed across hops.
85
- */
86
- export declare function safeFetch(rawUrl: string | URL, init?: RequestInit, opts?: SafeFetchOptions): Promise<Response>;
87
- type LookupCallback = (err: NodeJS.ErrnoException | null, address?: string | LookupAddress[], family?: number) => void;
88
- /**
89
- * A `dns.lookup`-compatible function that ONLY ever returns the pre-validated
90
- * `addresses`. Pass it to `new http.Agent({ lookup })` or an undici
91
- * `connect:{ lookup }` dispatcher so the socket connects to an address the
92
- * guard already cleared — closing the DNS-rebinding TOCTOU between check and
93
- * connect. Use the `addresses` from `assertFetchableUrl()`.
94
- */
95
- export declare function pinnedLookup(addresses: readonly string[]): (hostname: string, options: unknown, callback?: LookupCallback) => void;
96
- export {};
@@ -1 +0,0 @@
1
- "use strict";var h=Object.defineProperty;var l=(e,t)=>h(e,"name",{value:t,configurable:!0});var u=Object.defineProperty,i=l((e,t)=>u(e,"name",{value:t,configurable:!0}),"i");Object.defineProperty(exports,"__esModule",{value:!0}),exports.SsrfBlockedError=void 0,exports.isBlockedAddress=isBlockedAddress,exports.assertFetchableUrl=assertFetchableUrl,exports.safeFetch=safeFetch,exports.pinnedLookup=pinnedLookup;const node_net_1=require("node:net"),promises_1=require("node:dns/promises");class SsrfBlockedError extends Error{static{l(this,"SsrfBlockedError")}static{i(this,"SsrfBlockedError")}constructor(t,o,s,r){super(`SSRF guard blocked ${o??"request"}: ${t}${s?` (${s})`:""}`,r!==void 0?{cause:r}:void 0),this.name="SsrfBlockedError",this.reason=t,this.url=o,this.address=s}}exports.SsrfBlockedError=SsrfBlockedError;function buildDefaultBlockList(){const e=new node_net_1.BlockList;return e.addSubnet("0.0.0.0",8,"ipv4"),e.addSubnet("10.0.0.0",8,"ipv4"),e.addSubnet("100.64.0.0",10,"ipv4"),e.addSubnet("127.0.0.0",8,"ipv4"),e.addSubnet("169.254.0.0",16,"ipv4"),e.addSubnet("172.16.0.0",12,"ipv4"),e.addSubnet("192.0.0.0",24,"ipv4"),e.addSubnet("192.168.0.0",16,"ipv4"),e.addSubnet("198.18.0.0",15,"ipv4"),e.addSubnet("240.0.0.0",4,"ipv4"),e.addAddress("::","ipv6"),e.addAddress("::1","ipv6"),e.addSubnet("fc00::",7,"ipv6"),e.addSubnet("fe80::",10,"ipv6"),e}l(buildDefaultBlockList,"buildDefaultBlockList"),i(buildDefaultBlockList,"buildDefaultBlockList");const DEFAULT_BLOCK_LIST=buildDefaultBlockList();function isBlockedAddress(e,t=DEFAULT_BLOCK_LIST){const o=(0,node_net_1.isIP)(e);return o===0?!0:t.check(e,o===6?"ipv6":"ipv4")}l(isBlockedAddress,"isBlockedAddress"),i(isBlockedAddress,"isBlockedAddress");const stripBrackets=i(e=>e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e,"stripBrackets"),defaultResolve=i(async e=>(await(0,promises_1.lookup)(e,{all:!0,verbatim:!0})).map(t=>t.address),"defaultResolve");async function assertFetchableUrl(e,t={}){const o=t.allowedProtocols??["http:","https:"];let s;try{s=new URL(e)}catch{throw new SsrfBlockedError("malformed-url",String(e))}if(!o.includes(s.protocol))throw new SsrfBlockedError(`scheme-not-allowed:${s.protocol}`,s.href);if(s.username!==""||s.password!=="")throw new SsrfBlockedError("embedded-credentials",s.href);const r=stripBrackets(s.hostname);if(r==="")throw new SsrfBlockedError("missing-host",s.href);if(t.allowPrivate)return{url:s,hostname:r,addresses:(0,node_net_1.isIP)(r)?[r]:[]};const d=t.blockList??DEFAULT_BLOCK_LIST;if((0,node_net_1.isIP)(r)!==0){if(isBlockedAddress(r,d))throw new SsrfBlockedError("blocked-address",s.href,r);return{url:s,hostname:r,addresses:[r]}}const c=t.resolve??defaultResolve;let a;try{a=await c(r)}catch(n){throw new SsrfBlockedError("dns-resolution-failed",s.href,void 0,n)}if(a.length===0)throw new SsrfBlockedError("dns-no-records",s.href);for(const n of a)if(isBlockedAddress(n,d))throw new SsrfBlockedError("blocked-resolved-address",s.href,n);return{url:s,hostname:r,addresses:a}}l(assertFetchableUrl,"assertFetchableUrl"),i(assertFetchableUrl,"assertFetchableUrl");async function safeFetch(e,t={},o={}){const s=o.fetchImpl??globalThis.fetch,r=o.maxRedirects??5;let d=e;for(let c=0;;c++){const{url:a}=await assertFetchableUrl(d,o),n=await s(a,{...t,redirect:"manual"}),f=n.headers.get("location");if(n.status>=300&&n.status<400&&f){if(c>=r)throw new SsrfBlockedError("too-many-redirects",a.href);d=new URL(f,a).href;continue}return n}}l(safeFetch,"safeFetch"),i(safeFetch,"safeFetch");function pinnedLookup(e){const t=e.map(o=>({address:o,family:(0,node_net_1.isIP)(o)===6?6:4}));return(o,s,r)=>{const d=typeof s=="function"?s:r,c=typeof s=="object"&&s!==null&&s.all===!0;if(t.length===0){d(new Error(`SSRF guard: no pinned address for ${o}`));return}c?d(null,t):d(null,t[0].address,t[0].family)}}l(pinnedLookup,"pinnedLookup"),i(pinnedLookup,"pinnedLookup");
@@ -1,100 +0,0 @@
1
- /**
2
- * A workspace's gateway middleware, and the one thing it may hand core auth: the token to verify (version 1).
3
- *
4
- * A middleware is either
5
- * - a FUNCTION `(req, ctx) => void | Promise<void>` — it runs right after core auth on a public route, as it always
6
- * has, and refuses a request by throwing; or
7
- * - a VERSION-1 MODULE `{ version: 1, preAuth, afterAuth?, beforeForward? }` — its steps run on every public route
8
- * (the HTTP pipeline and a WS upgrade alike): `preAuth` before core auth, `afterAuth` right after it, with the
9
- * claims core verified, and `beforeForward` before the request goes to the service. A function that also carries
10
- * `version: 1` and the steps is read as the module (a middleware that still loads in an older gateway).
11
- *
12
- * `preAuth` may return `{ token, identity: 'workload' }`: a JWT for core to verify INSTEAD of the `Authorization:
13
- * Bearer` one — e.g. the access token of an `Authorization: DPoP <jwt>` (RFC 9449) whose proof the module checked.
14
- * The module supplies the token, never claims: core still verifies it against the host's JWKS (no HS256 shared secret
15
- * and no insecure decode for it) and still applies the route's ABAC. The token holds for that one request, and only
16
- * while its `authorization`, `dpop`, method, url and host are what they were (an act-as grant that rewrites the
17
- * Authorization drops it). A workload is a service, not a person: the gateway stamps no `x-user-id` and no
18
- * `x-user-roles` for it — its tenant and permissions still.
19
- *
20
- * Shared by both gateways (two-gateways rule: only lifted modules are shared). The dev gateway runs a workspace's
21
- * module itself (runtime/server.ts); a prod gateway's composition calls `dispatchMiddleware` from its own `beforeAuth`
22
- * hook and `requestToken` from its `identify`, and the prod trust stamping (prod-runtime/trust.ts) honours
23
- * `workloadToken`. `runtime/workspace-auth` re-exports this file from the address a consumer already imports.
24
- */
25
- import type * as http from 'node:http';
26
- /**
27
- * What a middleware is told besides the request: whose route it is. A middleware runs inside the daemon, so its
28
- * `process.env` is the daemon owner's — a worktree instance's middleware reads the instance's own addresses (its
29
- * `AUTH_API_RESOURCE`, …) from `env`: the instance's variables (instance.ts), empty for any other workspace.
30
- */
31
- export interface EdgeMiddlewareContext {
32
- wsKey?: string;
33
- root?: string;
34
- env: Readonly<Record<string, string>>;
35
- /** The claims core auth verified — given to `afterAuth` and `beforeForward` on a JWT route. */
36
- claims?: Record<string, unknown>;
37
- /**
38
- * A call to one of THIS workspace's services on its `internal.*` route, as the internal caller `gateway`
39
- * (issues/closed/foodguard-285) — given only to a middleware that asks (`internalFetch: true`), and only by the dev
40
- * gateway (runtime/internal-fetch.ts). The daemon holds the caller's credential: the middleware never sees it. Absent
41
- * on a gateway that does not offer it, or when the workspace has a service named `gateway`: a middleware that needs
42
- * it refuses the request then, so an older gateway fails closed.
43
- */
44
- fetchInternal?: InternalFetch;
45
- }
46
- /** What {@link EdgeMiddlewareContext.fetchInternal} sends: a path on the service's internal route, never an origin. */
47
- export interface InternalFetchInit {
48
- /** GET, HEAD, POST, PUT, PATCH or DELETE. Default GET, or POST with a body. */
49
- method?: string;
50
- /** The path and query, beginning with `/`. */
51
- path: string;
52
- /** Request headers. The gateway's own (`x-api-key*`, `x-internal-token`, identity stamps), `host` and hop-by-hop ones are dropped. */
53
- headers?: Readonly<Record<string, string>>;
54
- body?: string | Uint8Array;
55
- /** Default 10 s, at most 30 s. */
56
- timeoutMs?: number;
57
- }
58
- /** The service's answer, as it gave it: a redirect is returned, never followed. The body is at most 1 MiB. */
59
- export interface InternalFetchResponse {
60
- status: number;
61
- headers: Record<string, string | string[] | undefined>;
62
- body: Buffer;
63
- }
64
- export type InternalFetch = (service: string, init: InternalFetchInit) => Promise<InternalFetchResponse>;
65
- /** The token a version-1 `preAuth` hands core auth. `workload`: a service's identity, not a person's. */
66
- export interface OriginalTokenInput {
67
- token: string;
68
- identity: 'workload';
69
- }
70
- export interface WorkspaceAuthModuleV1 {
71
- version: 1;
72
- /** Asks for {@link EdgeMiddlewareContext.fetchInternal} (issues/closed/foodguard-285). */
73
- internalFetch?: true;
74
- /**
75
- * Called when its workspace is unregistered or registered again (issues/closed/dev-gateway-25): stop what it started
76
- * inside the daemon — a child process, a timer, `require('esbuild').stop()` after a `buildSync`. A function middleware
77
- * may carry one too. Then the modules it loaded from the workspace's tree leave the daemon's `require.cache`.
78
- */
79
- dispose?(): void | Promise<void>;
80
- preAuth(req: http.IncomingMessage, ctx?: EdgeMiddlewareContext): void | OriginalTokenInput | Promise<void | OriginalTokenInput>;
81
- afterAuth?(req: http.IncomingMessage, ctx?: EdgeMiddlewareContext): void | Promise<void>;
82
- beforeForward?(req: http.IncomingMessage, ctx?: EdgeMiddlewareContext): void | Promise<void>;
83
- }
84
- export type EdgeMiddlewareFunction = (req: http.IncomingMessage, ctx?: EdgeMiddlewareContext) => void | Promise<void>;
85
- export type EdgeMiddleware = EdgeMiddlewareFunction | WorkspaceAuthModuleV1;
86
- export type MiddlewarePhase = 'preAuth' | 'afterAuth' | 'beforeForward';
87
- /** Why a module was refused — the code a load warning shows (the message may quote the workspace's own source). */
88
- export declare const INVALID_MIDDLEWARE = "LENSMCP_INVALID_MIDDLEWARE";
89
- /** The token a `preAuth` handed core auth for THIS request — undefined once anything it was bound to changed. */
90
- export declare function requestToken(req: http.IncomingMessage): string | undefined;
91
- /** True when the request's verified identity is a workload's (a `preAuth` token still bound to it). */
92
- export declare function workloadToken(req: http.IncomingMessage): boolean;
93
- /** The middleware a module exports, checked: a function, or a version-1 module. Throws (code `INVALID_MIDDLEWARE`). */
94
- export declare function validateMiddleware(value: unknown): EdgeMiddleware;
95
- /**
96
- * Run one phase of a middleware on a request. A function runs at `afterAuth` only (awaited). A module's step runs when
97
- * it has one; a `preAuth` that returns a token has it held for the request (`requestToken`) — anything other than
98
- * `{ token, identity: 'workload' }` throws. A throw (or rejection) is the middleware refusing the request.
99
- */
100
- export declare function dispatchMiddleware(middleware: EdgeMiddleware, phase: MiddlewarePhase, req: http.IncomingMessage, ctx?: EdgeMiddlewareContext): Promise<void>;
@@ -1 +0,0 @@
1
- "use strict";var c=Object.defineProperty;var i=(t,e)=>c(t,"name",{value:e,configurable:!0});var f=Object.defineProperty,r=i((t,e)=>f(t,"name",{value:e,configurable:!0}),"r");Object.defineProperty(exports,"__esModule",{value:!0}),exports.INVALID_MIDDLEWARE=void 0,exports.requestToken=requestToken,exports.workloadToken=workloadToken,exports.validateMiddleware=validateMiddleware,exports.dispatchMiddleware=dispatchMiddleware,exports.INVALID_MIDDLEWARE="LENSMCP_INVALID_MIDDLEWARE";const held=new WeakMap,isFunction=r(t=>typeof t=="function"&&t.version!==1,"isFunction");function requestToken(t){const e=held.get(t);if(e&&!(e.authorization!==t.headers.authorization||e.dpop!==t.headers.dpop||e.method!==t.method||e.url!==t.url||e.host!==t.headers.host))return e.token}i(requestToken,"requestToken"),r(requestToken,"requestToken");function workloadToken(t){return requestToken(t)!==void 0&&held.get(t)?.identity==="workload"}i(workloadToken,"workloadToken"),r(workloadToken,"workloadToken");function validateMiddleware(t){if(isFunction(t))return t;const e=t;if(!e||typeof e!="object"&&typeof e!="function"||e.version!==1||typeof e.preAuth!="function"||e.afterAuth!==void 0&&typeof e.afterAuth!="function"||e.beforeForward!==void 0&&typeof e.beforeForward!="function"||e.internalFetch!==void 0&&e.internalFetch!==!0||e.dispose!==void 0&&typeof e.dispose!="function")throw Object.assign(new Error("Invalid gateway middleware: export a function, or { version: 1, preAuth, afterAuth?, beforeForward? }"),{code:exports.INVALID_MIDDLEWARE});return e}i(validateMiddleware,"validateMiddleware"),r(validateMiddleware,"validateMiddleware");async function dispatchMiddleware(t,e,o,a){if(isFunction(t)){e==="afterAuth"&&await t(o,a);return}const d=validateMiddleware(t),s=d[e];if(!s)return;const u=await s.call(d,o,a);if(e!=="preAuth"||u===void 0)return;const n=u;if(!n||typeof n!="object"||typeof n.token!="string"||!n.token||n.identity!=="workload"||Object.keys(n).some(p=>p!=="token"&&p!=="identity"))throw new Error("Invalid original token input");held.set(o,{token:n.token,identity:"workload",authorization:o.headers.authorization,dpop:o.headers.dpop,method:o.method,url:o.url,host:o.headers.host})}i(dispatchMiddleware,"dispatchMiddleware"),r(dispatchMiddleware,"dispatchMiddleware");