tina4-nodejs 3.13.165 → 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.
@@ -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
  /**
@@ -56,6 +56,7 @@ import { I18n } from "./i18n.js";
56
56
  import { stopAllBackgroundTasks } from "./background.js";
57
57
  import { startAllTcpServices, stopAcceptingAllTcpServices, drainAllTcpServices } from "./tcp.js";
58
58
  import { TINA4_VERSION } from "./version.js";
59
+ import { stripCredentials } from "./urlRedaction.js";
59
60
 
60
61
  const __filename = fileURLToPath(import.meta.url);
61
62
  const __dirname = dirname(__filename);
@@ -115,6 +116,22 @@ export function shutdownTimeoutSeconds(): number {
115
116
  return parsed;
116
117
  }
117
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
+
118
135
  /**
119
136
  * Build the startup banner's optional surface lines (issue #99).
120
137
  *
@@ -163,12 +180,13 @@ function swaggerAdvertised(): boolean {
163
180
 
164
181
  /**
165
182
  * A connection URL (or any text that may embed one) with every `user:pass@`
166
- * removed, for a boot log line. Core never imports the ORM statically, so this
167
- * cannot borrow its redactCredentials(); stripping the whole userinfo is
168
- * 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).
169
187
  */
170
188
  function stripUrlCredentials(text: string): string {
171
- return text.replace(/:\/\/[^/\s]*@/g, "://");
189
+ return stripCredentials(text);
172
190
  }
173
191
 
174
192
  /** A dynamic import that failed because the module itself is absent. */
@@ -2743,18 +2761,18 @@ ${reset}
2743
2761
  process.exit(0);
2744
2762
  };
2745
2763
 
2746
- const onSigterm = (): void => {
2747
- // gracefulShutdown is internally exception-safe, so this cannot reject;
2748
- // the `.catch` is belt-and-braces so the discarded (`void`) promise can
2749
- // never become an unhandledRejection that exits non-zero on a handled
2750
- // signal.
2751
- void gracefulShutdown("SIGTERM").catch(() => process.exit(0));
2752
- };
2753
- const onSigint = (): void => {
2754
- void gracefulShutdown("SIGINT").catch(() => process.exit(0));
2755
- };
2756
- process.on("SIGTERM", onSigterm);
2757
- 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));
2758
2776
 
2759
2777
  // Raw TCP services (feature 142, ADR-0102 D1) bind on THIS event loop,
2760
2778
  // beside the HTTP server — one process serves both the device gateway and
@@ -2774,8 +2792,7 @@ ${reset}
2774
2792
  // An explicit close() is not a signal shutdown: drop the handlers so
2775
2793
  // a test that starts many servers in one process does not pile up
2776
2794
  // listeners (and trip Node's MaxListeners warning).
2777
- process.off("SIGTERM", onSigterm);
2778
- process.off("SIGINT", onSigint);
2795
+ signalListeners.forEach(({ signal, listener }) => process.off(signal, listener));
2779
2796
  // Clear any registered background timers so graceful shutdown actually exits.
2780
2797
  stopAllBackgroundTasks();
2781
2798
  // Release raw TCP listeners + connections on an explicit close() too.
