tina4-nodejs 3.13.164 → 3.13.166

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CLAUDE.md +12 -5
  2. package/package.json +1 -1
  3. package/packages/cli/dist/bin.js +1312 -979
  4. package/packages/cli/src/bin.ts +5 -2
  5. package/packages/cli/src/commands/lint.ts +3 -1
  6. package/packages/cli/src/commands/seed.ts +10 -11
  7. package/packages/core/dist/index.js +1232 -897
  8. package/packages/core/src/batchSpawn.ts +129 -0
  9. package/packages/core/src/connectionUrl.ts +242 -0
  10. package/packages/core/src/devAdmin.ts +25 -11
  11. package/packages/core/src/fakeData.ts +51 -13
  12. package/packages/core/src/index.ts +1 -1
  13. package/packages/core/src/mcp.ts +4 -1
  14. package/packages/core/src/mqtt.ts +24 -48
  15. package/packages/core/src/portTakeover.ts +31 -13
  16. package/packages/core/src/projectIndex.ts +3 -4
  17. package/packages/core/src/projectIndexStorage.ts +9 -1
  18. package/packages/core/src/queueBackends/rabbitmqBackend.ts +32 -20
  19. package/packages/core/src/response.ts +4 -1
  20. package/packages/core/src/routeDiscovery.ts +8 -2
  21. package/packages/core/src/router.ts +44 -30
  22. package/packages/core/src/server.ts +53 -33
  23. package/packages/core/src/session.ts +5 -0
  24. package/packages/core/src/sessionHandlers/databaseHandler.ts +16 -0
  25. package/packages/core/src/urlRedaction.ts +252 -0
  26. package/packages/core/src/websocketBackplane.ts +15 -3
  27. package/packages/orm/dist/index.js +1259 -925
  28. package/packages/orm/src/database.ts +7 -1
  29. package/packages/orm/src/databaseUrl.ts +73 -190
  30. package/packages/orm/src/docstore.ts +8 -1
  31. package/packages/orm/src/graph/graphUrl.ts +43 -7
  32. package/packages/orm/src/model.ts +2 -1
  33. package/types/core/src/batchSpawn.d.ts +28 -0
  34. package/types/core/src/connectionUrl.d.ts +61 -0
  35. package/types/core/src/fakeData.d.ts +11 -2
  36. package/types/core/src/index.d.ts +1 -1
  37. package/types/core/src/portTakeover.d.ts +15 -0
  38. package/types/core/src/projectIndexStorage.d.ts +5 -0
  39. package/types/core/src/queueBackends/rabbitmqBackend.d.ts +0 -7
  40. package/types/core/src/router.d.ts +17 -2
  41. package/types/core/src/server.d.ts +13 -0
  42. package/types/core/src/session.d.ts +5 -0
  43. package/types/core/src/sessionHandlers/databaseHandler.d.ts +8 -0
  44. package/types/core/src/urlRedaction.d.ts +61 -0
  45. package/types/orm/src/databaseUrl.d.ts +18 -19
  46. package/types/orm/src/graph/graphUrl.d.ts +18 -0
@@ -48,6 +48,7 @@ import { Env } from "./env.js";
48
48
  import { Log } from "./logger.js";
49
49
  import { background } from "./background.js";
50
50
  import { MqttMessage } from "./mqttMessage.js";
51
+ import { splitConnectionUrl, type ConnectionUrlParts } from "./connectionUrl.js";
51
52
 
52
53
  /** Any MQTT protocol / connection failure. */
