@lensmcp/cluster 1.25.79 → 1.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build-scope-patterns.d.ts +1 -11
- package/build-scope-patterns.js +1 -1
- package/create-webpack-prod.d.ts +1 -27
- package/create-webpack-prod.js +1 -1
- package/executors/build/build.impl.js +1 -1
- package/executors/gateway/daemon.d.ts +43 -0
- package/executors/gateway/daemon.js +1 -0
- package/executors/gateway/gateway.lib.d.ts +1 -1
- package/executors/gateway/gateway.lib.js +1 -1
- package/executors/gateway/jwks-verify.d.ts +1 -79
- package/executors/gateway/jwks-verify.js +1 -1
- package/executors/gateway/main.rollout.d.ts +2 -1
- package/executors/gateway/main.rollout.js +1 -24
- package/executors/gateway/manifest.d.ts +1 -418
- package/executors/gateway/manifest.js +1 -1
- package/executors/gateway/prod-runtime/trust.d.ts +1 -80
- package/executors/gateway/prod-runtime/trust.js +1 -1
- package/executors/gateway/rate-limit.d.ts +1 -81
- package/executors/gateway/rate-limit.js +1 -18
- package/executors/gateway/runtime/auth.d.ts +1 -1
- package/executors/gateway/runtime/auth.js +1 -1
- package/executors/gateway/runtime/dev-auth.d.ts +3 -2
- package/executors/gateway/runtime/dev-auth.js +1 -1
- package/executors/gateway/runtime/discovery.js +1 -1
- package/executors/gateway/runtime/edge.d.ts +2 -2
- package/executors/gateway/runtime/edge.js +1 -1
- package/executors/gateway/runtime/handler.js +1 -1
- package/executors/gateway/runtime/internal-fetch.d.ts +1 -1
- package/executors/gateway/runtime/lens-children.js +1 -1
- package/executors/gateway/runtime/lens-modules.d.ts +13 -0
- package/executors/gateway/runtime/lens-modules.js +1 -0
- package/executors/gateway/runtime/lifecycle.js +1 -1
- package/executors/gateway/runtime/observability.js +1 -1
- package/executors/gateway/runtime/proxy.js +1 -1
- package/executors/gateway/runtime/route-registry.js +1 -1
- package/executors/gateway/runtime/serve-launch.d.ts +27 -0
- package/executors/gateway/runtime/serve-launch.js +3 -3
- package/executors/gateway/runtime/server.d.ts +1 -1
- package/executors/gateway/runtime/server.js +2 -2
- package/executors/gateway/runtime/services-decl.d.ts +24 -0
- package/executors/gateway/runtime/services-decl.js +1 -0
- package/executors/gateway/runtime/shared-build.d.ts +2 -2
- package/executors/gateway/runtime/shared-build.js +3 -3
- package/executors/gateway/runtime/types.d.ts +9 -3
- package/executors/gateway/runtime/upgrade.js +1 -1
- package/executors/gateway/runtime/workspace-auth.d.ts +1 -1
- package/executors/gateway/runtime/workspace-auth.js +1 -1
- package/executors/gateway/runtime/workspace-middleware.d.ts +2 -2
- package/executors/gateway/runtime/workspace-middleware.js +1 -1
- package/executors/serve/lens-run.d.ts +6 -0
- package/executors/serve/lens-run.js +1 -0
- package/executors/serve/schema.d.ts +2 -0
- package/executors/serve/schema.json +4 -0
- package/executors/serve/serve.impl.js +1 -1
- package/executors/trust/run.d.ts +19 -0
- package/executors/trust/run.js +1 -0
- package/executors/trust/trust.impl.js +5 -5
- package/gateway.d.ts +7 -19
- package/gateway.js +1 -1
- package/gc-notice.d.ts +3 -1
- package/gc-notice.js +1 -1
- package/main.devserver.js +7 -7
- package/package.json +6 -34
- package/pod-memory.d.ts +19 -2
- package/pod-memory.js +1 -1
- package/tsgo-check-plugin.d.ts +3 -2
- package/tsgo-check-plugin.js +3 -3
- package/typecheck-bus.d.ts +17 -0
- package/typecheck-bus.js +4 -3
- package/executors/gateway/body-stall.d.ts +0 -62
- package/executors/gateway/body-stall.js +0 -1
- package/executors/gateway/canonical-path.d.ts +0 -65
- package/executors/gateway/canonical-path.js +0 -1
- package/executors/gateway/client-ip.d.ts +0 -82
- package/executors/gateway/client-ip.js +0 -1
- package/executors/gateway/gateway-errors.d.ts +0 -43
- package/executors/gateway/gateway-errors.js +0 -1
- package/executors/gateway/health-check.d.ts +0 -52
- package/executors/gateway/health-check.js +0 -1
- package/executors/gateway/jwt-claims.d.ts +0 -51
- package/executors/gateway/jwt-claims.js +0 -1
- package/executors/gateway/main.prod-gateway.d.ts +0 -1
- package/executors/gateway/main.prod-gateway.js +0 -2
- package/executors/gateway/metrics.d.ts +0 -36
- package/executors/gateway/metrics.js +0 -1
- package/executors/gateway/otel-tracing.d.ts +0 -46
- package/executors/gateway/otel-tracing.js +0 -1
- package/executors/gateway/prod-config.d.ts +0 -130
- package/executors/gateway/prod-config.js +0 -1
- package/executors/gateway/prod-gateway.lib.d.ts +0 -19
- package/executors/gateway/prod-gateway.lib.js +0 -1
- package/executors/gateway/prod-runtime/access-log.d.ts +0 -8
- package/executors/gateway/prod-runtime/access-log.js +0 -1
- package/executors/gateway/prod-runtime/app.d.ts +0 -30
- package/executors/gateway/prod-runtime/app.js +0 -1
- package/executors/gateway/prod-runtime/auth.d.ts +0 -29
- package/executors/gateway/prod-runtime/auth.js +0 -1
- package/executors/gateway/prod-runtime/body-stall.d.ts +0 -5
- package/executors/gateway/prod-runtime/body-stall.js +0 -1
- package/executors/gateway/prod-runtime/cors.d.ts +0 -18
- package/executors/gateway/prod-runtime/cors.js +0 -1
- package/executors/gateway/prod-runtime/edge.d.ts +0 -44
- package/executors/gateway/prod-runtime/edge.js +0 -1
- package/executors/gateway/prod-runtime/handler.d.ts +0 -33
- package/executors/gateway/prod-runtime/handler.js +0 -1
- package/executors/gateway/prod-runtime/hooks.d.ts +0 -19
- package/executors/gateway/prod-runtime/hooks.js +0 -1
- package/executors/gateway/prod-runtime/observability.d.ts +0 -24
- package/executors/gateway/prod-runtime/observability.js +0 -1
- package/executors/gateway/prod-runtime/rollout.d.ts +0 -33
- package/executors/gateway/prod-runtime/rollout.js +0 -1
- package/executors/gateway/prod-runtime/route-limits.d.ts +0 -30
- package/executors/gateway/prod-runtime/route-limits.js +0 -1
- package/executors/gateway/prod-runtime/routing.d.ts +0 -3
- package/executors/gateway/prod-runtime/routing.js +0 -1
- package/executors/gateway/prod-runtime/server.d.ts +0 -17
- package/executors/gateway/prod-runtime/server.js +0 -1
- package/executors/gateway/prod-runtime/types.d.ts +0 -335
- package/executors/gateway/prod-runtime/types.js +0 -1
- package/executors/gateway/prod-runtime/upgrade.d.ts +0 -23
- package/executors/gateway/prod-runtime/upgrade.js +0 -16
- package/executors/gateway/prod-runtime/upstream-errors.d.ts +0 -33
- package/executors/gateway/prod-runtime/upstream-errors.js +0 -1
- package/executors/gateway/prod-runtime/upstream.d.ts +0 -14
- package/executors/gateway/prod-runtime/upstream.js +0 -1
- package/executors/gateway/providers-prod.d.ts +0 -54
- package/executors/gateway/providers-prod.js +0 -1
- package/executors/gateway/registry-source.d.ts +0 -68
- package/executors/gateway/registry-source.js +0 -2
- package/executors/gateway/rollout-ops.d.ts +0 -53
- package/executors/gateway/rollout-ops.js +0 -2
- package/executors/gateway/ssrf-guard.d.ts +0 -96
- package/executors/gateway/ssrf-guard.js +0 -1
- package/executors/gateway/workspace-auth.d.ts +0 -100
- package/executors/gateway/workspace-auth.js +0 -1
|
@@ -1,418 +1 @@
|
|
|
1
|
-
|
|
2
|
-
export interface RouteMount {
|
|
3
|
-
host: string;
|
|
4
|
-
/** Path prefix under the host; omit for the host root. */
|
|
5
|
-
path?: string;
|
|
6
|
-
}
|
|
7
|
-
/** How the edge guards a route. `jwt` runs the configured authenticator
|
|
8
|
-
* (dev middleware seam / prod JWKS); `internal` requires a valid x-api-key;
|
|
9
|
-
* `public` is unguarded. */
|
|
10
|
-
export type AuthMode = 'jwt' | 'public' | 'internal';
|
|
11
|
-
/**
|
|
12
|
-
* A per-path auth refinement. `mode` overrides the service default for paths under
|
|
13
|
-
* `path` (longest / first match wins — callers emit most-specific-first). For `jwt`
|
|
14
|
-
* paths an optional ABAC requirement gates the request at the edge:
|
|
15
|
-
* - `permission` is sugar for "the verified token's `perms` claim contains it"
|
|
16
|
-
* (→ `{ attr:'perms', op:'contains', value }`).
|
|
17
|
-
* - `rule` is the full predicate over the request {@link Attrs} (verified claims + ip/headers).
|
|
18
|
-
* - `methods` scopes the override to specific HTTP methods — permissions are per-handler
|
|
19
|
-
* (POST needs `campaigns.write`, GET needs `campaigns.read`). Omit = all methods.
|
|
20
|
-
* (`RuleNode`/`Attrs` are declared with the targeting engine below.)
|
|
21
|
-
*/
|
|
22
|
-
export interface AuthOverride {
|
|
23
|
-
path: string;
|
|
24
|
-
mode: AuthMode;
|
|
25
|
-
methods?: string[];
|
|
26
|
-
permission?: string;
|
|
27
|
-
rule?: RuleNode;
|
|
28
|
-
}
|
|
29
|
-
export interface AuthPolicy {
|
|
30
|
-
default?: AuthMode;
|
|
31
|
-
overrides?: AuthOverride[];
|
|
32
|
-
}
|
|
33
|
-
/**
|
|
34
|
-
* Per-route rate limit, declared by the service and ENFORCED at the prod edge after auth (`prod-runtime/route-limits.ts`,
|
|
35
|
-
* issues/closed/prod-gateway-4-19). The field used to be carried and never read: a service that declared a limit on
|
|
36
|
-
* its login path got none and was told nothing.
|
|
37
|
-
*/
|
|
38
|
-
export interface RateLimit {
|
|
39
|
-
/** Path this limit applies to (segment-prefix, like an auth override's); omit for the whole service. */
|
|
40
|
-
path?: string;
|
|
41
|
-
/** Bucket key dimension: `ip` (the resolved client address), `tenant` (the verified `tid`) or `user` (the verified
|
|
42
|
-
* `sub`). A caller with no such identity is bucketed by address. */
|
|
43
|
-
key: string;
|
|
44
|
-
/** Requests allowed per window. */
|
|
45
|
-
points: number;
|
|
46
|
-
/** Window length in SECONDS. */
|
|
47
|
-
duration: number;
|
|
48
|
-
}
|
|
49
|
-
/** The dimensions a {@link RateLimit} may key on. */
|
|
50
|
-
export declare const RATE_LIMIT_KEYS: ReadonlySet<string>;
|
|
51
|
-
/**
|
|
52
|
-
* A service's self-description — the canonical thing the gateway routes from.
|
|
53
|
-
* In dev this is synthesized from project.json; in prod the service publishes
|
|
54
|
-
* it. One manifest per service, with one or more mounts.
|
|
55
|
-
*/
|
|
56
|
-
export interface RouteManifest {
|
|
57
|
-
service: string;
|
|
58
|
-
/** Build/image version — lets a gateway log/track which manifest it serves. */
|
|
59
|
-
version?: string;
|
|
60
|
-
mounts: RouteMount[];
|
|
61
|
-
/** Default auth for the service + per-path overrides (incl. edge permission rules). */
|
|
62
|
-
auth?: AuthPolicy;
|
|
63
|
-
/** Expose `internal.<host>` (east-west, x-api-key) for this service. */
|
|
64
|
-
internal?: boolean;
|
|
65
|
-
/** Override the auto `internal.<host>` name, or `false` to disable it. */
|
|
66
|
-
internalHost?: string | false;
|
|
67
|
-
/** This service is the catch-all for unclaimed hostnames. */
|
|
68
|
-
default?: boolean;
|
|
69
|
-
/** Rewrite forwarded URLs (e.g. mount at root in dev, `/api` downstream). */
|
|
70
|
-
prependPrefix?: string;
|
|
71
|
-
/** TCP upstream URL (apps/vite, or a prod service addressed directly).
|
|
72
|
-
* When absent, the PodProvider resolves `service` to an upstream. */
|
|
73
|
-
upstream?: string;
|
|
74
|
-
rateLimits?: RateLimit[];
|
|
75
|
-
}
|
|
76
|
-
/** Where a request is forwarded: a unix socket (dev pods) or a TCP url.
|
|
77
|
-
* `version` (when set) is the rollout cohort that served it — surfaced on the
|
|
78
|
-
* trace + `x-lensmcp-version` so a canary's traffic is visible. */
|
|
79
|
-
export type Upstream = ({
|
|
80
|
-
socketPath: string;
|
|
81
|
-
} | {
|
|
82
|
-
url: string;
|
|
83
|
-
}) & {
|
|
84
|
-
version?: string;
|
|
85
|
-
};
|
|
86
|
-
/** A discovered version of a service + the endpoints serving it. The unit of
|
|
87
|
-
* progressive rollout: weights across cohorts split traffic (canary 90/10,
|
|
88
|
-
* blue/green 0→100). */
|
|
89
|
-
export interface VersionCohort {
|
|
90
|
-
version: string;
|
|
91
|
-
/** Relative traffic share. 0 = drain (receive no new traffic). */
|
|
92
|
-
weight: number;
|
|
93
|
-
urls: string[];
|
|
94
|
-
}
|
|
95
|
-
/** Supplies + watches the manifest source. */
|
|
96
|
-
export interface ManifestProvider {
|
|
97
|
-
/** The current manifests (synchronously). */
|
|
98
|
-
list(): RouteManifest[];
|
|
99
|
-
/** Subscribe to changes; returns an unsubscribe. Optional (static sources). */
|
|
100
|
-
watch?(cb: (manifests: RouteManifest[]) => void): () => void;
|
|
101
|
-
}
|
|
102
|
-
/** Resolves a service to a concrete upstream, with optional scale-from-zero. */
|
|
103
|
-
export interface PodProvider {
|
|
104
|
-
/** Pick an upstream for this service. `opts.version` pins a rollout cohort
|
|
105
|
-
* (sticky canary / debugging); otherwise traffic is split by cohort weight.
|
|
106
|
-
* `opts.isHealthy` (when given) steers a pooled pick toward healthy endpoints
|
|
107
|
-
* — fail-open: if a whole pool looks down it still returns one.
|
|
108
|
-
* `opts.allowDrained` admits a `weight: 0` cohort as a pin target. The GATEWAY sets it when
|
|
109
|
-
* the version came from its own targeting (an ABAC rule aimed at a canary that takes no
|
|
110
|
-
* organic traffic — the point of a targeted rollout); a version named by the CLIENT never
|
|
111
|
-
* gets it, so a rolled-back build cannot be reached by sending its version string. */
|
|
112
|
-
pick(service: string, opts?: {
|
|
113
|
-
version?: string;
|
|
114
|
-
isHealthy?: (url: string) => boolean;
|
|
115
|
-
allowDrained?: boolean;
|
|
116
|
-
}): Upstream | undefined;
|
|
117
|
-
/** All upstream URLs this provider could route to — for active health-checking. */
|
|
118
|
-
endpoints?(): string[];
|
|
119
|
-
/** Bring a scaled-to-zero service up (dev). Prod returns true (always on). */
|
|
120
|
-
ensureUp?(service: string): Promise<boolean>;
|
|
121
|
-
/** Drop a dead upstream so the next pick avoids it (refused socket / 502). */
|
|
122
|
-
drop?(service: string, upstream: Upstream): void;
|
|
123
|
-
/** Evaluate this service's targeting rules against a request's attributes;
|
|
124
|
-
* the first matching rule's version (sticky-by-attribute). */
|
|
125
|
-
resolveVersion?(service: string, attrs: Attrs): {
|
|
126
|
-
version: string;
|
|
127
|
-
rule?: string;
|
|
128
|
-
} | undefined;
|
|
129
|
-
/** Consistent-hash a stable device/user key to a cohort version — the
|
|
130
|
-
* sticky weighted split (same key → same version across requests + ramps). */
|
|
131
|
-
bucket?(service: string, key: string): {
|
|
132
|
-
version: string;
|
|
133
|
-
} | undefined;
|
|
134
|
-
}
|
|
135
|
-
/**
|
|
136
|
-
* Smooth weighted round-robin (nginx-style). Returns a stateful selector that,
|
|
137
|
-
* over time, hands out indices in proportion to `weights` — but INTERLEAVED
|
|
138
|
-
* (90/10 yields the rare cohort roughly every tenth pick, not in a burst at
|
|
139
|
-
* the end). Deterministic given the weights, so rollout splits are testable.
|
|
140
|
-
* A zero/negative total (all cohorts drained) falls back to index 0.
|
|
141
|
-
*/
|
|
142
|
-
export declare function smoothWeightedSelector(weights: readonly number[]): () => number;
|
|
143
|
-
/** A flat routing entry built from manifests — provider-agnostic. The pod
|
|
144
|
-
* resolution happens at request time via the PodProvider, keyed by `service`. */
|
|
145
|
-
export interface Route {
|
|
146
|
-
service: string;
|
|
147
|
-
host?: string;
|
|
148
|
-
prefix?: string;
|
|
149
|
-
prependPrefix?: string;
|
|
150
|
-
internal?: boolean;
|
|
151
|
-
default?: boolean;
|
|
152
|
-
/** For a host-less `default` catch-all: the apex (base domain) it belongs to — set when a shared
|
|
153
|
-
* multi-workspace gateway merges several workspaces' fragments, so an unclaimed host routes to the
|
|
154
|
-
* default of ITS apex, not another workspace's. Undefined = a truly-global catch-all. */
|
|
155
|
-
apex?: string;
|
|
156
|
-
/** Direct TCP upstream (app/vite/prod-direct) — bypasses pod resolution. */
|
|
157
|
-
upstream?: string;
|
|
158
|
-
/** Resolved auth for the route root (overrides refine per-path at match). */
|
|
159
|
-
auth: AuthMode;
|
|
160
|
-
/**
|
|
161
|
-
* The auth policy of the manifest THIS route was built from — carried on the route so the edge never
|
|
162
|
-
* re-resolves it by service NAME at request time. Resolving by name let a second manifest that reused a
|
|
163
|
-
* service name judge the first one's host with its own policy (a `jwt` host served under a `public` twin's
|
|
164
|
-
* policy, PG3-28), and let a registry reload during a JWKS wait drop a route's overrides (PG3-15).
|
|
165
|
-
* `buildRouteTable` always sets it (`{}` when the manifest declares none).
|
|
166
|
-
*/
|
|
167
|
-
policy?: AuthPolicy;
|
|
168
|
-
/** The manifest's per-route limits, carried like the policy (PG4-19). */
|
|
169
|
-
rateLimits?: RateLimit[];
|
|
170
|
-
}
|
|
171
|
-
/**
|
|
172
|
-
* Exact hostname or `*.suffix` wildcard (the bare suffix also matches).
|
|
173
|
-
*
|
|
174
|
-
* Case-INSENSITIVE, because DNS is: `APP.X` and `app.x` name the same host to every other layer,
|
|
175
|
-
* and a byte-exact compare here meant an upper-cased `Host` missed its own route and fell through
|
|
176
|
-
* to whatever claimed the rest of the request — usually the host-less catch-all, under ITS auth
|
|
177
|
-
* policy. Where that catch-all and the named host share an upstream, that was a way to reach a
|
|
178
|
-
* guarded service unauthenticated. The path matcher folds for the same reason.
|
|
179
|
-
*/
|
|
180
|
-
export declare function hostMatches(pattern: string, host: string): boolean;
|
|
181
|
-
/**
|
|
182
|
-
* THE matcher — shared by dev and prod. Generic over the route shape so the
|
|
183
|
-
* dev gateway can pass its pod-rich routes and prod its upstream routes; only
|
|
184
|
-
* `host`/`prefix` are read here.
|
|
185
|
-
*
|
|
186
|
-
* Rules (each one a fixed bug):
|
|
187
|
-
* - A host CLAIMED by any declaration never falls through to the catch-all
|
|
188
|
-
* default; its unmatched paths belong to the gateway's own infra.
|
|
189
|
-
* - An UNCLAIMED host may only reach the host-less `default` route — never a
|
|
190
|
-
* host route by accident of sort order (unknown host → default or 404).
|
|
191
|
-
* - An EXACT host match beats a wildcard (`internal.api.x` is served by its
|
|
192
|
-
* own route, not a co-existing `*.x` app).
|
|
193
|
-
* - Within the candidates, the most specific path prefix wins (callers sort
|
|
194
|
-
* routes by specificity: host+path before host before catch-all).
|
|
195
|
-
*/
|
|
196
|
-
export declare function matchRoute<R extends {
|
|
197
|
-
host?: string;
|
|
198
|
-
prefix?: string;
|
|
199
|
-
apex?: string;
|
|
200
|
-
}>(routes: readonly R[], host: string, url: string): R | undefined;
|
|
201
|
-
/**
|
|
202
|
-
* Is `url` at or under the mount `prefix`? Segment-anchored and case-insensitive.
|
|
203
|
-
*
|
|
204
|
-
* Both properties are fixed bugs. A bare `startsWith` let `/adminx` fall into the `/admin`
|
|
205
|
-
* mount (`handler.ts` already enforces a segment boundary for `prependPrefix`, and the two
|
|
206
|
-
* must agree), and a case-SENSITIVE compare let `/Admin/x` miss the mount entirely and fall
|
|
207
|
-
* through to a sibling — most often the host-less catch-all, under ITS auth policy. Folding
|
|
208
|
-
* is safe in both directions: an upstream that routes case-sensitively simply 404s a path
|
|
209
|
-
* whose case it does not serve, whereas NOT folding hands the request to the wrong policy.
|
|
210
|
-
*/
|
|
211
|
-
export declare function pathUnderPrefix(url: string, prefix: string): boolean;
|
|
212
|
-
/**
|
|
213
|
-
* Specificity sort: host+path beats host-only beats catch-all, and among equals the LONGER path
|
|
214
|
-
* wins. Mutates+returns.
|
|
215
|
-
*
|
|
216
|
-
* The length tie-break is what makes `buildRouteTable`'s promise ("sorted by specificity so
|
|
217
|
-
* `matchRoute` picks the most specific") true for two path mounts on ONE host. The rank alone
|
|
218
|
-
* scores the PRESENCE of host/prefix, never its length, so `/api` and `/api/tasks` tie at 3 and
|
|
219
|
-
* `Array.sort` — stable — leaves them in manifest-arrival order. `matchRoute` then takes the FIRST
|
|
220
|
-
* `startsWith` hit, so whichever arrived first swallows the other's whole surface: `/api` catches
|
|
221
|
-
* `/api/tasks/v1`, or `/api/tasks` sorts first and `/api` never matches anything under it.
|
|
222
|
-
*
|
|
223
|
-
* Measured before this tie-break existed (foodguard, 2026-08-31): a second service declaring `/api`
|
|
224
|
-
* beside the incumbent took the ENTIRE mount, and a `@Public` health route on the incumbent began
|
|
225
|
-
* answering 401 because the edge was applying the OTHER service's auth policy to its path. Two
|
|
226
|
-
* services could not share a host prefix at all, in dev or prod — both run this function.
|
|
227
|
-
*
|
|
228
|
-
* Longest-prefix-match is the standard routing semantic and the one the caller already documents;
|
|
229
|
-
* the rank ordering above is unchanged, so only the previously-arbitrary tie moves.
|
|
230
|
-
*/
|
|
231
|
-
export declare function sortBySpecificity<R extends {
|
|
232
|
-
host?: string;
|
|
233
|
-
prefix?: string;
|
|
234
|
-
}>(routes: R[]): R[];
|
|
235
|
-
/** Resolve the auth mode for a concrete request path against a manifest. */
|
|
236
|
-
export declare function authForPath(manifest: RouteManifest, path: string, internal: boolean): AuthMode;
|
|
237
|
-
/** The auth mode for a request + the ABAC predicate (if any) to enforce at the edge. */
|
|
238
|
-
export interface ResolvedAuth {
|
|
239
|
-
mode: AuthMode;
|
|
240
|
-
rule?: RuleNode;
|
|
241
|
-
}
|
|
242
|
-
/**
|
|
243
|
-
* Resolve the auth mode + any edge ABAC rule for a concrete (path, method) against an
|
|
244
|
-
* {@link AuthPolicy} — the shared core both gateways use. First override whose `path` is a
|
|
245
|
-
* prefix and whose `methods` include the method wins (callers emit most-specific-first);
|
|
246
|
-
* `permission` is compiled to a `perms contains` condition.
|
|
247
|
-
*/
|
|
248
|
-
/**
|
|
249
|
-
* Segment-prefix match where a pattern segment of `*` or `:param` matches ANY one path segment —
|
|
250
|
-
* so a route override like `/engage/tenants/:companyId/campaigns` matches the real request
|
|
251
|
-
* `/engage/tenants/abc-123/campaigns` (and anything deeper). Stricter than `startsWith` (it won't
|
|
252
|
-
* cross a segment boundary), which is also more correct. Lets `@RequirePermission` enforce on
|
|
253
|
-
* tenant-scoped (`:param`) routes, not just static prefixes.
|
|
254
|
-
*/
|
|
255
|
-
export declare function authPathMatches(pattern: string, path: string): boolean;
|
|
256
|
-
export declare function authRuleFor(policy: AuthPolicy | undefined, path: string, method: string): ResolvedAuth;
|
|
257
|
-
/**
|
|
258
|
-
* Resolve the auth mode AND any edge ABAC rule for a concrete (path, method) on a manifest —
|
|
259
|
-
* the permission-aware companion to {@link authForPath}. Internal routes are always `internal`;
|
|
260
|
-
* otherwise delegates to {@link authRuleFor}. The gateway verifies the JWT for `jwt` mode and,
|
|
261
|
-
* when a `rule` is present, requires `evalRule(rule, attrs)` (else 403).
|
|
262
|
-
*/
|
|
263
|
-
export declare function authRuleForPath(manifest: RouteManifest, path: string, method: string, internal: boolean): ResolvedAuth;
|
|
264
|
-
/**
|
|
265
|
-
* Build the flat route table from manifests. Each mount becomes a host route;
|
|
266
|
-
* a service flagged `internal` also gets an `internal.<host>` route per mount;
|
|
267
|
-
* a `default` service contributes the host-less catch-all. Sorted by
|
|
268
|
-
* specificity so `matchRoute` picks the most specific.
|
|
269
|
-
*/
|
|
270
|
-
export declare function buildRouteTable(manifests: readonly RouteManifest[]): Route[];
|
|
271
|
-
/**
|
|
272
|
-
* Everything wrong with ONE manifest's shape, or `[]` (PG4-05). The loaders used to check `service` and
|
|
273
|
-
* `Array.isArray(mounts)` and nothing else: `mounts:[{host:123}]` then made `hostMatches` throw for EVERY request on
|
|
274
|
-
* EVERY host, `mounts:[null]` and `auth.overrides:{}` threw out of `buildRouteTable` (a boot crash, and a route table
|
|
275
|
-
* that could never be rebuilt), and `mounts:[{}]` quietly became a second catch-all. A manifest is published by the
|
|
276
|
-
* service it describes; one service's malformed publish must cost that service its routes and nobody else theirs.
|
|
277
|
-
*/
|
|
278
|
-
export declare function manifestDefects(m: unknown): string[];
|
|
279
|
-
/**
|
|
280
|
-
* Who may mount which host — the operator's map, `{ hostPattern: [service, …] }` (PG4-06). A pattern is an exact
|
|
281
|
-
* host or `*.suffix`; the key `(default)` names the services that may be the catch-all. A host no pattern covers is
|
|
282
|
-
* free, so a deployment can pin just the hosts that matter (the IdP's, the API's).
|
|
283
|
-
*
|
|
284
|
-
* Without it any registry writer can mount `/login` on the IdP's host from its own key and be handed every caller's
|
|
285
|
-
* credentials: longest-prefix-match decides, and nothing in a manifest says whose host that is.
|
|
286
|
-
*/
|
|
287
|
-
export type HostOwners = Readonly<Record<string, readonly string[]>>;
|
|
288
|
-
/**
|
|
289
|
-
* Split a manifest set into what the edge will route and what it refuses, naming every refusal (PG4-05, PG4-06):
|
|
290
|
-
* - a manifest with a shape defect is dropped whole ({@link manifestDefects});
|
|
291
|
-
* - with `owners`, a mount on a host that belongs to other services is dropped (the manifest keeps its own hosts),
|
|
292
|
-
* as is a `default: true` from a service the map does not allow to be the catch-all.
|
|
293
|
-
* Never throws — whatever a provider hands in.
|
|
294
|
-
*/
|
|
295
|
-
export declare function admitManifests(manifests: readonly unknown[], owners?: HostOwners): {
|
|
296
|
-
ok: RouteManifest[];
|
|
297
|
-
problems: ManifestProblem[];
|
|
298
|
-
};
|
|
299
|
-
/** A configuration defect found in a manifest set — reported loudly at load, never served open. */
|
|
300
|
-
export interface ManifestProblem {
|
|
301
|
-
service: string;
|
|
302
|
-
problem: string;
|
|
303
|
-
}
|
|
304
|
-
/**
|
|
305
|
-
* Name every configuration defect in a manifest set that the edge would otherwise have to guess about. The
|
|
306
|
-
* gateway still FAILS CLOSED on each at request time (an `internal`/unknown mode answers 401, an unsafe regex
|
|
307
|
-
* never matches, a duplicated service keeps each route's own policy); this is the loud half, so an operator sees
|
|
308
|
-
* at boot and on every reload what a manifest asked for and did not get.
|
|
309
|
-
*
|
|
310
|
-
* - `internal` (or any string that is not `jwt`/`public`) as `auth.default` or an override `mode` (PG3-01);
|
|
311
|
-
* - two manifests with the same `service` name (PG3-28);
|
|
312
|
-
* - a `regex` rule the engine refuses to run ({@link unsafeRegex}, PG3-25).
|
|
313
|
-
*/
|
|
314
|
-
export declare function manifestProblems(manifests: readonly RouteManifest[]): ManifestProblem[];
|
|
315
|
-
/** Every `regex` pattern in a rule tree. */
|
|
316
|
-
export declare function regexSources(node: RuleNode | undefined): string[];
|
|
317
|
-
/** Synthesize a manifest from a dev project.json `cluster` declaration —
|
|
318
|
-
* the dev ManifestProvider's adapter, and the seed for `lensmcp`-generated
|
|
319
|
-
* prod manifests (same fields, prod adds version/rateLimits). */
|
|
320
|
-
export declare function manifestFromClusterDecl(project: string, decl: {
|
|
321
|
-
host?: string;
|
|
322
|
-
path?: string;
|
|
323
|
-
service?: string;
|
|
324
|
-
upstream?: string;
|
|
325
|
-
port?: number;
|
|
326
|
-
prependPrefix?: string;
|
|
327
|
-
default?: boolean;
|
|
328
|
-
internalHost?: string | false;
|
|
329
|
-
auth?: AuthPolicy;
|
|
330
|
-
}): RouteManifest | undefined;
|
|
331
|
-
/** A flat, read-only attribute bag assembled per request: verified JWT claims,
|
|
332
|
-
* `ip`, `header.<name>`, `device` (sticky key), `path`, `method`. */
|
|
333
|
-
export type Attrs = Record<string, unknown>;
|
|
334
|
-
/**
|
|
335
|
-
* The verified claims as the first layer of an attribute bag, minus every name the gateway owns (`ip`, `method`,
|
|
336
|
-
* `path`, `device`, `header.*`). A claim named `header.cf-ipcountry` (or `device`) used to survive whenever the
|
|
337
|
-
* gateway left that attribute unset and satisfied its rule (PG3-27); built-ins are set AFTER this by the caller.
|
|
338
|
-
* Spread-then-delete, never `a[k] = v` per claim, which would run the `__proto__` setter.
|
|
339
|
-
*/
|
|
340
|
-
export declare function claimAttrs(claims: Record<string, unknown> | undefined): Attrs;
|
|
341
|
-
export type RuleOp = 'eq' | 'ne' | 'in' | 'nin' | 'prefix' | 'suffix' | 'contains' | 'domain' | 'hastoken' | 'regex' | 'exists' | 'gt' | 'lt' | 'cidr';
|
|
342
|
-
export interface Condition {
|
|
343
|
-
attr: string;
|
|
344
|
-
op: RuleOp;
|
|
345
|
-
value?: unknown;
|
|
346
|
-
}
|
|
347
|
-
export interface RuleGroup {
|
|
348
|
-
all?: RuleNode[];
|
|
349
|
-
any?: RuleNode[];
|
|
350
|
-
not?: RuleNode;
|
|
351
|
-
}
|
|
352
|
-
export type RuleNode = Condition | RuleGroup;
|
|
353
|
-
/** A targeting rule: when the predicate matches the request attributes, pin `version`. */
|
|
354
|
-
export interface TargetRule {
|
|
355
|
-
name?: string;
|
|
356
|
-
when: RuleNode;
|
|
357
|
-
version: string;
|
|
358
|
-
}
|
|
359
|
-
/** Longest pattern, and longest attribute value, a `regex` condition runs on. Attributes are claims and headers. */
|
|
360
|
-
export declare const MAX_REGEX_LENGTH = 512;
|
|
361
|
-
/**
|
|
362
|
-
* Bound every rule regex in TIME (PG4-07). A lexical check cannot: `^(a|a)+$` — an alternation that overlaps under one
|
|
363
|
-
* quantifier — passed {@link unsafeRegex} and held the event loop 6.6 s on a 26-character path, and the 512-character
|
|
364
|
-
* value bound does not bound exponential cost at all.
|
|
365
|
-
*
|
|
366
|
-
* V8 ships a second, linear-time matcher. With `--enable-experimental-regexp-engine-on-excessive-backtracks` the
|
|
367
|
-
* ordinary engine hands a match over to it after 50 000 backtracks, so a pathological input costs about a millisecond
|
|
368
|
-
* instead of seconds; the result is the same. Both flags are settable at runtime, so this needs no launch flag and
|
|
369
|
-
* holds for a process that embeds the gateway. The linear engine cannot run lookaheads, backreferences or large
|
|
370
|
-
* counted repetitions; `--enable-experimental-regexp-engine` makes the `l` flag available, which is how
|
|
371
|
-
* {@link unsafeRegex} asks whether a given pattern HAS a linear fallback — one that has none is refused.
|
|
372
|
-
*
|
|
373
|
-
* Process-wide and idempotent; armed on the first regex rule. Returns false on a runtime without the engine, where
|
|
374
|
-
* the lexical check stands alone.
|
|
375
|
-
*/
|
|
376
|
-
export declare function armRegexGuard(): boolean;
|
|
377
|
-
/**
|
|
378
|
-
* Why a rule pattern is refused, or undefined when it is safe to run. A pattern-length bound alone let
|
|
379
|
-
* `^(\w+\s?)+$` hold the event loop for 8 s on a 27-byte client header (PG3-25): the cost of a backtracking match
|
|
380
|
-
* is set by the pattern's SHAPE. Refused here:
|
|
381
|
-
* - a quantified group that itself contains a repeating quantifier (star height > 1: `(a+)+`, `(\w+\s?)*`,
|
|
382
|
-
* `(a*b){2,}`) — the classic exponential shape, what `safe-regex` checks;
|
|
383
|
-
* - a backreference (`\1`, `\k<x>`), which no engine matches in linear time.
|
|
384
|
-
* A lexical check, not a proof: overlapping alternations under one quantifier (`(a|aa)+`) pass it. What bounds
|
|
385
|
-
* those is {@link armRegexGuard} — and a pattern the linear engine cannot take over (a lookahead, a large counted
|
|
386
|
-
* repetition) is refused here, because for it there is no bound at all.
|
|
387
|
-
*/
|
|
388
|
-
export declare function unsafeRegex(src: string): string | undefined;
|
|
389
|
-
/**
|
|
390
|
-
* An IPv6 address as a 128-bit integer, or null if it is not one. Accepts `::` compression, a zone id, brackets and
|
|
391
|
-
* an embedded IPv4 tail (`::ffff:1.2.3.4`) — every spelling of one address yields one number, which is what makes a
|
|
392
|
-
* prefix comparison (and a limiter key, `client-ip.ts`) independent of how a proxy chose to write it.
|
|
393
|
-
*/
|
|
394
|
-
export declare function ipv6ToBigInt(ip: string): bigint | null;
|
|
395
|
-
/**
|
|
396
|
-
* `ip ∈ cidr`, IPv4 and IPv6. An IPv4-mapped IPv6 address is judged by IPv4 rules; an IPv4 address never matches an
|
|
397
|
-
* IPv6 network and vice versa. False for anything malformed. (IPv6 networks used to be unmatchable — PG4-10 — so an
|
|
398
|
-
* `ip` rule or `internalPeers` could not name an IPv6 caller at all.)
|
|
399
|
-
*/
|
|
400
|
-
export declare function matchCidr(ip: string, cidr: string): boolean;
|
|
401
|
-
/** Evaluate a rule node (condition or all/any/not group) against attributes. Pure. A condition that cannot be
|
|
402
|
-
* evaluated safely makes the WHOLE rule false (deny / no targeting), wherever it sits. */
|
|
403
|
-
export declare function evalRule(node: RuleNode, attrs: Attrs): boolean;
|
|
404
|
-
/** First matching rule's version (top-to-bottom), or undefined. */
|
|
405
|
-
export declare function pickTargetedVersion(rules: readonly TargetRule[], attrs: Attrs): {
|
|
406
|
-
version: string;
|
|
407
|
-
rule?: string;
|
|
408
|
-
} | undefined;
|
|
409
|
-
/** 32-bit FNV-1a hash → unsigned int. Stable across processes (no seed). */
|
|
410
|
-
export declare function fnv1a(s: string): number;
|
|
411
|
-
/**
|
|
412
|
-
* Consistent-hash a stable key to a cohort INDEX by weight. The hash point uses
|
|
413
|
-
* a FIXED modulus (10000) so it is stable per key regardless of the weights;
|
|
414
|
-
* only the cohort thresholds move when weights change — so ramping a weight
|
|
415
|
-
* moves a key across the boundary AT MOST ONCE (no reshuffle/flapping). Fixed
|
|
416
|
-
* cohort order. All-zero weights → 0.
|
|
417
|
-
*/
|
|
418
|
-
export declare function bucketByWeight(key: string, weights: readonly number[]): number;
|
|
1
|
+
export * from 'edgeward/manifest';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var v=Object.defineProperty;var c=(e,t)=>v(e,"name",{value:t,configurable:!0});var d=Object.defineProperty,u=c((e,t)=>d(e,"name",{value:t,configurable:!0}),"u");Object.defineProperty(exports,"__esModule",{value:!0}),exports.MAX_REGEX_LENGTH=exports.RATE_LIMIT_KEYS=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.manifestDefects=manifestDefects,exports.admitManifests=admitManifests,exports.manifestProblems=manifestProblems,exports.regexSources=regexSources,exports.manifestFromClusterDecl=manifestFromClusterDecl,exports.claimAttrs=claimAttrs,exports.armRegexGuard=armRegexGuard,exports.unsafeRegex=unsafeRegex,exports.ipv6ToBigInt=ipv6ToBigInt,exports.matchCidr=matchCidr,exports.evalRule=evalRule,exports.pickTargetedVersion=pickTargetedVersion,exports.fnv1a=fnv1a,exports.bucketByWeight=bucketByWeight;const node_v8_1=require("node:v8");exports.RATE_LIMIT_KEYS=new Set(["ip","tenant","user"]);function smoothWeightedSelector(e){const t=e.map(()=>0),r=e.reduce((n,s)=>n+Math.max(0,s),0);return()=>{if(r<=0||e.length===0)return 0;let n=0;for(let s=0;s<e.length;s++)t[s]+=Math.max(0,e[s]),t[s]>t[n]&&(n=s);return t[n]-=r,n}}c(smoothWeightedSelector,"smoothWeightedSelector"),u(smoothWeightedSelector,"smoothWeightedSelector");function hostMatches(e,t){const r=e.toLowerCase(),n=t.toLowerCase();return r.startsWith("*.")?n.endsWith(r.slice(1))||n===r.slice(2):n===r}c(hostMatches,"hostMatches"),u(hostMatches,"hostMatches");function matchRoute(e,t,r){const n=e.some(o=>o.host&&hostMatches(o.host,t));let s;if(n){s=e.filter(i=>i.host&&hostMatches(i.host,t));const o=t.toLowerCase();s.some(i=>i.host.toLowerCase()===o)?s=s.filter(i=>i.host.toLowerCase()===o):s.length>1&&(s=[...s].sort((i,a)=>a.host.length-i.host.length))}else{const o=e.filter(i=>!i.host);if(o.length<=1)s=o;else{const i=t.toLowerCase(),a=o.filter(l=>{const h=l.apex?.toLowerCase();return!!h&&(i===h||i.endsWith("."+h))}).sort((l,h)=>h.apex.length-l.apex.length);s=a.length>0?a:o.filter(l=>!l.apex)}}return s.find(o=>!o.prefix||pathUnderPrefix(r,o.prefix))}c(matchRoute,"matchRoute"),u(matchRoute,"matchRoute");function pathUnderPrefix(e,t){let r=t.length;for(;r>0&&t.charCodeAt(r-1)===47;)r-=1;if(r===0)return!0;if(e.length<r||e.slice(0,r).toLowerCase()!==t.slice(0,r).toLowerCase())return!1;const n=e.charCodeAt(r);return Number.isNaN(n)||n===47||n===63}c(pathUnderPrefix,"pathUnderPrefix"),u(pathUnderPrefix,"pathUnderPrefix");function sortBySpecificity(e){const t=u(r=>(r.host?2:0)+(r.prefix?1:0),"rank");return e.sort((r,n)=>t(n)-t(r)||(n.prefix?.length??0)-(r.prefix?.length??0)),e}c(sortBySpecificity,"sortBySpecificity"),u(sortBySpecificity,"sortBySpecificity");function authForPath(e,t,r){if(r)return"internal";const n=e.auth?.overrides??[];for(const s of n)if(t.startsWith(s.path))return s.mode;return e.auth?.default??"jwt"}c(authForPath,"authForPath"),u(authForPath,"authForPath");function authPathMatches(e,t){const r=e.split("/").filter(Boolean),n=t.split("/").filter(Boolean);if(n.length<r.length)return!1;for(let s=0;s<r.length;s++){const o=r[s];if(!(o==="*"||o.startsWith(":"))&&o.toLowerCase()!==n[s].toLowerCase())return!1}return!0}c(authPathMatches,"authPathMatches"),u(authPathMatches,"authPathMatches");function authRuleFor(e,t,r){const n=r.toUpperCase();for(const s of e?.overrides??[]){if(!authPathMatches(s.path,t)||s.methods&&!s.methods.some(i=>{const a=i.toUpperCase();return a===n||n==="HEAD"&&a==="GET"}))continue;const o=s.rule??(s.permission?{attr:"perms",op:"hastoken",value:s.permission}:void 0);return{mode:s.mode??e?.default??"jwt",...o?{rule:o}:{}}}return{mode:e?.default??"jwt"}}c(authRuleFor,"authRuleFor"),u(authRuleFor,"authRuleFor");function authRuleForPath(e,t,r,n){return n?{mode:"internal"}:authRuleFor(e.auth,t,r)}c(authRuleForPath,"authRuleForPath"),u(authRuleForPath,"authRuleForPath");function buildRouteTable(e){const t=[];for(const r of e){const n=r.auth?.default??"jwt",s=r.auth??{};for(const o of r.mounts){const i={service:r.service,...o.path?{prefix:o.path}:{},...r.prependPrefix?{prependPrefix:r.prependPrefix}:{},...r.upstream?{upstream:r.upstream}:{},...Array.isArray(r.rateLimits)&&r.rateLimits.length?{rateLimits:r.rateLimits}:{}};t.push({...i,host:o.host,auth:n,policy:s}),r.internal&&r.internalHost!==!1&&t.push({...i,host:typeof r.internalHost=="string"?r.internalHost:`internal.${o.host}`,internal:!0,auth:"internal"})}r.default&&t.push({service:r.service,...r.prependPrefix?{prependPrefix:r.prependPrefix}:{},...r.upstream?{upstream:r.upstream}:{},...Array.isArray(r.rateLimits)&&r.rateLimits.length?{rateLimits:r.rateLimits}:{},default:!0,auth:n,policy:s})}return sortBySpecificity(t)}c(buildRouteTable,"buildRouteTable"),u(buildRouteTable,"buildRouteTable");const MOUNT_HOST=/^(\*\.)?[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]+)*\.?$/,isObj=u(e=>!!e&&typeof e=="object"&&!Array.isArray(e),"isObj"),isPath=u(e=>typeof e=="string"&&e.startsWith("/"),"isPath");function manifestDefects(e){if(!isObj(e))return["the manifest is not an object"];const t=[];(typeof e.service!="string"||e.service==="")&&t.push("`service` must be a non-empty string"),Array.isArray(e.mounts)?e.mounts.forEach((s,o)=>{if(!isObj(s)){t.push(`mounts[${o}] is not an object`);return}(typeof s.host!="string"||!MOUNT_HOST.test(s.host))&&t.push(`mounts[${o}].host must be a hostname (a catch-all is \`default: true\`, not a mount without a host)`),s.path!==void 0&&!isPath(s.path)&&t.push(`mounts[${o}].path must be a string starting with \xAB/\xBB`)}):t.push("`mounts` must be an array");const r=e.auth;if(r!==void 0)if(!isObj(r))t.push("`auth` must be an object");else{r.default!==void 0&&typeof r.default!="string"&&t.push("`auth.default` must be a string");const s=r.overrides;s!==void 0&&!Array.isArray(s)?t.push("`auth.overrides` must be an array"):s?.forEach((o,i)=>{if(!isObj(o)){t.push(`auth.overrides[${i}] is not an object`);return}isPath(o.path)||t.push(`auth.overrides[${i}].path must be a string starting with \xAB/\xBB`),o.mode!==void 0&&typeof o.mode!="string"&&t.push(`auth.overrides[${i}].mode must be a string`),o.methods!==void 0&&!(Array.isArray(o.methods)&&o.methods.every(a=>typeof a=="string"))&&t.push(`auth.overrides[${i}].methods must be an array of strings`),o.permission!==void 0&&typeof o.permission!="string"&&t.push(`auth.overrides[${i}].permission must be a string`),o.rule!==void 0&&!isObj(o.rule)&&t.push(`auth.overrides[${i}].rule must be an object`)})}if(e.upstream!==void 0&&e.upstream!==null&&e.upstream!==""){let s=!1;if(typeof e.upstream=="string")try{s=/^(https?|wss?):$/.test(new URL(e.upstream).protocol)}catch{s=!1}s||t.push("`upstream` must be an http(s) URL")}e.internalHost!==void 0&&e.internalHost!==!1&&!(typeof e.internalHost=="string"&&MOUNT_HOST.test(e.internalHost))&&t.push("`internalHost` must be a hostname or false"),e.prependPrefix!==void 0&&!isPath(e.prependPrefix)&&t.push("`prependPrefix` must be a string starting with \xAB/\xBB");const n=e.rateLimits;return n!==void 0&&(Array.isArray(n)?n.forEach((s,o)=>{if(!isObj(s)){t.push(`rateLimits[${o}] is not an object`);return}s.path!==void 0&&!isPath(s.path)&&t.push(`rateLimits[${o}].path must be a string starting with \xAB/\xBB`),(typeof s.key!="string"||!exports.RATE_LIMIT_KEYS.has(s.key))&&t.push(`rateLimits[${o}].key must be one of ${[...exports.RATE_LIMIT_KEYS].join(" | ")}`),typeof s.points=="number"&&Number.isFinite(s.points)&&s.points>=1||t.push(`rateLimits[${o}].points must be a number \u2265 1`),typeof s.duration=="number"&&Number.isFinite(s.duration)&&s.duration>0||t.push(`rateLimits[${o}].duration must be a number of seconds > 0`)}):t.push("`rateLimits` must be an array")),t}c(manifestDefects,"manifestDefects"),u(manifestDefects,"manifestDefects");function ownersOf(e,t){let r;for(const[n,s]of Object.entries(e)){if(n==="(default)")continue;const o=t.startsWith("*.")?t.slice(2):t;(n.toLowerCase()===t.toLowerCase()||hostMatches(n,o))&&(r??=[]).push(...s)}return r}c(ownersOf,"ownersOf"),u(ownersOf,"ownersOf");function admitManifests(e,t){const r=[],n=[];for(const s of Array.isArray(e)?e:[]){const o=isObj(s)&&typeof s.service=="string"&&s.service?s.service:"(unnamed)",i=manifestDefects(s);if(i.length){n.push({service:o,problem:`the manifest is malformed and was NOT loaded \u2014 ${i.slice(0,4).join("; ")}${i.length>4?`; and ${i.length-4} more`:""}`});continue}let a=s;if(t){const l=a.mounts.filter(p=>{const m=ownersOf(t,p.host);return m===void 0||m.includes(a.service)?!0:(n.push({service:a.service,problem:`mount ${p.host}${p.path??""} was NOT loaded \u2014 that host belongs to ${m.join(", ")||"no service"} (host owners)`}),!1)});let h=l.length===a.mounts.length?a:{...a,mounts:l};if(typeof h.internalHost=="string"){const p=ownersOf(t,h.internalHost);p!==void 0&&!p.includes(a.service)&&(n.push({service:a.service,problem:`internalHost ${h.internalHost} was NOT loaded \u2014 that host belongs to ${p.join(", ")||"no service"} (host owners)`}),h={...h,internalHost:!1})}const f=t["(default)"];h.default&&f!==void 0&&!f.includes(a.service)&&(n.push({service:a.service,problem:`\`default: true\` was NOT honoured \u2014 the catch-all belongs to ${f.join(", ")||"no service"} (host owners)`}),h={...h,default:!1}),a=h}r.push(a)}return{ok:r,problems:n}}c(admitManifests,"admitManifests"),u(admitManifests,"admitManifests");const HOST_ROUTE_MODES=new Set(["jwt","public"]);function manifestProblems(e){const t=[],r=new Map,n=new Map;for(const s of e)for(const o of s.mounts){const i=`${o.host.toLowerCase()}|${(o.path??"").replace(/\/+$/,"").toLowerCase()}`,a=n.get(i);a!==void 0&&a!==s.service?t.push({service:s.service,problem:`mounts ${o.host}${o.path??""}, which \xAB${a}\xBB already mounts \u2014 the first one listed serves it; set host owners to decide`}):n.set(i,s.service)}for(const s of e){const o=s.mounts.map(l=>l.host+(l.path??"")),i=r.get(s.service);i&&t.push({service:s.service,problem:`the service name is declared by more than one manifest (${[...i,...o].join(", ")}) \u2014 each route keeps its own manifest's auth policy; give each manifest its own name`}),r.set(s.service,[...i??[],...o]);const a=s.auth?.default;a!==void 0&&!HOST_ROUTE_MODES.has(a)&&t.push({service:s.service,problem:`auth.default is \xAB${String(a)}\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 l of s.auth?.overrides??[]){l.mode!==void 0&&!HOST_ROUTE_MODES.has(l.mode)&&t.push({service:s.service,problem:`the override for ${l.path} has mode \xAB${String(l.mode)}\xBB \u2014 only \`jwt\` and \`public\` are modes; requests under it answer 401`});for(const h of regexSources(l.rule)){const f=unsafeRegex(h);f&&t.push({service:s.service,problem:`the override for ${l.path} has a regex rule the edge will not run (${f}): ${h.slice(0,80)}`})}}}return t}c(manifestProblems,"manifestProblems"),u(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)]:[]:[]}c(regexSources,"regexSources"),u(regexSources,"regexSources");function manifestFromClusterDecl(e,t){const r=t.upstream??(t.port?`http://localhost:${t.port}`:void 0);if(!(!t.service&&!r))return{service:t.service??e,mounts:t.host?[{host:t.host,...t.path?{path:t.path}:{}}]:[],internal:!!t.service,...t.internalHost!==void 0?{internalHost:t.internalHost}:{},...t.default?{default:!0}:{},...t.prependPrefix?{prependPrefix:t.prependPrefix}:{},...t.auth?{auth:t.auth}:{},...r?{upstream:r}:{}}}c(manifestFromClusterDecl,"manifestFromClusterDecl"),u(manifestFromClusterDecl,"manifestFromClusterDecl");const RESERVED_ATTRS=new Set(["ip","method","path","device"]);function claimAttrs(e){const t={...e??{}};for(const r of Object.keys(t))(RESERVED_ATTRS.has(r)||r.startsWith("header."))&&delete t[r];return t}c(claimAttrs,"claimAttrs"),u(claimAttrs,"claimAttrs");const isGroup=u(e=>"all"in e||"any"in e||"not"in e,"isGroup");exports.MAX_REGEX_LENGTH=512;const LINEAR=["l"].join("");let linearGuard;function armRegexGuard(){if(linearGuard!==void 0)return linearGuard;try{(0,node_v8_1.setFlagsFromString)("--enable-experimental-regexp-engine-on-excessive-backtracks"),(0,node_v8_1.setFlagsFromString)("--enable-experimental-regexp-engine"),new RegExp("a",LINEAR),linearGuard=!0}catch{linearGuard=!1}return linearGuard}c(armRegexGuard,"armRegexGuard"),u(armRegexGuard,"armRegexGuard");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";if(armRegexGuard()){let n=!0;try{new RegExp(e)}catch{n=!1}if(n)try{new RegExp(e,LINEAR)}catch{return"no linear-time fallback (a lookahead, or a counted repetition too large to expand)"}}const t=[];let r;for(let n=0;n<e.length;){const s=e[n];if(s==="\\"){n+=2,r=!1;continue}if(s==="["){for(n+=1,e[n]==="^"&&(n+=1),e[n]==="]"&&(n+=1);n<e.length&&e[n]!=="]";)n+=e[n]==="\\"?2:1;n+=1,r=!1;continue}if(s==="("){if(t.push(!1),n+=1,r=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(s===")"){const a=t.pop()??!1;n+=1,a&&t.length&&(t[t.length-1]=!0),r=a;continue}if(s==="|"){n+=1,r=void 0;continue}let o,i=1;if(s==="*"||s==="+")o=!0;else if(s==="?")o=!1;else if(s==="{"){const a=/^\{(\d+)(,(\d*))?\}/.exec(e.slice(n));if(a){i=a[0].length;const l=Number(a[1]);o=(a[2]===void 0?l:a[3]===""?1/0:Number(a[3]))>1}}if(o===void 0){n+=1,r=!1;continue}if(n+=i,e[n]==="?"&&(n+=1),r!==void 0){if(o&&r)return"nested quantifiers";o&&t.length&&(t[t.length-1]=!0),r=!1}}}c(unsafeRegex,"unsafeRegex"),u(unsafeRegex,"unsafeRegex");class Indeterminate extends Error{static{c(this,"Indeterminate")}static{u(this,"Indeterminate")}}const reCache=new Map,compileRe=u(e=>{if(reCache.has(e))return reCache.get(e);let t=null;if(armRegexGuard(),!unsafeRegex(e))try{t=new RegExp(e)}catch{t=null}return reCache.size>=1024&&reCache.clear(),reCache.set(e,t),t},"compileRe");function ipToInt(e){const t=(e.startsWith("::ffff:")?e.slice(7):e).split(".");if(t.length!==4)return null;let r=0;for(const n of t){const s=Number(n);if(!Number.isInteger(s)||s<0||s>255||n.length>1&&n[0]==="0")return null;r=r*256+s}return r>>>0}c(ipToInt,"ipToInt"),u(ipToInt,"ipToInt");function ipv6ToBigInt(e){let t=e;const r=t.indexOf("%");if(r!==-1&&(t=t.slice(0,r)),t.startsWith("[")&&t.endsWith("]")&&(t=t.slice(1,-1)),!t.includes(":")||t.length>45)return null;const n=t.lastIndexOf(":"),s=t.slice(n+1);if(s.includes(".")){const l=ipToInt(s);if(l===null)return null;t=`${t.slice(0,n+1)}${(l>>>16).toString(16)}:${(l&65535).toString(16)}`}const o=t.indexOf("::");if(o!==t.lastIndexOf("::"))return null;let i;if(o===-1){if(i=t.split(":"),i.length!==8)return null}else{const l=t.slice(0,o)?t.slice(0,o).split(":"):[],h=t.slice(o+2)?t.slice(o+2).split(":"):[];if(l.length+h.length>7)return null;i=[...l,...new Array(8-l.length-h.length).fill("0"),...h]}let a=0n;for(const l of i){if(!/^[0-9a-fA-F]{1,4}$/.test(l))return null;a=a<<16n|BigInt(parseInt(l,16))}return a}c(ipv6ToBigInt,"ipv6ToBigInt"),u(ipv6ToBigInt,"ipv6ToBigInt");function matchCidr(e,t){const r=t.indexOf("/");if(r<0)return!1;const n=Number(t.slice(r+1)),s=t.slice(0,r);if(s.includes(":")){if(!Number.isInteger(n)||n<0||n>128||ipToInt(e)!==null)return!1;const l=ipv6ToBigInt(e),h=ipv6ToBigInt(s);if(l===null||h===null)return!1;if(n===0)return!0;const f=BigInt(128-n);return l>>f===h>>f}if(!Number.isInteger(n)||n<0||n>32)return!1;const o=ipToInt(e),i=ipToInt(s);if(o===null||i===null)return!1;if(n===0)return!0;const a=(n===32?4294967295:~((1<<32-n)-1))>>>0;return(o&a)>>>0===(i&a)>>>0}c(matchCidr,"matchCidr"),u(matchCidr,"matchCidr");const str=u(e=>e==null?"":String(e),"str"),eq=u((e,t)=>str(e)===str(t),"eq");function evalCondition(e,t){const r=t[e.attr],n=r!=null;switch(e.op){case"exists":return n;case"ne":return!n||!eq(r,e.value)}if(!n)return!1;switch(e.op){case"eq":return eq(r,e.value);case"in":return Array.isArray(e.value)&&e.value.some(s=>Array.isArray(r)?r.some(o=>eq(o,s)):eq(r,s));case"nin":return Array.isArray(e.value)&&!e.value.some(s=>Array.isArray(r)?r.some(o=>eq(o,s)):eq(r,s));case"prefix":return str(r).startsWith(str(e.value));case"suffix":return str(r).endsWith(str(e.value));case"domain":{const s=str(r).lastIndexOf("@"),o=(s===-1?str(r):str(r).slice(s+1)).toLowerCase().replace(/\.$/,""),i=str(e.value).toLowerCase().replace(/^\./,"").replace(/\.$/,"");return!!i&&(o===i||o.endsWith("."+i))}case"contains":return Array.isArray(r)?r.some(s=>eq(s,e.value)):str(r).includes(str(e.value));case"hastoken":{const s=str(e.value);return Array.isArray(r)?r.some(o=>eq(o,e.value)):str(r).split(/[\s,]+/).filter(Boolean).includes(s)}case"regex":{const s=compileRe(str(e.value)),o=str(r);if(!s||o.length>exports.MAX_REGEX_LENGTH)throw new Indeterminate;return s.test(o)}case"gt":return Number(r)>Number(e.value);case"lt":return Number(r)<Number(e.value);case"cidr":return matchCidr(str(r),str(e.value));default:return!1}}c(evalCondition,"evalCondition"),u(evalCondition,"evalCondition");function evalNode(e,t){if(!isGroup(e))return evalCondition(e,t);const r=Array.isArray(e.all)&&e.all.length?e.all:void 0,n=Array.isArray(e.any)&&e.any.length?e.any:void 0,s=e.not&&Object.keys(e.not).length?e.not:void 0;return s&&evalNode(s,t)||r&&!r.every(o=>evalNode(o,t))||n&&!n.some(o=>evalNode(o,t))?!1:!!(r||n||s)}c(evalNode,"evalNode"),u(evalNode,"evalNode");function evalRule(e,t){try{return evalNode(e,t)}catch(r){if(r instanceof Indeterminate)return!1;throw r}}c(evalRule,"evalRule"),u(evalRule,"evalRule");function pickTargetedVersion(e,t){for(const r of e)if(evalRule(r.when,t))return{version:r.version,...r.name?{rule:r.name}:{}}}c(pickTargetedVersion,"pickTargetedVersion"),u(pickTargetedVersion,"pickTargetedVersion");function fnv1a(e){let t=2166136261;for(let r=0;r<e.length;r++)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return t>>>0}c(fnv1a,"fnv1a"),u(fnv1a,"fnv1a");function bucketByWeight(e,t){const r=t.reduce((o,i)=>o+Math.max(0,i),0);if(r<=0||t.length===0)return 0;const n=fnv1a(e)%1e4;let s=0;for(let o=0;o<t.length;o++)if(s+=Math.max(0,t[o])/r*1e4,n<s)return o;return t.length-1}c(bucketByWeight,"bucketByWeight"),u(bucketByWeight,"bucketByWeight");
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});const tslib_1=require("tslib");tslib_1.__exportStar(require("edgeward/manifest"),exports);
|
|
@@ -1,80 +1 @@
|
|
|
1
|
-
|
|
2
|
-
* The trust boundary (verbatim dev model). The gateway OWNS the identity/trust
|
|
3
|
-
* headers — drop any client-supplied copy at ingress so identity can only
|
|
4
|
-
* originate from a verified token, then re-stamp on forward. Pure.
|
|
5
|
-
*/
|
|
6
|
-
import type * as http from 'node:http';
|
|
7
|
-
import type { ProxyKind } from '../client-ip';
|
|
8
|
-
export declare const TRUST_HEADERS: string[];
|
|
9
|
-
export declare const HOP_BY_HOP: string[];
|
|
10
|
-
export declare const METHOD_OVERRIDE_HEADERS: string[];
|
|
11
|
-
/** Forwarding headers the GATEWAY states on the way out — a client's copy is never what the upstream reads. */
|
|
12
|
-
export declare const FORWARDED_HEADERS: string[];
|
|
13
|
-
/** The hop counter (PG4-16): how many times this request has passed a LensMCP gateway. */
|
|
14
|
-
export declare const HOP_HEADER = "x-lensmcp-hops";
|
|
15
|
-
/** A request that has been through the gateway this often is a loop, not a chain of proxies. */
|
|
16
|
-
export declare const MAX_HOPS = 8;
|
|
17
|
-
/**
|
|
18
|
-
* Headers that name a DIFFERENT path, or restate the forwarding chain in a second dialect — dropped from every
|
|
19
|
-
* request (PG4-08). `X-Original-URL` / `X-Rewrite-URL` are honoured by IIS, Symfony and friends as THE request path:
|
|
20
|
-
* the edge authorises `/public` and the upstream serves `/admin`. `Forwarded` (RFC 7239) is preferred over
|
|
21
|
-
* `X-Forwarded-*` by Spring and Rack; the gateway rewrites the `X-Forwarded-*` family and never wrote this one, so a
|
|
22
|
-
* client's copy was the only statement an upstream that reads it ever got.
|
|
23
|
-
*/
|
|
24
|
-
export declare const ALWAYS_DROPPED: string[];
|
|
25
|
-
/**
|
|
26
|
-
* Client-address and forwarding headers a front proxy may assert and a caller may not (PG4-08). Kept from a counted
|
|
27
|
-
* `X-Forwarded-For` chain (a generic load balancer legitimately sets `X-Forwarded-Port`); dropped from everyone
|
|
28
|
-
* else — a proxy trusted for its OWN header (`cf-connecting-ip`) vouches for its own family, not for these, which
|
|
29
|
-
* Cloudflare passes through from the client untouched.
|
|
30
|
-
*/
|
|
31
|
-
export declare const PROXY_CLAIM_HEADERS: string[];
|
|
32
|
-
export declare const stripTrust: (req: http.IncomingMessage) => void;
|
|
33
|
-
/**
|
|
34
|
-
* Drop what a caller may not assert about itself, given what its peer is to the gateway (PG4-08):
|
|
35
|
-
* - `'chain'` (a counted X-Forwarded-For chain) — nothing more: a generic proxy's forwarding headers are its own;
|
|
36
|
-
* - `'header'` (trusted for `clientIpHeader`) — the generic claims go, its own header family stays;
|
|
37
|
-
* - `'none'` — the generic claims go, and so do the CONFIGURED proxy's headers: `configured` (its client-address
|
|
38
|
-
* header) and every header of the same vendor family (`cf-…` beside `cf-connecting-ip`). Rule attribute headers
|
|
39
|
-
* are NOT among them — they may be ordinary request headers an upstream needs from every caller. The gateway already ignored those for its own decisions; it used to forward them, so an
|
|
40
|
-
* upstream that reads `cf-connecting-ip` or `cf-access-authenticated-user-email` was told whatever a direct
|
|
41
|
-
* caller wrote. With no proxy configured the gateway has no proxy model, and only the generic claims are dropped.
|
|
42
|
-
* - `'peer'` (a trusted peer, no client-address header configured) — as `'header'`: the generic claims go.
|
|
43
|
-
*/
|
|
44
|
-
export declare const stripProxyClaims: (headers: http.IncomingHttpHeaders, kind: ProxyKind, configured: readonly string[]) => void;
|
|
45
|
-
/**
|
|
46
|
-
* Count this hop on the request, or return undefined when it has been through a LensMCP gateway {@link MAX_HOPS}
|
|
47
|
-
* times already (PG4-16). A route whose upstream resolves back to the gateway used to turn ONE request into 257 —
|
|
48
|
-
* the whole upstream pool — before a timeout ended it; nothing marked a request as having been here before. A
|
|
49
|
-
* client's own value is read as a number or not at all, and can only cut its own request short.
|
|
50
|
-
*/
|
|
51
|
-
export declare const countHop: (req: http.IncomingMessage) => number | undefined;
|
|
52
|
-
/**
|
|
53
|
-
* Request headers undici's `Request` constructor REFUSES, each with the error it would raise (PG3-17). Forwarded
|
|
54
|
-
* unchanged, a client's copy made the dispatch throw synchronously, and undici's pool read that `false` as
|
|
55
|
-
* backpressure: the connection was marked `needDrain` with nothing in flight to ever drain it, so ONE pool slot was
|
|
56
|
-
* lost per request — four anonymous requests to a public path wedged a pool of four, i.e. every service on that
|
|
57
|
-
* upstream origin. (`connection`/`keep-alive` are already dropped above; reply-from drops `transfer-encoding`.)
|
|
58
|
-
* - `upgrade`: `invalid upgrade header`. A real upgrade never reaches the HTTP path — Node routes a request that
|
|
59
|
-
* carries `Connection: upgrade` to the `upgrade` event; a bare `Upgrade:` is a client's noise.
|
|
60
|
-
* - `expect`: `expect header not supported`. Node already answered `100 Continue` at the edge; the body is
|
|
61
|
-
* forwarded without the header.
|
|
62
|
-
* HTTP path ONLY — the WebSocket path rebuilds its handshake from `rawHeaders` and must keep `Upgrade`.
|
|
63
|
-
*/
|
|
64
|
-
export declare const UNFORWARDABLE_HEADERS: string[];
|
|
65
|
-
export declare const stripUnforwardable: (req: http.IncomingMessage) => void;
|
|
66
|
-
/**
|
|
67
|
-
* The first outgoing header whose value undici would refuse, or undefined. Node's parser already refuses such bytes
|
|
68
|
-
* from a CLIENT, so what this catches is what the gateway itself put on the request — a verified claim stamped as
|
|
69
|
-
* `x-user-id` / `x-tenant-id` / `x-user-roles` carrying CR, LF or NUL, or a customer hook's header. Checked BEFORE
|
|
70
|
-
* dispatch, because undici refusing it inside the pool costs a connection slot for good (the PG3-17 mechanism).
|
|
71
|
-
*/
|
|
72
|
-
export declare const unforwardableHeader: (headers: http.IncomingHttpHeaders) => string | undefined;
|
|
73
|
-
/**
|
|
74
|
-
* Stamp the verified identity onto the forwarded request — tenant from the `tid` CLAIM, never a client header. A
|
|
75
|
-
* workload's token (a composition's `preAuth`, `../workspace-auth`) is a service's: no `x-user-id`, no `x-user-roles`.
|
|
76
|
-
* Returns how many role / permission elements were refused, so the caller can say so.
|
|
77
|
-
*/
|
|
78
|
-
export declare const stampIdentity: (req: http.IncomingMessage, claims: Record<string, unknown>) => {
|
|
79
|
-
dropped: number;
|
|
80
|
-
};
|
|
1
|
+
export * from 'edgeward/prod-runtime/trust';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});const tslib_1=require("tslib");tslib_1.__exportStar(require("edgeward/prod-runtime/trust"),exports);
|
|
@@ -1,81 +1 @@
|
|
|
1
|
-
|
|
2
|
-
* In-memory token-bucket rate limiter — OPT-IN, per-instance, per-key.
|
|
3
|
-
*
|
|
4
|
-
* Defense-in-depth, NOT the primary limiter: Cloudflare / Cloud Armor remain the
|
|
5
|
-
* global edge throttle. This caps abuse per gateway instance, keyed by the real
|
|
6
|
-
* client IP (resolved through the same trusted-proxy logic as ABAC), and only on
|
|
7
|
-
* the proxied catch-all — the ops endpoints (/livez, /readyz, /statusz) are
|
|
8
|
-
* registered routes and are never subject to it.
|
|
9
|
-
*
|
|
10
|
-
* Token bucket: `limit` tokens refill smoothly over `windowMs`; each request
|
|
11
|
-
* spends one. Empty bucket → denied with the ms until the next token. Idle
|
|
12
|
-
* (refilled-to-full) buckets are swept so the key map can't grow unbounded.
|
|
13
|
-
*/
|
|
14
|
-
export interface RateLimiterOptions {
|
|
15
|
-
/** Tokens (requests) per window. */
|
|
16
|
-
limit: number;
|
|
17
|
-
/** Window length the `limit` refills over (ms). */
|
|
18
|
-
windowMs: number;
|
|
19
|
-
/** Injectable clock (tests). Defaults to Date.now. */
|
|
20
|
-
now?: () => number;
|
|
21
|
-
}
|
|
22
|
-
export interface RateDecision {
|
|
23
|
-
allowed: boolean;
|
|
24
|
-
remaining: number;
|
|
25
|
-
retryAfterMs: number;
|
|
26
|
-
}
|
|
27
|
-
export interface RateLimiter {
|
|
28
|
-
/** Spend one token for `key`. In-memory returns synchronously; the Redis-backed
|
|
29
|
-
* limiter returns a Promise (one round-trip) — the gateway `await`s either. */
|
|
30
|
-
check(key: string): RateDecision | Promise<RateDecision>;
|
|
31
|
-
stop(): void;
|
|
32
|
-
}
|
|
33
|
-
/** The in-memory limiter — its `check` is SYNCHRONOUS (no round-trip). Assignable to {@link RateLimiter}
|
|
34
|
-
* (a `RateDecision` widens to `RateDecision | Promise<RateDecision>`), so it drops in wherever the async
|
|
35
|
-
* interface is expected while callers/tests can read the result without an `await`. */
|
|
36
|
-
export interface SyncRateLimiter {
|
|
37
|
-
check(key: string): RateDecision;
|
|
38
|
-
stop(): void;
|
|
39
|
-
}
|
|
40
|
-
export declare function createRateLimiter(opts: RateLimiterOptions): SyncRateLimiter;
|
|
41
|
-
/**
|
|
42
|
-
* Redis-backed token-bucket rate limiter — ONE GLOBAL budget shared by every
|
|
43
|
-
* gateway container/instance (so a per-IP limit is N-container-independent, unlike
|
|
44
|
-
* the in-memory limiter whose limit silently multiplies by instance count).
|
|
45
|
-
*
|
|
46
|
-
* The check is a single atomic Lua EVAL (no GET-then-SET race), using Redis's own
|
|
47
|
-
* clock (`TIME`) so instances agree on refill regardless of host clock skew. The
|
|
48
|
-
* bucket key TTLs out shortly after a full refill, so idle clients leave no residue.
|
|
49
|
-
*
|
|
50
|
-
* Hot-path cost: one Redis round-trip per request. It is bounded by `timeoutMs` and
|
|
51
|
-
* **fails open** by default — a slow/unreachable Redis must not 429 all traffic and
|
|
52
|
-
* take the gateway down (it's defense-in-depth; Cloudflare/Cloud Armor stay the
|
|
53
|
-
* primary edge throttle). Set `failOpen: false` only if you'd rather shed load than
|
|
54
|
-
* risk exceeding the budget during a Redis outage.
|
|
55
|
-
*/
|
|
56
|
-
export interface RedisRateLimiterOptions {
|
|
57
|
-
/** Tokens (requests) per window. */
|
|
58
|
-
limit: number;
|
|
59
|
-
/** Window the `limit` refills over (ms). */
|
|
60
|
-
windowMs: number;
|
|
61
|
-
/** Key namespace — the Redis key is `<prefix><key>`. Default 'lensmcp:gw:rl:'. */
|
|
62
|
-
prefix?: string;
|
|
63
|
-
/** Max ms to wait on the Redis round-trip before applying the fail policy. Default 100. */
|
|
64
|
-
timeoutMs?: number;
|
|
65
|
-
/** On Redis error/timeout: true → allow (default), false → deny. */
|
|
66
|
-
failOpen?: boolean;
|
|
67
|
-
/**
|
|
68
|
-
* Called ONCE, the first time the limiter falls back to its fail policy.
|
|
69
|
-
*
|
|
70
|
-
* A limiter that fails open answers "allowed" to everything and says nothing, while startup has
|
|
71
|
-
* already logged that GLOBAL rate limiting is on — so a namespace/ACL mismatch looks exactly like
|
|
72
|
-
* a working limiter (issues/closed/codex-security-34). Once, not per request: the point is to be noticed,
|
|
73
|
-
* not to become the flood.
|
|
74
|
-
*/
|
|
75
|
-
onFailure?: (reason: string) => void;
|
|
76
|
-
}
|
|
77
|
-
/** The single ioredis method the limiter needs — an atomic script eval. */
|
|
78
|
-
export interface RateLimitRedis {
|
|
79
|
-
eval(script: string, numKeys: number, ...args: (string | number)[]): Promise<unknown>;
|
|
80
|
-
}
|
|
81
|
-
export declare function createRedisRateLimiter(client: RateLimitRedis, opts: RedisRateLimiterOptions): RateLimiter;
|
|
1
|
+
export * from 'edgeward/rate-limit';
|