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
@@ -181,6 +181,11 @@ export interface SessionHandler {
181
181
  destroy(sessionId: string): void;
182
182
  /** Garbage-collect expired sessions. Optional — Redis/Valkey/Mongo handle TTL natively. */
183
183
  gc?(maxLifetime: number): void;
184
+ /**
185
+ * Release a connection the handler opened itself. Optional; idempotent; the
186
+ * next read or write reopens it.
187
+ */
188
+ close?(): void;
184
189
  }
185
190
 
186
191
  // ── File Session Handler ──────────────────────────────────────────
@@ -244,6 +244,22 @@ export class DatabaseSessionHandler implements SessionHandler {
244
244
  return this.sqliteHandle;
245
245
  }
246
246
 
247
+ /**
248
+ * Release the SQLite connection this handler opened, so its file (and the
249
+ * WAL's -wal / -shm side files) is no longer held open: on Windows an open
250
+ * file cannot be deleted or replaced. Idempotent, and the next read or write
251
+ * reopens the connection. A server engine needs nothing here - each call goes
252
+ * through the sync bridge, which holds no connection between calls.
253
+ */
254
+ close(): void {
255
+ if (this.sqliteHandle === null) return;
256
+ try {
257
+ this.sqliteHandle.close();
258
+ } finally {
259
+ this.sqliteHandle = null;
260
+ }
261
+ }
262
+
247
263
  private get engine(): string {
248
264
  return this.target === null ? "sqlite" : this.target.engine;
249
265
  }
@@ -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");