cabloy 5.1.239 → 5.1.240

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/.cabloy-version CHANGED
@@ -1 +1 @@
1
- 5.1.239
1
+ 5.1.240
package/CHANGELOG.md CHANGED
@@ -1,5 +1,12 @@
1
1
  # Changelog
2
2
 
3
+ ## 5.1.240
4
+
5
+ ### Improvements
6
+
7
+ - Enhance rate limiting.
8
+ - Update hot module replacement (HMR) handling.
9
+
3
10
  ## 5.1.239
4
11
 
5
12
  ### Improvements
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cabloy",
3
- "version": "5.1.239",
3
+ "version": "5.1.240",
4
4
  "gitHead": "2c5c19284bab738e492856189acb6fad74b8a7b7",
5
5
  "description": "A Node.js fullstack framework",
6
6
  "keywords": [
@@ -2,11 +2,56 @@
2
2
 
3
3
  ## Overview
4
4
 
5
- `a-ratelimit` limits matched Vona HTTP API actions across all application workers. It runs as the global `a-ratelimit:rateLimit` interceptor after Passport has resolved an authenticated or anonymous subject, and before request-body parsing, pipes, local middleware, and controller code. See [Controller AOP Guide](/backend/controller-aop-guide) for the general request-stage diagram and the distinction between a local aspect and a route override of an existing global onion.
5
+ `a-ratelimit` provides two independent admission controls:
6
6
 
7
- It protects controller APIs. Put volumetric, static-file, unknown-route, and network-edge protection in the reverse proxy, WAF, or gateway.
7
+ - The identity interceptor, `a-ratelimit:rateLimit`, limits matched Vona HTTP API actions across all application workers. It runs after Passport has resolved an authenticated or anonymous subject, and before request-body parsing, pipes, local middleware, and controller code.
8
+ - The aggregate system middleware, `a-ratelimit:aggregate`, limits incoming HTTP requests across the application before the application/instance readiness middleware and routing, but after the HTTP executor's initial instance lookup. It is disabled by default and requires explicit configuration.
8
9
 
9
- ## Enablement and rollout
10
+ The identity interceptor protects controller APIs only; its route matching and instance isolation do not describe the aggregate middleware. Keep volumetric and network-edge protection in the reverse proxy, WAF, or gateway even when aggregate admission is enabled. See [Controller AOP Guide](/backend/controller-aop-guide) for the general request-stage diagram and the distinction between a local aspect and a route override of an existing global onion.
11
+
12
+ The aggregate middleware documented here is a Cabloy Basic runtime addition. Cabloy Start is maintained separately and does not automatically receive this runtime change; shared documentation does not imply aggregate middleware availability in Start.
13
+
14
+ ## Aggregate application admission
15
+
16
+ Enable the system middleware through application configuration, starting in observe mode:
17
+
18
+ ```ts
19
+ config.onions.middlewareSystem['a-ratelimit:aggregate'] = {
20
+ enable: true,
21
+ rateLimit: {
22
+ mode: 'observe',
23
+ limit: 100,
24
+ },
25
+ };
26
+ ```
27
+
28
+ `100` is an example limit, not a measured application capacity or a recommended production value. An enabled aggregate middleware requires an explicit valid `limit` and a `mode` of either `'observe'` or `'enforce'`; there is no enabled default quota. Review observed traffic and Redis health before changing `mode` to `'enforce'`.
29
+
30
+ ### Coverage and ordering
31
+
32
+ The aggregate middleware runs after `httpLog` and before health handling, the application/instance readiness middleware, routing, and authentication. The HTTP listener enters the executor first: it resolves the instance name and, when applicable, loads the instance record before dispatching system middleware. Aggregate admission does not protect that initial lookup or any instance registration it triggers, and requests that fail before middleware dispatch are not counted.
33
+
34
+ By default, aggregate admission covers all requests that reach the system middleware chain, including API, SSR, static-file, preflight, health, and unknown-route requests. Standard system middleware `match` and `ignore` options can narrow this coverage; they match the incoming `ctx.path`, including the API prefix where present, before routing. Traffic served entirely by a proxy or CDN never reaches this counter. Other programs, background work, and later WebSocket messages are outside its coverage.
35
+
36
+ Aggregate admission is independent of the identity interceptor. Both can be enabled, and a controller/action identity policy with `enable: false` does not bypass aggregate admission. There are no built-in aggregate path exemptions: unless explicitly excluded through system middleware matching, saturation can reject health probes and control requests before their handlers run. Account for this operational consequence before enforcing the quota.
37
+
38
+ ### Shared counter and fixed windows
39
+
40
+ The aggregate counter uses the `limiter` Redis client and the application Redis prefix. It is shared across users, routes, instances, and workers rather than partitioned by identity or active instance. Multiple hosts using the same prefix and Redis share the quota; this is not physical-host discovery or an automatic per-host capacity limit. Keep custom application prefixes unique for applications or environments that require independent quotas.
41
+
42
+ The window is fixed at `1000` ms and aligned to one-second boundaries. Attempts count toward the window, including requests already rejected for exceeding the limit. As with other fixed-window counters, traffic can burst around a window boundary; the limit is not a rolling-window guarantee.
43
+
44
+ ### Modes, responses, and logs
45
+
46
+ In `observe` mode, requests over the limit log `rate_limit.would_reject` and still continue to the next middleware. Redis failures log `rate_limit.redis_error` and fail open, allowing the request to continue.
47
+
48
+ In `enforce` mode, an over-limit request logs `rate_limit.rejected` and returns HTTP `429` with `Retry-After`. A Redis failure logs `rate_limit.redis_error` and returns HTTP `503` instead of allowing unbounded admission. Both responses are direct JSON bodies with the shape `{ code, message }`, even for requests expecting HTML; they do not enter the normal page/error rendering path.
49
+
50
+ Aggregate admission does not add success `RateLimit-*` headers. The identity interceptor's response headers remain unchanged when a request reaches that interceptor.
51
+
52
+ Aggregate logs use the same event names as the identity interceptor, with `scope: 'aggregate'`. Redis failures expose only a sanitized error class, not a raw error message. Do not include raw identities, routes, full URLs, or Redis keys in aggregate logs or metric labels.
53
+
54
+ ## Identity interceptor enablement and rollout
10
55
 
11
56
  The interceptor ships with `enable: false` to preserve compatibility. Enable the global interceptor through standard onion configuration and begin in observe mode:
12
57
 
@@ -36,9 +81,9 @@ config.onions.interceptor['a-ratelimit:rateLimit'] = {
36
81
  };
37
82
  ```
38
83
 
39
- Use instance configuration when tenants require different policy values. Each limiter key always includes the active instance, so one instance never consumes another instance’s quota.
84
+ Use instance configuration when tenants require different identity policy values. Each identity interceptor key includes the active instance, so one instance never consumes another instance’s identity quota. The aggregate middleware instead shares one application-prefix quota across instances.
40
85
 
41
- ## Route policies
86
+ ## Identity route policies
42
87
 
43
88
  Use `Core.rateLimit(...)` on a controller for its baseline policy, or on an action for a stricter policy, an intentional shared bucket, or an explicit exemption:
44
89
 
@@ -64,7 +109,7 @@ async requestReset() {}
64
109
  health() {}
65
110
  ```
66
111
 
67
- `enable`, matching, and ordering remain outer interceptor options. The nested `rateLimit` object contains the quota policy, so partial controller/action overrides inherit the remaining policy fields through normal Vona onion merging. Interceptor options use normal Vona precedence: application config, active-instance config, controller/action decorators, then controlled dynamic onion overrides used by tests. A controller/action can enable a narrower policy while the global interceptor is disabled, or set `enable: false` as a reviewed exemption after global activation. Do not put this policy in another middleware’s options: only `a-ratelimit:rateLimit` consumes the `rateLimit` object at the post-Passport interceptor stage.
112
+ `enable`, matching, and ordering remain outer interceptor options. The nested `rateLimit` object contains the quota policy, so partial controller/action overrides inherit the remaining policy fields through normal Vona onion merging. Interceptor options use normal Vona precedence: application config, active-instance config, controller/action decorators, then controlled dynamic onion overrides used by tests. A controller/action can enable a narrower policy while the global interceptor is disabled, or set `enable: false` as a reviewed exemption after global activation. These identity policy fields belong to `a-ratelimit:rateLimit` at the post-Passport interceptor stage, not to another middleware. The aggregate system middleware has its own independent `rateLimit` configuration described above.
68
113
 
69
114
  ## Identity and Redis storage
70
115
 
@@ -72,11 +117,11 @@ The default `key: 'identity'` combines the proxy-trusted `ctx.ip` with the authe
72
117
 
73
118
  Do not parse `X-Forwarded-For` in application code. Vona resolves `ctx.ip` according to its configured proxy trust settings. The trusted reverse proxy must replace client-supplied forwarding headers before forwarding a request.
74
119
 
75
- The limiter always uses the dedicated `limiter` Redis client; this infrastructure choice is not a route-policy field. It registers one atomic Lua fixed-window counter command during module startup and invokes that command for each request. Redis keys contain the instance, policy, normalized route, window start, and a SHA-256 digest of the identity; raw IP addresses and subject IDs are not stored in key text.
120
+ The identity interceptor always uses the dedicated `limiter` Redis client; this infrastructure choice is not a route-policy field. It registers one atomic Lua fixed-window counter command during module startup and invokes that command for each evaluated request. Identity Redis keys contain the instance, policy, normalized route, window start, and a SHA-256 digest of the identity; raw IP addresses and subject IDs are not stored in key text.
76
121
 
77
122
  Fixed windows provide one low-cost atomic operation per request. A limit can burst around a window boundary; choose lower limits or shorter windows for especially sensitive actions.
78
123
 
79
- ## HTTP response contract
124
+ ## Identity HTTP response contract
80
125
 
81
126
  In enforce mode, evaluated requests expose RFC 9333 fields when `headers` is enabled:
82
127
 
@@ -90,7 +135,7 @@ If the limiter Redis operation fails during enforce mode, Cabloy returns `503`,
90
135
 
91
136
  ## Operations
92
137
 
93
- The primary structured events are `rate_limit.would_reject`, `rate_limit.rejected`, and `rate_limit.redis_error`. They contain only route/policy/instance and error-class information; do not add raw identities, full URLs, or Redis keys to logs or metric labels.
138
+ The primary structured events are `rate_limit.would_reject`, `rate_limit.rejected`, and `rate_limit.redis_error`. Identity interceptor events contain only route/policy/instance and error-class information. Aggregate events carry `scope: 'aggregate'` and omit route/identity detail, with only a sanitized error class for Redis failures. Do not add raw identities, full URLs, or Redis keys to logs or metric labels.
94
139
 
95
140
  The `limiter` client may initially use the same Redis deployment as other Vona clients, but it is separately configured so production can isolate its endpoint, timeout, and capacity. Ensure Redis remains available before globally setting `enable: true` with `rateLimit.mode: 'enforce'`.
96
141
 
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vona",
3
- "version": "5.1.118",
3
+ "version": "5.1.119",
4
4
  "gitHead": "a79189b882c17af5911573896a781bbb0046d37d",
5
5
  "description": "Vona is an intuitive, elegant and powerful Node.js framework for rapidly developing enterprise applications of any size",
6
6
  "keywords": [
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vona-module-a-hmr",
3
- "version": "5.1.15",
3
+ "version": "5.1.16",
4
4
  "gitHead": "a79189b882c17af5911573896a781bbb0046d37d",
5
5
  "description": "",
6
6
  "keywords": [
@@ -34,7 +34,7 @@ export class ServiceHmr extends BeanBase {
34
34
  if (sceneName === '_error') {
35
35
  await this._reloadError(moduleName!, fileModule.errors);
36
36
  } else if (sceneName === '_locale') {
37
- await this._reloadLocale(moduleName!, fileModule.default, file);
37
+ await this._reloadLocale();
38
38
  } else if (sceneName === '_config') {
39
39
  await this._reloadConfig(moduleName!, fileModule.config);
40
40
  } else if (sceneName === '_constant') {
@@ -50,17 +50,10 @@ export class ServiceHmr extends BeanBase {
50
50
  deepExtend(this.app.meta.error.ebErrors[moduleName], errors);
51
51
  }
52
52
 
53
- private async _reloadLocale(moduleName: string, moduleLocales: {}, file: string) {
54
- const locale = path.basename(file, '.ts');
55
- // localeModules
56
- if (!this.app.meta.localeModules[moduleName]) this.app.meta.localeModules[moduleName] = {};
57
- this.app.meta.localeModules[moduleName][locale] = Object.assign(
58
- {},
59
- moduleLocales,
60
- this.app.meta.hmrCacheLocaleModules[moduleName]?.[locale],
61
- );
62
- // openapi
63
- await this.bean.openapi.clearAllCaches();
53
+ private async _reloadLocale() {
54
+ // Ordinary dictionaries also contribute to the ordered global fallback map.
55
+ // Restart to remove stale values and restore project/provider precedence in both maps.
56
+ this.app.bean.worker.reload();
64
57
  }
65
58
 
66
59
  private async _reloadConfig(moduleName: string, config: TypeModuleResourceConfig) {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vona-module-a-ratelimit",
3
- "version": "5.1.3",
3
+ "version": "5.1.4",
4
4
  "description": "",
5
5
  "keywords": [
6
6
  "Vona Module"
@@ -25,6 +25,32 @@ declare module 'vona-module-a-ratelimit' {
25
25
  }
26
26
  }
27
27
  /** interceptor: end */
28
+ /** middlewareSystem: begin */
29
+ export * from '../bean/middlewareSystem.aggregate.ts';
30
+ import type { IMiddlewareSystemOptionsAggregate } from '../bean/middlewareSystem.aggregate.ts';
31
+ import 'vona-module-a-aspect';
32
+ declare module 'vona-module-a-aspect' {
33
+
34
+ export interface IMiddlewareSystemRecord {
35
+ 'a-ratelimit:aggregate': IMiddlewareSystemOptionsAggregate;
36
+ }
37
+
38
+
39
+ }
40
+ declare module 'vona-module-a-ratelimit' {
41
+
42
+ export interface MiddlewareSystemAggregate {
43
+ /** @internal */
44
+ get scope(): ScopeModuleARatelimit;
45
+ }
46
+
47
+ export interface MiddlewareSystemAggregate {
48
+ get $beanFullName(): 'a-ratelimit.middlewareSystem.aggregate';
49
+ get $onionName(): 'a-ratelimit:aggregate';
50
+ get $onionOptions(): IMiddlewareSystemOptionsAggregate;
51
+ }
52
+ }
53
+ /** middlewareSystem: end */
28
54
  /** service: begin */
29
55
  export * from '../service/rateLimit.ts';
30
56
 
@@ -0,0 +1,58 @@
1
+ import type { Next } from 'vona';
2
+ import type {
3
+ IDecoratorMiddlewareSystemOptions,
4
+ IMiddlewareSystemExecute,
5
+ } from 'vona-module-a-aspect';
6
+
7
+ import { BeanBase } from 'vona';
8
+ import { MiddlewareSystem } from 'vona-module-a-aspect';
9
+
10
+ import type { IRateLimitAggregatePolicy, IRateLimitResult } from '../types/rateLimit.ts';
11
+
12
+ export interface IMiddlewareSystemOptionsAggregate extends IDecoratorMiddlewareSystemOptions {
13
+ rateLimit?: IRateLimitAggregatePolicy;
14
+ }
15
+
16
+ @MiddlewareSystem<IMiddlewareSystemOptionsAggregate>({
17
+ enable: false,
18
+ dependencies: 'a-logger:httpLog',
19
+ dependents: ['a-metrics:health', 'a-instance:app'],
20
+ })
21
+ export class MiddlewareSystemAggregate extends BeanBase implements IMiddlewareSystemExecute {
22
+ async execute(options: IMiddlewareSystemOptionsAggregate, next: Next) {
23
+ const policy = options.rateLimit;
24
+ if (!policy) throw new Error('rate-limit aggregate policy is required when enabled');
25
+ // Validation is synchronous; only Redis admission failures enter the catch below.
26
+ const admission = this.scope.service.rateLimit.admitAggregate(policy);
27
+ let result: IRateLimitResult;
28
+ try {
29
+ result = await admission;
30
+ } catch (error) {
31
+ this.$logger.warn({
32
+ event: 'rate_limit.redis_error',
33
+ scope: 'aggregate',
34
+ mode: policy.mode,
35
+ error: error instanceof Error ? error.name : 'Error',
36
+ });
37
+ if (policy.mode === 'observe') return next();
38
+ this._reject(503, 'Service Unavailable');
39
+ return;
40
+ }
41
+ if (result.allowed) return next();
42
+ this.$logger.warn({
43
+ event: policy.mode === 'observe' ? 'rate_limit.would_reject' : 'rate_limit.rejected',
44
+ scope: 'aggregate',
45
+ mode: policy.mode,
46
+ limit: policy.limit,
47
+ });
48
+ if (policy.mode === 'observe') return next();
49
+ this.ctx.set('Retry-After', String(result.retryAfterSeconds));
50
+ this._reject(429, 'Too Many Requests');
51
+ }
52
+
53
+ private _reject(status: number, message: string) {
54
+ this.ctx.status = status;
55
+ this.ctx.type = 'application/json';
56
+ this.ctx.body = { code: status, message };
57
+ }
58
+ }
@@ -2,7 +2,11 @@ import { createHash } from 'node:crypto';
2
2
  import { BeanBase, cast } from 'vona';
3
3
  import { Service } from 'vona-module-a-bean';
4
4
 
5
- import type { IRateLimitPolicy, IRateLimitResult } from '../types/rateLimit.ts';
5
+ import type {
6
+ IRateLimitAggregatePolicy,
7
+ IRateLimitPolicy,
8
+ IRateLimitResult,
9
+ } from '../types/rateLimit.ts';
6
10
 
7
11
  @Service()
8
12
  export class ServiceRateLimit extends BeanBase {
@@ -14,16 +18,32 @@ export class ServiceRateLimit extends BeanBase {
14
18
  this._validatePolicy(policy);
15
19
  const now = Date.now();
16
20
  const key = this._createKey(policy, now);
17
- const result = (await cast(this.clientRedis).rateLimitAdmit(key, String(policy.windowMs))) as [
21
+ return this._admit(key, policy.limit, policy.windowMs);
22
+ }
23
+
24
+ admitAggregate(policy: IRateLimitAggregatePolicy): Promise<IRateLimitResult> {
25
+ if (!['observe', 'enforce'].includes(policy.mode)) {
26
+ throw new Error('rate-limit aggregate mode must be observe or enforce');
27
+ }
28
+ if (!Number.isSafeInteger(policy.limit) || policy.limit < 1) {
29
+ throw new Error('rate-limit aggregate limit must be a positive safe integer');
30
+ }
31
+ const windowMs = 1_000;
32
+ const windowStart = Math.floor(Date.now() / windowMs) * windowMs;
33
+ return this._admit(`rate-limit:aggregate:v1:${windowStart}`, policy.limit, windowMs);
34
+ }
35
+
36
+ private async _admit(key: string, limit: number, windowMs: number): Promise<IRateLimitResult> {
37
+ const result = (await cast(this.clientRedis).rateLimitAdmit(key, String(windowMs))) as [
18
38
  number | string,
19
39
  number | string,
20
40
  ];
21
41
  const current = Number(result[0]);
22
42
  const resetAfterMs = Math.max(0, Number(result[1]));
23
43
  return {
24
- allowed: current <= policy.limit,
25
- limit: policy.limit,
26
- remaining: Math.max(0, policy.limit - current),
44
+ allowed: current <= limit,
45
+ limit,
46
+ remaining: Math.max(0, limit - current),
27
47
  resetAfterMs,
28
48
  retryAfterSeconds: Math.max(1, Math.ceil(resetAfterMs / 1000)),
29
49
  };
@@ -14,6 +14,11 @@ export interface IRateLimitPolicy {
14
14
  headers: boolean;
15
15
  }
16
16
 
17
+ export interface IRateLimitAggregatePolicy {
18
+ mode: RateLimitMode;
19
+ limit: number;
20
+ }
21
+
17
22
  export interface IRateLimitResult {
18
23
  allowed: boolean;
19
24
  limit: number;
@@ -0,0 +1,247 @@
1
+ import type { IMiddlewareSystemOptionsAggregate, RateLimitMode } from 'vona-module-a-ratelimit';
2
+
3
+ import assert from 'node:assert/strict';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { once } from 'node:events';
6
+ import { createServer } from 'node:http';
7
+ import { describe, it } from 'node:test';
8
+ import { setTimeout } from 'node:timers/promises';
9
+ import { cast, compose } from 'vona';
10
+ import { app } from 'vona-mock';
11
+ import { MiddlewareSystemAggregate, ServiceRateLimit } from 'vona-module-a-ratelimit';
12
+
13
+ const exemptPath = '/api/test/vona/performAction/rateLimitExempt';
14
+ const limitedPath = '/api/test/vona/performAction/rateLimit';
15
+
16
+ type AdmitCommand = (key: string, windowMs: string) => Promise<[number, number]>;
17
+
18
+ function createService(command: AdmitCommand) {
19
+ const service = app.bean._newBean(ServiceRateLimit);
20
+ Object.defineProperty(service, 'bean', {
21
+ value: { redis: { get: () => ({ rateLimitAdmit: command }) } },
22
+ });
23
+ return service;
24
+ }
25
+
26
+ type Request = (path: string, options?: RequestInit) => Promise<Response>;
27
+
28
+ async function withGate(
29
+ mode: RateLimitMode,
30
+ limit: number,
31
+ command: AdmitCommand,
32
+ fn: (request: Request) => Promise<void>,
33
+ ) {
34
+ await app.bean.executor.mockCtx(async () => {
35
+ const middleware = app.bean._newBean(MiddlewareSystemAggregate);
36
+ Object.defineProperty(middleware, 'scope', {
37
+ value: { service: { rateLimit: createService(command) } },
38
+ });
39
+ const policyName = `test-aggregate-${randomUUID()}`;
40
+ // Keep admission and its listener local; never patch the shared application chain.
41
+ const chain = compose([
42
+ (_ctx, next) => middleware.execute({ rateLimit: { mode, limit } }, next),
43
+ ...app.middleware,
44
+ ]);
45
+ const server = createServer((req, res) => {
46
+ void app.bean.executor
47
+ .newCtx(
48
+ () => {
49
+ app.ctx.onionsDynamic = {
50
+ interceptor: { 'a-ratelimit:rateLimit': { rateLimit: { name: policyName } } },
51
+ };
52
+ return cast(app).handleRequest(app.ctx, chain);
53
+ },
54
+ { dbInfo: { level: 0 }, innerAccess: false, req, res },
55
+ )
56
+ .catch(error => res.destroy(error));
57
+ });
58
+ try {
59
+ server.listen(0, '127.0.0.1');
60
+ await once(server, 'listening');
61
+ const address = server.address();
62
+ assert.ok(address && typeof address !== 'string');
63
+ await fn((path, options) =>
64
+ fetch(`http://127.0.0.1:${address.port}${path}`, {
65
+ ...options,
66
+ headers: { accept: 'application/json', ...options?.headers },
67
+ signal: AbortSignal.timeout(10_000),
68
+ }),
69
+ );
70
+ } finally {
71
+ await new Promise<void>((resolve, reject) => {
72
+ server.close(error => (error ? reject(error) : resolve()));
73
+ server.closeAllConnections();
74
+ });
75
+ const redis = app.bean.redis.get('limiter');
76
+ const prefix = redis.options.keyPrefix ?? '';
77
+ const keys = await redis.keys(`${prefix}rate-limit:v1:*:${encodeURIComponent(policyName)}:*`);
78
+ if (keys.length) await redis.del(...keys.map(key => key.slice(prefix.length)));
79
+ }
80
+ });
81
+ }
82
+
83
+ function counter(): AdmitCommand {
84
+ let current = 0;
85
+ return async () => [++current, 1_000];
86
+ }
87
+
88
+ describe('aggregate.test.ts', { concurrency: false }, () => {
89
+ it('shares an atomic Redis budget across request contexts and expires its counter', async () => {
90
+ const key = `test:aggregate:${randomUUID()}`;
91
+ const redis = cast(app.bean.redis.get('limiter'));
92
+ const keys: string[] = [];
93
+ // Isolate this test's bucket without changing the production key dimensions or TTL.
94
+ const service = createService((actualKey, windowMs) => {
95
+ keys.push(actualKey);
96
+ return redis.rateLimitAdmit(key, windowMs);
97
+ });
98
+ try {
99
+ const results = await Promise.all(
100
+ [0, 1, 2, 3].map(index =>
101
+ app.bean.executor.mockCtx(async () => {
102
+ app.ctx.req.url = `/aggregate-${index}`;
103
+ return service.admitAggregate({
104
+ mode: 'enforce',
105
+ limit: 2,
106
+ });
107
+ }),
108
+ ),
109
+ );
110
+ assert.equal(results.filter(result => result.allowed).length, 2);
111
+ assert.ok(keys.every(actualKey => /^rate-limit:aggregate:v1:\d+$/.test(actualKey)));
112
+ assert.equal(await redis.get(key), '4');
113
+ const ttl = await redis.pttl(key);
114
+ assert.ok(ttl > 0 && ttl <= 1_000);
115
+ await setTimeout(ttl + 20);
116
+ assert.equal(await redis.get(key), null);
117
+ await app.bean.executor.mockCtx(async () => {
118
+ const result = await service.admitAggregate({
119
+ mode: 'enforce',
120
+ limit: 2,
121
+ });
122
+ assert.equal(result.allowed, true);
123
+ assert.equal(result.remaining, 1);
124
+ });
125
+ } finally {
126
+ await redis.del(key);
127
+ }
128
+ });
129
+
130
+ it('counts health, preflight, unknown paths and identity-exempt actions in one HTTP budget', async () => {
131
+ await withGate('enforce', 3, counter(), async request => {
132
+ const health = await request('/health/live');
133
+ assert.equal(health.status, 200);
134
+ await health.text();
135
+ const preflight = await request('/aggregate-unknown', {
136
+ method: 'OPTIONS',
137
+ headers: { 'origin': 'https://example.test', 'access-control-request-method': 'GET' },
138
+ });
139
+ assert.notEqual(preflight.status, 429);
140
+ await preflight.text();
141
+ const unknown = await request(`/aggregate-unknown-${randomUUID()}`);
142
+ assert.equal(unknown.status, 404);
143
+ await unknown.text();
144
+ const rejected = await request(exemptPath);
145
+ assert.equal(rejected.status, 429);
146
+ assert.equal(rejected.headers.get('retry-after'), '1');
147
+ assert.equal(rejected.headers.get('ratelimit-limit'), null);
148
+ assert.deepEqual(await rejected.json(), { code: 429, message: 'Too Many Requests' });
149
+ });
150
+ });
151
+
152
+ it('observes excess requests without rejecting or replacing identity headers', async () => {
153
+ await withGate('observe', 1, counter(), async request => {
154
+ for (let index = 0; index < 2; index++) {
155
+ const response = await request(exemptPath);
156
+ assert.equal(response.status, 200);
157
+ assert.equal(response.headers.get('ratelimit-limit'), null);
158
+ assert.equal(response.headers.get('retry-after'), null);
159
+ await response.text();
160
+ }
161
+ });
162
+ await withGate('enforce', 100, counter(), async request => {
163
+ for (let index = 0; index < 2; index++) {
164
+ const response = await request(limitedPath);
165
+ assert.equal(response.status, 200);
166
+ assert.equal(response.headers.get('ratelimit-limit'), '2');
167
+ await response.text();
168
+ }
169
+ const response = await request(limitedPath);
170
+ assert.equal(response.status, 429);
171
+ assert.equal(response.headers.get('ratelimit-limit'), '2');
172
+ await response.text();
173
+ });
174
+ });
175
+
176
+ it('fails open only in observe mode and preserves HTTP 503 for HTML callers', async () => {
177
+ const unavailable: AdmitCommand = async () => {
178
+ throw new Error('redis unavailable');
179
+ };
180
+ await withGate('observe', 1, unavailable, async request => {
181
+ const response = await request('/health/live');
182
+ assert.equal(response.status, 200);
183
+ await response.text();
184
+ });
185
+ await withGate('enforce', 1, unavailable, async request => {
186
+ const response = await request(exemptPath, { headers: { accept: 'text/html' } });
187
+ assert.equal(response.status, 503);
188
+ assert.match(response.headers.get('content-type')!, /application\/json/);
189
+ assert.equal(response.headers.get('retry-after'), null);
190
+ assert.deepEqual(await response.json(), { code: 503, message: 'Service Unavailable' });
191
+ });
192
+ });
193
+
194
+ it('keeps competing gates and the shared application listener independent', async () => {
195
+ await Promise.all([
196
+ withGate(
197
+ 'enforce',
198
+ 1,
199
+ async () => [2, 1_000],
200
+ async request => {
201
+ const response = await request('/health/live');
202
+ assert.equal(response.status, 429);
203
+ await response.text();
204
+ const address = app.server.address();
205
+ assert.ok(address && typeof address !== 'string');
206
+ const shared = await fetch(`http://127.0.0.1:${address.port}/health/live`, {
207
+ signal: AbortSignal.timeout(10_000),
208
+ });
209
+ assert.equal(shared.status, 200);
210
+ await shared.text();
211
+ },
212
+ ),
213
+ withGate(
214
+ 'enforce',
215
+ 1,
216
+ async () => [1, 1_000],
217
+ async request => {
218
+ const response = await request('/health/live');
219
+ assert.equal(response.status, 200);
220
+ await response.text();
221
+ },
222
+ ),
223
+ ]);
224
+ });
225
+
226
+ it('requires valid explicit configuration even in observe mode', async () => {
227
+ await app.bean.executor.mockCtx(async () => {
228
+ const middleware = app.bean._newBean(MiddlewareSystemAggregate);
229
+ let downstream = false;
230
+ const next = async () => {
231
+ downstream = true;
232
+ };
233
+ for (const options of [
234
+ {},
235
+ { rateLimit: { mode: 'observe', limit: 0 } },
236
+ { rateLimit: { mode: 'observe', limit: 1.5 } },
237
+ { rateLimit: { mode: 'invalid', limit: 1 } },
238
+ ]) {
239
+ await assert.rejects(
240
+ middleware.execute(options as IMiddlewareSystemOptionsAggregate, next),
241
+ /rate-limit aggregate/,
242
+ );
243
+ }
244
+ assert.equal(downstream, false);
245
+ });
246
+ });
247
+ });
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vona-suite-a-vona",
3
- "version": "5.1.109",
3
+ "version": "5.1.110",
4
4
  "gitHead": "a79189b882c17af5911573896a781bbb0046d37d",
5
5
  "description": "",
6
6
  "author": "",