53
54
  export class MqttError extends Error {
@@ -219,68 +220,43 @@ export class Mqtt {
219
220
  throw new Error(`MQTT url is empty -- set TINA4_MQTT_URL (e.g. ${DEFAULT_URL})`);
220
221
  }
221
222
 
222
- let scheme: string | null = null;
223
- let rest = raw;
223
+ // GHSA-h2mr-m3v3-cq8c: no message below may quote the url - it can carry a
224
+ // password, and four of them used to. The scheme alone is safe to name.
224
225
  const schemeMatch = raw.match(/^([A-Za-z][A-Za-z0-9+.-]*):\/\//);
226
+ let target = raw;
225
227
  if (schemeMatch) {
226
- scheme = schemeMatch[1].toLowerCase();
228
+ const scheme = schemeMatch[1].toLowerCase();
227
229
  if (!["mqtt", "tcp", "mqtts"].includes(scheme)) {
228
230
  throw new Error(
229
- `unsupported MQTT url scheme '${scheme}' in '${raw}' -- this client speaks ` +
231
+ `unsupported MQTT url scheme '${scheme}' -- this client speaks ` +
230
232
  "mqtt://, tcp:// or mqtts:// (TLS). WebSocket transports are not implemented.",
231
233
  );
232
234
  }
233
- rest = raw.slice(schemeMatch[0].length);
235
+ } else if (/^(\[[^\]\s]*\]|[^\s:/@?#[\]]+)(:\d*)?$/.test(raw)) {
236
+ // A bare "host" or "host:port" stays accepted. Anything else without
237
+ // "scheme://" (`mqtt:/u:pw@h`, `u:pw@h`) is refused by the splitter below.
238
+ target = `mqtt://${raw}`;
234
239
  }
235
240
 
236
- const tlsFlag = scheme === "mqtts";
237
-
238
- // Split on the LAST "@" so a password containing an un-encoded "@" still
239
- // leaves the host intact.
240
- let username: string | null = null;
241
- let password: string | null = null;
242
- const atPos = rest.lastIndexOf("@");
243
- if (atPos !== -1) {
244
- const userinfo = rest.slice(0, atPos);
245
- rest = rest.slice(atPos + 1);
246
- const colon = userinfo.indexOf(":");
247
- if (colon === -1) {
248
- username = Mqtt.percentDecode(userinfo);
249
- } else {
250
- username = Mqtt.percentDecode(userinfo.slice(0, colon));
251
- password = Mqtt.percentDecode(userinfo.slice(colon + 1));
252
- }
253
- }
254
-
255
- // host is a [bracketed ipv6] or a run without : or /
256
- const hostPort = rest.split("/", 1)[0];
257
- let host = hostPort;
258
- let portStr: string | null = null;
259
- if (hostPort.startsWith("[")) {
260
- const close = hostPort.indexOf("]");
261
- if (close === -1) throw new Error(`malformed MQTT url '${raw}' -- unclosed IPv6 bracket`);
262
- host = hostPort.slice(1, close);
263
- const after = hostPort.slice(close + 1);
264
- if (after.startsWith(":")) portStr = after.slice(1);
265
- } else {
266
- const colon = hostPort.indexOf(":");
267
- if (colon !== -1) {
268
- host = hostPort.slice(0, colon);
269
- portStr = hostPort.slice(colon + 1);
270
- }
241
+ // Userinfo by the shared rule: it ends at the LAST "@", so a password
242
+ // holding an un-encoded @ : / ? or # still leaves the host intact.
243
+ let parts: ConnectionUrlParts;
244
+ try {
245
+ parts = splitConnectionUrl(target, { label: "Mqtt", expected: "mqtt://[user[:password]@]host[:port]" });
246
+ } catch (err) {
247
+ throw new MqttError(`malformed MQTT url -- ${(err as Error).message.replace(/^Mqtt: /, "")}`);
271
248
  }
272
-
273
- if (host === "") throw new Error(`malformed MQTT url '${raw}' -- expected mqtt://host:port`);
274
- if (portStr !== null && portStr !== "" && !/^\d+$/.test(portStr)) {
275
- throw new Error(`malformed MQTT url '${raw}' -- port must be numeric`);
249
+ if (parts.host === "") {
250
+ throw new MqttError("malformed MQTT url -- expected mqtt://host:port. The url is not shown because it may contain a password.");
276
251
  }
252
+ const tlsFlag = parts.scheme === "mqtts";
277
253
 
278
254
  return {
279
- host,
280
- port: portStr !== null && portStr !== "" ? parseInt(portStr, 10) : tlsFlag ? DEFAULT_TLS_PORT : DEFAULT_PORT,
255
+ host: parts.host,
256
+ port: parts.port !== null ? parts.port : tlsFlag ? DEFAULT_TLS_PORT : DEFAULT_PORT,
281
257
  tls: tlsFlag,
282
- username: username !== null && username !== "" ? username : null,
283
- password,
258
+ username: parts.rawUsername !== null && parts.rawUsername !== "" ? Mqtt.percentDecode(parts.rawUsername) : null,
259
+ password: parts.rawPassword !== null ? Mqtt.percentDecode(parts.rawPassword) : null,
284
260
  };
285
261
  }
286
262
 
@@ -177,20 +177,37 @@ function sleepSync(ms: number): void {
177
177
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
178
178
  }
179
179
 
180
- // Listens on argv host:port and exits 0 once bound, 1 on any error. A child
181
- // process, because takeOverPort is synchronous and a Node bind is not. The
182
- // host and port arrive as argv, never interpolated into the code.
180
+ // Listens on argv host:port and exits 0 once bound, PROBE_HELD when the bind
181
+ // fails with EADDRINUSE, and PROBE_OTHER on any other bind error. A child
182
+ // process, because takeOverPort is synchronous and a Node bind is not. The host
183
+ // and port arrive as argv, never interpolated into the code.
184
+ const PROBE_HELD = 3;
185
+ const PROBE_OTHER = 4;
183
186
  const BIND_PROBE = 'const s = require("node:net").createServer();'
184
- + 's.on("error", () => process.exit(1));'
187
+ + `s.on("error", (e) => process.exit(e && e.code === "EADDRINUSE" ? ${PROBE_HELD} : ${PROBE_OTHER}));`
185
188
  + 's.listen({ host: process.argv[1], port: Number(process.argv[2]) }, () => s.close(() => process.exit(0)));';
186
189
 
187
- /** True when a plain TCP listener on `host`:`port` binds right now (the same net.listen the server uses). */
188
- function bindable(host: string, port: number): boolean {
190
+ /** What a bind probe learned about a port. */
191
+ export type BindProbe = "free" | "held" | "unknown";
192
+
193
+ /**
194
+ * Try a plain TCP listener on `host`:`port` (the same net.listen the server
195
+ * uses) and report what happened.
196
+ *
197
+ * Only a bind that fails with EADDRINUSE is "held". A probe that times out,
198
+ * cannot start, or hits any other bind error (EACCES, EADDRNOTAVAIL) is
199
+ * "unknown": it says nothing about whether something holds the port, so the
200
+ * caller must not report the port as in use. The real bind then decides, and
201
+ * it fails loudly with the true error. A probe is a child `node`, so on a slow
202
+ * host (arm64 under emulation, a small board, a CPU-throttled container) the
203
+ * child alone can take longer than the timeout to start.
204
+ */
205
+ export function probeBind(host: string, port: number, timeout = 5000): BindProbe {
189
206
  try {
190
- execFileSync(process.execPath, ["-e", BIND_PROBE, host, String(port)], { stdio: "ignore", timeout: 5000 });
191
- return true;
192
- } catch {
193
- return false;
207
+ execFileSync(process.execPath, ["-e", BIND_PROBE, host, String(port)], { stdio: "ignore", timeout });
208
+ return "free";
209
+ } catch (err) {
210
+ return (err as { status?: number | null }).status === PROBE_HELD ? "held" : "unknown";
194
211
  }
195
212
  }
196
213
 
@@ -198,12 +215,13 @@ function bindable(host: string, port: number): boolean {
198
215
  * The result to return before any holder lookup, or null to carry on.
199
216
  *
200
217
  * Takeover is refused when opted out or outside dev mode. Before a bind, the
201
- * caller passes the host it will bind: if that bind succeeds, nothing holds the
202
- * port, so there is nothing to refuse and nothing to say.
218
+ * caller passes the host it will bind: unless a probe sees that port held,
219
+ * there is nothing to refuse and nothing to say (an inconclusive probe leaves
220
+ * the decision to the real bind).
203
221
  */
204
222
  function refusal(port: number, dev: boolean, noTakeover: boolean, host?: string): TakeoverResult | null {
205
223
  if (dev && !noTakeover) return null;
206
- if (host !== undefined && bindable(host, port)) {
224
+ if (host !== undefined && probeBind(host, port) !== "held") {
207
225
  return { status: TAKEOVER_NOTHING, port, killed: [], message: "" };
208
226
  }
209
227
  if (noTakeover) {
@@ -17,9 +17,8 @@ file, You can obtain one at https://mozilla.org/MPL/2.0/.
17
17
  * Python) using regex. No LLM involvement — pure static analysis.
18
18
  */
19
19
 
20
- import * as path from "node:path";
21
20
  import * as fs from "node:fs";
22
- import { extract, indexPath, loadRaw, projectRoot, saveRaw, walk } from "./projectIndexStorage.js";
21
+ import { extract, indexKey, indexPath, loadRaw, projectRoot, saveRaw, walk } from "./projectIndexStorage.js";
23
22
  import type { IndexData } from "./projectIndexStorage.js";
24
23
 
25
24
  export interface FileRoute {
@@ -80,7 +79,7 @@ export const ProjectIndex = {
80
79
  const found: string[] = [];
81
80
  walk(root, found);
82
81
  for (const fp of found) {
83
- const rel = path.relative(root, fp);
82
+ const rel = indexKey(root, fp);
84
83
  seen.add(rel);
85
84
  let mtime: number;
86
85
  try {
@@ -106,7 +105,7 @@ export const ProjectIndex = {
106
105
  updated,
107
106
  removed: removed.length,
108
107
  total: Object.keys(files).length,
109
- path: path.relative(root, indexPath()),
108
+ path: indexKey(root, indexPath()),
110
109
  };
111
110
  },
112
111
 
@@ -31,6 +31,14 @@ export interface IndexData {
31
31
  generated_at: number;
32
32
  }
33
33
 
34
+ /**
35
+ * The index key for a file: its path relative to `root`, always `/`-separated
36
+ * so the same file has the same key on every OS (PHP's rule).
37
+ */
38
+ export function indexKey(root: string, fullPath: string): string {
39
+ return path.relative(root, fullPath).split(path.sep).join("/");
40
+ }
41
+
34
42
  export function projectRoot(): string {
35
43
  return path.resolve(process.cwd());
36
44
  }
@@ -69,7 +77,7 @@ export function extract(fullPath: string): FileEntry {
69
77
  return {};
70
78
  }
71
79
  const entry: FileEntry = {
72
- path: path.relative(projectRoot(), fullPath),
80
+ path: indexKey(projectRoot(), fullPath),
73
81
  size: st.size,
74
82
  mtime: Math.floor(st.mtimeMs / 1000),
75
83
  language: languageFor(fullPath),
@@ -25,6 +25,7 @@ file, You can obtain one at https://mozilla.org/MPL/2.0/.
25
25
  */
26
26
  import net from "node:net";
27
27
  import { execFileSync } from "node:child_process";
28
+ import { splitConnectionUrl } from "../connectionUrl.js";
28
29
  import { randomUUID } from "node:crypto";
29
30
  import type { QueueJob } from "../queue.js";
30
31
 
@@ -51,28 +52,39 @@ export interface RabbitMQConfig {
51
52
  * and reads the path segment as the URL-decoded vhost name. Only fields
52
53
  * present in the URL are populated.
53
54
  */
55
+ /**
56
+ * A bare "host[:port][/vhost]" stays accepted, as before. Anything carrying a
57
+ * scheme marker (`://`, `:/`, `//`), credentials or whitespace goes to the
58
+ * splitter as written, which refuses every form but `scheme://`.
59
+ */
60
+ function amqpTarget(url: string): string {
61
+ return /^[A-Za-z][A-Za-z0-9+.-]*(:\/|\/\/)|[@\s]/.test(url) ? url : `amqp://${url}`;
62
+ }
63
+
64
+ /** Only the credentials the URL actually wrote. */
65
+ function amqpCredentials(username: string | null, password: string | null): RabbitMQConfig {
66
+ const creds: RabbitMQConfig = {};
67
+ if (username !== null) creds.username = username;
68
+ if (password !== null) creds.password = password;
69
+ return creds;
70
+ }
71
+
54
72
  export function parseAmqpUrl(url: string): RabbitMQConfig {
55
73
  const config: RabbitMQConfig = {};
56
- let rest = url.replace(/^amqps:\/\//, "").replace(/^amqp:\/\//, "");
57
-
58
- const atIndex = rest.indexOf("@");
59
- if (atIndex !== -1) {
60
- const creds = rest.slice(0, atIndex);
61
- rest = rest.slice(atIndex + 1);
62
- const colonIndex = creds.indexOf(":");
63
- if (colonIndex !== -1) {
64
- config.username = creds.slice(0, colonIndex);
65
- config.password = creds.slice(colonIndex + 1);
66
- } else {
67
- config.username = creds;
68
- }
69
- }
70
-
71
- let hostport = rest;
72
- const slashIndex = rest.indexOf("/");
73
- if (slashIndex !== -1) {
74
- hostport = rest.slice(0, slashIndex);
75
- const vhost = rest.slice(slashIndex + 1);
74
+ // Userinfo by the shared rule (GHSA-h2mr-m3v3-cq8c): it ends at the LAST "@".
75
+ // This split at the FIRST, so `amqp://u:p@ss@rabbit/v` connected to a host
76
+ // named "ss@rabbit", and a password holding "/" became the vhost. A shape the
77
+ // rule cannot split is refused, naming nothing from the value.
78
+ const parts = splitConnectionUrl(amqpTarget(url), {
79
+ label: "parseAmqpUrl",
80
+ expected: "amqp://[user[:password]@]host[:port][/vhost]",
81
+ });
82
+ // Credentials pass through as written (undecoded) - unchanged behaviour.
83
+ Object.assign(config, amqpCredentials(parts.rawUsername, parts.rawPassword));
84
+
85
+ const hostport = parts.hostPort;
86
+ if (parts.tail.startsWith("/")) {
87
+ const vhost = parts.tail.slice(1);
76
88
  // THE VHOST IS THE PATH SEGMENT, URL-DECODED, WITH NO LEADING SLASH
77
89
  // (RabbitMQ URI spec). This used to prepend "/", so
78
90
  // amqp://guest:guest@rabbit:5672/orders asked for a vhost literally named
@@ -9,6 +9,7 @@ file, You can obtain one at https://mozilla.org/MPL/2.0/.
9
9
  import type { ServerResponse } from "node:http";
10
10
  import fs from "node:fs";
11
11
  import nodePath from "node:path";
12
+ import { fileURLToPath } from "node:url";
12
13
  import { once } from "node:events";
13
14
  import type { Tina4Response, CookieOptions } from "./types.js";
14
15
  import { currentCspNonce } from "./csp.js";
@@ -108,7 +109,9 @@ export async function getFrond(): Promise<InstanceType<any>> {
108
109
  * Syncs custom filters/globals from the user engine.
109
110
  */
110
111
  export async function getFrameworkFrond(): Promise<InstanceType<any> | null> {
111
- const frameworkDir = nodePath.resolve(nodePath.dirname(import.meta.url.replace("file://", "")), "..", "templates");
112
+ // fileURLToPath, not a string replace of "file://": the URL of a module under
113
+ // C:\ is file:///C:/..., and any path with a space or # is percent-encoded.
114
+ const frameworkDir = nodePath.resolve(nodePath.dirname(fileURLToPath(import.meta.url)), "..", "templates");
112
115
  if (!_frameworkFrond && fs.existsSync(frameworkDir)) {
113
116
  try {
114
117
  const { Frond, setCspNonceProvider } = await import("../../frond/src/engine.js");
@@ -8,6 +8,7 @@ file, You can obtain one at https://mozilla.org/MPL/2.0/.
8
8
 
9
9
  import { readdirSync, statSync, mkdirSync, writeFileSync, existsSync } from "node:fs";
10
10
  import { join, relative, basename, extname } from "node:path";
11
+ import { pathToFileURL } from "node:url";
11
12
  import type { RouteDefinition, RouteHandler, RouteMeta } from "./types.js";
12
13
 
13
14
  const VALID_METHODS = new Set(["get", "post", "put", "delete", "patch"]);
@@ -71,7 +72,9 @@ export async function discoverRoutes(routesDir: string): Promise<RouteDefinition
71
72
  try {
72
73
  // Cache-bust for hot-reload, keyed on mtime: identical content reuses the
73
74
  // same module URL (no needless re-import), an edit produces a fresh URL.
74
- const moduleUrl = `file://${filePath}?t=${currentMtime}`;
75
+ // pathToFileURL, not a hand-built file:// string: it percent-encodes #, ? and %, which
76
+ // would otherwise end the path early, and writes a drive letter correctly.
77
+ const moduleUrl = `${pathToFileURL(filePath).href}?t=${currentMtime}`;
75
78
  const mod = await import(moduleUrl);
76
79
 
77
80
  const handler: RouteHandler = mod.default ?? mod.handler;
@@ -146,7 +149,10 @@ function recordBrokenImport(filePath: string, error: Error): void {
146
149
  try {
147
150
  const brokenDir = join(process.cwd(), "data", ".broken");
148
151
  if (!existsSync(brokenDir)) mkdirSync(brokenDir, { recursive: true });
149
- const slug = filePath.replace(/[/\\]/g, "_");
152
+ // `:` too: an absolute Windows path starts with a drive letter, and on NTFS
153
+ // a colon in a file name writes an alternate data stream instead of a file,
154
+ // so no *.broken listing would ever see the marker.
155
+ const slug = filePath.replace(/[/\\:]/g, "_");
150
156
  const payload = JSON.stringify({
151
157
  type: "auto_discover_failure",
152
158
  file: filePath,
@@ -124,21 +124,29 @@ export class WsRouteRef {
124
124
  /**
125
125
  * Thin reference to a registered route, enabling chained modifiers.
126
126
  *
127
+ * A ref may cover several compiled routes: `any()` registers one route per
128
+ * method, and a modifier chained on it must reach every one of them, not only
129
+ * the last one registered.
130
+ *
127
131
  * Usage:
128
132
  * router.get("/api/data", handler).secure().cache();
129
133
  */
130
134
  export class RouteRef {
131
- constructor(private route: CompiledRoute) {}
135
+ private routes: CompiledRoute[];
136
+
137
+ constructor(route: CompiledRoute | CompiledRoute[]) {
138
+ this.routes = Array.isArray(route) ? route : [route];
139
+ }
132
140
 
133
141
  /** Mark this route as requiring bearer-token authentication. */
134
142
  secure(): this {
135
- this.route.secure = true;
143
+ for (const route of this.routes) route.secure = true;
136
144
  return this;
137
145
  }
138
146
 
139
147
  /** Opt out of secure-by-default auth (for public write routes). */
140
148
  noAuth(): this {
141
- this.route.noAuth = true;
149
+ for (const route of this.routes) route.noAuth = true;
142
150
  return this;
143
151
  }
144
152
 
@@ -149,7 +157,7 @@ export class RouteRef {
149
157
  * (identity) are orthogonal — chain `.noAuth().noCsrf()` for a public webhook.
150
158
  */
151
159
  noCsrf(): this {
152
- this.route.noCsrf = true;
160
+ for (const route of this.routes) route.noCsrf = true;
153
161
  return this;
154
162
  }
155
163
 
@@ -158,12 +166,7 @@ export class RouteRef {
158
166
  * claim. Chain .role()/.can() for AND. Implies auth. Feature 138 / ADR-0058.
159
167
  */
160
168
  role(...names: string[]): this {
161
- const clean = names.filter((n) => n !== "");
162
- if (clean.length > 0) {
163
- (this.route.requiredRoles ??= []).push(clean);
164
- this.route.secure = true;
165
- }
166
- return this;
169
+ return this.guard("requiredRoles", names);
167
170
  }
168
171
 
169
172
  /**
@@ -172,17 +175,28 @@ export class RouteRef {
172
175
  * concrete requirement. Chain for AND. Implies auth. Feature 138.
173
176
  */
174
177
  can(...permissions: string[]): this {
175
- const clean = permissions.filter((p) => p !== "");
178
+ return this.guard("requiredPerms", permissions);
179
+ }
180
+
181
+ /**
182
+ * Add one OR-group of roles or permissions to every route this ref covers,
183
+ * and secure them (a guard implies auth). Empty names are dropped; a call
184
+ * with none left changes nothing.
185
+ */
186
+ private guard(key: "requiredRoles" | "requiredPerms", names: string[]): this {
187
+ const clean = names.filter((n) => n !== "");
176
188
  if (clean.length > 0) {
177
- (this.route.requiredPerms ??= []).push(clean);
178
- this.route.secure = true;
189
+ for (const route of this.routes) {
190
+ (route[key] ??= []).push(clean);
191
+ route.secure = true;
192
+ }
179
193
  }
180
194
  return this;
181
195
  }
182
196
 
183
197
  /** Mark this route's response as cacheable. */
184
198
  cache(): this {
185
- this.route.cached = true;
199
+ for (const route of this.routes) route.cached = true;
186
200
  return this;
187
201
  }
188
202
 
@@ -191,7 +205,9 @@ export class RouteRef {
191
205
  * string specs (e.g. `"ResponseCache:300"`), resolved when the route runs.
192
206
  */
193
207
  middleware(...middlewareClasses: MiddlewareSpec[]): this {
194
- this.route.middlewares = [...(this.route.middlewares ?? []), ...middlewareClasses];
208
+ for (const route of this.routes) {
209
+ route.middlewares = [...(route.middlewares ?? []), ...middlewareClasses];
210
+ }
195
211
  return this;
196
212
  }
197
213
  }
@@ -240,6 +256,11 @@ export class Router {
240
256
  * Add a raw route definition (used internally and by file-based routing).
241
257
  */
242
258
  addRoute(definition: RouteDefinition): RouteRef {
259
+ return new RouteRef(this.registerRoute(definition));
260
+ }
261
+
262
+ /** Compile and store one route definition; returns the stored route. */
263
+ private registerRoute(definition: RouteDefinition): CompiledRoute {
243
264
  const method = definition.method.toUpperCase();
244
265
  const { regex, paramNames, paramTypes } = this.compilePattern(definition.pattern);
245
266
 
@@ -281,7 +302,7 @@ export class Router {
281
302
  requiredPerms: definition.requiredPerms,
282
303
  };
283
304
  routes.push(compiled);
284
- return new RouteRef(compiled);
305
+ return compiled;
285
306
  }
286
307
 
287
308
  /**
@@ -343,13 +364,16 @@ export class Router {
343
364
 
344
365
  /**
345
366
  * Register a route that matches ANY HTTP method.
367
+ *
368
+ * One route is stored per method; the returned ref covers all of them, so
369
+ * `any(...).secure()` / `.role()` / `.noAuth()` apply to every method.
346
370
  */
347
371
  any(path: string, handler: RouteHandler, middlewares?: MiddlewareSpec[], meta?: RouteMeta): RouteRef {
348
- let lastRef!: RouteRef;
372
+ const compiled: CompiledRoute[] = [];
349
373
  for (const method of ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"]) {
350
- lastRef = this.addRoute({ method, pattern: path, handler, middlewares, meta });
374
+ compiled.push(this.registerRoute({ method, pattern: path, handler, middlewares, meta }));
351
375
  }
352
- return lastRef;
376
+ return new RouteRef(compiled);
353
377
  }
354
378
 
355
379
  /**
@@ -850,17 +874,7 @@ export class RouteGroup {
850
874
  }
851
875
 
852
876
  any(path: string, handler: RouteHandler, middlewares?: MiddlewareSpec[], meta?: RouteMeta): RouteRef {
853
- let lastRef!: RouteRef;
854
- for (const method of ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"]) {
855
- lastRef = this.router.addRoute({
856
- method,
857
- pattern: joinGroupPath(this.prefix, path),
858
- handler,
859
- middlewares: this.mergeMiddlewares(middlewares),
860
- meta,
861
- });
862
- }
863
- return lastRef;
877
+ return this.router.any(joinGroupPath(this.prefix, path), handler, this.mergeMiddlewares(middlewares), meta);
864
878
  }
865
879
 
866
880
  /**
@@ -14,7 +14,7 @@ import { resolve, dirname, join, relative } from "node:path";
14
14
  import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
15
15
  import { isatty } from "node:tty";
16
16
  import { fileURLToPath } from "node:url";
17
- import { execFileSync, execFile } from "node:child_process";
17
+ import { execFile } from "node:child_process";
18
18
  import cluster from "node:cluster";
19
19
  import os from "node:os";
20
20
  import type { Socket } from "node:net";
@@ -24,6 +24,7 @@ import { enforceRouteAuth } from "./authGate.js";
24
24
  import { discoverRoutes } from "./routeDiscovery.js";
25
25
  import {
26
26
  takeOverPort,
27
+ probeBind,
27
28
  isDev as isTakeoverDev,
28
29
  noTakeoverOptedOut,
29
30
  writePidfile,
@@ -55,6 +56,7 @@ import { I18n } from "./i18n.js";
55
56
  import { stopAllBackgroundTasks } from "./background.js";
56
57
  import { startAllTcpServices, stopAcceptingAllTcpServices, drainAllTcpServices } from "./tcp.js";
57
58
  import { TINA4_VERSION } from "./version.js";
59
+ import { stripCredentials } from "./urlRedaction.js";
58
60
 
59
61
  const __filename = fileURLToPath(import.meta.url);
60
62
  const __dirname = dirname(__filename);
@@ -114,6 +116,22 @@ export function shutdownTimeoutSeconds(): number {
114
116
  return parsed;
115
117
  }
116
118
 
119
+ /**
120
+ * The signals `startServer()` traps into its graceful shutdown on this platform.
121
+ *
122
+ * POSIX: SIGTERM (an orchestrator's stop) and SIGINT (Ctrl+C).
123
+ *
124
+ * Windows adds SIGBREAK: Ctrl+Break, and the CTRL_BREAK_EVENT a console or
125
+ * service manager sends a process group, arrive as SIGBREAK, and with no
126
+ * listener Node's default action kills the process on the spot (exit
127
+ * 0xC000013A) - in-flight requests dropped, no drain. Parity with tina4-python,
128
+ * which traps SIGINT/SIGBREAK/SIGTERM on Windows. Every listener registered for
129
+ * these replaces Node's default and therefore MUST exit (see background.ts).
130
+ */
131
+ export function shutdownSignals(platform: NodeJS.Platform = process.platform): NodeJS.Signals[] {
132
+ return platform === "win32" ? ["SIGTERM", "SIGINT", "SIGBREAK"] : ["SIGTERM", "SIGINT"];
133
+ }
134
+
117
135
  /**
118
136
  * Build the startup banner's optional surface lines (issue #99).
119
137
  *
@@ -162,12 +180,13 @@ function swaggerAdvertised(): boolean {
162
180
 
163
181
  /**
164
182
  * A connection URL (or any text that may embed one) with every `user:pass@`
165
- * removed, for a boot log line. Core never imports the ORM statically, so this
166
- * cannot borrow its redactCredentials(); stripping the whole userinfo is
167
- * stricter than redaction anyway (the user name goes too).
183
+ * removed, for a boot log line - stricter than redaction (the user name goes
184
+ * too). The shared rule (urlRedaction.ts): this used to be a regex that could
185
+ * not cross a `/` or a space, so `postgres://u:Pq1/Rs2@h/db` and
186
+ * `postgres:/u:pw@h/db` went into the boot log whole (GHSA-h2mr-m3v3-cq8c).
168
187
  */
169
188
  function stripUrlCredentials(text: string): string {
170
- return text.replace(/:\/\/[^/\s]*@/g, "://");
189
+ return stripCredentials(text);
171
190
  }
172
191
 
173
192
  /** A dynamic import that failed because the module itself is absent. */
@@ -412,22 +431,17 @@ export function killPort(port: number): void {
412
431
  }
413
432
 
414
433
  /**
415
- * Check if *port* is available; if not, kill the process on it and return *port*.
416
- * The auto-increment behaviour is intentionally removed — the server always
417
- * claims the requested port.
434
+ * Check if *port* is held; if it is, reclaim it through the guarded takeover
435
+ * path and return *port*. The auto-increment behaviour is intentionally
436
+ * removed — the server always claims the requested port.
437
+ *
438
+ * Only a probe that sees EADDRINUSE counts as held. A probe that times out on a
439
+ * slow start says nothing about the port, so the real bind decides: it used to
440
+ * count as "in use", and a production server on a slow host refused a free port.
418
441
  */
419
442
  function findAvailablePort(start: number): number {
420
- try {
421
- execFileSync(process.execPath, ["-e", `
422
- const s = require("net").createServer();
423
- s.listen(${start}, "0.0.0.0", () => { s.close(); process.exit(0); });
424
- s.on("error", () => process.exit(1));
425
- `], { timeout: 1000 });
426
- return start;
427
- } catch {
428
- killPort(start);
429
- return start;
430
- }
443
+ if (probeBind("0.0.0.0", start) === "held") killPort(start);
444
+ return start;
431
445
  }
432
446
 
433
447
  /**
@@ -2147,6 +2161,13 @@ function startProductionCluster(port: number, host: string): {
2147
2161
  Debug: OFF (Log level: ${logLevel})
2148
2162
  ${reset}`);
2149
2163
  }
2164
+ // Round-robin, so every worker gets requests. Node already defaults to it
2165
+ // everywhere except Windows, where the default is SCHED_NONE (the OS picks a
2166
+ // worker, and under load it may keep picking the same one). Must be set before
2167
+ // the first fork. An operator's explicit NODE_CLUSTER_SCHED_POLICY wins.
2168
+ if (process.env.NODE_CLUSTER_SCHED_POLICY === undefined) {
2169
+ cluster.schedulingPolicy = cluster.SCHED_RR;
2170
+ }
2150
2171
  for (let i = 0; i < numCPUs; i++) cluster.fork();
2151
2172
  cluster.on("exit", (worker, code) => {
2152
2173
  if (code !== 0) {
@@ -2740,18 +2761,18 @@ ${reset}
2740
2761
  process.exit(0);
2741
2762
  };
2742
2763
 
2743
- const onSigterm = (): void => {
2744
- // gracefulShutdown is internally exception-safe, so this cannot reject;
2745
- // the `.catch` is belt-and-braces so the discarded (`void`) promise can
2746
- // never become an unhandledRejection that exits non-zero on a handled
2747
- // signal.
2748
- void gracefulShutdown("SIGTERM").catch(() => process.exit(0));
2749
- };
2750
- const onSigint = (): void => {
2751
- void gracefulShutdown("SIGINT").catch(() => process.exit(0));
2752
- };
2753
- process.on("SIGTERM", onSigterm);
2754
- process.on("SIGINT", onSigint);
2764
+ // One listener per shutdown signal: SIGTERM + SIGINT everywhere, plus
2765
+ // SIGBREAK on Windows (see shutdownSignals()). gracefulShutdown is
2766
+ // internally exception-safe, so this cannot reject; the `.catch` is
2767
+ // belt-and-braces so the discarded (`void`) promise can never become an
2768
+ // unhandledRejection that exits non-zero on a handled signal.
2769
+ const signalListeners = shutdownSignals().map((signal) => ({
2770
+ signal,
2771
+ listener: (): void => {
2772
+ void gracefulShutdown(signal).catch(() => process.exit(0));
2773
+ },
2774
+ }));
2775
+ signalListeners.forEach(({ signal, listener }) => process.on(signal, listener));
2755
2776
 
2756
2777
  // Raw TCP services (feature 142, ADR-0102 D1) bind on THIS event loop,
2757
2778
  // beside the HTTP server — one process serves both the device gateway and
@@ -2771,8 +2792,7 @@ ${reset}
2771
2792
  // An explicit close() is not a signal shutdown: drop the handlers so
2772
2793
  // a test that starts many servers in one process does not pile up
2773
2794
  // listeners (and trip Node's MaxListeners warning).
2774
- process.off("SIGTERM", onSigterm);
2775
- process.off("SIGINT", onSigint);
2795
+ signalListeners.forEach(({ signal, listener }) => process.off(signal, listener));
2776
2796
  // Clear any registered background timers so graceful shutdown actually exits.
2777
2797
  stopAllBackgroundTasks();
2778
2798
  // Release raw TCP listeners + connections on an explicit close() too.