my-durable 0.0.44 → 0.0.46

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.
@@ -23,6 +23,12 @@ export interface BackendConfig {
23
23
 
24
24
  const expand = (p: string) => (p === "~" ? homedir() : p.startsWith("~/") ? join(homedir(), p.slice(2)) : p);
25
25
 
26
+ /** The device home, the same way loadConfig derives it — the crash handlers
27
+ * need it BEFORE loadConfig runs (a config failure must still leave a report). */
28
+ export function deviceHome(env: NodeJS.ProcessEnv = process.env): string {
29
+ return expand(env.DPI_HOME ?? join(homedir(), ".dpi"));
30
+ }
31
+
26
32
  export async function loadConfig(argv = process.argv.slice(2), env = process.env): Promise<BackendConfig> {
27
33
  const flag = (key: string, fallback: string) => {
28
34
  const i = argv.indexOf(key);
@@ -31,7 +37,7 @@ export async function loadConfig(argv = process.argv.slice(2), env = process.env
31
37
  if (!value || value.startsWith("--")) throw Error(`${key} needs a value`);
32
38
  return value;
33
39
  };
34
- const home = expand(env.DPI_HOME ?? join(homedir(), ".dpi"));
40
+ const home = deviceHome(env);
35
41
  const envFile = expand(flag("--env-file", env.DPI_ENV_FILE ?? join(home, "backend.env")));
36
42
  if (existsSync(envFile)) process.loadEnvFile(envFile);
37
43
  // First-run bootstrap: an npm-installed `dpi device` has no token and no `npm run token`.
@@ -0,0 +1,338 @@
1
+ /**
2
+ * Local-only crash reports for the device daemon — Gate #1 of the crash
3
+ * policy. The daemon runs detached, so when it dies on an uncaught exception
4
+ * journald holds nothing useful and the operator is left guessing. This module
5
+ * writes one short markdown file per crash into the device home
6
+ * (`<home>/backend/crashes/`): fixed headings, one fact per line, readable by
7
+ * both a human and an independent agent, ~25 lines.
8
+ *
9
+ * NOTHING is ever uploaded anywhere. There is no telemetry and no opt-in or
10
+ * opt-out question to answer — we cannot leak what we never send. What the
11
+ * file deliberately does NOT contain is written down in the report itself
12
+ * ("## not included"): no environment values, tokens, credentials, file
13
+ * contents, or transcripts. Every line still passes `redactLine` before it
14
+ * reaches disk, so a secret embedded in an error message is masked even
15
+ * though it was never supposed to be there.
16
+ *
17
+ * The writer is synchronous on purpose: `uncaughtException` fires when the
18
+ * process is already dying, and an async write may never flush — a crash
19
+ * report that races the exit is not a crash report. The write is still atomic
20
+ * (tmp file + rename, the backup.ts discipline); a `.bak` makes no sense here
21
+ * because every crash creates its own NEW file and rotation deletes the
22
+ * oldest silently, keeping the newest 10. Dirs are 0700, files 0600.
23
+ *
24
+ * `installCrashHandlers` registers the two process-level hooks.
25
+ * uncaughtException writes the report, notes the path on stderr (the one line
26
+ * journald keeps), and exits 1 on `setImmediate` so pending IO can flush.
27
+ * unhandledRejection writes the report but does NOT exit — Node's default is
28
+ * to keep running, and that default is preserved. Both handlers are wrapped
29
+ * so the handler itself can never throw: a crashing crash handler would only
30
+ * lose the report.
31
+ */
32
+ import { chmodSync, mkdirSync, readdirSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
33
+ import { join } from "node:path";
34
+
35
+ /** The 0700/0600 rule every private file in the device home follows (backup.ts / diagnostics.ts). */
36
+ const DIR_MODE = 0o700;
37
+ const FILE_MODE = 0o600;
38
+ /** Rotation: the newest reports kept on disk; older ones are deleted silently. */
39
+ export const MAX_CRASH_REPORTS = 10;
40
+ /** Longest the one-line error message may be after redaction — a crash report is short by design. */
41
+ const MESSAGE_MAX = 600;
42
+ /** Stack frames kept — enough to see where, not enough to pad the file. */
43
+ const STACK_FRAMES = 5;
44
+ /** `crash-20261025-074812-010.md` — UTC so the name sorts and round-trips through `listCrashReports`. */
45
+ const CRASH_NAME_RE = /^crash-(\d{4})(\d{2})(\d{2})-(\d{2})(\d{2})(\d{2})-(\d{3})\.md$/;
46
+
47
+ /** Live counts the leader wires in later; every field optional because a broken device still gets a report. */
48
+ export interface CrashStateSnapshot {
49
+ openSessions?: number;
50
+ totalSessions?: number;
51
+ schedules?: number;
52
+ graphs?: number;
53
+ runsInFlight?: string[];
54
+ notifySinks?: number;
55
+ }
56
+
57
+ export interface CrashHandlerDeps {
58
+ /** Device home dir; reports land in `<home>/backend/crashes/`. */
59
+ home: string;
60
+ /** packageVersion, e.g. "0.0.46". */
61
+ version: string;
62
+ /** Leader wires the real counts in later; wrapped in try so it can never take the report down. */
63
+ state?: () => CrashStateSnapshot;
64
+ /** Injectable clock — tests pin it instead of sleeping. */
65
+ now?: () => Date;
66
+ /** `Date.now()` of daemon start; present → the uptime line, absent → no line at all. */
67
+ startedAt?: number;
68
+ }
69
+
70
+ /** One report as `listCrashReports` hands it to a caller. */
71
+ export interface CrashReportEntry {
72
+ file: string;
73
+ whenMs: number;
74
+ ageLabel: string;
75
+ }
76
+
77
+ // ----------------------------------------------------------------- redaction
78
+
79
+ /**
80
+ * Mask secret-shaped values in one line, mirroring the hub audit's
81
+ * `scrubSecrets` (a different package — the shapes are mirrored, not shared):
82
+ * prefixed tokens keep their prefix, `name=value` keeps the name, a PEM block
83
+ * collapses to a single marker. NEVER the words themselves, only the values.
84
+ */
85
+ export function redactLine(line: string): string {
86
+ return (
87
+ line
88
+ // Bearer headers first: the token after them is 8+ chars of credential.
89
+ .replace(/(bearer\s+)([A-Za-z0-9._-]{8,})/gi, "$1<redacted>")
90
+ // Prefixed tokens (OpenAI sk-, dpt_/dpi_/adm_ device tokens, GitHub, Slack) — word-bounded so
91
+ // "risk-management" is a word, not a secret.
92
+ .replace(/\b(sk-|dpt_|dpi_|adm_|ghp_|gho_|xox)[A-Za-z0-9_-]{8,}/g, "$1<redacted>")
93
+ // A value LABELLED a credential is a credential: keep the name, drop the value. No \b — it
94
+ // would fail after the "_" in DPI_TOKEN (a word char), exactly the shape real env leaks take.
95
+ .replace(
96
+ /(token|secret|password|passwd|api[_-]?key)(\s*[:=]\s*)\S+/gi,
97
+ "$1$2<redacted>",
98
+ )
99
+ // PEM blocks: BEGIN to END, or to the end of the line when the block is truncated.
100
+ .replace(/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(-----END [A-Z ]*PRIVATE KEY-----|$)/g, "<private-key-redacted>")
101
+ );
102
+ }
103
+
104
+ // ------------------------------------------------------------------ helpers
105
+
106
+ const pad = (value: number, width = 2): string => String(value).padStart(width, "0");
107
+
108
+ /** `crash-<YYYYMMDD-HHMMSS-mmm>.md`, UTC — fixed-width so lexicographic order is time order. */
109
+ export function crashFileName(now: Date): string {
110
+ return `crash-${now.getUTCFullYear()}${pad(now.getUTCMonth() + 1)}${pad(now.getUTCDate())}-${pad(
111
+ now.getUTCHours(),
112
+ )}${pad(now.getUTCMinutes())}${pad(now.getUTCSeconds())}-${pad(now.getUTCMilliseconds(), 3)}.md`;
113
+ }
114
+
115
+ /** The timestamp encoded in a report filename, or null when the name is not ours. */
116
+ function crashWhenMs(name: string): number | null {
117
+ const match = CRASH_NAME_RE.exec(name);
118
+ if (!match) return null;
119
+ const whenMs = Date.UTC(
120
+ Number(match[1]),
121
+ Number(match[2]) - 1,
122
+ Number(match[3]),
123
+ Number(match[4]),
124
+ Number(match[5]),
125
+ Number(match[6]),
126
+ Number(match[7]),
127
+ );
128
+ return Number.isFinite(whenMs) ? whenMs : null;
129
+ }
130
+
131
+ /** `3h 12m`-style uptime; anything not a sane duration reads `unknown`, never NaN. */
132
+ function formatUptime(ms: number): string {
133
+ if (!Number.isFinite(ms) || ms < 0) return "unknown";
134
+ if (ms < 60_000) return "<1m";
135
+ const totalMinutes = Math.floor(ms / 60_000);
136
+ if (totalMinutes < 60) return `${totalMinutes}m`;
137
+ const hours = Math.floor(totalMinutes / 60);
138
+ if (hours < 24) return `${hours}h ${totalMinutes % 60}m`;
139
+ return `${Math.floor(hours / 24)}d ${hours % 24}h`;
140
+ }
141
+
142
+ /** `just now` / `5m ago` / `2h ago` / `3d ago` — the label a human reads at a glance. */
143
+ export function ageLabel(ageMs: number): string {
144
+ if (!Number.isFinite(ageMs) || ageMs < 60_000) return "just now";
145
+ if (ageMs < 3_600_000) return `${Math.floor(ageMs / 60_000)}m ago`;
146
+ if (ageMs < 86_400_000) return `${Math.floor(ageMs / 3_600_000)}h ago`;
147
+ return `${Math.floor(ageMs / 86_400_000)}d ago`;
148
+ }
149
+
150
+ /** A number for a fact line: finite numbers as-is, everything else `unknown` — never NaN/undefined. */
151
+ const factNumber = (value: number | undefined): string =>
152
+ typeof value === "number" && Number.isFinite(value) ? String(value) : "unknown";
153
+
154
+ /** Run ids for the fact line: present ids comma-joined, an empty list is `none`, absent is `unknown`. */
155
+ const factRuns = (runs: string[] | undefined): string => {
156
+ if (runs === undefined) return "unknown";
157
+ return runs.length ? runs.join(", ") : "none";
158
+ };
159
+
160
+ /** The state snapshot, or `{}` — a state callback that throws loses its line, not the report. */
161
+ function readSnapshot(deps: CrashHandlerDeps): CrashStateSnapshot {
162
+ try {
163
+ return deps.state?.() ?? {};
164
+ } catch {
165
+ return {};
166
+ }
167
+ }
168
+
169
+ /** The one-line error label: the error's own name for Errors, `Error:` for anything else. */
170
+ function errorName(error: unknown): string {
171
+ return error instanceof Error && error.name ? error.name : "Error";
172
+ }
173
+
174
+ /** The error message flattened to one line, redacted, then capped — cap AFTER redaction so a cut cannot split a secret back open. */
175
+ function errorLine(error: unknown): string {
176
+ const message = (error instanceof Error ? error.message : String(error)).replace(/\r?\n/g, " ").trim();
177
+ return redactLine(`${errorName(error)}: ${message}`).slice(0, MESSAGE_MAX);
178
+ }
179
+
180
+ /** Top 5 `at …` frames, indented as a code block; no stack → the one line `no stack captured`. */
181
+ function stackLines(error: unknown): string[] {
182
+ const frames =
183
+ (error instanceof Error && typeof error.stack === "string" ? error.stack : "")
184
+ .split(/\r?\n/)
185
+ .map((line) => line.trim())
186
+ .filter((line) => line.startsWith("at "))
187
+ .slice(0, STACK_FRAMES)
188
+ .map((line) => redactLine(` ${line}`));
189
+ return frames.length ? frames : [" no stack captured"];
190
+ }
191
+
192
+ /**
193
+ * The report body — every line redacted at the end, so the fixed boilerplate
194
+ * (which contains no secrets) and the variable facts take the same path.
195
+ */
196
+ export function buildCrashReport(deps: CrashHandlerDeps, reason: string, error: unknown, now: Date): string {
197
+ const snapshot = readSnapshot(deps);
198
+ const lines: string[] = [
199
+ "# my-durable crash report",
200
+ "",
201
+ `- when: ${now.toISOString()}`,
202
+ `- version: ${deps.version} (node v${process.versions.node}, ${process.platform})`,
203
+ `- reason: ${reason}`,
204
+ ];
205
+ if (deps.startedAt !== undefined) lines.push(`- uptime: ${formatUptime(now.getTime() - deps.startedAt)}`);
206
+ lines.push(
207
+ "",
208
+ "## error",
209
+ "",
210
+ errorLine(error),
211
+ "",
212
+ ...stackLines(error),
213
+ "",
214
+ "## state at crash",
215
+ "",
216
+ `- sessions: ${factNumber(snapshot.openSessions)} open / ${factNumber(snapshot.totalSessions)} total`,
217
+ `- schedules: ${factNumber(snapshot.schedules)}, graphs: ${factNumber(snapshot.graphs)}, runs in flight: ${factRuns(
218
+ snapshot.runsInFlight,
219
+ )}`,
220
+ `- notify sinks: ${factNumber(snapshot.notifySinks)}`,
221
+ "",
222
+ "## not included",
223
+ "",
224
+ "No environment values, tokens, credentials, file contents, or transcripts",
225
+ "are ever written to this file.",
226
+ "",
227
+ "## what to do",
228
+ "",
229
+ "1. Restart the device: dpi device start (with your DPI_HOME / DPI_ENV_FILE)",
230
+ "2. If it repeats, attach this file to an issue: https://github.com/baphuongnb/my-durable",
231
+ );
232
+ return `${lines.map(redactLine).join("\n")}\n`;
233
+ }
234
+
235
+ /** Delete everything but the newest `MAX_CRASH_REPORTS` reports; a prune that fails is silent. */
236
+ function pruneCrashReports(dir: string): void {
237
+ let names: string[];
238
+ try {
239
+ names = readdirSync(dir).filter((name) => CRASH_NAME_RE.test(name));
240
+ } catch {
241
+ return;
242
+ }
243
+ names.sort(); // fixed-width UTC names: lexicographic order is oldest → newest
244
+ for (const name of names.slice(0, Math.max(0, names.length - MAX_CRASH_REPORTS))) {
245
+ try {
246
+ unlinkSync(join(dir, name));
247
+ } catch {
248
+ // already gone or unremovable — rotation is best effort
249
+ }
250
+ }
251
+ }
252
+
253
+ /**
254
+ * Write one crash report to `<home>/backend/crashes/` and return its path, or
255
+ * null on any IO failure — this function never throws, because its callers
256
+ * are crash handlers with nowhere left to throw to.
257
+ */
258
+ export function writeCrashReport(deps: CrashHandlerDeps, reason: string, error: unknown): string | null {
259
+ try {
260
+ const dir = join(deps.home, "backend", "crashes");
261
+ mkdirSync(dir, { recursive: true, mode: DIR_MODE });
262
+ const now = deps.now?.() ?? new Date();
263
+ const path = join(dir, crashFileName(now));
264
+ const tmp = `${path}.tmp`;
265
+ writeFileSync(tmp, buildCrashReport(deps, reason, error, now), { mode: FILE_MODE });
266
+ renameSync(tmp, path);
267
+ chmodSync(path, FILE_MODE);
268
+ pruneCrashReports(dir);
269
+ return path;
270
+ } catch {
271
+ return null;
272
+ }
273
+ }
274
+
275
+ /**
276
+ * The newest crash reports, newest first. The timestamp comes from the FILENAME
277
+ * only — bodies are never parsed or read, so listing stays cheap and safe.
278
+ * Absent dir, unreadable dir, foreign filenames: an empty list, never a throw.
279
+ */
280
+ export function listCrashReports(home: string, limit = 5): CrashReportEntry[] {
281
+ let names: string[];
282
+ try {
283
+ names = readdirSync(join(home, "backend", "crashes"));
284
+ } catch {
285
+ return [];
286
+ }
287
+ const entries: { name: string; whenMs: number }[] = [];
288
+ for (const name of names) {
289
+ const whenMs = crashWhenMs(name);
290
+ if (whenMs !== null) entries.push({ name, whenMs });
291
+ }
292
+ entries.sort((a, b) => b.whenMs - a.whenMs);
293
+ const nowMs = Date.now();
294
+ const dir = join(home, "backend", "crashes");
295
+ return entries.slice(0, limit).map((entry) => ({
296
+ file: join(dir, entry.name),
297
+ whenMs: entry.whenMs,
298
+ ageLabel: ageLabel(nowMs - entry.whenMs),
299
+ }));
300
+ }
301
+
302
+ /**
303
+ * Register the process-level crash hooks. uncaughtException: write the report,
304
+ * say where on stderr (the one line journald keeps for a detached daemon),
305
+ * then exit 1 on `setImmediate` so pending IO flushes — the exit happens even
306
+ * when the report failed, because the process is already dying. unhandledRejection:
307
+ * write the report and keep running, exactly Node's default. Returns a dispose
308
+ * fn that removes both listeners (tests use it; nothing else should).
309
+ */
310
+ export function installCrashHandlers(deps: CrashHandlerDeps): () => void {
311
+ const onUncaughtException = (error: Error): void => {
312
+ let path: string | null = null;
313
+ try {
314
+ path = writeCrashReport(deps, "uncaughtException", error);
315
+ } catch {
316
+ // the handler itself never throws; writeCrashReport already returns null on failure
317
+ }
318
+ try {
319
+ process.stderr.write(`my-durable: uncaught exception — crash report ${path ?? "FAILED to write"}; exiting (code 1)\n`);
320
+ } catch {
321
+ // stderr gone: nothing to say
322
+ }
323
+ setImmediate(() => process.exit(1));
324
+ };
325
+ const onUnhandledRejection = (reason: unknown): void => {
326
+ try {
327
+ writeCrashReport(deps, "unhandledRejection", reason);
328
+ } catch {
329
+ // report lost; the process keeps running by design
330
+ }
331
+ };
332
+ process.on("uncaughtException", onUncaughtException);
333
+ process.on("unhandledRejection", onUnhandledRejection);
334
+ return () => {
335
+ process.off("uncaughtException", onUncaughtException);
336
+ process.off("unhandledRejection", onUnhandledRejection);
337
+ };
338
+ }
@@ -21,9 +21,10 @@
21
21
  */
22
22
  import { accessSync, constants as fsConstants, existsSync, readFileSync } from "node:fs";
23
23
  import { homedir } from "node:os";
24
- import { join, resolve } from "node:path";
24
+ import { basename, join, resolve } from "node:path";
25
25
  // Reuse the updater's engine comparison instead of a second semver implementation.
26
26
  import { satisfiesEngine } from "../../../bin/update.mjs";
27
+ import { listCrashReports } from "./crash.js";
27
28
 
28
29
  export type DoctorStatus = "ok" | "warn" | "fail" | "skip";
29
30
 
@@ -367,6 +368,19 @@ async function healthzCheck(
367
368
  // ------------------------------------------------------------------- driver
368
369
 
369
370
  /** Run every check. Warnings never make `ok` false; only a FAIL does. */
371
+ /**
372
+ * Local crash reports (policy gate #1): a warn, never a fail — a past crash is
373
+ * information for the operator, not a broken device. Latest first, filename
374
+ * timestamps only, no file bodies parsed.
375
+ */
376
+ function crashReportCheck(home: string): DoctorCheck {
377
+ const reports = listCrashReports(home);
378
+ const detail = !reports.length
379
+ ? "none — the daemon has not crashed"
380
+ : `${reports.length} report${reports.length === 1 ? "" : "s"} — newest ${reports[0]!.ageLabel} (${basename(reports[0]!.file)})`;
381
+ return { id: "crash-reports", status: reports.length ? "warn" : "ok", label: "crash reports", detail };
382
+ }
383
+
370
384
  export async function runDoctor(opts: Partial<DoctorIo> = {}): Promise<DoctorReport> {
371
385
  const io: DoctorIo = { ...defaultDoctorIo(), ...opts };
372
386
  const cfg = deviceEndpoint(io);
@@ -377,6 +391,7 @@ export async function runDoctor(opts: Partial<DoctorIo> = {}): Promise<DoctorRep
377
391
  checks.push(...startDirChecks(io, cfg));
378
392
  checks.push(await probeCheck(io, cfg, health.reachable));
379
393
  checks.push(await hubCheck(io, cfg));
394
+ checks.push(crashReportCheck(cfg.home));
380
395
 
381
396
  return { checks, ok: checks.every((c) => c.status !== "fail") };
382
397
  }