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.
- package/CLAUDE.md +12 -5
- package/package.json +1 -1
- package/packages/cli/dist/bin.js +1312 -979
- package/packages/cli/src/bin.ts +5 -2
- package/packages/cli/src/commands/lint.ts +3 -1
- package/packages/cli/src/commands/seed.ts +10 -11
- package/packages/core/dist/index.js +1232 -897
- package/packages/core/src/batchSpawn.ts +129 -0
- package/packages/core/src/connectionUrl.ts +242 -0
- package/packages/core/src/devAdmin.ts +25 -11
- package/packages/core/src/fakeData.ts +51 -13
- package/packages/core/src/index.ts +1 -1
- package/packages/core/src/mcp.ts +4 -1
- package/packages/core/src/mqtt.ts +24 -48
- package/packages/core/src/portTakeover.ts +31 -13
- package/packages/core/src/projectIndex.ts +3 -4
- package/packages/core/src/projectIndexStorage.ts +9 -1
- package/packages/core/src/queueBackends/rabbitmqBackend.ts +32 -20
- package/packages/core/src/response.ts +4 -1
- package/packages/core/src/routeDiscovery.ts +8 -2
- package/packages/core/src/router.ts +44 -30
- package/packages/core/src/server.ts +53 -33
- package/packages/core/src/session.ts +5 -0
- package/packages/core/src/sessionHandlers/databaseHandler.ts +16 -0
- package/packages/core/src/urlRedaction.ts +252 -0
- package/packages/core/src/websocketBackplane.ts +15 -3
- package/packages/orm/dist/index.js +1259 -925
- package/packages/orm/src/database.ts +7 -1
- package/packages/orm/src/databaseUrl.ts +73 -190
- package/packages/orm/src/docstore.ts +8 -1
- package/packages/orm/src/graph/graphUrl.ts +43 -7
- package/packages/orm/src/model.ts +2 -1
- package/types/core/src/batchSpawn.d.ts +28 -0
- package/types/core/src/connectionUrl.d.ts +61 -0
- package/types/core/src/fakeData.d.ts +11 -2
- package/types/core/src/index.d.ts +1 -1
- package/types/core/src/portTakeover.d.ts +15 -0
- package/types/core/src/projectIndexStorage.d.ts +5 -0
- package/types/core/src/queueBackends/rabbitmqBackend.d.ts +0 -7
- package/types/core/src/router.d.ts +17 -2
- package/types/core/src/server.d.ts +13 -0
- package/types/core/src/session.d.ts +5 -0
- package/types/core/src/sessionHandlers/databaseHandler.d.ts +8 -0
- package/types/core/src/urlRedaction.d.ts +61 -0
- package/types/orm/src/databaseUrl.d.ts +18 -19
- package/types/orm/src/graph/graphUrl.d.ts +18 -0
|
@@ -0,0 +1,129 @@
|
|
|
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
|
+
* Run a program that may be a Windows batch file (`.cmd` / `.bat`).
|
|
11
|
+
*
|
|
12
|
+
* Since the 2024 BatBadBut fix (CVE-2024-27980) Node refuses to spawn a batch
|
|
13
|
+
* file without a shell: `spawnSync("C:\\...\\npm.cmd", args)` fails with EINVAL.
|
|
14
|
+
* The other three Tina4 frameworks start batch files directly, so `npm.cmd`
|
|
15
|
+
* and a `tina4.cmd` client have to work here too.
|
|
16
|
+
*
|
|
17
|
+
* Handing the arguments to `shell: true` is not the fix: Node joins them with
|
|
18
|
+
* spaces and no escaping, so an argument such as `a&calc` would run `calc`.
|
|
19
|
+
* Instead the command line is built here the way cross-spawn builds it
|
|
20
|
+
* (https://qntm.org/cmd): each argument is quoted, embedded quotes and the
|
|
21
|
+
* backslashes before them are escaped, and every cmd.exe metacharacter is
|
|
22
|
+
* caret-escaped TWICE - once for the `cmd /c` line, once more because a batch
|
|
23
|
+
* file re-parses the `%*` it forwards. The line goes to cmd.exe verbatim
|
|
24
|
+
* (`windowsVerbatimArguments`) so libuv adds no quoting of its own.
|
|
25
|
+
*
|
|
26
|
+
* Anything that is not a batch file, and every non-Windows platform, is spawned
|
|
27
|
+
* exactly as before.
|
|
28
|
+
*/
|
|
29
|
+
import { spawnSync } from "node:child_process";
|
|
30
|
+
import type { SpawnSyncOptions, SpawnSyncReturns } from "node:child_process";
|
|
31
|
+
import { existsSync, statSync } from "node:fs";
|
|
32
|
+
import { delimiter, extname, join } from "node:path";
|
|
33
|
+
|
|
34
|
+
/** cmd.exe metacharacters, the same set cross-spawn escapes. */
|
|
35
|
+
const CMD_META = /([()\][%!^"`<>&|;, *?])/g;
|
|
36
|
+
|
|
37
|
+
/** True when `file` is a batch file that Node will not spawn without a shell. */
|
|
38
|
+
export function isBatchFile(file: string, platform: NodeJS.Platform = process.platform): boolean {
|
|
39
|
+
return platform === "win32" && /\.(cmd|bat)$/i.test(file);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** One argument, quoted and escaped for a batch file run through `cmd /d /s /c`. */
|
|
43
|
+
export function escapeBatchArgument(arg: string): string {
|
|
44
|
+
let quoted = String(arg)
|
|
45
|
+
// backslashes before a quote double, and the quote is backslash-escaped
|
|
46
|
+
.replace(/(\\*)"/g, '$1$1\\"')
|
|
47
|
+
// backslashes before the closing quote we are about to add double too
|
|
48
|
+
.replace(/(\\*)$/, "$1$1");
|
|
49
|
+
quoted = `"${quoted}"`;
|
|
50
|
+
return quoted.replace(CMD_META, "^$1").replace(CMD_META, "^$1");
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** The batch file's own path, escaped for the head of the `cmd /c` line. */
|
|
54
|
+
function escapeBatchCommand(file: string): string {
|
|
55
|
+
return file.replace(CMD_META, "^$1");
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Resolve a bare program name such as `npm` to the file Windows would run.
|
|
60
|
+
*
|
|
61
|
+
* Without a shell, Windows' CreateProcess only adds `.exe`, so `npm` (which is
|
|
62
|
+
* `npm.cmd`) is never found and the spawn fails with ENOENT. This walks PATH
|
|
63
|
+
* with PATHEXT the way cmd.exe does. A name that already has a directory or an
|
|
64
|
+
* extension, every other platform, and a name that is not found are returned
|
|
65
|
+
* unchanged, so the spawn reports its own error exactly as before.
|
|
66
|
+
*/
|
|
67
|
+
export function findExecutable(name: string, platform: NodeJS.Platform = process.platform): string {
|
|
68
|
+
if (platform !== "win32" || /[\\/]/.test(name) || extname(name) !== "") return name;
|
|
69
|
+
const exts = (process.env.PATHEXT || ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean);
|
|
70
|
+
const dirs = (process.env.PATH || "").split(delimiter).filter(Boolean);
|
|
71
|
+
// PATH order first, then PATHEXT order within each directory, as cmd.exe does.
|
|
72
|
+
const candidates = dirs.flatMap((dir) => exts.map((ext) => join(dir, name + ext.toLowerCase())));
|
|
73
|
+
return candidates.find(isRegularFile) ?? name;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** True when `path` exists and is a file (a directory named `npm.cmd` is not). */
|
|
77
|
+
function isRegularFile(path: string): boolean {
|
|
78
|
+
try {
|
|
79
|
+
return existsSync(path) && statSync(path).isFile();
|
|
80
|
+
} catch {
|
|
81
|
+
return false;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* `spawnSync`, except that a batch file on Windows runs through cmd.exe with
|
|
87
|
+
* every argument escaped. Returns what spawnSync returns either way.
|
|
88
|
+
*/
|
|
89
|
+
export function spawnSyncAllowingBatch(
|
|
90
|
+
file: string,
|
|
91
|
+
args: readonly string[],
|
|
92
|
+
options: SpawnSyncOptions = {},
|
|
93
|
+
): SpawnSyncReturns<Buffer | string> {
|
|
94
|
+
if (!isBatchFile(file)) return spawnSync(file, args, options);
|
|
95
|
+
const line = [escapeBatchCommand(file), ...args.map(escapeBatchArgument)].join(" ");
|
|
96
|
+
const shell = process.env.comspec || "cmd.exe";
|
|
97
|
+
return spawnSync(shell, ["/d", "/s", "/c", `"${line}"`], {
|
|
98
|
+
...options,
|
|
99
|
+
windowsVerbatimArguments: true,
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* `execFileSync` for a bare program name (`npm`, `npx`) that may be a batch
|
|
105
|
+
* file: resolves it with {@link findExecutable}, runs it with
|
|
106
|
+
* {@link spawnSyncAllowingBatch}, and like execFileSync returns stdout and
|
|
107
|
+
* throws on a spawn error or a non-zero exit (the error carries `status`,
|
|
108
|
+
* `stdout` and `stderr`).
|
|
109
|
+
*/
|
|
110
|
+
export function execFileSyncAllowingBatch(
|
|
111
|
+
name: string,
|
|
112
|
+
args: readonly string[],
|
|
113
|
+
options: SpawnSyncOptions = {},
|
|
114
|
+
): string {
|
|
115
|
+
const result = spawnSyncAllowingBatch(findExecutable(name), args, { encoding: "utf-8", ...options });
|
|
116
|
+
if (result.error) throw result.error;
|
|
117
|
+
const stdout = String(result.stdout ?? "");
|
|
118
|
+
const stderr = String(result.stderr ?? "");
|
|
119
|
+
if (result.status !== 0) {
|
|
120
|
+
const err = new Error(
|
|
121
|
+
`Command failed: ${name} ${args.join(" ")} (exit ${result.status ?? result.signal})\n${stderr}`.trim(),
|
|
122
|
+
) as Error & { status: number | null; stdout: string; stderr: string };
|
|
123
|
+
err.status = result.status;
|
|
124
|
+
err.stdout = stdout;
|
|
125
|
+
err.stderr = stderr;
|
|
126
|
+
throw err;
|
|
127
|
+
}
|
|
128
|
+
return stdout;
|
|
129
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -21,6 +21,7 @@ import { cpus as osCpus } from "node:os";
|
|
|
21
21
|
import { rtrimSlashes } from "./slashTrim.js";
|
|
22
22
|
import { readFileSync, writeFileSync, existsSync, readdirSync, mkdirSync, copyFileSync, statSync, openSync, closeSync, fstatSync, fchmodSync, ftruncateSync, constants, realpathSync, lstatSync } from "node:fs";
|
|
23
23
|
import { join, dirname, resolve, relative, sep, basename } from "node:path";
|
|
24
|
+
import { execFileSyncAllowingBatch } from "./batchSpawn.js";
|
|
24
25
|
import { fileURLToPath } from "node:url";
|
|
25
26
|
import type { Router } from "./router.js";
|
|
26
27
|
import type { RouteHandler, Tina4Request } from "./types.js";
|
|
@@ -38,6 +39,7 @@ import net from "node:net";
|
|
|
38
39
|
// (which also floored at "0.0.0" once @tina4/core was relocated out of the
|
|
39
40
|
// monorepo layout).
|
|
40
41
|
import { TINA4_VERSION } from "./version.js";
|
|
42
|
+
import { redactCredentials } from "./urlRedaction.js";
|
|
41
43
|
|
|
42
44
|
const cpuCount = osCpus().length;
|
|
43
45
|
|
|
@@ -2030,10 +2032,24 @@ function parseEnvFile(): Record<string, string> {
|
|
|
2030
2032
|
return result;
|
|
2031
2033
|
}
|
|
2032
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
|
+
|
|
2033
2046
|
const handleConnections: RouteHandler = (_req, res) => {
|
|
2034
2047
|
const env = parseEnvFile();
|
|
2035
2048
|
res.json({
|
|
2036
|
-
|
|
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 ?? ""),
|
|
2037
2053
|
username: env.TINA4_DATABASE_USERNAME ?? "",
|
|
2038
2054
|
password: env.TINA4_DATABASE_PASSWORD ? "***" : "",
|
|
2039
2055
|
});
|
|
@@ -2041,7 +2057,7 @@ const handleConnections: RouteHandler = (_req, res) => {
|
|
|
2041
2057
|
|
|
2042
2058
|
const handleConnectionsTest: RouteHandler = async (req, res) => {
|
|
2043
2059
|
const body = req.body as Record<string, string> | undefined;
|
|
2044
|
-
const url = body?.url ?? "";
|
|
2060
|
+
const url = savedUrlIfRedacted(body?.url ?? "");
|
|
2045
2061
|
const username = body?.username ?? "";
|
|
2046
2062
|
const password = body?.password ?? "";
|
|
2047
2063
|
if (!url) {
|
|
@@ -2098,7 +2114,7 @@ const handleConnectionsTest: RouteHandler = async (req, res) => {
|
|
|
2098
2114
|
|
|
2099
2115
|
const handleConnectionsSave: RouteHandler = (req, res) => {
|
|
2100
2116
|
const body = req.body as Record<string, string> | undefined;
|
|
2101
|
-
const url = body?.url ?? "";
|
|
2117
|
+
const url = savedUrlIfRedacted(body?.url ?? "");
|
|
2102
2118
|
const username = body?.username ?? "";
|
|
2103
2119
|
const password = body?.password ?? "";
|
|
2104
2120
|
if (!url) {
|
|
@@ -2752,13 +2768,12 @@ const handleDepsInstall: RouteHandler = async (req, res) => {
|
|
|
2752
2768
|
return;
|
|
2753
2769
|
}
|
|
2754
2770
|
try {
|
|
2755
|
-
const { execFileSync } = await import("node:child_process");
|
|
2756
2771
|
const args = ["install", dev ? "--save-dev" : "--save", pkg];
|
|
2757
|
-
|
|
2772
|
+
// npm is npm.cmd on Windows, which execFileSync cannot find or start.
|
|
2773
|
+
const output = execFileSyncAllowingBatch("npm", args, {
|
|
2758
2774
|
cwd: resolve(process.cwd()),
|
|
2759
2775
|
timeout: 120_000,
|
|
2760
|
-
|
|
2761
|
-
}).toString();
|
|
2776
|
+
});
|
|
2762
2777
|
res.json({ ok: true, package: pkg, output });
|
|
2763
2778
|
} catch (e) {
|
|
2764
2779
|
res.json({ error: (e as Error).message }, 500);
|
|
@@ -2994,12 +3009,11 @@ const handleScaffoldRun: RouteHandler = async (req, res) => {
|
|
|
2994
3009
|
return;
|
|
2995
3010
|
}
|
|
2996
3011
|
try {
|
|
2997
|
-
|
|
2998
|
-
const output =
|
|
3012
|
+
// npx is npx.cmd on Windows, which execFileSync cannot find or start.
|
|
3013
|
+
const output = execFileSyncAllowingBatch("npx", ["tina4nodejs", "generate", kind, name], {
|
|
2999
3014
|
cwd: resolve(process.cwd()),
|
|
3000
3015
|
timeout: 30_000,
|
|
3001
|
-
|
|
3002
|
-
}).toString();
|
|
3016
|
+
});
|
|
3003
3017
|
res.json({ ok: true, kind, name, output });
|
|
3004
3018
|
} catch (e) {
|
|
3005
3019
|
res.json({ error: (e as Error).message }, 500);
|
|
@@ -26,7 +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
|
+
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
|
+
}
|
|
30
65
|
|
|
31
66
|
// ── Word Banks ───────────────────────────────────────────────────
|
|
32
67
|
|
|
@@ -339,27 +374,30 @@ export class FakeData {
|
|
|
339
374
|
}
|
|
340
375
|
|
|
341
376
|
/**
|
|
342
|
-
* Run seed files
|
|
343
|
-
*
|
|
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).
|
|
344
383
|
*/
|
|
345
384
|
async seedDir(seedDir?: string): Promise<string[]> {
|
|
346
385
|
const dir = resolve(seedDir ?? "src/seeds");
|
|
347
386
|
if (!existsSync(dir)) return [];
|
|
348
|
-
const files = readdirSync(dir)
|
|
349
|
-
.filter((f) => f.endsWith(".ts") || f.endsWith(".js"))
|
|
350
|
-
.sort();
|
|
387
|
+
const files = readdirSync(dir).filter(isSeedFile).sort();
|
|
351
388
|
const executed: string[] = [];
|
|
352
389
|
for (const file of files) {
|
|
353
390
|
const fullPath = join(dir, file);
|
|
354
391
|
try {
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
392
|
+
// A raw path is not an import specifier: D:\... reads as a URL scheme,
|
|
393
|
+
// and a # anywhere in the path starts a URL fragment.
|
|
394
|
+
const mod = await import(pathToFileURL(fullPath).href);
|
|
395
|
+
await seedEntry(mod)?.();
|
|
396
|
+
} catch (error) {
|
|
397
|
+
Log.error(`Seeder: ${file} failed, seeding stopped: ${errorText(error)}`);
|
|
398
|
+
throw new SeedError(fullPath, executed, error);
|
|
362
399
|
}
|
|
400
|
+
executed.push(fullPath);
|
|
363
401
|
}
|
|
364
402
|
return executed;
|
|
365
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";
|
package/packages/core/src/mcp.ts
CHANGED
|
@@ -27,6 +27,7 @@ import { rtrimSlashes } from "./slashTrim.js";
|
|
|
27
27
|
import * as path from "node:path";
|
|
28
28
|
import * as os from "node:os";
|
|
29
29
|
import { spawnSync } from "node:child_process";
|
|
30
|
+
import { findExecutable, spawnSyncAllowingBatch } from "./batchSpawn.js";
|
|
30
31
|
import { createRequire } from "node:module";
|
|
31
32
|
import { randomBytes } from "node:crypto";
|
|
32
33
|
import { TINA4_VERSION } from "./version.js";
|
|
@@ -1109,7 +1110,9 @@ function verifyNodeSyntax(absPath: string, relPath: string): string | null {
|
|
|
1109
1110
|
if (!target) return null;
|
|
1110
1111
|
const { cmd, args } = syntaxCheckCommand(absPath, target.ext);
|
|
1111
1112
|
try {
|
|
1112
|
-
|
|
1113
|
+
// npx is npx.cmd on Windows: a plain spawnSync gets ENOENT, which reads as
|
|
1114
|
+
// "tsc not installed" below and skips the check without a word.
|
|
1115
|
+
const proc = spawnSyncAllowingBatch(findExecutable(cmd), args, {
|
|
1113
1116
|
encoding: "utf-8",
|
|
1114
1117
|
timeout: 5000,
|
|
1115
1118
|
cwd: path.dirname(path.dirname(absPath)),
|