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.
@@ -0,0 +1,242 @@
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 parsing: the ONE userinfo splitter every parser uses
11
+ * (DatabaseUrl, GraphUrl, Mqtt.parseUrl, parseAmqpUrl, the Mongo and backplane
12
+ * driver hand-offs) - GHSA-h2mr-m3v3-cq8c. The redaction half, and THE RULE
13
+ * both halves apply, are in urlRedaction.ts.
14
+ *
15
+ * Imports only urlRedaction.ts, itself import-free, so @tina4/core and
16
+ * @tina4/orm both reach it without a cycle.
17
+ */
18
+ import { digitLedPassword } from "./urlRedaction.js";
19
+
20
+ /**
21
+ * The error every parser throws for a connection URL it will not accept.
22
+ *
23
+ * The message NEVER carries the value and the error NEVER has a `cause`: a
24
+ * TypeError from `new URL()` keeps the input on `.input`, and a driver's parse
25
+ * error quotes it, so chaining either would put the password straight back.
26
+ */
27
+ export class ConnectionUrlError extends Error {
28
+ constructor(message: string) {
29
+ super(message);
30
+ this.name = "ConnectionUrlError";
31
+ }
32
+ }
33
+
34
+ export interface ConnectionUrlParts {
35
+ /** Lower-cased scheme, e.g. `postgres`, `mongodb+srv`. */
36
+ scheme: string;
37
+ /** Raw (still-encoded) userinfo, or null when the URL has no `@`. */
38
+ userinfo: string | null;
39
+ /** Raw (still-encoded) user, or null. */
40
+ rawUsername: string | null;
41
+ /** Raw (still-encoded) password, or null when no `:` was written. */
42
+ rawPassword: string | null;
43
+ /** Decoded user, or null. */
44
+ username: string | null;
45
+ /** Decoded password, or null when no `:` was written ("" when written blank). */
46
+ password: string | null;
47
+ /** The raw `host[:port]` (or host list) after userinfo - credential-free. */
48
+ hostPort: string;
49
+ /** First host, brackets removed for IPv6, or "" when there is none. */
50
+ host: string;
51
+ /** First host's port, or null when none was written. */
52
+ port: number | null;
53
+ /** Path, query and fragment as written: "" or starting with `/`, `?` or `#`. */
54
+ tail: string;
55
+ }
56
+
57
+ export interface SplitOptions {
58
+ /** Prefix for the error message, e.g. "DatabaseUrl". */
59
+ label: string;
60
+ /** What the message says was expected, e.g. "scheme://[user[:password]@]host[:port]/database". */
61
+ expected?: string;
62
+ /** Accept `h1:1,h2:2` (MongoDB). */
63
+ allowHostList?: boolean;
64
+ }
65
+
66
+ /** Percent-decode, leaving an invalid escape as written instead of throwing. */
67
+ export function decodeComponent(value: string): string {
68
+ try {
69
+ return decodeURIComponent(value);
70
+ } catch {
71
+ return value.replace(/(?:%[0-9A-Fa-f]{2})+/g, (seq) => {
72
+ try { return decodeURIComponent(seq); } catch { return seq; }
73
+ });
74
+ }
75
+ }
76
+
77
+ const count = (text: string, ch: string): number => text.split(ch).length - 1;
78
+
79
+ /** `host[:port]` -> [host, port]; null when the shape is wrong. */
80
+ function splitHostPort(hostPort: string): [string, string | null] | null {
81
+ if (hostPort.startsWith("[")) {
82
+ const close = hostPort.indexOf("]");
83
+ if (close === -1) return null;
84
+ const after = hostPort.slice(close + 1);
85
+ if (after !== "" && !after.startsWith(":")) return null;
86
+ return [hostPort.slice(1, close), after === "" ? null : after.slice(1)];
87
+ }
88
+ const colon = hostPort.indexOf(":");
89
+ if (colon === -1) return [hostPort, null];
90
+ return [hostPort.slice(0, colon), hostPort.slice(colon + 1)];
91
+ }
92
+
93
+ /**
94
+ * Split `scheme://[user[:password]@]host[:port][/path][?query][#fragment]`
95
+ * under THE RULE (see the header), refusing what it cannot split safely.
96
+ *
97
+ * Accepts an unencoded `/`, `?`, `#`, `@`, `:` or `%` in a password, which is
98
+ * what people actually paste into a .env file. Refuses, with a message that
99
+ * never echoes the value:
100
+ * - no `scheme://` (including `scheme:/` and `scheme//`)
101
+ * - an `@` outside userinfo (`?email=a@b` - encode it as `%40`)
102
+ * - userinfo with no host after it, a non-numeric port, a bad IPv6 bracket,
103
+ * or whitespace in the host
104
+ */
105
+ export function splitConnectionUrl(raw: string, options: SplitOptions): ConnectionUrlParts {
106
+ const refuse = refuser(raw, options);
107
+ const { scheme, rest } = schemeAndRest(raw, refuse);
108
+ const { userinfo, afterUserinfo } = splitUserinfo(rest, refuse);
109
+ const { hostPort, tail } = hostPortAndTail(afterUserinfo, userinfo !== null, refuse);
110
+ // Only text after the last `@` may be named: with no `@`, "host:port" can be
111
+ // `user:password` (`postgres://u:secret`).
112
+ const { host, port } = firstHost(hostPort, options.allowHostList === true, refuse, userinfo !== null ? hostPort : undefined);
113
+ refuseDigitLedPassword(userinfo, port, tail, refuse);
114
+ const { rawUsername, rawPassword } = userinfoParts(userinfo);
115
+ return {
116
+ scheme,
117
+ userinfo,
118
+ rawUsername,
119
+ rawPassword,
120
+ username: decodeOrNull(rawUsername),
121
+ password: decodeOrNull(rawPassword),
122
+ hostPort,
123
+ host,
124
+ port,
125
+ tail,
126
+ };
127
+ }
128
+
129
+ /** Builds the one refusal message: label, scheme, why - never the value. */
130
+ type Refuse = (why: string, hostPort?: string) => ConnectionUrlError;
131
+
132
+ const SCHEME_PREFIX = /^([A-Za-z][A-Za-z0-9+.-]*):/;
133
+
134
+ function refuser(raw: unknown, options: SplitOptions): Refuse {
135
+ const expected = options.expected ?? "scheme://[user[:password]@]host[:port]/path";
136
+ const named = SCHEME_PREFIX.exec(String(raw ?? ""))?.[1]?.toLowerCase();
137
+ const subject = `${options.label}: invalid ${named ? `${named} ` : ""}URL`;
138
+ return (why, hostPort) =>
139
+ new ConnectionUrlError(
140
+ `${subject}${hostPort ? ` at '${hostPort}'` : ""} (${why}) - expected ` +
141
+ `${expected}. The URL itself is not shown because it may contain a password.`,
142
+ );
143
+ }
144
+
145
+ /** `scheme` and everything after `scheme://`; `scheme:/` and `scheme//` are refused. */
146
+ function schemeAndRest(raw: unknown, refuse: Refuse): { scheme: string; rest: string } {
147
+ if (typeof raw !== "string") throw refuse("not a string");
148
+ const head = /^([A-Za-z][A-Za-z0-9+.-]*):\/\//.exec(raw);
149
+ if (!head) throw refuse(SCHEME_PREFIX.test(raw) ? "the scheme must be followed by ://" : "no scheme:// found");
150
+ return { scheme: head[1].toLowerCase(), rest: raw.slice(head[0].length) };
151
+ }
152
+
153
+ const AT_OUTSIDE_USERINFO = "an @ outside the user:password part - percent-encode it as %40";
154
+
155
+ /**
156
+ * Userinfo by the last-`@` rule. The RFC reading cuts the authority at the
157
+ * first / ? #. Where every `@` is inside that, it agrees with the last-`@`
158
+ * rule. Where none is, the cut fell INSIDE a password holding / ? or #.
159
+ * Anything in between means an `@` sits in the path or query, and which `@`
160
+ * ends userinfo is a guess - refuse.
161
+ */
162
+ function splitUserinfo(rest: string, refuse: Refuse): { userinfo: string | null; afterUserinfo: string } {
163
+ const totalAt = count(rest, "@");
164
+ if (totalAt === 0) return { userinfo: null, afterUserinfo: rest };
165
+ const rfcEnd = rest.search(/[/?#]/);
166
+ const rfcAt = count(rfcEnd === -1 ? rest : rest.slice(0, rfcEnd), "@");
167
+ const lastAt = rest.lastIndexOf("@");
168
+ const candidate = rest.slice(0, lastAt);
169
+ const agrees = rfcAt === totalAt || (rfcAt === 0 && hasCleanUser(candidate));
170
+ if (!agrees) throw refuse(AT_OUTSIDE_USERINFO);
171
+ return { userinfo: candidate, afterUserinfo: rest.slice(lastAt + 1) };
172
+ }
173
+
174
+ /** A `:` exists, with no `/`, `?` or `#` in the user before it. */
175
+ function hasCleanUser(userinfo: string): boolean {
176
+ const colon = userinfo.indexOf(":");
177
+ return colon !== -1 && !/[/?#]/.test(userinfo.slice(0, colon));
178
+ }
179
+
180
+ /** The raw `host[:port]` up to the first / ? #, and the path+query+fragment after it. */
181
+ function hostPortAndTail(afterUserinfo: string, hasUserinfo: boolean, refuse: Refuse): { hostPort: string; tail: string } {
182
+ const hostEnd = afterUserinfo.search(/[/?#]/);
183
+ const hostPort = hostEnd === -1 ? afterUserinfo : afterUserinfo.slice(0, hostEnd);
184
+ if (/\s/.test(hostPort)) throw refuse("whitespace in the host");
185
+ if (hasUserinfo && hostPort === "") throw refuse("no host after the credentials");
186
+ return { hostPort, tail: afterUserinfo.slice(hostPort.length) };
187
+ }
188
+
189
+ /** The first host and its port; every host in a list must be well formed. */
190
+ function firstHost(
191
+ hostPort: string,
192
+ allowHostList: boolean,
193
+ refuse: Refuse,
194
+ nameable: string | undefined,
195
+ ): { host: string; port: number | null } {
196
+ const hosts = allowHostList ? hostPort.split(",") : [hostPort];
197
+ return hosts.map((piece) => oneHost(piece, refuse, nameable))[0];
198
+ }
199
+
200
+ function oneHost(piece: string, refuse: Refuse, nameable: string | undefined): { host: string; port: number | null } {
201
+ const split = splitHostPort(piece);
202
+ if (split === null) throw refuse("a malformed IPv6 host", nameable);
203
+ const [host, port] = split;
204
+ if (port === null || port === "") return { host, port: null };
205
+ if (!/^\d+$/.test(port)) throw refuse("the port must be numeric", nameable);
206
+ return { host, port: parseInt(port, 10) };
207
+ }
208
+
209
+ /**
210
+ * No `@`, a numeric port, then a fragment or a non-`key=value` query: that is
211
+ * a digit-led password (`u:12?Pq1Rs2`), not host `u` port 12 - a whole-value
212
+ * parser (`new URL` included) would put the password in the query.
213
+ */
214
+ function refuseDigitLedPassword(userinfo: string | null, port: number | null, tail: string, refuse: Refuse): void {
215
+ if (userinfo !== null || port === null) return;
216
+ if (digitLedPassword(tail)) throw refuse("a port followed by a fragment or a query that is not key=value");
217
+ }
218
+
219
+ /** Raw `user` and `password` (null when no `:` was written) from userinfo. */
220
+ function userinfoParts(userinfo: string | null): { rawUsername: string | null; rawPassword: string | null } {
221
+ if (userinfo === null) return { rawUsername: null, rawPassword: null };
222
+ const colon = userinfo.indexOf(":");
223
+ if (colon === -1) return { rawUsername: userinfo, rawPassword: null };
224
+ return { rawUsername: userinfo.slice(0, colon), rawPassword: userinfo.slice(colon + 1) };
225
+ }
226
+
227
+ const decodeOrNull = (value: string | null): string | null => (value === null ? null : decodeComponent(value));
228
+
229
+ /**
230
+ * The same URL with its credentials percent-encoded - what a driver that runs
231
+ * its own URL parser (mongodb, redis) is handed, so it can never re-split a
232
+ * password holding `/`, `?`, `#` or `@` and quote the pieces in its errors.
233
+ */
234
+ export function canonicalConnectionUrl(parts: ConnectionUrlParts): string {
235
+ let auth = "";
236
+ if (parts.userinfo !== null) {
237
+ auth = encodeURIComponent(parts.username ?? "");
238
+ if (parts.password !== null) auth += `:${encodeURIComponent(parts.password)}`;
239
+ auth += "@";
240
+ }
241
+ return `${parts.scheme}://${auth}${parts.hostPort}${parts.tail}`;
242
+ }
@@ -39,6 +39,7 @@ import net from "node:net";
39
39
  // (which also floored at "0.0.0" once @tina4/core was relocated out of the
40
40
  // monorepo layout).
41
41
  import { TINA4_VERSION } from "./version.js";
42
+ import { redactCredentials } from "./urlRedaction.js";
42
43
 
43
44
  const cpuCount = osCpus().length;
44
45
 
@@ -2031,10 +2032,24 @@ function parseEnvFile(): Record<string, string> {
2031
2032
  return result;
2032
2033
  }
2033
2034
 
2035
+ /**
2036
+ * GET /connections serves the saved URL REDACTED. A client that posts that
2037
+ * form straight back (to test or save) means "the saved one" - writing it
2038
+ * would replace the real password in .env with ***.
2039
+ */
2040
+ function savedUrlIfRedacted(posted: string): string {
2041
+ const current = parseEnvFile().TINA4_DATABASE_URL ?? "";
2042
+ if (posted === "" || current === "" || posted === current) return posted;
2043
+ return posted === redactCredentials(current) ? current : posted;
2044
+ }
2045
+
2034
2046
  const handleConnections: RouteHandler = (_req, res) => {
2035
2047
  const env = parseEnvFile();
2036
2048
  res.json({
2037
- url: env.TINA4_DATABASE_URL ?? "",
2049
+ // Redacted like the password field below: this used to hand the raw .env
2050
+ // URL - password and all - to any page that could reach the dev API
2051
+ // (GHSA-h2mr-m3v3-cq8c). Save recognises this form and keeps the real URL.
2052
+ url: redactCredentials(env.TINA4_DATABASE_URL ?? ""),
2038
2053
  username: env.TINA4_DATABASE_USERNAME ?? "",
2039
2054
  password: env.TINA4_DATABASE_PASSWORD ? "***" : "",
2040
2055
  });
@@ -2042,7 +2057,7 @@ const handleConnections: RouteHandler = (_req, res) => {
2042
2057
 
2043
2058
  const handleConnectionsTest: RouteHandler = async (req, res) => {
2044
2059
  const body = req.body as Record<string, string> | undefined;
2045
- const url = body?.url ?? "";
2060
+ const url = savedUrlIfRedacted(body?.url ?? "");
2046
2061
  const username = body?.username ?? "";
2047
2062
  const password = body?.password ?? "";
2048
2063
  if (!url) {
@@ -2099,7 +2114,7 @@ const handleConnectionsTest: RouteHandler = async (req, res) => {
2099
2114
 
2100
2115
  const handleConnectionsSave: RouteHandler = (req, res) => {
2101
2116
  const body = req.body as Record<string, string> | undefined;
2102
- const url = body?.url ?? "";
2117
+ const url = savedUrlIfRedacted(body?.url ?? "");
2103
2118
  const username = body?.username ?? "";
2104
2119
  const password = body?.password ?? "";
2105
2120
  if (!url) {
@@ -26,8 +26,42 @@ file, You can obtain one at https://mozilla.org/MPL/2.0/.
26
26
 
27
27
  import { randomInt, randomUUID } from "node:crypto";
28
28
  import { existsSync, readdirSync } from "node:fs";
29
- import { resolve, join } from "node:path";
29
+ import { resolve, join, basename } from "node:path";
30
30
  import { pathToFileURL } from "node:url";
31
+ import { Log } from "./logger.js";
32
+
33
+ /**
34
+ * A seed file threw, so the seed run stopped at it (ADR-0108). `seedFile` is
35
+ * the failing file, `completed` the files that ran before it, and `cause` the
36
+ * original error.
37
+ */
38
+ /** The message of anything thrown, Error or not. */
39
+ function errorText(error: unknown): string {
40
+ return error instanceof Error ? error.message : String(error);
41
+ }
42
+
43
+ /** A .ts/.js seed file that is not a `_`-prefixed helper. */
44
+ function isSeedFile(name: string): boolean {
45
+ return (name.endsWith(".ts") || name.endsWith(".js")) && !name.startsWith("_");
46
+ }
47
+
48
+ /** What a seed module runs: its default export, or else the named run() that `generate seeder` writes. */
49
+ function seedEntry(mod: Record<string, unknown>): (() => unknown) | undefined {
50
+ const entry = typeof mod.default === "function" ? mod.default : mod.run;
51
+ return typeof entry === "function" ? (entry as () => unknown) : undefined;
52
+ }
53
+
54
+ export class SeedError extends Error {
55
+ readonly seedFile: string;
56
+ readonly completed: string[];
57
+
58
+ constructor(seedFile: string, completed: string[], cause: unknown) {
59
+ super(`Seed file failed: ${basename(seedFile)}: ${errorText(cause)}`, { cause });
60
+ this.name = "SeedError";
61
+ this.seedFile = seedFile;
62
+ this.completed = [...completed];
63
+ }
64
+ }
31
65
 
32
66
  // ── Word Banks ───────────────────────────────────────────────────
33
67
 
@@ -340,15 +374,17 @@ export class FakeData {
340
374
  }
341
375
 
342
376
  /**
343
- * Run seed files from a directory. Each file should export a default async function.
344
- * Returns an array of executed file paths.
377
+ * Run the seed files in a directory in name order, skipping files whose name
378
+ * starts with "_". A file's default export, or else the named run() that
379
+ * `generate seeder` writes, is awaited when it is a function.
380
+ * Returns the executed file paths in order ([] when the directory is missing).
381
+ * A seed file that throws stops the run: it is logged and a SeedError naming
382
+ * it is thrown, and no later file runs (ADR-0108).
345
383
  */
346
384
  async seedDir(seedDir?: string): Promise<string[]> {
347
385
  const dir = resolve(seedDir ?? "src/seeds");
348
386
  if (!existsSync(dir)) return [];
349
- const files = readdirSync(dir)
350
- .filter((f) => f.endsWith(".ts") || f.endsWith(".js"))
351
- .sort();
387
+ const files = readdirSync(dir).filter(isSeedFile).sort();
352
388
  const executed: string[] = [];
353
389
  for (const file of files) {
354
390
  const fullPath = join(dir, file);
@@ -356,13 +392,12 @@ export class FakeData {
356
392
  // A raw path is not an import specifier: D:\... reads as a URL scheme,
357
393
  // and a # anywhere in the path starts a URL fragment.
358
394
  const mod = await import(pathToFileURL(fullPath).href);
359
- if (typeof mod.default === "function") {
360
- await mod.default();
361
- }
362
- executed.push(fullPath);
363
- } catch {
364
- // skip failed seed files
395
+ await seedEntry(mod)?.();
396
+ } catch (error) {
397
+ Log.error(`Seeder: ${file} failed, seeding stopped: ${errorText(error)}`);
398
+ throw new SeedError(fullPath, executed, error);
365
399
  }
400
+ executed.push(fullPath);
366
401
  }
367
402
  return executed;
368
403
  }
@@ -84,7 +84,7 @@ export {
84
84
  export { Session, FileSessionHandler, RedisSessionHandler, buildSessionCookie, isSecureScheme, isValidSessionId, sessionCookieName, VALID_SESSION_BACKENDS, CANONICAL_SESSION_BACKENDS } from "./session.js";
85
85
  export type { SessionConfig, SessionHandler } from "./session.js";
86
86
  export { I18n } from "./i18n.js";
87
- export { FakeData } from "./fakeData.js";
87
+ export { FakeData, SeedError } from "./fakeData.js";
88
88
  export { Queue } from "./queue.js";
89
89
  export type { QueueConfig, QueueJob, ProcessOptions } from "./queue.js";
90
90
  export { createJob } from "./job.js";
@@ -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
 
@@ -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