actual-mcp-server 0.22.31 → 0.22.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -525,8 +525,8 @@ All configuration is via environment variables. Copy `.env.example` to `.env` to
525
525
  | `OIDC_JWKS_URI` | _(none)_ | No | Direct JWKS URL that bypasses OpenID discovery (#462), for issuers with no discovery document (Cloudflare Access: `https://<team>.cloudflareaccess.com/cdn-cgi/access/certs`). Same https, credentials and origin-or-trusted-host rules as a discovered `jwks_uri`, plus no query or fragment. When set, `/.well-known/oauth-authorization-server` is not served and `AUTH_BUDGET_ACL_IDENTITY_SOURCE=userinfo` is refused |
526
526
  | `OIDC_TOKEN_SOURCE` | `authorization` | No | Where the bearer JWT is read from (#462): `authorization` (default) or `cf-access-jwt-assertion` for an MCP server behind Cloudflare Access with Managed OAuth (the edge forwards the signed Access JWT in that header; `Authorization` is then never consulted, `OIDC_SCOPES` must be empty, `OIDC_SCOPES_SUPPORTED` is allowed, and the origin must be reachable only via Cloudflare). See the Cloudflare recipe in `docs/guides/AI_CLIENT_SETUP.md` |
527
527
  | `OIDC_SCOPES` | _(none)_ | No | Comma-separated required (enforced) scopes, also advertised. Leave empty when the IdP's JWTs carry no `scope` claim (Cloudflare Access for SaaS, or Casdoor when the client requests no scope) |
528
- | `OIDC_SCOPES_SUPPORTED` | _(none)_ | No | Comma-separated scopes advertised in `scopes_supported` but not enforced. Use when the IdP's JWTs carry no `scope` claim but the client needs a scope such as `offline_access` advertised (e.g. Gemini with Cloudflare Access for SaaS). Required scopes from `OIDC_SCOPES` are always advertised too |
529
- | `AUTH_BUDGET_ACL` | _(none)_ | No | Per-user budget ACL; see [AI Client Setup](docs/guides/AI_CLIENT_SETUP.md#oidc-authentication-multi-user) |
528
+ | `OIDC_SCOPES_SUPPORTED` | _(none)_ | No | Comma-separated scopes advertised in `scopes_supported` but not enforced. Use when the IdP's JWTs carry no `scope` claim but the client needs a scope such as `offline_access` advertised (e.g. Gemini with Cloudflare Access for SaaS). Required scopes from `OIDC_SCOPES` are always advertised too. Advertising `offline_access` unlocks a refresh token this server cannot revoke: see [Limiting a leaked refresh token](docs/SECURITY_AND_PRIVACY.md#limiting-a-leaked-refresh-token-488) |
529
+ | `AUTH_BUDGET_ACL` | _(none)_ | No | Per-user budget ACL; see [AI Client Setup](docs/guides/AI_CLIENT_SETUP.md#oidc-authentication-multi-user). Validated at startup: a value that is not a JSON object of string arrays refuses to start (#551). Unset or `{}` means no restrictions |
530
530
  | `AUTH_BUDGET_ACL_SOURCE` | `static` | No | `static` uses the `AUTH_BUDGET_ACL` map above. `actual` derives the ACL from the Actual server's own per-file access list, so revoking someone in Actual takes effect here without a config edit. Requires a multi-user (OpenID) Actual server that was password-bootstrapped first |
531
531
  | `AUTH_BUDGET_ACL_CLAIM` | `auto` | No | Which token claim identifies the principal when the source is `actual`. `auto` mirrors Actual's own precedence (`preferred_username`, `login`, `email`, `id`, `sub`) and matches the result against Actual's `userName`. Set a single claim name to pin one instead |
532
532
  | `AUTH_BUDGET_ACL_IDENTITY_MAP` | _(empty)_ | No | Explicit `<sub>=<Actual userName>` bindings, comma separated, used when the source is `actual`. Consulted before the claim precedence and authoritative: a bound `sub` whose target matches no budget file is denied rather than falling back to a claim. Use it when your access token does not carry the claim Actual stored, or after an IdP-side rename |
@@ -836,7 +836,7 @@ The software is provided **as-is**, without warranty of any kind. The author acc
836
836
 
837
837
  ---
838
838
 
839
- **Version:** 0.22.31 | **Tool Count:** 84 (verified LibreChat-compatible)
839
+ **Version:** 0.22.37 | **Tool Count:** 84 (verified LibreChat-compatible)
840
840
 
841
841
  ## Sponsor
842
842
 
@@ -16,6 +16,10 @@ let initializing = false;
16
16
  let initializationError = null;
17
17
  // Feature flag to enable connection pooling - can be disabled via environment variable
18
18
  let useConnectionPool = process.env.USE_CONNECTION_POOL !== 'false';
19
+ /** #530: httpServer registers sessions with the pool only when the pool is in use. */
20
+ export function isConnectionPoolEnabled() {
21
+ return useConnectionPool;
22
+ }
19
23
  export async function connectToActual() {
20
24
  if (initialized)
21
25
  return;
@@ -0,0 +1,82 @@
1
+ // src/auth/budget-acl-parse.ts
2
+ //
3
+ // #551: the pure parser for AUTH_BUDGET_ACL, shared by config.ts (startup
4
+ // validation) and budget-acl.ts (runtime classification).
5
+ //
6
+ // Before #551 a set-but-invalid value was parsed lazily in budget-acl.ts, logged
7
+ // once, and replaced by an EMPTY map, which getAllowedBudgets read as "no ACL
8
+ // configured": every authenticated principal was granted every budget. A typo in
9
+ // the one variable that restricts users to their budgets opened them all. Now a
10
+ // set value is validated at startup, and the runtime path denies on failure.
11
+ //
12
+ // WHY THIS MODULE HAS NO IMPORTS. config.ts validates the raw env value at
13
+ // startup by calling parseBudgetAcl. If the parser lived in budget-acl.ts, config
14
+ // would import a module that imports config (an ESM cycle leaving one of them
15
+ // half-initialised at evaluation time) and would also pull in the chain
16
+ // budget-acl.ts -> budget-acl-dynamic.ts -> lib/actual-adapter.ts -> @actual-app/api
17
+ // into every config load, stdio included. Keeping this file dependency-free (no
18
+ // logger, no config, no zod) is what makes validation at config-parse time
19
+ // possible at all. It throws and never logs.
20
+ //
21
+ // ERROR-TEXT CONTRACT. A thrown message may contain only the variable name, the
22
+ // problem class (not JSON, not an object, entry not an array of non-empty
23
+ // strings), the zero-based entry index in PARSED key order (JSON.parse puts
24
+ // integer-like keys first, so it is not always the order the operator wrote; the
25
+ // message says so), and the JSON type found.
26
+ // Never a key, a value, JSON.parse's own message (on Node 22 it echoes the input,
27
+ // which may hold email addresses), or an Error `cause` carrying any of those. The
28
+ // message is printed to stderr at startup and logged at runtime, so it must be
29
+ // safe to surface verbatim.
30
+ function jsonTypeOf(value) {
31
+ if (value === null)
32
+ return 'null';
33
+ if (Array.isArray(value))
34
+ return 'array';
35
+ return typeof value;
36
+ }
37
+ /**
38
+ * Parse the raw `AUTH_BUDGET_ACL` value.
39
+ *
40
+ * Accepts a JSON object whose every value is an array of non-empty strings
41
+ * (`["*"]` is the wildcard). `{}` is valid and means no restrictions; an empty
42
+ * array for a principal is valid and denies that principal. Throws a TypeError
43
+ * under the error-text contract above on anything else, including whitespace-only
44
+ * input, `null`, an array, a scalar, a non-array entry, and an array holding a
45
+ * non-string or an empty string. The caller decides what unset and '' mean.
46
+ */
47
+ export function parseBudgetAcl(raw) {
48
+ let parsed;
49
+ try {
50
+ parsed = JSON.parse(raw);
51
+ }
52
+ catch {
53
+ throw new TypeError('AUTH_BUDGET_ACL: not valid JSON');
54
+ }
55
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
56
+ throw new TypeError(`AUTH_BUDGET_ACL: must be a JSON object (got ${jsonTypeOf(parsed)})`);
57
+ }
58
+ // Null prototype on purpose (see BudgetAclMap). On such an object a plain
59
+ // assignment of the "__proto__" key stores an own property, so no setter can fire.
60
+ const map = Object.create(null);
61
+ // The index follows Object.entries order: integer-like keys (a numeric `sub`)
62
+ // come first and a duplicate key keeps only its last copy, so the message
63
+ // states the order rather than letting the operator count lines in the file.
64
+ const order = '; indexes are zero-based in parsed key order, integer-like keys first';
65
+ let index = 0;
66
+ for (const [key, value] of Object.entries(parsed)) {
67
+ if (!Array.isArray(value)) {
68
+ throw new TypeError(`AUTH_BUDGET_ACL: entry ${index} must be an array of non-empty strings (got ${jsonTypeOf(value)}${order})`);
69
+ }
70
+ for (const id of value) {
71
+ if (typeof id !== 'string') {
72
+ throw new TypeError(`AUTH_BUDGET_ACL: entry ${index} must be an array of non-empty strings (got an array with a ${jsonTypeOf(id)} element${order})`);
73
+ }
74
+ if (id.length === 0) {
75
+ throw new TypeError(`AUTH_BUDGET_ACL: entry ${index} must be an array of non-empty strings (got an array with an empty string${order})`);
76
+ }
77
+ }
78
+ map[key] = [...value];
79
+ index++;
80
+ }
81
+ return map;
82
+ }
@@ -9,13 +9,21 @@
9
9
  // { "<principal>": ["<syncId1>", "<syncId2>"] }
10
10
  //
11
11
  // Principal keys:
12
- // "alice@example.com" — matched against token email claim
13
- // "some-sub-uuid" — matched against token sub claim
14
- // "group:admin" — matched against token groups/roles array
12
+ // "alice@example.com" matched against the token email claim
13
+ // "some-sub-uuid" matched against the token sub claim
14
+ // "group:admin" matched against the token groups/roles array
15
15
  //
16
16
  // Value ["*"] grants access to all budgets (admin shorthand).
17
17
  //
18
- // When AUTH_BUDGET_ACL is unset, all authenticated users are allowed ("*").
18
+ // Three states, classified once from the raw value and cached (#551):
19
+ // open (AUTH_BUDGET_ACL unset, '' or '{}'): every authenticated user is
20
+ // allowed ("*"), as documented.
21
+ // map (a valid non-empty object): the per-principal lookup below.
22
+ // deny (a value that does not parse): every principal gets [] and a 403.
23
+ // config.ts refuses startup on such a value, so this state is a
24
+ // defence in depth for any caller that reaches the parser another way.
25
+ // Before #551 a parse failure degraded to an EMPTY map, which read as
26
+ // "open": a typo in the ACL granted every budget to every user.
19
27
  //
20
28
  // Usage in httpServer.ts:
21
29
  // app.use(httpPath, budgetAclMiddleware); // after bearerAuth()
@@ -24,31 +32,36 @@
24
32
  // to filter results by permitted sync IDs (forward-looking multi-budget support).
25
33
  import config from '../config.js';
26
34
  import logger from '../logger.js';
35
+ import { parseBudgetAcl } from './budget-acl-parse.js';
27
36
  import { resolveAllowedBudgetsFromActual, resolvePrincipalAsync } from './budget-acl-dynamic.js';
28
- // ---------------------------------------------------------------------------
29
- // ACL map (parsed once from env, cached)
30
- // ---------------------------------------------------------------------------
31
- let _aclMap = null;
32
- function getAclMap() {
33
- if (_aclMap !== null)
34
- return _aclMap;
35
- if (!config.AUTH_BUDGET_ACL) {
36
- _aclMap = {};
37
- return _aclMap;
38
- }
37
+ let _aclState = null;
38
+ // Test seam (#551): when set, classify this raw value instead of config.AUTH_BUDGET_ACL.
39
+ let _rawOverride = null;
40
+ function classify(raw) {
41
+ if (raw === undefined || raw === '')
42
+ return { kind: 'open' };
43
+ let map;
39
44
  try {
40
- const parsed = JSON.parse(config.AUTH_BUDGET_ACL);
41
- if (typeof parsed !== 'object' || Array.isArray(parsed)) {
42
- throw new TypeError('AUTH_BUDGET_ACL must be a JSON object');
43
- }
44
- _aclMap = parsed;
45
- logger.info(`[ACL] Budget ACL loaded: ${Object.keys(_aclMap).length} principal(s)`);
45
+ map = parseBudgetAcl(raw);
46
46
  }
47
47
  catch (err) {
48
- logger.error('[ACL] Invalid AUTH_BUDGET_ACL JSON — treating as empty (no budget restrictions):', err);
49
- _aclMap = {};
48
+ // Only the parser's message, which is safe by contract (it never names a key
49
+ // or a value); never the raw error object, whose cause or stack could.
50
+ const reason = err instanceof Error ? err.message : 'AUTH_BUDGET_ACL: unparseable';
51
+ logger.error(`[ACL] Invalid AUTH_BUDGET_ACL: access denied to every principal until it is fixed (${reason})`);
52
+ return { kind: 'deny' };
50
53
  }
51
- return _aclMap;
54
+ const count = Object.keys(map).length;
55
+ if (count === 0)
56
+ return { kind: 'open' };
57
+ logger.info(`[ACL] Budget ACL loaded: ${count} principal(s)`);
58
+ return { kind: 'map', map };
59
+ }
60
+ function getAclState() {
61
+ if (_aclState === null) {
62
+ _aclState = classify(_rawOverride !== null ? _rawOverride.raw : config.AUTH_BUDGET_ACL);
63
+ }
64
+ return _aclState;
52
65
  }
53
66
  // ---------------------------------------------------------------------------
54
67
  // Public helpers
@@ -57,15 +70,23 @@ function getAclMap() {
57
70
  * Returns the list of allowed budget sync-IDs for the currently authenticated
58
71
  * request principal.
59
72
  *
60
- * - Returns `['*']` when ACL is empty / unset (no restrictions).
73
+ * - Returns `['*']` in the open state (ACL unset, empty, or `{}`).
61
74
  * - Returns `['*']` when any matched principal has wildcard access.
62
75
  * - Returns `[]` when the user is authenticated but not in the ACL at all.
76
+ * - Returns `[]` for every principal in the deny state (the ACL value does not
77
+ * parse), never `['*']`.
78
+ *
79
+ * Lookups use Object.hasOwn so a principal named like an Object.prototype member
80
+ * (`constructor`, `toString`) is simply absent instead of matching the inherited
81
+ * function (which used to throw and surface as a 500).
63
82
  */
64
83
  export function getAllowedBudgets(req) {
65
- const acl = getAclMap();
66
- // No ACL configured → allow everything
67
- if (Object.keys(acl).length === 0)
84
+ const state = getAclState();
85
+ if (state.kind === 'open')
68
86
  return ['*'];
87
+ if (state.kind === 'deny')
88
+ return [];
89
+ const acl = state.map;
69
90
  const auth = req.auth;
70
91
  if (!auth)
71
92
  return [];
@@ -84,13 +105,15 @@ export function getAllowedBudgets(req) {
84
105
  principals.push(`group:${g}`);
85
106
  // Check for wildcard admin access first
86
107
  for (const p of principals) {
87
- if (acl[p]?.includes('*'))
108
+ if (Object.hasOwn(acl, p) && acl[p].includes('*'))
88
109
  return ['*'];
89
110
  }
90
111
  // Collect all permitted sync-IDs
91
112
  const permitted = new Set();
92
113
  for (const p of principals) {
93
- for (const id of acl[p] ?? [])
114
+ if (!Object.hasOwn(acl, p))
115
+ continue;
116
+ for (const id of acl[p])
94
117
  permitted.add(id);
95
118
  }
96
119
  return [...permitted];
@@ -108,8 +131,8 @@ export function canAccessBudget(req, budgetSyncId) {
108
131
  /**
109
132
  * Express middleware that enforces the budget ACL when OIDC auth is active.
110
133
  *
111
- * - Falls through immediately when AUTH_PROVIDER !== 'oidc' or AUTH_BUDGET_ACL
112
- * is unset (no-op — keeps backward compatibility).
134
+ * - Falls through immediately when AUTH_PROVIDER !== 'oidc' (no-op, keeps
135
+ * backward compatibility). With OIDC and the ACL unset it attaches `['*']`.
113
136
  * - Attaches `req.allowedBudgets` for downstream use (multi-budget tools).
114
137
  * - Returns HTTP 403 if the authenticated user has no permitted budgets.
115
138
  *
@@ -178,11 +201,23 @@ async function resolveDynamicAcl(req, res, next) {
178
201
  res.status(403).json({ error: 'Forbidden: budget access could not be determined' });
179
202
  }
180
203
  }
181
- /** Reset cached state (test helper). */
204
+ /** Reset cached state and the raw override (test helper). */
182
205
  export function _resetAclForTests() {
183
- _aclMap = null;
206
+ _aclState = null;
207
+ _rawOverride = null;
184
208
  }
185
- /** Directly set the ACL map (test helper — bypasses config/env). */
209
+ /**
210
+ * Directly set the ACL map (test helper; bypasses config/env). `{}` is the open
211
+ * state, exactly as an unset variable is.
212
+ */
186
213
  export function _setAclForTests(aclMap) {
187
- _aclMap = aclMap;
214
+ _aclState = Object.keys(aclMap).length === 0 ? { kind: 'open' } : { kind: 'map', map: aclMap };
215
+ }
216
+ /**
217
+ * #551 test seam: classify `raw` as if it were the AUTH_BUDGET_ACL value, through
218
+ * the same parser and logging as the real path. Cleared by _resetAclForTests.
219
+ */
220
+ export function _setRawAclForTests(raw) {
221
+ _rawOverride = { raw };
222
+ _aclState = null;
188
223
  }
@@ -1,5 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  import { parseIdentityMap } from './auth/identity-map.js';
3
+ import { parseBudgetAcl } from './auth/budget-acl-parse.js';
3
4
  // #466: the byte count body-parser will ACTUALLY enforce for MCP_HTTP_BODY_LIMIT, or
4
5
  // null when the value must be refused. Mirrors `bytes.parse` (what body-parser uses)
5
6
  // without importing that transitive package: floor(number * unit), units b and kb
@@ -192,7 +193,34 @@ export const configSchema = z.object({
192
193
  // Keys: email, sub, or "group:<name>". Values: array of sync IDs or ["*"] for all.
193
194
  // Example: {"alice@example.com":["budget-1"],"group:admin":["*"]}
194
195
  // Leave unset to allow all authenticated users to access all budgets.
195
- AUTH_BUDGET_ACL: z.string().optional(),
196
+ // #551: a SET value must parse, whatever AUTH_PROVIDER and AUTH_BUDGET_ACL_SOURCE
197
+ // are. Unset and '' mean "no restrictions" and are not validated. Before this
198
+ // refine an invalid value was parsed lazily at runtime and degraded to an empty
199
+ // map, which the ACL read as "open": a typo granted every budget to every user.
200
+ // The parser is a zero-import leaf so this file can call it (see its header).
201
+ AUTH_BUDGET_ACL: z
202
+ .string()
203
+ .optional()
204
+ .superRefine((v, ctx) => {
205
+ if (v === undefined || v === '')
206
+ return;
207
+ try {
208
+ parseBudgetAcl(v);
209
+ }
210
+ catch (err) {
211
+ // The parser's message is safe by contract (variable name, problem class,
212
+ // entry index and JSON type only; never a key, a value or JSON.parse's
213
+ // echo of the input). Its own "AUTH_BUDGET_ACL: " prefix is dropped here
214
+ // because the sentence already names the variable.
215
+ const reason = (err instanceof Error ? err.message : String(err)).replace(/^AUTH_BUDGET_ACL: /, '');
216
+ ctx.addIssue({
217
+ code: 'custom',
218
+ message: `AUTH_BUDGET_ACL is malformed (${reason}). ` +
219
+ 'Expected a JSON object mapping each principal to an array of budget sync ids, for example ' +
220
+ '{"<email or sub>":["<sync id>"],"group:<name>":["*"]}. See docs/CONFIGURATION.md.',
221
+ });
222
+ }
223
+ }),
196
224
  // #338: where the budget ACL comes from.
197
225
  // 'static' (default) = AUTH_BUDGET_ACL above, exactly as before.
198
226
  // 'actual' = derived from the Actual server's own per-file access
@@ -36,6 +36,22 @@ class ActualConnectionPool {
36
36
  // a lazily-cleaned table would leak transport objects for sessions a client
37
37
  // abandons without reconnecting.
38
38
  evictionCallbacks = [];
39
+ // #530: every HTTP session the transport layer registered, with the time it was last
40
+ // served. An entry in `connections` is not the only thing that must expire: an
41
+ // infra-error drop (or `switchBudget`'s slow path) removes the pool entry WITHOUT
42
+ // evicting the transport, and before #530 a client that then went away left its
43
+ // transport, owner record and init promise behind forever, because nothing timed an
44
+ // entry-less session. The sweep reaps a registered id that has no entry and was not
45
+ // served for one idle window ("orphaned"). `touch()` stamps it, so a served request
46
+ // keeps the session alive whether or not the entry is back.
47
+ registered = new Map();
48
+ // #530 (review M1): requests currently being served per session. The orphan sweep skips a
49
+ // session with a request in flight: an entry-less session running a long operation (an
50
+ // import past the idle window, or a request queued behind another session's drain) has
51
+ // stamped its registration only at the START of the request, so without this the sweep
52
+ // would close its transport mid-operation. Entries have the #392 lock re-check and the
53
+ // #378 in-drain touch for the same hazard; registrations have neither.
54
+ inFlight = new Map();
39
55
  constructor() {
40
56
  // Read from environment variable or default to 15
41
57
  // @actual-app/api is a singleton, so concurrent sessions cause conflicts
@@ -116,7 +132,24 @@ class ActualConnectionPool {
116
132
  * sweep so the two can never disagree about where the boundary is (#167).
117
133
  */
118
134
  isExpired(conn) {
119
- return (Date.now() - conn.lastActivity) > this.IDLE_TIMEOUT;
135
+ // #530: a registered session's clock is the later of the entry's lastActivity and its
136
+ // last served request, so a recycled entry cannot make a session look idle.
137
+ return this.isPastIdle(Math.max(conn.lastActivity, this.registered.get(conn.sessionId) ?? 0));
138
+ }
139
+ /** The one boundary for entries and registrations alike (#167, #530). */
140
+ isPastIdle(lastActivity) {
141
+ return (Date.now() - lastActivity) > this.IDLE_TIMEOUT;
142
+ }
143
+ /**
144
+ * #530: the transport layer registers each HTTP session when it registers the transport,
145
+ * so the pool can time it even while it has no entry. Idempotent; stamps "now".
146
+ */
147
+ registerSession(sessionId) {
148
+ this.registered.set(sessionId, Date.now());
149
+ }
150
+ /** #530: drop a registration (idempotent). Every eviction path calls this itself. */
151
+ forgetSession(sessionId) {
152
+ this.registered.delete(sessionId);
120
153
  }
121
154
  /**
122
155
  * Refresh a session's activity timestamp. Called by the transport layer on
@@ -124,28 +157,61 @@ class ActualConnectionPool {
124
157
  * this, the pool only stamped lastActivity at init/switch, so an actively
125
158
  * used session's pool clock never advanced; httpServer kept a parallel
126
159
  * activity map to compensate, which is the drift this consolidation removes.
127
- * No-op for unknown sessions (does NOT create an entry).
160
+ * No-op for unknown sessions (does NOT create an entry). #530: also stamps the session's
161
+ * registration when it has one, so a session whose entry was dropped stays alive while
162
+ * it is being served (the #378 in-drain touch feeds the same clock). Never registers.
128
163
  */
129
164
  touch(sessionId) {
165
+ const now = Date.now();
130
166
  const conn = this.connections.get(sessionId);
131
167
  if (conn) {
132
- conn.lastActivity = Date.now();
168
+ conn.lastActivity = now;
169
+ }
170
+ if (this.registered.has(sessionId)) {
171
+ this.registered.set(sessionId, now);
133
172
  }
134
173
  }
174
+ /**
175
+ * #530: mark a request as in flight for the session (and touch it). While the count is
176
+ * above zero the orphan sweep leaves the session alone. httpServer calls this on POST only:
177
+ * an open GET event stream is idle by nature and must not pin an orphan.
178
+ */
179
+ beginRequest(sessionId) {
180
+ this.touch(sessionId);
181
+ this.inFlight.set(sessionId, (this.inFlight.get(sessionId) ?? 0) + 1);
182
+ }
183
+ /**
184
+ * #530: the request has ended (response finished or the client went away). Drops the
185
+ * in-flight count and touches, so the idle window starts from the END of a long request,
186
+ * not its start. Idempotent for an unknown or already-evicted session.
187
+ */
188
+ endRequest(sessionId) {
189
+ const n = this.inFlight.get(sessionId);
190
+ if (n !== undefined) {
191
+ if (n <= 1)
192
+ this.inFlight.delete(sessionId);
193
+ else
194
+ this.inFlight.set(sessionId, n - 1);
195
+ }
196
+ this.touch(sessionId);
197
+ }
135
198
  /**
136
199
  * Register a listener invoked when the pool removes a session (idle sweep or
137
200
  * explicit close). httpServer registers one that closes the transport and
138
201
  * drops its table entries, keeping both tables consistent (#167). Listeners
139
202
  * must not throw; any error is logged and swallowed so one bad listener
140
- * cannot abort the removal of others.
203
+ * cannot abort the removal of others. #530: the listener also receives the reason
204
+ * (`evicted` for the #167 paths, `orphaned` for the entry-less sweep).
141
205
  */
142
206
  onSessionEvicted(cb) {
143
207
  this.evictionCallbacks.push(cb);
144
208
  }
145
- fireEviction(sessionId) {
209
+ fireEviction(sessionId, reason = 'evicted') {
210
+ this.registered.delete(sessionId); // #530: whatever the path, the session is gone
211
+ this.inFlight.delete(sessionId); // #530: a late endRequest finds nothing to decrement
146
212
  for (const cb of this.evictionCallbacks) {
147
213
  try {
148
- cb(sessionId);
214
+ cb(sessionId, reason);
149
215
  }
150
216
  catch (err) {
151
217
  logger.error(`[ConnectionPool] Eviction listener threw for session ${sessionId} (ignoring):`, err);
@@ -632,6 +698,23 @@ class ActualConnectionPool {
632
698
  await this.shutdownConnection(sessionId, { evict: true, onlyIfExpired: true });
633
699
  }
634
700
  }
701
+ // #530: registered sessions with no entry. Walked AFTER the entry evictions (each of
702
+ // which already dropped its registration) and synchronously: there is no api call to
703
+ // make, only the transport layer's tables to clear, so the lock is not involved and a
704
+ // request served in the meantime has already stamped the registration. A session with
705
+ // a request still in flight is never an orphan, however long that request runs.
706
+ const orphans = [];
707
+ for (const [sessionId, lastServed] of this.registered.entries()) {
708
+ if (!this.connections.has(sessionId) && !this.inFlight.has(sessionId) && this.isPastIdle(lastServed)) {
709
+ orphans.push(sessionId);
710
+ }
711
+ }
712
+ if (orphans.length > 0) {
713
+ logger.info(`[ConnectionPool] Reaping ${orphans.length} orphaned sessions (no pool entry, idle for one window)`);
714
+ for (const sessionId of orphans) {
715
+ this.fireEviction(sessionId, 'orphaned');
716
+ }
717
+ }
635
718
  }
636
719
  /**
637
720
  * Shutdown all connections and stop cleanup timer
@@ -680,6 +763,8 @@ class ActualConnectionPool {
680
763
  // otherwise fire once per session at the exact moment the code chose not to take it.
681
764
  await teardown(true).catch(() => { });
682
765
  });
766
+ this.registered.clear(); // #530: the transport layer is going down with the pool
767
+ this.inFlight.clear();
683
768
  logger.info('[ConnectionPool] All connections shut down');
684
769
  }
685
770
  /**
@@ -2794,19 +2794,116 @@ export async function getSchedules() {
2794
2794
  return Array.isArray(raw) ? raw : [];
2795
2795
  });
2796
2796
  }
2797
+ /**
2798
+ * #547: upstream builds a schedule's rule with one `is` condition per field and STRINGIFIES the
2799
+ * value on create (`scheduleModel.fromExternal` in loot-core/src/server/api-models.ts), so an
2800
+ * OMITTED payee or account becomes the literal string "undefined". On update
2801
+ * (`api/schedule-update`) an EXISTING condition takes the raw value and only a MISSING one is
2802
+ * pushed as String(value); the server read back the literal "null" after a clear all the same,
2803
+ * and the layer that stringifies it was not identified, so the strip treats raw null, "null"
2804
+ * and "undefined" alike. None of them can ever equal an id, so the rule never links a
2805
+ * transaction: the schedule shows in the UI and in actual_schedules_get but is inert. Reproduced through the server on 2026-10-13 with
2806
+ * @actual-app/api 26.10.0 on every shape (no payee, no account, neither, payee cleared, account
2807
+ * cleared); the control with both fields linked its import.
2808
+ *
2809
+ * The repair drops the dead condition from the schedule's rule inside the SAME drain as the
2810
+ * schedule write, so the rule is right before the drain's api.sync() and no later reader sees
2811
+ * the inert shape. Only a condition whose value is nullish or one of those two literals is
2812
+ * dropped: if upstream stops emitting it there is nothing to strip and no rule write happens.
2813
+ * A schedule without a payee or an account is a legitimate shape (the UI builds it and the tool
2814
+ * description promises it), so it is repaired rather than refused.
2815
+ *
2816
+ * The rule is read back inside the drain, straight after a raw write (the #493 measurement:
2817
+ * upstream can resolve before the row lands), so the read is a bounded poll with the #489 shape.
2818
+ *
2819
+ * A RAW null value is treated as dead too. Upstream's rule engine would match it ("transactions
2820
+ * with no payee"), but the only way it reaches a schedule rule is through a field the caller sent
2821
+ * as null, and the tool contract says null CLEARS the link. Stripping it enforces that contract;
2822
+ * it never deletes a user-authored condition.
2823
+ */
2824
+ const DEAD_SCHEDULE_CONDITION_VALUES = new Set(['undefined', 'null']);
2825
+ function isDeadScheduleCondition(cond, fields) {
2826
+ if (!fields.includes(cond?.field))
2827
+ return false;
2828
+ const v = cond.value;
2829
+ return v == null || (typeof v === 'string' && DEAD_SCHEDULE_CONDITION_VALUES.has(v));
2830
+ }
2831
+ /** Which of the two linkable fields the caller left unset (create) or set to null (update). */
2832
+ function unsetScheduleLinkFields(input, mode) {
2833
+ const unset = (field) => (mode === 'create' ? input[field] == null : input[field] === null);
2834
+ return ['payee', 'account'].filter(unset);
2835
+ }
2836
+ async function stripDeadScheduleConditions(scheduleId, fields, opStartedAt, mode) {
2837
+ if (fields.length === 0)
2838
+ return;
2839
+ const repair = fields.map((f) => `actual_schedules_update { ${f}: null }`).join(' or ');
2840
+ // Every message below avoids the TRANSIENT_ERROR_PATTERNS substrings ("timed out" included):
2841
+ // _shouldDropPoolOnError would otherwise drop the session's connection. Upstream causes stay
2842
+ // in `cause`, never in the text, for the same reason.
2843
+ const tail = mode === 'create'
2844
+ ? `The schedule EXISTS, so do not create it again: repair it with ${repair}, or delete it with actual_schedules_delete.`
2845
+ : `The schedule was updated; retrying ${repair} is safe.`;
2846
+ const failed = (what, err) => new Error(`Schedule "${scheduleId}" was saved, but ${what}, so the ${fields.join(' and ')} condition may not be cleared and the schedule may not link any transaction. ${tail}`, { cause: err });
2847
+ // #494: same cap as the split poll, measured from the start of the operation.
2848
+ const T = config.ACTUAL_OP_TIMEOUT_MS;
2849
+ const deadline = T > 0
2850
+ ? Math.min(Date.now() + SPLIT_VERIFY_TIMEOUT_MS, opStartedAt + Math.floor(T / 2))
2851
+ : Date.now() + SPLIT_VERIFY_TIMEOUT_MS;
2852
+ const boundMs = T > 0 ? Math.min(SPLIT_VERIFY_TIMEOUT_MS, Math.floor(T / 2)) : SPLIT_VERIFY_TIMEOUT_MS;
2853
+ let rule;
2854
+ for (;;) {
2855
+ let rules;
2856
+ try {
2857
+ rules = await withConcurrency(() => retry(() => rawGetRules(), { retries: 2, backoffMs: 200 }));
2858
+ }
2859
+ catch (err) {
2860
+ throw failed('its rule could not be read back', err);
2861
+ }
2862
+ rule = (Array.isArray(rules) ? rules : []).find((r) => (Array.isArray(r?.actions) ? r.actions : []).some((a) => a?.op === 'link-schedule' && a?.value === scheduleId));
2863
+ if (rule)
2864
+ break;
2865
+ if (Date.now() >= deadline) {
2866
+ // Thrown from the callback so the caller sees it (the drain's closing api.sync() still
2867
+ // saves the schedule).
2868
+ throw new Error(`Schedule "${scheduleId}" was saved, but its rule was not visible within ${boundMs}ms, so the ${fields.join(' and ')} ` +
2869
+ `condition could not be cleared and the schedule will not link any transaction. ${tail}`);
2870
+ }
2871
+ await new Promise((resolve) => setTimeout(resolve, SPLIT_VERIFY_INTERVAL_MS));
2872
+ }
2873
+ const conditions = Array.isArray(rule.conditions) ? rule.conditions : [];
2874
+ // Review round 1: the rule is in hand, so drop EVERY dead link condition, not only the fields
2875
+ // this call unset. A schedule created before this fix with a payee and no account carries a
2876
+ // dead account condition; the prescribed repair `{ payee: null }` must clear it too, or the
2877
+ // call reports success and the schedule still never links. `fields` only decides whether the
2878
+ // strip runs at all (a name-only update does not reach here) and words the error.
2879
+ const kept = conditions.filter((c) => !isDeadScheduleCondition(c, ['payee', 'account']));
2880
+ if (kept.length === conditions.length)
2881
+ return;
2882
+ try {
2883
+ await withConcurrency(() => retry(() => rawUpdateRule({ ...rule, conditions: kept }), { retries: 0, backoffMs: 200, isRetryable: isRetryableError }));
2884
+ }
2885
+ catch (err) {
2886
+ throw failed('its rule could not be rewritten', err);
2887
+ }
2888
+ }
2797
2889
  export async function createSchedule(schedule) {
2798
2890
  observability.incrementToolCall('actual.schedules.create').catch(() => { });
2799
2891
  return queueWriteOperation(async () => {
2892
+ const opStartedAt = Date.now();
2893
+ const input = (schedule ?? {});
2800
2894
  // Note: rawCreateSchedule(schedule) passes the external schedule object directly.
2801
- // Do NOT wrap in { schedule: ... } — that would double-nest and break date parsing.
2802
- const raw = await withConcurrency(() => retry(() => rawCreateSchedule(schedule), { retries: 0, backoffMs: 200, isRetryable: isRetryableError }));
2895
+ // Do NOT wrap in { schedule: ... }: that would double-nest and break date parsing.
2896
+ const raw = await withConcurrency(() => retry(() => rawCreateSchedule(input), { retries: 0, backoffMs: 200, isRetryable: isRetryableError }));
2803
2897
  const id = normalizeToId(raw);
2898
+ // #547: an omitted payee or account is stored as a condition that can never match.
2899
+ await stripDeadScheduleConditions(id, unsetScheduleLinkFields(input, 'create'), opStartedAt, 'create');
2804
2900
  return id;
2805
2901
  }, { preservesListings: PRESERVES_ALL_ENTITY_LISTINGS });
2806
2902
  }
2807
2903
  export async function updateSchedule(id, fields, resetNextDate) {
2808
2904
  observability.incrementToolCall('actual.schedules.update').catch(() => { });
2809
2905
  return queueWriteOperation(async () => {
2906
+ const opStartedAt = Date.now();
2810
2907
  // #527: upstream MERGES a partial update, so `amountOp` alone keeps the stored amount and
2811
2908
  // `amount` alone keeps the stored op. Whether the pair fits ('isbetween' takes a
2812
2909
  // { num1, num2 } range, every other op a number) therefore depends on the stored row when
@@ -2829,6 +2926,8 @@ export async function updateSchedule(id, fields, resetNextDate) {
2829
2926
  }
2830
2927
  }
2831
2928
  await withConcurrency(() => retry(() => rawUpdateSchedule(id, patch, resetNextDate), { retries: 0, backoffMs: 200, isRetryable: isRetryableError }));
2929
+ // #547: a payee or account cleared with null is stored as the literal string "null".
2930
+ await stripDeadScheduleConditions(id, unsetScheduleLinkFields(patch, 'update'), opStartedAt, 'update');
2832
2931
  }, { preservesListings: PRESERVES_ALL_ENTITY_LISTINGS });
2833
2932
  }
2834
2933
  /**
@@ -12,6 +12,7 @@
12
12
  * Volume is bounded by ONE per-process window limiter.
13
13
  */
14
14
  import { createModuleLogger } from './loggerFactory.js';
15
+ import { requestContext } from './requestContext.js';
15
16
  const MAX_DETAIL_CODE_POINTS = 200;
16
17
  const CUT_CHARS = /[{["'`]/;
17
18
  // Control (C0, C1), line/paragraph separators, bidi format characters, and (#535) the
@@ -47,12 +48,42 @@ export function sanitizeTransportErrorDetail(value) {
47
48
  s = s ? `${s} ${OMITTED}` : OMITTED;
48
49
  return s === '' ? '[no message]' : s;
49
50
  }
50
- /** Fixed-window limiter: first `max` calls per window pass, the rest are counted. */
51
+ function defaultSchedule(fn, delayMs) {
52
+ setTimeout(fn, delayMs).unref();
53
+ }
54
+ /**
55
+ * Fixed-window limiter: first `max` calls per window pass, the rest are counted.
56
+ *
57
+ * The count is reported by whichever comes first: the next allowed call (it carries
58
+ * `suppressed` on its own record) or, when `onWindowEnd` is set, a flush scheduled on
59
+ * the FIRST suppressed call of the window for the window's end (#536: before that a
60
+ * burst that was the last error ever lost its count). Each path zeroes the count, so
61
+ * the other finds 0 and reports nothing: never twice. A late flush (busy event loop)
62
+ * reports whatever accumulated by then, and the next suppression after a flush
63
+ * schedules a fresh one, so while the process runs a count is delayed at worst. The
64
+ * default timer is unref'd by design (it must not hold a stdio process open), so a
65
+ * shutdown inside the window drops the pending count.
66
+ */
51
67
  export function createWindowLimiter(opts) {
52
68
  let windowStart = 0;
53
69
  let count = 0;
54
70
  let suppressed = 0;
55
71
  let started = false;
72
+ let flushPending = false;
73
+ const schedule = opts.schedule ?? defaultSchedule;
74
+ const flush = () => {
75
+ flushPending = false;
76
+ if (suppressed <= 0)
77
+ return;
78
+ const reported = suppressed;
79
+ suppressed = 0;
80
+ try {
81
+ opts.onWindowEnd?.(reported);
82
+ }
83
+ catch {
84
+ // a throwing reporter must not escape the timer callback
85
+ }
86
+ };
56
87
  return {
57
88
  take() {
58
89
  const t = opts.now();
@@ -68,12 +99,48 @@ export function createWindowLimiter(opts) {
68
99
  return { allowed: true, suppressed: reported };
69
100
  }
70
101
  suppressed++;
102
+ if (opts.onWindowEnd && !flushPending) {
103
+ flushPending = true;
104
+ try {
105
+ // Clamp to [0, windowMs]: a backward clock step would otherwise grow the
106
+ // delay past the window (and past Node's 2^31 ms timer limit, which fires
107
+ // after 1 ms and turns the summary into one line per error).
108
+ schedule(flush, Math.min(opts.windowMs, Math.max(0, windowStart + opts.windowMs - t)));
109
+ }
110
+ catch {
111
+ flushPending = false; // a failed schedule must not escape take(); the next suppression retries
112
+ }
113
+ }
71
114
  return { allowed: false, suppressed: 0 };
72
115
  },
73
116
  };
74
117
  }
118
+ let summaryLog;
119
+ /**
120
+ * #536: the window-end summary. One constant message, one number, never stdout.
121
+ * Logged inside `requestContext.exit`: the flush timer inherits the AsyncLocalStorage
122
+ * store of the request that first hit the limit (ALS propagates through setTimeout),
123
+ * and `addCorrelation` in src/logger.ts would stamp that one session's ids on an
124
+ * aggregate that counts errors from every session. Never throws.
125
+ */
126
+ export function reportSuppressedTransportErrors(suppressed, logger) {
127
+ try {
128
+ const log = logger ?? (summaryLog = summaryLog ?? createModuleLogger('TRANSPORT'));
129
+ requestContext.exit(() => {
130
+ log.warn('MCP transport errors suppressed', { suppressed });
131
+ });
132
+ }
133
+ catch {
134
+ // never throw into a timer callback
135
+ }
136
+ }
75
137
  // ONE limiter per process so many HTTP sessions cannot multiply the budget.
76
- const moduleLimiter = createWindowLimiter({ max: 50, windowMs: 60_000, now: Date.now });
138
+ const moduleLimiter = createWindowLimiter({
139
+ max: 50,
140
+ windowMs: 60_000,
141
+ now: Date.now,
142
+ onWindowEnd: (n) => reportSuppressedTransportErrors(n),
143
+ });
77
144
  function safeErrorName(error) {
78
145
  try {
79
146
  const name = error?.name;
@@ -7,7 +7,7 @@ import logger, { resolveRequestId } from '../logger.js';
7
7
  import { attachTransportErrorLogger } from '../lib/transportErrorLogger.js';
8
8
  import { getLocalIp } from '../utils.js';
9
9
  import actualToolsManager from '../actualToolsManager.js';
10
- import { getConnectionState, connectToActualForSession, shutdownActualForSession, shutdownActual, canAcceptNewSession } from '../actualConnection.js';
10
+ import { getConnectionState, connectToActualForSession, shutdownActualForSession, shutdownActual, canAcceptNewSession, isConnectionPoolEnabled } from '../actualConnection.js';
11
11
  import { connectionPool } from '../lib/ActualConnectionPool.js';
12
12
  import observability from '../observability.js';
13
13
  import config from '../config.js';
@@ -23,6 +23,7 @@ import { parseScopeList } from '../lib/oidc-scopes.js';
23
23
  import { budgetAclMiddleware } from '../auth/budget-acl.js';
24
24
  import { runAclPreflight } from '../auth/budget-acl-dynamic.js';
25
25
  import * as https from 'node:https';
26
+ import { finished } from 'node:stream';
26
27
  import * as fs from 'node:fs';
27
28
  // AsyncLocalStorage for request context: moved to src/lib/requestContext.ts
28
29
  // so adapter code can import it without a circular dependency on httpServer.
@@ -235,8 +236,15 @@ advertisedUrl) {
235
236
  // loser would silently get the generic 404, restoring this bug at random.
236
237
  const INIT_FAILURE_TTL_MS = 60_000;
237
238
  const INIT_FAILURE_MAX = 1000;
239
+ // #550: the record carries the principal that initiated the session (the same value
240
+ // recordSessionOwner stores on success) and is served only to that principal. A failed
241
+ // init records no owner in session-owners.ts, and the POST cause branch runs before the
242
+ // ownership guard, so without this ANY authenticated principal presenting the id got
243
+ // the cause reply for 60 s, which contradicts the unknown-id equivalence #529 gives
244
+ // initialized sessions. Under a static bearer or no auth every caller is the same
245
+ // principal, so those deployments keep the #438 behaviour unchanged.
238
246
  const sessionInitFailures = new Map();
239
- const rememberInitFailure = (sid, err) => {
247
+ const rememberInitFailure = (sid, err, owner) => {
240
248
  const now = Date.now();
241
249
  for (const [k, v] of sessionInitFailures) {
242
250
  if (now - v.at > INIT_FAILURE_TTL_MS)
@@ -250,15 +258,22 @@ advertisedUrl) {
250
258
  break;
251
259
  sessionInitFailures.delete(oldest);
252
260
  }
253
- sessionInitFailures.set(sid, { ...classifyInitFailure(err), at: now });
261
+ sessionInitFailures.set(sid, { ...classifyInitFailure(err), at: now, owner });
254
262
  };
255
- /** Peek. Never deletes. Returns undefined once the TTL has elapsed. */
256
- const peekInitFailure = (sid) => {
263
+ /**
264
+ * Peek. Never deletes. Returns undefined once the TTL has elapsed, and (#550) for a
265
+ * principal other than the one that initiated the session: the caller then falls
266
+ * through to the reply an unknown id gets, and the record is neither consumed nor
267
+ * extended. Strict equality, like sessionOwnerMatches.
268
+ */
269
+ const peekInitFailure = (sid, principal) => {
257
270
  const rec = sessionInitFailures.get(sid);
258
271
  if (!rec)
259
272
  return undefined;
260
273
  if (Date.now() - rec.at > INIT_FAILURE_TTL_MS)
261
274
  return undefined;
275
+ if (rec.owner !== principal)
276
+ return undefined;
262
277
  return { cause: rec.cause, sentence: rec.sentence };
263
278
  };
264
279
  // safe fallback if index didn't provide implementedTools
@@ -279,21 +294,27 @@ advertisedUrl) {
279
294
  // the matching transport in the same window. This is what keeps the two
280
295
  // tables from drifting: no "alive in httpServer, dead in the pool" state, and
281
296
  // no transport object left behind for a session the client abandoned.
282
- connectionPool.onSessionEvicted((sessionId) => {
297
+ // #530: the pool also reaps a session it has no entry for (an infra-error drop
298
+ // recycles the entry without evicting the transport) once it goes one idle
299
+ // window without a served request, with reason `orphaned`; same teardown. The
300
+ // body is synchronous on purpose: the pool walks its registrations in one pass.
301
+ connectionPool.onSessionEvicted(teardownSession);
302
+ function teardownSession(sessionId, reason) {
283
303
  const transport = transports.get(sessionId);
284
304
  if (transport) {
285
305
  try {
286
306
  transport.close?.();
287
307
  }
288
308
  catch (err) {
289
- logger.debug(`[SESSION] Error closing transport for evicted session ${sessionId} (ignoring): ${err}`);
309
+ logger.debug(`[SESSION] Error closing transport for ${reason} session ${sessionId} (ignoring): ${err}`);
290
310
  }
291
311
  }
292
312
  transports.delete(sessionId);
293
313
  sessionInitPromises.delete(sessionId);
294
314
  forgetSessionOwner(sessionId);
295
- logger.info(`[SESSION] Transport torn down for evicted session: ${sessionId}`);
296
- });
315
+ connectionPool.forgetSession(sessionId);
316
+ logger.info(`[SESSION] Transport torn down for ${reason} session: ${sessionId}`);
317
+ }
297
318
  // Authentication middleware
298
319
  const authenticateRequest = (req, res) => {
299
320
  // OIDC mode: verify the request principal directly rather than inferring auth
@@ -511,6 +532,10 @@ advertisedUrl) {
511
532
  // is already the source of truth for this session's idle clock.
512
533
  recordSessionOwner(sid, sessionOwner);
513
534
  transports.set(sid, transport);
535
+ // #530: let the pool time this session even after its entry is recycled.
536
+ // Pooling off (USE_CONNECTION_POOL=false) has no sweep, so nothing to register.
537
+ if (isConnectionPoolEnabled())
538
+ connectionPool.registerSession(sid);
514
539
  logger.info(`[SESSION] Actual connection initialized for session: ${sid}`);
515
540
  resolveInit?.();
516
541
  }
@@ -523,7 +548,7 @@ advertisedUrl) {
523
548
  // cause is known here and discarded, and the client's next request gets
524
549
  // a bare "Session not found" that says nothing about a schema mismatch,
525
550
  // a bad password or an unreachable server.
526
- rememberInitFailure(sid, err);
551
+ rememberInitFailure(sid, err, sessionOwner);
527
552
  rejectInit?.(err);
528
553
  }
529
554
  finally {
@@ -595,7 +620,7 @@ advertisedUrl) {
595
620
  // enum-only contract through the very hole left open there.
596
621
  let knownFailure;
597
622
  try {
598
- knownFailure = peekInitFailure(sessionId);
623
+ knownFailure = peekInitFailure(sessionId, resolvePrincipal(req));
599
624
  }
600
625
  catch {
601
626
  knownFailure = undefined;
@@ -676,8 +701,18 @@ advertisedUrl) {
676
701
  });
677
702
  return;
678
703
  }
679
- // Refresh the pool's idle clock for this session (single source of truth, #167).
680
- connectionPool.touch(sessionId);
704
+ // Refresh the pool's idle clock for this session (single source of truth, #167) and
705
+ // count the request in flight (#530): the orphan sweep must not reap a session whose
706
+ // own request is still running. The END marker is the response's completion, not a
707
+ // finally block: with enableJsonResponse `handleRequest` can resolve before the body
708
+ // is written. `stream.finished` rather than `res.once('close')`: a client that gave
709
+ // up during the init wait above has ALREADY closed the response, its `close` event
710
+ // fired before this line ran, and a listener attached now would never run, leaving
711
+ // the count at one for good (review round 2). `finished` calls back for an
712
+ // already-closed response too, and once, whether the response completed, errored
713
+ // or the client went away.
714
+ connectionPool.beginRequest(sessionId);
715
+ finished(res, () => connectionPool.endRequest(sessionId));
681
716
  // Run in AsyncLocalStorage context so tools and the adapter can access
682
717
  // sessionId (pool branch, #134) and allowedBudgets (ACL enforcement, #156).
683
718
  const allowedBudgets = req.allowedBudgets;
@@ -734,15 +769,17 @@ advertisedUrl) {
734
769
  res.status(400).json({ jsonrpc: '2.0', error: { code: -32000, message: 'No session id' }, id: null });
735
770
  return;
736
771
  }
737
- // Same ownership rule as the POST route, checked before the idle clock is
738
- // touched so another principal cannot keep a session alive either. A refusal
739
- // reads like an unknown session.
772
+ // Same ownership rule as the POST route. A refusal reads like an unknown
773
+ // session. The `transports.has` guard is load bearing: a session whose init
774
+ // FAILED never had an owner recorded, and under OIDC or a static bearer every
775
+ // caller has a principal, so without it that session would be refused here
776
+ // instead of reaching the #438 cause report below. That report is owner-bound
777
+ // on its own since #550 (the peek takes the principal).
740
778
  if (transports.has(sessionId) && !sessionOwnerMatches(sessionId, resolvePrincipal(req))) {
741
779
  logger.warn(`[SESSION] Refused a GET for session ${sessionId} from a principal that does not own it`);
742
780
  res.status(400).json({ jsonrpc: '2.0', error: { code: -32000, message: 'Transport not ready' }, id: null });
743
781
  return;
744
782
  }
745
- connectionPool.touch(sessionId); // Refresh the pool's idle clock (#167)
746
783
  const transport = transports.get(sessionId);
747
784
  if (!transport) {
748
785
  // #438: same cause, this route's own status and code. The classifier owns no
@@ -763,7 +800,7 @@ advertisedUrl) {
763
800
  // NODE_ENV is not production.
764
801
  let knownFailure;
765
802
  try {
766
- knownFailure = peekInitFailure(sessionId);
803
+ knownFailure = peekInitFailure(sessionId, resolvePrincipal(req));
767
804
  }
768
805
  catch {
769
806
  knownFailure = undefined;
@@ -780,6 +817,12 @@ advertisedUrl) {
780
817
  });
781
818
  return;
782
819
  }
820
+ // #529: the idle clock is refreshed only for a session this route will serve,
821
+ // after the ownership check and the transport lookup, in the same order as
822
+ // POST. Touching before the lookup let a request that was about to be
823
+ // answered "Transport not ready" (a pool entry whose transport is gone, or
824
+ // one still initializing) keep that session alive.
825
+ connectionPool.touch(sessionId); // Refresh the pool's idle clock (#167)
783
826
  await transport.handleRequest(req, res);
784
827
  });
785
828
  // Quick GET server-info probe used by our test harness (testMcpClient.ts, the
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "actual-mcp-server",
3
3
  "displayName": "Actual MCP Server",
4
- "version": "0.22.31",
4
+ "version": "0.22.37",
5
5
  "engines": {
6
6
  "node": ">=22.0.0",
7
7
  "npm": ">=10.0.0"
@@ -30,7 +30,7 @@
30
30
  "verify-tools": "npm run build && node scripts/verify-tools.js",
31
31
  "check:coverage": "node scripts/list-actual-api-methods.mjs",
32
32
  "direct-sync": "node scripts/direct-sync/bank-sync-direct.mjs",
33
- "test:unit-js": "node tests/unit/transactions_create.test.js && node tests/unit/transactions_aggregate.test.js && node tests/unit/account_flow_summary.test.js && node tests/unit/recurring_expenses_summary.test.js && node tests/unit/generated_tools.smoke.test.js &&node tests/unit/schema_validation.test.js && node tests/unit/schema_json_openai_compat.test.js && node tests/unit/config_https_validation.test.js && node tests/unit/config_data_dir.test.js && node tests/unit/config_drift.test.js && node tests/unit/port_alignment.test.js && node tests/unit/dockerfile_data_dir_alignment.test.js && node tests/unit/unraid_template_alignment.test.js && node tests/unit/entrypoint_invariants.test.js && node tests/unit/e2e_spec_collection.test.js && node tests/unit/compose_profile_sync.test.js && node tests/unit/advertised_tools_sync.test.js && node tests/unit/new_tool_completeness.test.js && node tests/unit/knip_config.test.js && node tests/unit/readme_stats_sync.test.js && node tests/unit/config_insecure_upstream.test.js && node tests/unit/workflow_release_guards.test.js && node tests/unit/report_train_failure.test.js && node tests/unit/unit_chain_membership.test.js && node tests/unit/api_surface_drift.test.js && node tests/unit/write_effect_audit_staleness.test.js && node tests/unit/write_effect_audit_membership.test.js && node tests/unit/tool_annotations.test.js && node tests/unit/tool_id_schema_drift.test.js && node tests/unit/filter_id_resolution.test.js && node tests/unit/filter_id_tool_wiring.test.js && node tests/unit/api_coverage_baseline.test.js && node tests/unit/train_preflight.test.js && node tests/unit/verify_published_artifacts.test.js && node tests/unit/report_train_stale.test.js && node tests/unit/stdio_framing_check.test.js && node tests/unit/server_info.test.js && node tests/unit/transfers_create.test.js && node tests/unit/bot_target_branch.test.js && node tests/unit/auth_posture.test.js && node tests/unit/auth_posture_wiring.test.js && node tests/unit/auth-acl.test.js && node tests/unit/bug76.test.js && node tests/unit/budgets_setAmount.test.js && node tests/unit/adapter_set_budget_batch.test.js && node tests/unit/budget_updates_batch.test.js && node tests/unit/rules_create.test.js && node tests/unit/adapter_rule_reference_guard.test.js && node tests/unit/rules_create_batch.test.js && node tests/unit/budgets_hold_for_next_month.test.js && node tests/unit/budgets_transfer.test.js && node tests/unit/transactions_uncategorized.test.js && node tests/unit/httpServer_session_init.test.js && node tests/unit/httpServer_session_not_found.test.js && node tests/unit/httpServer_init_failure_report.test.js && node tests/unit/stdio_init_failure_report.test.js && node tests/unit/manual_mcp_client_retry.test.js && node tests/unit/manual_mcp_client_session.test.js && node tests/unit/manual_mcp_client_circuit.test.js && node tests/unit/manual_runner_killswitch.test.js && node tests/unit/adapter_auth_rate_limit.test.js && node tests/unit/adapter_session_reuse.test.js && node tests/unit/retry_classifier.test.js && node tests/unit/adapter_module_surface.test.js && node tests/unit/adapter_nonidempotent_no_retry.test.js && node tests/unit/pool_liveness.test.js && node tests/unit/pool_shutdown_all.test.js && node tests/unit/query_where_operators.test.js && node tests/unit/query_run_validation.test.js && node tests/unit/adapter_with_write_session.test.js && node tests/unit/category_groups_delete.test.js && node tests/unit/rules_delete.test.js && node tests/unit/schedules_delete.test.js && node tests/unit/accounts_delete.test.js && node tests/unit/update_tools_not_found.test.js && node tests/unit/accounts_close.test.js && node tests/unit/accounts_reopen.test.js && node tests/unit/payees_delete.test.js && node tests/unit/payees_merge.test.js && node tests/unit/rules_create_or_update.test.js && node tests/unit/unhandled-rejection.test.js && node tests/unit/rejection-allowlist-purity.test.js && node tests/unit/httpServer_bearer_auth.test.js && node tests/unit/session_ownership.test.js && node tests/unit/httpServer_oidc_audience.test.js && node tests/unit/httpServer_oidc_auth_verification.test.js && node tests/unit/httpServer_oidc_jwks_discovery.test.js && node tests/unit/oidc_resource_identifier.test.js && node tests/unit/httpServer_oidc_resource_metadata.test.js && node tests/unit/oidc_error_cause.test.js && node tests/unit/httpServer_oidc_error_body.test.js && node tests/unit/oidc_token_source.test.js && node tests/unit/config_oidc_assertion_refines.test.js && node tests/unit/httpServer_oidc_assertion_mode.test.js && node tests/unit/httpServer_body_limit.test.js && node tests/unit/httpErrorHandler.test.js && node tests/unit/httpServer_error_handler_wiring.test.js && node tests/unit/httpServer_trust_proxy.test.js && node tests/unit/httpServer_batch_cap.test.js && node tests/unit/dotenv_stdout_quiet.test.js && node tests/unit/httpServer_bind_host.test.js && node tests/unit/adapter_write_pool_cooperation.test.js && node tests/unit/adapter_drain_listing_cache.test.js && node tests/unit/budget_acl_enforcement.test.js && node tests/unit/budget_selection_precondition.test.js && node tests/unit/budget_load_abandonment.test.js && node tests/unit/budget_loader_postcondition.test.js && node tests/unit/budget_loader_import_allowlist.test.js && node tests/unit/budget_import_tracking.test.js && node tests/unit/pool_shutdown_under_lock.test.js && node tests/unit/api_lock_affinity.test.js && node tests/unit/commit_message_closing_keyword.test.js && node tests/unit/write_queue_stranding.test.js && node tests/unit/write_queue_stranded_bound.test.js && node tests/unit/budget_preference_store.test.js && node tests/unit/budget_preference_restore.test.js && node tests/unit/tags_list.test.js && node tests/unit/tags_create.test.js && node tests/unit/tags_update.test.js && node tests/unit/tags_delete.test.js && node tests/unit/notes_get.test.js && node tests/unit/notes_update.test.js && node tests/unit/payees_common_list.test.js && node tests/unit/transactions_update_guard.test.js && node tests/unit/transactions_update_splits.test.js && node tests/unit/transactions_update_split_convert.test.js && node tests/unit/entities_search.test.js && node tests/unit/transactions_import_schema.test.js && node tests/unit/tool_schema_shape.test.js && node tests/unit/zod_error_format.test.js && node tests/unit/transactions_update_batch.test.js && node tests/unit/tool_count_sync.test.js && node tests/unit/stdio_transport.test.js && node tests/unit/stdio_budget_switch.test.js && node tests/unit/logger_structured.test.js && node tests/unit/logger_redaction.test.js && node tests/unit/logger_correlation.test.js && node tests/unit/check_coverage.test.js && node tests/unit/adapter_op_timeout.test.js && node tests/unit/adapter_write_queue_wakeup.test.js && node tests/unit/ci_workflow_guards.test.js && node tests/unit/node_version_guard.test.js && node tests/unit/node_version_drift.test.js && node tests/unit/playwright_version_drift.test.js && node tests/unit/observability_smoke.test.js && node tests/unit/residue_pattern.test.js && node tests/unit/batch_uncategorized_cleanup.test.js && node tests/unit/dual_transport_gate.test.js && node tests/unit/manual_assertions_use_helper.test.js && node tests/unit/server_version_guard.test.js && node tests/unit/server_version_probe_outside_op_timeout.test.js && node tests/unit/payee_rules_reference_filter.test.js && node tests/unit/oidc_metadata_discovery.test.js && node tests/unit/httpServer_oauth_metadata_route.test.js && node tests/unit/httpServer_mcp_info_route.test.js && node tests/unit/residue_sweep_balance_account.test.js && node tests/unit/tool_factory.test.js && node tests/unit/budget_registry_parse.test.js && node tests/unit/preferences_get.test.js && node tests/unit/budgets_export.test.js && node tests/unit/budgets_import.test.js && node tests/unit/budgets_import_syncid.test.js && node tests/unit/budget_acl_dynamic.test.js && node tests/unit/budget_acl_identity_map.test.js && node tests/unit/budget_acl_userinfo.test.js && node tests/unit/acl_e2e_fixture_contract.test.js && node tests/unit/budget_acl_middleware.test.js && node tests/unit/rules_stage.test.js && node tests/unit/oidc_scope_list.test.js && node tests/unit/get_context.test.js && node tests/unit/contributor_docs.test.js && node tests/unit/toolsets.test.js && node tests/unit/toolsets_entrypoint.test.js && node tests/unit/tools_list_size_budget.test.js && node tests/unit/rules_update_schedules_schema.test.js && node tests/unit/schedules_update_amount_guard.test.js && node tests/unit/source_text_helper.test.js && node tests/unit/transport_onerror.test.js && node tests/unit/adapter_transaction_batch_abort.test.js && node tests/unit/transactions_merge_adapter.test.js",
33
+ "test:unit-js": "node tests/unit/transactions_create.test.js && node tests/unit/transactions_aggregate.test.js && node tests/unit/account_flow_summary.test.js && node tests/unit/recurring_expenses_summary.test.js && node tests/unit/generated_tools.smoke.test.js &&node tests/unit/schema_validation.test.js && node tests/unit/schema_json_openai_compat.test.js && node tests/unit/config_https_validation.test.js && node tests/unit/config_data_dir.test.js && node tests/unit/config_drift.test.js && node tests/unit/port_alignment.test.js && node tests/unit/dockerfile_data_dir_alignment.test.js && node tests/unit/unraid_template_alignment.test.js && node tests/unit/entrypoint_invariants.test.js && node tests/unit/e2e_spec_collection.test.js && node tests/unit/compose_profile_sync.test.js && node tests/unit/advertised_tools_sync.test.js && node tests/unit/new_tool_completeness.test.js && node tests/unit/knip_config.test.js && node tests/unit/readme_stats_sync.test.js && node tests/unit/config_insecure_upstream.test.js && node tests/unit/workflow_release_guards.test.js && node tests/unit/report_train_failure.test.js && node tests/unit/unit_chain_membership.test.js && node tests/unit/api_surface_drift.test.js && node tests/unit/write_effect_audit_staleness.test.js && node tests/unit/write_effect_audit_membership.test.js && node tests/unit/tool_annotations.test.js && node tests/unit/tool_id_schema_drift.test.js && node tests/unit/filter_id_resolution.test.js && node tests/unit/filter_id_tool_wiring.test.js && node tests/unit/api_coverage_baseline.test.js && node tests/unit/train_preflight.test.js && node tests/unit/verify_published_artifacts.test.js && node tests/unit/report_train_stale.test.js && node tests/unit/stdio_framing_check.test.js && node tests/unit/server_info.test.js && node tests/unit/transfers_create.test.js && node tests/unit/bot_target_branch.test.js && node tests/unit/auth_posture.test.js && node tests/unit/auth_posture_wiring.test.js && node tests/unit/auth-acl.test.js && node tests/unit/bug76.test.js && node tests/unit/budgets_setAmount.test.js && node tests/unit/adapter_set_budget_batch.test.js && node tests/unit/budget_updates_batch.test.js && node tests/unit/rules_create.test.js && node tests/unit/adapter_rule_reference_guard.test.js && node tests/unit/rules_create_batch.test.js && node tests/unit/budgets_hold_for_next_month.test.js && node tests/unit/budgets_transfer.test.js && node tests/unit/transactions_uncategorized.test.js && node tests/unit/httpServer_session_init.test.js && node tests/unit/httpServer_session_not_found.test.js && node tests/unit/httpServer_init_failure_report.test.js && node tests/unit/stdio_init_failure_report.test.js && node tests/unit/manual_mcp_client_retry.test.js && node tests/unit/manual_mcp_client_session.test.js && node tests/unit/manual_mcp_client_circuit.test.js && node tests/unit/manual_runner_killswitch.test.js && node tests/unit/adapter_auth_rate_limit.test.js && node tests/unit/adapter_session_reuse.test.js && node tests/unit/retry_classifier.test.js && node tests/unit/adapter_module_surface.test.js && node tests/unit/adapter_nonidempotent_no_retry.test.js && node tests/unit/pool_liveness.test.js && node tests/unit/pool_shutdown_all.test.js && node tests/unit/query_where_operators.test.js && node tests/unit/query_run_validation.test.js && node tests/unit/adapter_with_write_session.test.js && node tests/unit/category_groups_delete.test.js && node tests/unit/rules_delete.test.js && node tests/unit/schedules_delete.test.js && node tests/unit/accounts_delete.test.js && node tests/unit/update_tools_not_found.test.js && node tests/unit/accounts_close.test.js && node tests/unit/accounts_reopen.test.js && node tests/unit/payees_delete.test.js && node tests/unit/payees_merge.test.js && node tests/unit/rules_create_or_update.test.js && node tests/unit/unhandled-rejection.test.js && node tests/unit/rejection-allowlist-purity.test.js && node tests/unit/httpServer_bearer_auth.test.js && node tests/unit/session_ownership.test.js && node tests/unit/httpServer_oidc_audience.test.js && node tests/unit/httpServer_oidc_auth_verification.test.js && node tests/unit/httpServer_oidc_jwks_discovery.test.js && node tests/unit/oidc_resource_identifier.test.js && node tests/unit/httpServer_oidc_resource_metadata.test.js && node tests/unit/oidc_error_cause.test.js && node tests/unit/httpServer_oidc_error_body.test.js && node tests/unit/oidc_token_source.test.js && node tests/unit/config_oidc_assertion_refines.test.js && node tests/unit/httpServer_oidc_assertion_mode.test.js && node tests/unit/httpServer_body_limit.test.js && node tests/unit/httpErrorHandler.test.js && node tests/unit/httpServer_error_handler_wiring.test.js && node tests/unit/httpServer_trust_proxy.test.js && node tests/unit/httpServer_batch_cap.test.js && node tests/unit/dotenv_stdout_quiet.test.js && node tests/unit/httpServer_bind_host.test.js && node tests/unit/adapter_write_pool_cooperation.test.js && node tests/unit/adapter_drain_listing_cache.test.js && node tests/unit/budget_acl_enforcement.test.js && node tests/unit/budget_selection_precondition.test.js && node tests/unit/budget_load_abandonment.test.js && node tests/unit/budget_loader_postcondition.test.js && node tests/unit/budget_loader_import_allowlist.test.js && node tests/unit/budget_import_tracking.test.js && node tests/unit/pool_shutdown_under_lock.test.js && node tests/unit/api_lock_affinity.test.js && node tests/unit/commit_message_closing_keyword.test.js && node tests/unit/write_queue_stranding.test.js && node tests/unit/write_queue_stranded_bound.test.js && node tests/unit/budget_preference_store.test.js && node tests/unit/budget_preference_restore.test.js && node tests/unit/tags_list.test.js && node tests/unit/tags_create.test.js && node tests/unit/tags_update.test.js && node tests/unit/tags_delete.test.js && node tests/unit/notes_get.test.js && node tests/unit/notes_update.test.js && node tests/unit/payees_common_list.test.js && node tests/unit/transactions_update_guard.test.js && node tests/unit/transactions_update_splits.test.js && node tests/unit/transactions_update_split_convert.test.js && node tests/unit/entities_search.test.js && node tests/unit/transactions_import_schema.test.js && node tests/unit/tool_schema_shape.test.js && node tests/unit/zod_error_format.test.js && node tests/unit/transactions_update_batch.test.js && node tests/unit/tool_count_sync.test.js && node tests/unit/stdio_transport.test.js && node tests/unit/stdio_budget_switch.test.js && node tests/unit/logger_structured.test.js && node tests/unit/logger_redaction.test.js && node tests/unit/logger_correlation.test.js && node tests/unit/check_coverage.test.js && node tests/unit/adapter_op_timeout.test.js && node tests/unit/adapter_write_queue_wakeup.test.js && node tests/unit/ci_workflow_guards.test.js && node tests/unit/node_version_guard.test.js && node tests/unit/node_version_drift.test.js && node tests/unit/playwright_version_drift.test.js && node tests/unit/observability_smoke.test.js && node tests/unit/residue_pattern.test.js && node tests/unit/batch_uncategorized_cleanup.test.js && node tests/unit/dual_transport_gate.test.js && node tests/unit/manual_assertions_use_helper.test.js && node tests/unit/server_version_guard.test.js && node tests/unit/server_version_probe_outside_op_timeout.test.js && node tests/unit/payee_rules_reference_filter.test.js && node tests/unit/oidc_metadata_discovery.test.js && node tests/unit/httpServer_oauth_metadata_route.test.js && node tests/unit/httpServer_mcp_info_route.test.js && node tests/unit/residue_sweep_balance_account.test.js && node tests/unit/tool_factory.test.js && node tests/unit/budget_registry_parse.test.js && node tests/unit/preferences_get.test.js && node tests/unit/budgets_export.test.js && node tests/unit/budgets_import.test.js && node tests/unit/budgets_import_syncid.test.js && node tests/unit/budget_acl_dynamic.test.js && node tests/unit/budget_acl_identity_map.test.js && node tests/unit/budget_acl_userinfo.test.js && node tests/unit/acl_e2e_fixture_contract.test.js && node tests/unit/budget_acl_middleware.test.js && node tests/unit/rules_stage.test.js && node tests/unit/oidc_scope_list.test.js && node tests/unit/get_context.test.js && node tests/unit/contributor_docs.test.js && node tests/unit/toolsets.test.js && node tests/unit/toolsets_entrypoint.test.js && node tests/unit/tools_list_size_budget.test.js && node tests/unit/rules_update_schedules_schema.test.js && node tests/unit/schedules_update_amount_guard.test.js && node tests/unit/source_text_helper.test.js && node tests/unit/transport_onerror.test.js && node tests/unit/adapter_transaction_batch_abort.test.js && node tests/unit/transactions_merge_adapter.test.js && node tests/unit/schedules_dead_conditions.test.js && node tests/unit/session_ownership_express.test.js && node tests/unit/pool_orphan_sweep.test.js && node tests/unit/budget_acl_parse.test.js",
34
34
  "test:adapter": "npm run build && node dist/src/tests_adapter_runner.js",
35
35
  "test:e2e": "npx playwright test",
36
36
  "test:e2e:docker": "./tests/e2e/run-docker-e2e.sh",