@@ -0,0 +1,252 @@
1
+ /*
2
+ Copyright (c) 2026 Code Infinity
3
+ SPDX-License-Identifier: MPL-2.0
4
+ This Source Code Form is subject to the terms of the Mozilla Public
5
+ License, v. 2.0. If a copy of the MPL was not distributed with this
6
+ file, You can obtain one at https://mozilla.org/MPL/2.0/.
7
+ */
8
+
9
+ /**
10
+ * Connection URL credentials: the ONE redaction rule, shared by every path
11
+ * that can put a connection string in front of a human (GHSA-h2mr-m3v3-cq8c).
12
+ * Its parsing half - the ONE userinfo splitter every parser uses - is the
13
+ * sibling connectionUrl.ts, which takes its port-versus-password test from
14
+ * here so the two halves cannot drift.
15
+ *
16
+ * IMPORTS NOTHING, on purpose. @tina4/orm imports it (databaseUrl.ts) and so
17
+ * does @tina4/core (the websocket backplane, the boot log, the dev admin) - a
18
+ * leaf module is the only place both can reach without a cycle.
19
+ *
20
+ * THE RULE
21
+ * - The authority starts after `scheme://`, `scheme:/` or `scheme//`.
22
+ * - Userinfo ends at the LAST `@` on the line; the password starts at the
23
+ * first `:` after the authority start. A `/`, `?` or `#` before that `:`
24
+ * means the text is a path, not a password.
25
+ * - With no `@`, a non-numeric "port" is the password: it is masked to the end
26
+ * of the line, keeping a trailing `?key=value` query.
27
+ * - Parsers refuse a URL without `scheme://`, or whose `@` count differs from
28
+ * what the parser took as userinfo, with a GENERIC message that never
29
+ * echoes the value and never chains an error that does.
30
+ * - Scheme, user and host stay visible, so the line is still useful.
31
+ *
32
+ * Why this replaced the old rules: they cut the authority at the first `/`, `?`
33
+ * or `#`, or split userinfo at the first `@`, so `postgres://u:Pq1/Rs2@h/db`,
34
+ * `postgres:/u:pw@h/db`, `postgres://u:pw` and `postgres://u:pw@h:notaport/db`
35
+ * all printed the password - in redacted log lines, in "invalid URL" errors
36
+ * that named `u:Pq1` as the host, and in driver errors downstream.
37
+ *
38
+ * KNOWN LIMITS (unmaskable by any rule):
39
+ * - A host-less URL whose password is all digits (`postgres://u:123/x`) is a
40
+ * valid URL with port 123, so the digits are shown.
41
+ * - A host-less URL whose password holds an unencoded `@`
42
+ * (`postgres://u:Pq1@Rs2`) is a valid URL whose HOST is `Rs2`; the tail
43
+ * after the `@` is shown as the host.
44
+ * Over-redaction is accepted instead: a second `@` later on the same line
45
+ * (`... failed for admin@corp`) masks up to it, hiding a host, never showing a
46
+ * password.
47
+ */
48
+
49
+ /** The single mask. One spelling, so grepping for it finds every redaction. */
50
+ export const REDACTED = "***";
51
+
52
+ /** `scheme` + one of the three authority markers, not glued to a path or word. */
53
+ const SCHEME_MARKER = /(?<![A-Za-z0-9+.\-/])([A-Za-z][A-Za-z0-9+.-]*)(:\/\/|:\/|\/\/)/g;
54
+
55
+ /** A trailing query worth keeping: `?k=v` pairs (and a fragment), nothing else. */
56
+ const KEPT_QUERY = /^\?[^\s=&#?]+=[^\s&#?]*(?:&[^\s=&#?]+=[^\s&#?]*)*(?:#\S*)?$/;
57
+
58
+ /**
59
+ * Where a keyword VALUE ends in a keyword/value connection string.
60
+ *
61
+ * NOT at the first whitespace. tina4-php redacted its connect-failure message
62
+ * with a `\bpassword=\S` + star pattern, and a password containing a SPACE kept
63
+ * its TAIL in the logged line. The real terminators are the field separators -
64
+ * `;` for ODBC/libpq, `&` for a query string - plus the closing brace/quote of
65
+ * a quoted value, since `PWD={p;w}` and the libpq quoted form both legally
66
+ * contain a separator.
67
+ */
68
+ function endOfKeywordValue(text: string, start: number): number {
69
+ const open = text[start];
70
+ if (open === "{") {
71
+ const close = text.indexOf("}", start + 1);
72
+ return close === -1 ? text.length : close + 1;
73
+ }
74
+ if (open === "'" || open === '"') return endOfQuoted(text, start, open);
75
+ const end = text.slice(start).search(/[;&]/);
76
+ return end === -1 ? text.length : start + end;
77
+ }
78
+
79
+ /** Just past the closing quote of a quoted value; a backslash escapes. */
80
+ function endOfQuoted(text: string, start: number, quote: string): number {
81
+ let i = start + 1;
82
+ while (i < text.length) {
83
+ if (text[i] === "\\") { i += 2; continue; }
84
+ if (text[i] === quote) return i + 1;
85
+ i++;
86
+ }
87
+ return text.length;
88
+ }
89
+
90
+ /** `PWD=`/`password=`/`passwd=` in an ODBC DSN, a libpq DSN or a query string. */
91
+ const SECRET_KEYWORD_PATTERN = /(^|[;&?\s])(pwd|password|passwd)(\s*=\s*)/gi;
92
+
93
+ function redactKeywordValues(text: string): string {
94
+ const pattern = new RegExp(SECRET_KEYWORD_PATTERN.source, SECRET_KEYWORD_PATTERN.flags);
95
+ let out = "";
96
+ let cursor = 0;
97
+ let match: RegExpExecArray | null;
98
+ while ((match = pattern.exec(text)) !== null) {
99
+ const valueStart = match.index + match[0].length;
100
+ out += text.slice(cursor, valueStart) + REDACTED;
101
+ cursor = endOfKeywordValue(text, valueStart);
102
+ pattern.lastIndex = cursor;
103
+ }
104
+ return out + text.slice(cursor);
105
+ }
106
+
107
+ /** One credential found on a line: the userinfo span and the password span in it. */
108
+ interface CredentialSpan {
109
+ /** Index where the authority (and so any userinfo) starts. */
110
+ authorityStart: number;
111
+ /** Index of the `@` that ends userinfo, or -1 for the no-`@` port-shaped password. */
112
+ at: number;
113
+ /** [start, end) of the text to mask as the password. */
114
+ passwordStart: number;
115
+ passwordEnd: number;
116
+ }
117
+
118
+ /**
119
+ * The credential spans on ONE line, left to right.
120
+ *
121
+ * The rule, applied per scheme marker: userinfo runs to the LAST `@` on the
122
+ * line; the password is from the first `:` after the authority start to that
123
+ * `@`, unless a `/`, `?` or `#` comes before the `:` (then it is a path). With
124
+ * no usable `@`, a port that is not all digits is the password, to the end of
125
+ * the line, less a trailing `?key=value` query.
126
+ */
127
+ function credentialSpans(line: string): CredentialSpan[] {
128
+ const spans: CredentialSpan[] = [];
129
+ const marker = new RegExp(SCHEME_MARKER.source, "g");
130
+ const lastAt = line.lastIndexOf("@");
131
+ let match: RegExpExecArray | null;
132
+ while ((match = marker.exec(line)) !== null) {
133
+ const start = match.index + match[0].length;
134
+ const withAt = userinfoSpan(line, start, lastAt);
135
+ if (withAt !== null) {
136
+ spans.push(withAt);
137
+ // Everything up to the last `@` is now accounted for.
138
+ marker.lastIndex = lastAt + 1;
139
+ continue;
140
+ }
141
+ const portShaped = portShapedSpan(line, start);
142
+ if (portShaped !== null) {
143
+ spans.push(portShaped);
144
+ break; // masked to the end of the line: nothing after it is left to scan
145
+ }
146
+ }
147
+ return spans;
148
+ }
149
+
150
+ /**
151
+ * `user:password@` for an authority starting at `start`, ending at the line's
152
+ * last `@` - or null when there is no such `@`, no `:` before it, or a `/`,
153
+ * `?` or `#` before the `:` (then the text is a path, not a password).
154
+ */
155
+ function userinfoSpan(line: string, start: number, lastAt: number): CredentialSpan | null {
156
+ if (lastAt < start) return null;
157
+ const colon = line.indexOf(":", start);
158
+ if (colon === -1 || colon >= lastAt || /[/?#]/.test(line.slice(start, colon))) return null;
159
+ return { authorityStart: start, at: lastAt, passwordStart: colon + 1, passwordEnd: lastAt };
160
+ }
161
+
162
+ /**
163
+ * No `@` reachable: the authority is host[:port], and a port that cannot be a
164
+ * port is the password. Whitespace ends the HOST scan (a host has none) but
165
+ * not the mask - `u:Pq1 Rs2` has to go to the end of the line.
166
+ *
167
+ * A numeric port is a port - unless what follows it cannot follow a port: a
168
+ * fragment, or a query that is not `key=value`. `u:12?Pq1Rs2` and
169
+ * `u:12#Pq1Rs2` are digit-led passwords, not port 12. (Known limit: an
170
+ * all-digit password, or digits then a path, `u:12/x`, looks exactly like a
171
+ * port and stays visible.)
172
+ */
173
+ function portShapedSpan(line: string, start: number): CredentialSpan | null {
174
+ const rest = line.slice(start);
175
+ const authorityEnd = rest.search(/[/?#\s]/);
176
+ const authority = authorityEnd === -1 ? rest : rest.slice(0, authorityEnd);
177
+ const colon = authority.indexOf(":", authority.startsWith("[") ? authority.indexOf("]") + 1 : 0);
178
+ if (colon === -1) return null;
179
+ const port = authority.slice(colon + 1);
180
+ if (port === "") return null;
181
+ if (/^\d+$/.test(port) && !digitLedPassword(rest.slice(authority.length))) return null;
182
+ const maskStart = start + colon + 1;
183
+ return { authorityStart: start, at: -1, passwordStart: maskStart, passwordEnd: keptQueryStart(line, maskStart) };
184
+ }
185
+
186
+ /** Where the mask stops: before a trailing `?key=value` query, else the line end. */
187
+ function keptQueryStart(line: string, from: number): number {
188
+ const query = line.indexOf("?", from);
189
+ return query !== -1 && KEPT_QUERY.test(line.slice(query)) ? query : line.length;
190
+ }
191
+
192
+ /**
193
+ * True when the text after a host-less `x:digits` cannot be what follows a
194
+ * port - a `#fragment`, or a `?query` that is not `key=value` pairs - so the
195
+ * digits are the start of a password (`postgres://u:12?Pq1Rs2`).
196
+ */
197
+ export function digitLedPassword(afterPort: string): boolean {
198
+ if (afterPort.startsWith("#")) return true;
199
+ return afterPort.startsWith("?") && !KEPT_QUERY.test(afterPort.split(/\s/, 1)[0]);
200
+ }
201
+
202
+ function rewriteLines(text: string, render: (line: string, spans: CredentialSpan[]) => string): string {
203
+ return text
204
+ .split(/(\r?\n)/)
205
+ .map((part) => (part === "\n" || part === "\r\n" ? part : render(part, credentialSpans(part))))
206
+ .join("");
207
+ }
208
+
209
+ /**
210
+ * Remove every password from an arbitrary connection string or message.
211
+ *
212
+ * THE single redaction primitive. It works on RAW text - valid or malformed, a
213
+ * URL, an ODBC DSN, or an error message that embeds either - so error paths can
214
+ * use it too. `postgres://u:pw@host/db` becomes `postgres://u:***@host/db`.
215
+ */
216
+ export function redactCredentials(raw: string): string {
217
+ if (typeof raw !== "string" || raw === "") return raw;
218
+ const masked = rewriteLines(raw, (line, spans) => {
219
+ let out = "";
220
+ let cursor = 0;
221
+ for (const span of spans) {
222
+ out += line.slice(cursor, span.passwordStart) + REDACTED;
223
+ cursor = span.passwordEnd;
224
+ }
225
+ return out + line.slice(cursor);
226
+ });
227
+ return redactKeywordValues(masked);
228
+ }
229
+
230
+ /**
231
+ * Like redactCredentials(), but drops the whole userinfo (`user:pass@`) rather
232
+ * than masking the password - for the boot log, which names the database
233
+ * target and nothing about who connects to it.
234
+ */
235
+ export function stripCredentials(raw: string): string {
236
+ if (typeof raw !== "string" || raw === "") return raw;
237
+ const stripped = rewriteLines(raw, (line, spans) => {
238
+ let out = "";
239
+ let cursor = 0;
240
+ for (const span of spans) {
241
+ if (span.at === -1) {
242
+ out += line.slice(cursor, span.passwordStart) + REDACTED;
243
+ cursor = span.passwordEnd;
244
+ } else {
245
+ out += line.slice(cursor, span.authorityStart);
246
+ cursor = span.at + 1;
247
+ }
248
+ }
249
+ return out + line.slice(cursor);
250
+ });
251
+ return redactKeywordValues(stripped);
252
+ }
@@ -26,7 +26,8 @@ file, You can obtain one at https://mozilla.org/MPL/2.0/.
26
26
  */
27
27
  import { randomUUID } from "node:crypto";
28
28
  import { resolveOptionalPackage } from "./optionalPackage.js";
29
- import { redactCredentials } from "../../orm/src/databaseUrl.js";
29
+ import { redactCredentials } from "./urlRedaction.js";
30
+ import { canonicalConnectionUrl, splitConnectionUrl } from "./connectionUrl.js";
30
31
 
31
32
  /**
32
33
  * The one "connected" line both backplanes print. The URL goes through the
@@ -37,6 +38,17 @@ function logConnected(backplaneName: string, url: string): void {
37
38
  console.log(`[Tina4] ${backplaneName} connected to ${redactCredentials(url)}`);
38
39
  }
39
40
 
41
+ /**
42
+ * The backplane URL as the driver receives it: split by the shared rule and
43
+ * re-encoded, so the driver's own URL parser never re-splits a password that
44
+ * holds `/`, `?`, `#` or `@` - a mis-split password becomes the "host" every
45
+ * connect error then prints. A shape the rule cannot split is refused here, in
46
+ * the constructor, with a message that does not echo it (GHSA-h2mr-m3v3-cq8c).
47
+ */
48
+ function driverUrl(backplaneName: string, url: string): string {
49
+ return canonicalConnectionUrl(splitConnectionUrl(url, { label: backplaneName, allowHostList: true }));
50
+ }
51
+
40
52
  /**
41
53
  * A backplane connects in the background, and publish()/subscribe() await that
42
54
  * connect. Until someone does, a failed connect is a rejected promise nobody is
@@ -85,7 +97,7 @@ export class RedisBackplane implements WebSocketBackplane {
85
97
  private ready: Promise<void>;
86
98
 
87
99
  constructor(url?: string) {
88
- const resolvedUrl = url ?? process.env.TINA4_WS_BACKPLANE_URL ?? "redis://localhost:6379";
100
+ const resolvedUrl = driverUrl("RedisBackplane", url ?? process.env.TINA4_WS_BACKPLANE_URL ?? "redis://localhost:6379");
89
101
  this.url = resolvedUrl;
90
102
 
91
103
  // Optional peer (ADR-0067): resolved NOW so a missing package throws from
@@ -147,7 +159,7 @@ export class NATSBackplane implements WebSocketBackplane {
147
159
  private natsModuleUrl: string;
148
160
 
149
161
  constructor(url?: string) {
150
- const resolvedUrl = url ?? process.env.TINA4_WS_BACKPLANE_URL ?? "nats://localhost:4222";
162
+ const resolvedUrl = driverUrl("NATSBackplane", url ?? process.env.TINA4_WS_BACKPLANE_URL ?? "nats://localhost:4222");
151
163
  this.url = resolvedUrl;
152
164
 
153
165
  const natsModuleUrl = resolveOptionalPackage("nats", "NATSBackplane");