pi-spine 2.14.0 → 2.15.0

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.
@@ -1,7 +1,18 @@
1
1
  /**
2
- * Cross-platform process liveness check (signal 0 / kill -0 equivalent).
2
+ * Cross-platform process liveness checks (signal 0 / kill -0 equivalent),
3
+ * plus engine liveness paired with process start time (SP-715 / #259).
3
4
  */
4
5
 
6
+ import { execFileSync } from "node:child_process";
7
+ import fs from "node:fs";
8
+
9
+ /**
10
+ * Default tolerance (ms) when comparing a probed process start time with the
11
+ * stored `engineStartedAt`. Absorbs `ps lstart` second-level granularity and
12
+ * the delay between engine process spawn and `recordBatchEnginePid`.
13
+ */
14
+ export const ENGINE_STARTTIME_TOLERANCE_MS = 60_000;
15
+
5
16
  /**
6
17
  * @param {unknown} pid
7
18
  * @returns {boolean}
@@ -19,3 +30,179 @@ export function isProcessAlive(pid) {
19
30
  return false;
20
31
  }
21
32
  }
33
+
34
+ /** @type {number|null} */
35
+ let cachedClockTicksPerSecond = null;
36
+
37
+ /**
38
+ * Clock ticks per second (sysconf _SC_CLK_TCK) for /proc starttime conversion.
39
+ *
40
+ * @returns {number}
41
+ */
42
+ function clockTicksPerSecond() {
43
+ if (cachedClockTicksPerSecond != null) return cachedClockTicksPerSecond;
44
+ let hz = 100;
45
+ try {
46
+ const out = execFileSync("getconf", ["CLK_TCK"], {
47
+ encoding: "utf-8",
48
+ stdio: ["ignore", "pipe", "ignore"],
49
+ }).trim();
50
+ const parsed = Number(out);
51
+ if (Number.isFinite(parsed) && parsed > 0) hz = parsed;
52
+ } catch {
53
+ /* getconf unavailable — Linux default USER_HZ is 100 */
54
+ }
55
+ cachedClockTicksPerSecond = hz;
56
+ return hz;
57
+ }
58
+
59
+ /**
60
+ * Linux: absolute process start time from `/proc/<pid>/starttime` (field 22 of
61
+ * stat, clock ticks since boot) combined with `btime` from /proc/stat.
62
+ * The comm field (2) may contain spaces/parens, so fields are parsed after the
63
+ * last ")".
64
+ *
65
+ * @param {number} pid
66
+ * @returns {number|null} epoch ms
67
+ */
68
+ function readLinuxProcessStartMs(pid) {
69
+ const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf-8");
70
+ const closeParen = stat.lastIndexOf(")");
71
+ if (closeParen < 0) return null;
72
+ const rest = stat.slice(closeParen + 1).trim().split(/\s+/);
73
+ // rest[0] is field 3 (state); starttime is field 22 → index 19.
74
+ const startTicks = Number(rest[19]);
75
+ if (!Number.isFinite(startTicks) || startTicks < 0) return null;
76
+ const procStat = fs.readFileSync("/proc/stat", "utf-8");
77
+ const btimeLine = procStat.split("\n").find((line) => line.startsWith("btime "));
78
+ if (!btimeLine) return null;
79
+ const bootSeconds = Number(btimeLine.slice("btime ".length).trim());
80
+ if (!Number.isFinite(bootSeconds) || bootSeconds <= 0) return null;
81
+ return (bootSeconds + startTicks / clockTicksPerSecond()) * 1000;
82
+ }
83
+
84
+ /** @type {Record<string, number>} */
85
+ const PS_MONTH_INDEX = {
86
+ Jan: 0,
87
+ Feb: 1,
88
+ Mar: 2,
89
+ Apr: 3,
90
+ May: 4,
91
+ Jun: 5,
92
+ Jul: 6,
93
+ Aug: 7,
94
+ Sep: 8,
95
+ Oct: 9,
96
+ Nov: 10,
97
+ Dec: 11,
98
+ };
99
+
100
+ /**
101
+ * Parse `ps -o lstart=` output ("Www Mmm dd hh:mm:ss yyyy") without relying on
102
+ * Date.parse, whose acceptance of this shape is implementation-defined.
103
+ *
104
+ * @param {string} text
105
+ * @returns {number|null} epoch ms (local time, matching ps output)
106
+ */
107
+ function parsePsLstartMs(text) {
108
+ const match = /^\w{3}\s+(\w{3})\s+(\d{1,2})\s+(\d{2}):(\d{2}):(\d{2})\s+(\d{4})$/.exec(
109
+ text.trim(),
110
+ );
111
+ if (!match) return null;
112
+ const month = PS_MONTH_INDEX[match[1]];
113
+ if (month == null) return null;
114
+ const ms = new Date(
115
+ Number(match[6]),
116
+ month,
117
+ Number(match[2]),
118
+ Number(match[3]),
119
+ Number(match[4]),
120
+ Number(match[5]),
121
+ ).getTime();
122
+ return Number.isFinite(ms) ? ms : null;
123
+ }
124
+
125
+ /**
126
+ * macOS / generic Unix fallback: process start time via `ps -p <pid> -o lstart=`.
127
+ *
128
+ * @param {number} pid
129
+ * @returns {number|null} epoch ms
130
+ */
131
+ function readPsProcessStartMs(pid) {
132
+ const out = execFileSync("ps", ["-p", String(pid), "-o", "lstart="], {
133
+ encoding: "utf-8",
134
+ env: { ...process.env, LC_ALL: "C" },
135
+ stdio: ["ignore", "pipe", "ignore"],
136
+ }).trim();
137
+ if (!out) return null;
138
+ return parsePsLstartMs(out);
139
+ }
140
+
141
+ /**
142
+ * Best-effort absolute process start time (epoch ms) for a live pid.
143
+ * Returns null when the platform or probe cannot provide one.
144
+ *
145
+ * @param {unknown} pid
146
+ * @returns {number|null}
147
+ */
148
+ export function probeProcessStartTimeMs(pid) {
149
+ const n = Number(pid);
150
+ if (!Number.isFinite(n) || n <= 0) return null;
151
+ // Windows limitation (SP-715 / #259): no start-time probe here; callers fall
152
+ // back to PID-only liveness, which can confuse a recycled PID for the engine.
153
+ if (process.platform === "win32") return null;
154
+ try {
155
+ if (process.platform === "linux") {
156
+ const fromProc = readLinuxProcessStartMs(n);
157
+ if (fromProc != null) return fromProc;
158
+ }
159
+ return readPsProcessStartMs(n);
160
+ } catch {
161
+ return null;
162
+ }
163
+ }
164
+
165
+ /**
166
+ * Engine liveness paired with the stored `engineStartedAt` so a recycled PID
167
+ * owned by an unrelated process is not mistaken for the batch engine
168
+ * (SP-715 / #259).
169
+ *
170
+ * Fallbacks (all preserve the previous PID-only behavior):
171
+ * - no `expectedStartedAt` recorded → PID-only
172
+ * - Windows → PID-only (documented limitation: PID reuse is not detected)
173
+ * - start-time probe unavailable → PID-only
174
+ *
175
+ * @param {unknown} pid
176
+ * @param {unknown} expectedStartedAt epoch ms recorded by recordBatchEnginePid
177
+ * @param {object} [options]
178
+ * @param {(pid: unknown) => boolean} [options.isAlive] injectable liveness probe
179
+ * @param {(pid: unknown) => number|null} [options.probeStartTimeMs] injectable start-time probe
180
+ * @param {string} [options.platform] injectable platform override
181
+ * @param {number} [options.toleranceMs] match tolerance (default ENGINE_STARTTIME_TOLERANCE_MS)
182
+ * @returns {boolean}
183
+ */
184
+ export function isEngineProcessAlive(pid, expectedStartedAt, options = {}) {
185
+ const isAlive = options.isAlive ?? isProcessAlive;
186
+ if (!isAlive(pid)) return false;
187
+
188
+ const expected = Number(expectedStartedAt);
189
+ if (!Number.isFinite(expected) || expected <= 0) return true;
190
+
191
+ const platform = options.platform ?? process.platform;
192
+ if (platform === "win32") return true;
193
+
194
+ const probe = options.probeStartTimeMs ?? probeProcessStartTimeMs;
195
+ /** @type {number|null} */
196
+ let startedMs = null;
197
+ try {
198
+ startedMs = probe(pid);
199
+ } catch {
200
+ startedMs = null;
201
+ }
202
+ if (startedMs == null || !Number.isFinite(startedMs) || startedMs <= 0) return true;
203
+
204
+ const tolerance = Number.isFinite(Number(options.toleranceMs))
205
+ ? Number(options.toleranceMs)
206
+ : ENGINE_STARTTIME_TOLERANCE_MS;
207
+ return Math.abs(startedMs - expected) <= tolerance;
208
+ }
@@ -0,0 +1,140 @@
1
+ /**
2
+ * Unified secret redaction policy shared across journal, worker-output,
3
+ * handoff, and metrics channels (SP-716, closes #260).
4
+ *
5
+ * Two complementary mechanisms:
6
+ * 1. Key denylist — object keys matching REDACT_KEY_PATTERN have their
7
+ * values replaced wholesale (see redactSecretsDeep).
8
+ * 2. Value patterns — well-known secret shapes (sk-, ghp_, bearer headers,
9
+ * connection strings, ENV-style assignments) are masked inside free
10
+ * text (see redactTextSecrets).
11
+ */
12
+
13
+ export const REDACTED = "[REDACTED]";
14
+
15
+ /**
16
+ * Keys whose values are always redacted, matched case-insensitively.
17
+ * Must stay non-global: it is used with RegExp.prototype.test, which is
18
+ * stateful for global regexes.
19
+ */
20
+ export const REDACT_KEY_PATTERN = /key|token|secret|password/i;
21
+
22
+ /**
23
+ * Value-shaped secret patterns, ordered most-specific first so that
24
+ * assignment-shaped matches (e.g. OPENAI_API_KEY=sk-...) are consumed whole
25
+ * before the generic key:value fallback can leave partial fragments behind.
26
+ *
27
+ * Safety: these regexes carry the global flag and are only safe to use with
28
+ * String.prototype.replace, which resets lastIndex before iterating. Do not
29
+ * use them with .test() or .exec().
30
+ */
31
+ export const SECRET_VALUE_PATTERNS = Object.freeze([
32
+ // ENV-style assignments: OPENAI_API_KEY=..., GITHUB_TOKEN = ...
33
+ /\b[A-Z][A-Z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD)[A-Z0-9_]*\s*=\s*\S+/g,
34
+ // Bearer authorization headers.
35
+ /\bBearer\s+[A-Za-z0-9._~+/=-]{8,}/g,
36
+ // Database connection strings embed credentials.
37
+ /(?:postgres|mysql|mongodb)(?:\+srv)?:\/\/[^\s]+/gi,
38
+ /\bDATABASE_URL=\S+/gi,
39
+ // Well-known token shapes.
40
+ /\bsk-[A-Za-z0-9_-]{8,}/g,
41
+ /\bghp_[A-Za-z0-9]{8,}/g,
42
+ /\bgithub_pat_[A-Za-z0-9_]{20,}/g,
43
+ /\bAKIA[0-9A-Z]{16}/g,
44
+ /\bxox[baprs]-[A-Za-z0-9-]{10,}/g,
45
+ // Generic key:value / key=value fallback.
46
+ /\b(?:bearer|token|secret|password|api[_-]?key)\s*[:=]\s*\S+/gi,
47
+ ]);
48
+
49
+ /**
50
+ * Mask value-shaped secrets in free text. Extra caller-supplied patterns
51
+ * (e.g. workerOutputDenyPatterns from config) run after the builtin set.
52
+ *
53
+ * @param {unknown} text
54
+ * @param {RegExp[]} [extraPatterns]
55
+ * @returns {unknown}
56
+ */
57
+ export function redactTextSecrets(text, extraPatterns = []) {
58
+ if (typeof text !== "string" || !text) return text;
59
+ let out = text;
60
+ for (const pattern of SECRET_VALUE_PATTERNS) {
61
+ out = out.replace(pattern, REDACTED);
62
+ }
63
+ for (const pattern of extraPatterns) {
64
+ out = out.replace(pattern, REDACTED);
65
+ }
66
+ return out;
67
+ }
68
+
69
+ /**
70
+ * Recursively redact secrets in a JSON-shaped value:
71
+ * - object keys matching the key denylist are replaced wholesale,
72
+ * - string values are scanned for value-shaped secrets,
73
+ * - arrays and nested objects are traversed.
74
+ *
75
+ * @param {unknown} value
76
+ * @param {object} [options]
77
+ * @param {RegExp} [options.keyPattern] Override key denylist (must be
78
+ * non-global; RegExp.prototype.test is stateful for global regexes).
79
+ * @param {Set<string>} [options.allowedKeys] Keys exempt from the denylist
80
+ * (e.g. usage counters like tokensIn).
81
+ * @param {RegExp[]} [options.extraPatterns] Additional value patterns.
82
+ * @returns {unknown}
83
+ */
84
+ export function redactSecretsDeep(value, options = {}) {
85
+ const keyPattern = options.keyPattern ?? REDACT_KEY_PATTERN;
86
+ const allowedKeys = options.allowedKeys ?? null;
87
+ const extraPatterns = Array.isArray(options.extraPatterns) ? options.extraPatterns : [];
88
+
89
+ if (typeof value === "string") {
90
+ return redactTextSecrets(value, extraPatterns);
91
+ }
92
+ if (value == null || typeof value !== "object") {
93
+ return value;
94
+ }
95
+ if (Array.isArray(value)) {
96
+ return value.map((entry) => redactSecretsDeep(entry, options));
97
+ }
98
+
99
+ /** @type {Record<string, unknown>} */
100
+ const out = {};
101
+ for (const [key, entry] of Object.entries(/** @type {Record<string, unknown>} */ (value))) {
102
+ if (keyPattern.test(key) && !(allowedKeys && allowedKeys.has(key))) {
103
+ out[key] = REDACTED;
104
+ } else {
105
+ out[key] = redactSecretsDeep(entry, options);
106
+ }
107
+ }
108
+ return out;
109
+ }
110
+
111
+ /**
112
+ * Cap a JSON-serializable payload by UTF-8 bytes — not string length — so
113
+ * multi-byte characters cannot push the serialized record past the budget.
114
+ * Returns the payload unchanged when it already fits; otherwise returns a
115
+ * truncation marker record whose preview is sliced on byte boundaries.
116
+ *
117
+ * @param {Record<string, unknown>} payload
118
+ * @param {number} maxBytes
119
+ * @returns {Record<string, unknown>}
120
+ */
121
+ export function capPayloadBytes(payload, maxBytes) {
122
+ const serialized = JSON.stringify(payload);
123
+ const originalBytes = Buffer.byteLength(serialized, "utf-8");
124
+ if (originalBytes <= maxBytes) {
125
+ return payload;
126
+ }
127
+
128
+ // Reserve 256 bytes of headroom for the truncation wrapper so the
129
+ // re-serialized record stays near maxBytes. Buffer.subarray slices on byte
130
+ // boundaries; decoding never emits invalid UTF-8 (partial trailing
131
+ // sequences become U+FFFD).
132
+ const budget = Math.max(0, maxBytes - 256);
133
+ const preview = Buffer.from(serialized, "utf-8").subarray(0, budget).toString("utf-8");
134
+ return {
135
+ _truncated: true,
136
+ _originalBytes: originalBytes,
137
+ _maxBytes: maxBytes,
138
+ preview,
139
+ };
140
+ }