my-durable 0.0.41 → 0.0.43
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/apps/dpi-backend/src/awake.ts +136 -0
- package/apps/dpi-backend/src/backup-cli.ts +220 -0
- package/apps/dpi-backend/src/backup.ts +523 -0
- package/apps/dpi-backend/src/diagnostics-cli.ts +134 -0
- package/apps/dpi-backend/src/diagnostics.ts +326 -0
- package/apps/dpi-backend/src/env-vars.ts +234 -0
- package/apps/dpi-backend/src/main.ts +1 -0
- package/apps/dpi-backend/src/projects.ts +33 -1
- package/apps/dpi-backend/src/routes.ts +21 -1
- package/apps/dpi-backend/src/store.ts +85 -3
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-BgKiQEMm.js +81 -0
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-EulngMVY.css +1 -0
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/index.html +2 -2
- package/apps/dpi-playground/apps/dpi-playground-fe/src/components/EnvPanel.vue +268 -0
- package/apps/dpi-playground/apps/dpi-playground-fe/src/components/HostPanel.vue +11 -0
- package/apps/dpi-playground/apps/dpi-playground-fe/src/components/Inspector.vue +4 -0
- package/apps/dpi-playground/apps/dpi-playground-fe/src/components/NewSessionDialog.vue +37 -0
- package/apps/dpi-playground/apps/dpi-playground-fe/src/components/ProjectBar.vue +41 -1
- package/apps/dpi-sdk/src/api.ts +29 -2
- package/apps/dpi-sdk/src/client.ts +12 -0
- package/apps/dpi-sdk/src/protocol/rest-routes.ts +3 -0
- package/bin/dpi.mjs +16 -0
- package/docs/host-project-checklist.md +8 -8
- package/package.json +1 -1
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-D6ClJqd8.css +0 -1
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-DMb-n4O-.js +0 -81
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `dpi diagnostics` — a redacted diagnostic bundle as one zip — "Diagnostic
|
|
3
|
+
* bundle" (SHOULD), Wave 3 of docs/host-project-checklist.md.
|
|
4
|
+
*
|
|
5
|
+
* Modelled on orca's PrivacyDiagnosticBundleControls idea: everything an
|
|
6
|
+
* operator would paste into a bug report, with secrets stripped. Every text
|
|
7
|
+
* that enters the bundle passes `redact`/`redactJson` (dpi_ tokens, Bearer
|
|
8
|
+
* headers, sk-/pk-/rk- keys, and any 32+ char token-shaped run); the bundle
|
|
9
|
+
* contains no transcripts by construction, so the raw-long-run rule cannot
|
|
10
|
+
* eat base64 payload it was never meant to see.
|
|
11
|
+
*
|
|
12
|
+
* Each section is INDEPENDENT: one that fails records `{"error": ...}` and the
|
|
13
|
+
* bundle still builds — a broken device is exactly when diagnostics matter
|
|
14
|
+
* most. The API sections talk to the LOCAL device the same way `dpi doctor`
|
|
15
|
+
* does (`deviceEndpoint` + `authHeaders`, `$DPI_HOST|$DPI_PORT`, token from
|
|
16
|
+
* the env file), and `doctor.json` is literally doctor's runner re-run through
|
|
17
|
+
* this module's io — not a reimplementation.
|
|
18
|
+
*
|
|
19
|
+
* Every fs/clock/network access goes through `DiagnosticsIo` (the `backup.ts`
|
|
20
|
+
* pattern: async fs + injectable fetch + clock). doctor.ts's own fs surface is
|
|
21
|
+
* synchronous (`existsSync`/`readFileSync`/`accessSync`), so the io carries
|
|
22
|
+
* that surface too and `diagnosticsDoctorIo` bridges the two worlds — one
|
|
23
|
+
* object to fake in tests, never the real fs or network.
|
|
24
|
+
*/
|
|
25
|
+
import { accessSync, existsSync, readFileSync } from "node:fs";
|
|
26
|
+
import { access, chmod, mkdir, readFile, writeFile } from "node:fs/promises";
|
|
27
|
+
import { homedir } from "node:os";
|
|
28
|
+
import { dirname, join, resolve } from "node:path";
|
|
29
|
+
import {
|
|
30
|
+
authHeaders,
|
|
31
|
+
defaultDoctorIo,
|
|
32
|
+
describeError,
|
|
33
|
+
deviceEndpoint,
|
|
34
|
+
expand,
|
|
35
|
+
runDoctor,
|
|
36
|
+
type DoctorIo,
|
|
37
|
+
} from "./doctor.js";
|
|
38
|
+
import { PACKAGE_VERSION } from "./store.js";
|
|
39
|
+
import { zipSync, type ZipEntry } from "./zip.js";
|
|
40
|
+
|
|
41
|
+
export type DiagnosticsErrorCode = "invalid";
|
|
42
|
+
|
|
43
|
+
/** Typed failure, same shape as `BackupError`: a CLI picks its exit code from `code`, not from message matching. */
|
|
44
|
+
export class DiagnosticsError extends Error {
|
|
45
|
+
readonly code: DiagnosticsErrorCode;
|
|
46
|
+
|
|
47
|
+
constructor(code: DiagnosticsErrorCode, message: string) {
|
|
48
|
+
super(message);
|
|
49
|
+
this.name = "DiagnosticsError";
|
|
50
|
+
this.code = code;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const invalid = (message: string) => new DiagnosticsError("invalid", message);
|
|
55
|
+
|
|
56
|
+
/** The io carries the same 0700/0600 rule `backup.ts` does (`ensurePrivateDir` is sync and not injectable). */
|
|
57
|
+
const DIR_MODE = 0o700;
|
|
58
|
+
const FILE_MODE = 0o600;
|
|
59
|
+
/** Per-section fetch budget: a hung device must not hang the bundle. */
|
|
60
|
+
const SECTION_TIMEOUT_MS = 10_000;
|
|
61
|
+
/** The device.log tail: the last 400 lines, never the whole file. */
|
|
62
|
+
export const DEVICE_LOG_LINES = 400;
|
|
63
|
+
|
|
64
|
+
/** Narrow fetch surface, `doctor.ts`'s init shape so its checks pass through unchanged. */
|
|
65
|
+
export interface DiagnosticsFetchInit {
|
|
66
|
+
method?: string;
|
|
67
|
+
headers?: Record<string, string>;
|
|
68
|
+
body?: string;
|
|
69
|
+
signal?: AbortSignal;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export interface DiagnosticsResponse {
|
|
73
|
+
ok: boolean;
|
|
74
|
+
status: number;
|
|
75
|
+
text(): Promise<string>;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export interface DiagnosticsIo {
|
|
79
|
+
readFile(path: string): Promise<string>;
|
|
80
|
+
/** `mode` applies when the file is created; an explicit `chmod` follows, like backup.ts's persist. */
|
|
81
|
+
writeFile(path: string, data: Uint8Array, mode?: number): Promise<void>;
|
|
82
|
+
chmod(path: string, mode: number): Promise<void>;
|
|
83
|
+
/** Recursive; `mode` (0700 by default) applies to the directories it creates. */
|
|
84
|
+
mkdir(path: string, mode?: number): Promise<void>;
|
|
85
|
+
exists(path: string): Promise<boolean>;
|
|
86
|
+
fetch(url: string, init?: DiagnosticsFetchInit): Promise<DiagnosticsResponse>;
|
|
87
|
+
now(): number;
|
|
88
|
+
env: Record<string, string | undefined>;
|
|
89
|
+
homedir: () => string;
|
|
90
|
+
nodeVersion: string;
|
|
91
|
+
/** doctor.ts's fs surface is synchronous; the io carries it so `runDoctor` runs through the same fake. */
|
|
92
|
+
existsSync(path: string): boolean;
|
|
93
|
+
readFileSync(path: string): string;
|
|
94
|
+
accessSync(path: string, mode?: number): void;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export const defaultDiagnosticsIo = (): DiagnosticsIo => ({
|
|
98
|
+
readFile: (path) => readFile(path, "utf8"),
|
|
99
|
+
writeFile: (path, data, mode) => writeFile(path, data, { mode }),
|
|
100
|
+
chmod: (path, mode) => chmod(path, mode),
|
|
101
|
+
// fs/promises mkdir(recursive) resolves with the first created path — dropped, the io promises void.
|
|
102
|
+
mkdir: async (path, mode) => {
|
|
103
|
+
await mkdir(path, { recursive: true, mode: mode ?? DIR_MODE });
|
|
104
|
+
},
|
|
105
|
+
exists: async (path) => {
|
|
106
|
+
try {
|
|
107
|
+
await access(path);
|
|
108
|
+
return true;
|
|
109
|
+
} catch {
|
|
110
|
+
return false;
|
|
111
|
+
}
|
|
112
|
+
},
|
|
113
|
+
fetch: (url, init) => fetch(url, init as RequestInit | undefined),
|
|
114
|
+
now: () => Date.now(),
|
|
115
|
+
env: process.env as Record<string, string | undefined>,
|
|
116
|
+
homedir,
|
|
117
|
+
existsSync,
|
|
118
|
+
readFileSync: (path) => readFileSync(path, "utf8"),
|
|
119
|
+
accessSync,
|
|
120
|
+
nodeVersion: process.versions.node,
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
// ---------------------------------------------------------------- redaction
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Mask secret-shaped runs in any text: dpi_ tokens, bearer headers, long
|
|
127
|
+
* key-looking strings. Order matters — the prefixed shapes run first so the
|
|
128
|
+
* raw 32+ catch-all only sees what is left. NEVER the words themselves, only
|
|
129
|
+
* the values.
|
|
130
|
+
*/
|
|
131
|
+
export function redact(text: string): string {
|
|
132
|
+
return text
|
|
133
|
+
.replace(/dpi_[A-Za-z0-9_-]{20,}/g, "dpi_••••")
|
|
134
|
+
.replace(/Bearer\s+[A-Za-z0-9._-]{16,}/g, "Bearer ••••")
|
|
135
|
+
.replace(/\b(sk|pk|rk)-[A-Za-z0-9]{16,}/g, "$1-••••")
|
|
136
|
+
.replace(/[A-Za-z0-9_-]{32,}/g, "••••");
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Walk a parsed JSON value and redact every string in it (values, not keys — keys are schema). */
|
|
140
|
+
export function redactJson(value: unknown): unknown {
|
|
141
|
+
if (typeof value === "string") return redact(value);
|
|
142
|
+
if (Array.isArray(value)) return value.map(redactJson);
|
|
143
|
+
if (value && typeof value === "object") {
|
|
144
|
+
const out: Record<string, unknown> = {};
|
|
145
|
+
for (const [key, entry] of Object.entries(value as Record<string, unknown>)) out[key] = redactJson(entry);
|
|
146
|
+
return out;
|
|
147
|
+
}
|
|
148
|
+
return value;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// ----------------------------------------------------------------- sections
|
|
152
|
+
|
|
153
|
+
/** One zip entry plus the outcome the CLI prints. */
|
|
154
|
+
export interface DiagnosticsSection {
|
|
155
|
+
name: string;
|
|
156
|
+
ok: boolean;
|
|
157
|
+
bytes: number;
|
|
158
|
+
/** Present when the section failed: what the CLI prints after the colon. */
|
|
159
|
+
error?: string;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** The `GET /v1/...` routes that become json sections, in bundle order. */
|
|
163
|
+
const API_SECTIONS: ReadonlyArray<{ name: string; route: string }> = [
|
|
164
|
+
{ name: "device.json", route: "/v1/device" },
|
|
165
|
+
{ name: "vitals.json", route: "/v1/device/vitals" },
|
|
166
|
+
{ name: "env.json", route: "/v1/device/env" },
|
|
167
|
+
{ name: "sessions.json", route: "/v1/sessions" },
|
|
168
|
+
{ name: "projects.json", route: "/v1/projects" },
|
|
169
|
+
{ name: "schedules.json", route: "/v1/schedules" },
|
|
170
|
+
{ name: "notify.json", route: "/v1/notify/sinks" },
|
|
171
|
+
];
|
|
172
|
+
|
|
173
|
+
const jsonText = (value: unknown): string => `${JSON.stringify(value, null, 2)}\n`;
|
|
174
|
+
|
|
175
|
+
/** `runDoctor` over this module's io: same checks, same fakes, doctor's own timeouts and engine floor. */
|
|
176
|
+
function diagnosticsDoctorIo(io: DiagnosticsIo): DoctorIo {
|
|
177
|
+
return {
|
|
178
|
+
...defaultDoctorIo(),
|
|
179
|
+
env: io.env,
|
|
180
|
+
nodeVersion: io.nodeVersion,
|
|
181
|
+
// doctor's FetchLike wants json(); this io speaks text() — adapt, never reimplement.
|
|
182
|
+
fetchImpl: async (url, init) => {
|
|
183
|
+
const res = await io.fetch(url, init);
|
|
184
|
+
return { ok: res.ok, status: res.status, json: async () => JSON.parse(await res.text()) };
|
|
185
|
+
},
|
|
186
|
+
access: io.accessSync,
|
|
187
|
+
exists: io.existsSync,
|
|
188
|
+
readFile: io.readFileSync,
|
|
189
|
+
homedir: io.homedir,
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** One JSON section from the device API: ok → redacted body; failure → `{"error": ...}` and the bundle carries on. */
|
|
194
|
+
async function apiSection(
|
|
195
|
+
io: DiagnosticsIo,
|
|
196
|
+
url: string,
|
|
197
|
+
route: string,
|
|
198
|
+
headers: Record<string, string>,
|
|
199
|
+
): Promise<{ text: string; ok: boolean; error?: string }> {
|
|
200
|
+
let ok: boolean;
|
|
201
|
+
let status: number;
|
|
202
|
+
let raw: string;
|
|
203
|
+
try {
|
|
204
|
+
const res = await io.fetch(url, { headers, signal: AbortSignal.timeout(SECTION_TIMEOUT_MS) });
|
|
205
|
+
ok = res.ok;
|
|
206
|
+
status = res.status;
|
|
207
|
+
raw = await res.text();
|
|
208
|
+
} catch (error) {
|
|
209
|
+
const detail = describeError(error, SECTION_TIMEOUT_MS);
|
|
210
|
+
return { text: jsonText({ error: `GET ${route} unreachable — ${detail}` }), ok: false, error: detail };
|
|
211
|
+
}
|
|
212
|
+
if (!ok) {
|
|
213
|
+
return { text: jsonText({ error: `GET ${route} → ${status}` }), ok: false, error: String(status) };
|
|
214
|
+
}
|
|
215
|
+
let body: unknown;
|
|
216
|
+
try {
|
|
217
|
+
body = JSON.parse(raw);
|
|
218
|
+
} catch {
|
|
219
|
+
return { text: jsonText({ error: `GET ${route} → non-JSON body` }), ok: false, error: "non-JSON body" };
|
|
220
|
+
}
|
|
221
|
+
return { text: jsonText(redactJson(body)), ok: true };
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** The device.log tail: last 400 lines, redacted. Missing → skipped (undefined); unreadable → a failed section. */
|
|
225
|
+
async function logSection(io: DiagnosticsIo, home: string): Promise<{ text: string; ok: boolean; error?: string } | undefined> {
|
|
226
|
+
const logPath = join(home, "device.log");
|
|
227
|
+
if (!(await io.exists(logPath))) return undefined;
|
|
228
|
+
let raw: string;
|
|
229
|
+
try {
|
|
230
|
+
raw = await io.readFile(logPath);
|
|
231
|
+
} catch (error) {
|
|
232
|
+
const detail = describeError(error, 0);
|
|
233
|
+
return { text: `# cannot read ${logPath}: ${detail}\n`, ok: false, error: detail };
|
|
234
|
+
}
|
|
235
|
+
const lines = raw.split(/\r?\n/);
|
|
236
|
+
if (lines.length && lines[lines.length - 1] === "") lines.pop(); // the split's trailing "" is not a line
|
|
237
|
+
const tail = lines.slice(-DEVICE_LOG_LINES);
|
|
238
|
+
return { text: tail.length ? `${redact(tail.join("\n"))}\n` : "", ok: true };
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// ----------------------------------------------------------------- collect
|
|
242
|
+
|
|
243
|
+
export interface CollectDiagnosticsOptions {
|
|
244
|
+
home: string;
|
|
245
|
+
out: string;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
export interface CollectDiagnosticsResult {
|
|
249
|
+
path: string;
|
|
250
|
+
sections: DiagnosticsSection[];
|
|
251
|
+
/** Total zip size in bytes — the CLI's "total". */
|
|
252
|
+
bytes: number;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* Collect the bundle into `opts.out` (0600, parent dirs 0700) and touch nothing
|
|
257
|
+
* else. The timestamped default name is the CLI's decision, not this module's.
|
|
258
|
+
*/
|
|
259
|
+
export async function collectDiagnostics(
|
|
260
|
+
io: DiagnosticsIo,
|
|
261
|
+
opts: CollectDiagnosticsOptions,
|
|
262
|
+
): Promise<CollectDiagnosticsResult> {
|
|
263
|
+
if (!opts.home) throw invalid("home is required");
|
|
264
|
+
if (!opts.out) throw invalid("out is required");
|
|
265
|
+
const home = resolve(expand(opts.home, io.homedir()));
|
|
266
|
+
const out = resolve(expand(opts.out, io.homedir()));
|
|
267
|
+
|
|
268
|
+
// The device API the way doctor sees it: $DPI_HOST|$DPI_PORT, token from the env file.
|
|
269
|
+
const doctorIo = diagnosticsDoctorIo(io);
|
|
270
|
+
const cfg = deviceEndpoint(doctorIo);
|
|
271
|
+
const headers = authHeaders(cfg.token);
|
|
272
|
+
|
|
273
|
+
const sections: DiagnosticsSection[] = [];
|
|
274
|
+
const entries: ZipEntry[] = [];
|
|
275
|
+
const push = (name: string, text: string, ok: boolean, error?: string): void => {
|
|
276
|
+
entries.push({ path: name, text });
|
|
277
|
+
sections.push({ name, ok, bytes: Buffer.byteLength(text, "utf8"), ...(error ? { error } : {}) });
|
|
278
|
+
};
|
|
279
|
+
|
|
280
|
+
// doctor.json — doctor's own runner, through this module's io.
|
|
281
|
+
{
|
|
282
|
+
let report: unknown;
|
|
283
|
+
let ok = true;
|
|
284
|
+
let error: string | undefined;
|
|
285
|
+
try {
|
|
286
|
+
report = redactJson(await runDoctor(doctorIo));
|
|
287
|
+
} catch (e) {
|
|
288
|
+
error = describeError(e, 0);
|
|
289
|
+
report = { error: `doctor failed — ${error}` };
|
|
290
|
+
ok = false;
|
|
291
|
+
}
|
|
292
|
+
push("doctor.json", jsonText(report), ok, error);
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
// the seven registry/summary routes — summaries by design (no transcripts)
|
|
296
|
+
for (const section of API_SECTIONS) {
|
|
297
|
+
const r = await apiSection(io, `${cfg.baseUrl}${section.route}`, section.route, headers);
|
|
298
|
+
push(section.name, r.text, r.ok, r.error);
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
// device.log — on-disk facts, tail only, redacted
|
|
302
|
+
{
|
|
303
|
+
const r = await logSection(io, home);
|
|
304
|
+
if (r) push("device.log", r.text, r.ok, r.error);
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
// The manifest is entry 0 (backup.ts's rule), so it lists the sections that
|
|
308
|
+
// actually made it in — including device.log only when the log was there.
|
|
309
|
+
const manifest = redactJson({
|
|
310
|
+
createdAt: new Date(io.now()).toISOString(),
|
|
311
|
+
packageVersion: PACKAGE_VERSION,
|
|
312
|
+
node: io.nodeVersion,
|
|
313
|
+
platform: process.platform,
|
|
314
|
+
arch: process.arch,
|
|
315
|
+
home,
|
|
316
|
+
sections: sections.map((s) => s.name),
|
|
317
|
+
});
|
|
318
|
+
entries.unshift({ path: "manifest.json", text: jsonText(manifest) });
|
|
319
|
+
sections.unshift({ name: "manifest.json", ok: true, bytes: Buffer.byteLength(jsonText(manifest), "utf8") });
|
|
320
|
+
|
|
321
|
+
const zip = zipSync(entries, new Date(io.now()));
|
|
322
|
+
await io.mkdir(dirname(out), DIR_MODE);
|
|
323
|
+
await io.writeFile(out, zip, FILE_MODE);
|
|
324
|
+
await io.chmod(out, FILE_MODE);
|
|
325
|
+
return { path: out, sections, bytes: zip.length };
|
|
326
|
+
}
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Device env-file editing — "Env-var management UI", Wave 2 SHOULD of
|
|
3
|
+
* docs/host-project-checklist.md.
|
|
4
|
+
*
|
|
5
|
+
* orca edits a host's default agent environment (HostAgentEnvironmentEditor);
|
|
6
|
+
* the device equivalent is the env file loadConfig reads at boot
|
|
7
|
+
* (~/.dpi/backend.env or $DPI_ENV_FILE — the same file `just net up` writes
|
|
8
|
+
* from dpi-network.yaml's env/env_keys). This module is the guarded read/edit
|
|
9
|
+
* surface for THAT file: list with secrets masked, set/unset one key, and a
|
|
10
|
+
* restart hint, because nothing takes effect until the daemon reboots.
|
|
11
|
+
*
|
|
12
|
+
* Three deliberate rules:
|
|
13
|
+
* - Managed/self-referential keys (DPI_TOKEN, DPI_PORT, DPI_HOME, …) are
|
|
14
|
+
* refused: each has its own dedicated setting, and editing them from a
|
|
15
|
+
* remote browser is how a device gets locked out.
|
|
16
|
+
* - Variables that came from the process (systemd `Environment=`, shell) are
|
|
17
|
+
* listed read-only: `process.loadEnvFile` does not override an existing
|
|
18
|
+
* value, so writing them to the file would look saved but never apply.
|
|
19
|
+
* - Secret-looking values are never returned over the wire — only a mask and
|
|
20
|
+
* the last 4 characters, enough to recognise, not enough to copy.
|
|
21
|
+
*
|
|
22
|
+
* Node builtins only; every fs access and the clock go through `io`.
|
|
23
|
+
*/
|
|
24
|
+
import { join } from "node:path";
|
|
25
|
+
|
|
26
|
+
/** Same validation as dpi-network.yaml's envMap: UPPER_SNAKE_CASE only. */
|
|
27
|
+
const KEY_PATTERN = /^[A-Z_][A-Z0-9_]*$/;
|
|
28
|
+
|
|
29
|
+
/** Keys with a dedicated setting (config.ts MANAGED_ENV) or that change where the daemon looks. */
|
|
30
|
+
export const READONLY_KEYS: readonly string[] = [
|
|
31
|
+
"DPI_TOKEN",
|
|
32
|
+
"DPI_DEVICE_NAME",
|
|
33
|
+
"DPI_PORT",
|
|
34
|
+
"DPI_HOST",
|
|
35
|
+
"DPI_START_DIRS",
|
|
36
|
+
"DPI_DATA_DIR",
|
|
37
|
+
"DPI_HOME",
|
|
38
|
+
"DPI_ENV_FILE",
|
|
39
|
+
];
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* A key that likely holds a credential. Matching is on the NAME, never the
|
|
43
|
+
* value. Bare `PRIVATE` is deliberately absent: `DPI_NOTIFY_ALLOW_PRIVATE=1`
|
|
44
|
+
* is a flag, not a secret.
|
|
45
|
+
*/
|
|
46
|
+
const SECRET_KEY = /TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|_KEY$|PRIVATE_KEY|CREDENTIAL/i;
|
|
47
|
+
|
|
48
|
+
export const MAX_VALUE_LENGTH = 2000;
|
|
49
|
+
|
|
50
|
+
export type EnvErrorCode = "invalid" | "not_found";
|
|
51
|
+
|
|
52
|
+
/** Typed failure so routes can answer 400 (`invalid`) or 404 (`not_found`) without string matching. */
|
|
53
|
+
export class EnvError extends Error {
|
|
54
|
+
readonly code: EnvErrorCode;
|
|
55
|
+
|
|
56
|
+
constructor(code: EnvErrorCode, message: string) {
|
|
57
|
+
super(message);
|
|
58
|
+
this.name = "EnvError";
|
|
59
|
+
this.code = code;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export interface EnvVarView {
|
|
64
|
+
key: string;
|
|
65
|
+
/** The value as the UI may show it: masked for secrets, verbatim otherwise. */
|
|
66
|
+
masked: string;
|
|
67
|
+
secret: boolean;
|
|
68
|
+
/** "file" = editable here; "process" = inherited (systemd/shell), read-only. */
|
|
69
|
+
source: "file" | "process";
|
|
70
|
+
/** Managed keys have a dedicated setting; the editor refuses them. */
|
|
71
|
+
managed: boolean;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export interface EnvFileView {
|
|
75
|
+
envFile: string;
|
|
76
|
+
exists: boolean;
|
|
77
|
+
/** True once a set/unset happened since this process booted — changes apply after restart. */
|
|
78
|
+
restartRequired: boolean;
|
|
79
|
+
vars: EnvVarView[];
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export interface EnvIo {
|
|
83
|
+
readFile(path: string): Promise<string>;
|
|
84
|
+
writeFile(path: string, data: string): Promise<void>;
|
|
85
|
+
chmod(path: string, mode: number): Promise<void>;
|
|
86
|
+
exists(path: string): Promise<boolean>;
|
|
87
|
+
/** Read-only view of the daemon's own environment (default: process.env). */
|
|
88
|
+
processEnv(): Record<string, string | undefined>;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export const defaultEnvIo = (): EnvIo => ({
|
|
92
|
+
readFile: async (path) => (await import("node:fs/promises")).readFile(path, "utf8"),
|
|
93
|
+
writeFile: async (path, data) => {
|
|
94
|
+
const fs = await import("node:fs/promises");
|
|
95
|
+
await fs.writeFile(path, data, { mode: 0o600 });
|
|
96
|
+
},
|
|
97
|
+
chmod: async (path, mode) => (await import("node:fs/promises")).chmod(path, mode),
|
|
98
|
+
exists: async (path) =>
|
|
99
|
+
(await import("node:fs/promises"))
|
|
100
|
+
.access(path)
|
|
101
|
+
.then(() => true)
|
|
102
|
+
.catch(() => false),
|
|
103
|
+
processEnv: () => process.env as Record<string, string | undefined>,
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
const invalid = (message: string) => new EnvError("invalid", message);
|
|
107
|
+
|
|
108
|
+
/** `•` + the tail: enough to recognise a saved key, not enough to copy it. */
|
|
109
|
+
export function maskValue(value: string): string {
|
|
110
|
+
if (value.length <= 8) return "•".repeat(Math.max(value.length, 4));
|
|
111
|
+
return `${"•".repeat(8)}${value.slice(-4)}`;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const isSecret = (key: string) => SECRET_KEY.test(key);
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Parse `KEY=VALUE` lines; comments/blanks/unparsed lines are preserved but not
|
|
118
|
+
* vars. The empty string after a trailing newline is an artifact of `split`,
|
|
119
|
+
* not a line — drop it so a rewrite does not grow blank lines.
|
|
120
|
+
*/
|
|
121
|
+
function parseLines(text: string): Array<{ key?: string; value?: string; line: string }> {
|
|
122
|
+
if (text === "") return [];
|
|
123
|
+
const raw = text.split("\n");
|
|
124
|
+
if (raw.length > 1 && raw[raw.length - 1] === "") raw.pop();
|
|
125
|
+
return raw.map((line) => {
|
|
126
|
+
const m = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(line);
|
|
127
|
+
return m ? { key: m[1], value: m[2], line } : { line };
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* One env file. Line-preserving: a rewrite keeps every comment and order
|
|
133
|
+
* intact and only touches the line being set or removed. Writes are atomic in
|
|
134
|
+
* the caller's hands (write the whole new text at once); the mode is forced to
|
|
135
|
+
* 0600 because provider keys live here.
|
|
136
|
+
*/
|
|
137
|
+
export class EnvFileEditor {
|
|
138
|
+
private readonly io: EnvIo;
|
|
139
|
+
readonly path: string;
|
|
140
|
+
private restartRequired = false;
|
|
141
|
+
|
|
142
|
+
constructor(path: string, io: EnvIo = defaultEnvIo()) {
|
|
143
|
+
this.path = path;
|
|
144
|
+
this.io = io;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
private async read(): Promise<string> {
|
|
148
|
+
return (await this.io.exists(this.path)) ? await this.io.readFile(this.path) : "";
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Full view: file vars first (editable), then DPI_* process-only vars (read-only). */
|
|
152
|
+
async view(): Promise<EnvFileView> {
|
|
153
|
+
const text = await this.read();
|
|
154
|
+
const seen = new Set<string>();
|
|
155
|
+
const vars: EnvVarView[] = [];
|
|
156
|
+
for (const { key, value } of parseLines(text)) {
|
|
157
|
+
if (!key || value === undefined || seen.has(key)) continue;
|
|
158
|
+
seen.add(key);
|
|
159
|
+
vars.push({
|
|
160
|
+
key,
|
|
161
|
+
masked: isSecret(key) ? maskValue(value) : value,
|
|
162
|
+
secret: isSecret(key),
|
|
163
|
+
source: "file",
|
|
164
|
+
managed: (READONLY_KEYS as readonly string[]).includes(key),
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
for (const [key, value] of Object.entries(this.io.processEnv())) {
|
|
168
|
+
if (!key.startsWith("DPI_") || seen.has(key) || value === undefined || value === "") continue;
|
|
169
|
+
seen.add(key);
|
|
170
|
+
vars.push({
|
|
171
|
+
key,
|
|
172
|
+
masked: isSecret(key) ? maskValue(value) : value,
|
|
173
|
+
secret: isSecret(key),
|
|
174
|
+
source: "process",
|
|
175
|
+
managed: (READONLY_KEYS as readonly string[]).includes(key),
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
vars.sort((a, b) => a.key.localeCompare(b.key));
|
|
179
|
+
return {
|
|
180
|
+
envFile: this.path,
|
|
181
|
+
exists: await this.io.exists(this.path),
|
|
182
|
+
restartRequired: this.restartRequired,
|
|
183
|
+
vars,
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Set one key. Refuses managed/self-referential keys and multi-line values. */
|
|
188
|
+
async set(key: string, value: string): Promise<EnvVarView> {
|
|
189
|
+
if (!KEY_PATTERN.test(key)) throw invalid(`${key}: keys are UPPER_SNAKE_CASE`);
|
|
190
|
+
if ((READONLY_KEYS as readonly string[]).includes(key))
|
|
191
|
+
throw invalid(`${key} has its own setting (port, host, start_dirs, …); change that instead`);
|
|
192
|
+
if (typeof value !== "string" || !value.length) throw invalid("a value is required");
|
|
193
|
+
if (/[\n\r]/.test(value)) throw invalid("the value must be a single line");
|
|
194
|
+
if (value.length > MAX_VALUE_LENGTH) throw invalid(`the value is longer than ${MAX_VALUE_LENGTH} characters`);
|
|
195
|
+
const lines = parseLines(await this.read());
|
|
196
|
+
const next = `${key}=${value}`;
|
|
197
|
+
let replaced = false;
|
|
198
|
+
const out = lines.map((entry) => {
|
|
199
|
+
if (entry.key !== key || replaced) return entry.line;
|
|
200
|
+
replaced = true;
|
|
201
|
+
return next;
|
|
202
|
+
});
|
|
203
|
+
if (!replaced) out.push(next);
|
|
204
|
+
await this.write(out);
|
|
205
|
+
return {
|
|
206
|
+
key,
|
|
207
|
+
masked: isSecret(key) ? maskValue(value) : value,
|
|
208
|
+
secret: isSecret(key),
|
|
209
|
+
source: "file",
|
|
210
|
+
managed: (READONLY_KEYS as readonly string[]).includes(key),
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** Remove one key's line. Only file-sourced keys can be removed. */
|
|
215
|
+
async unset(key: string): Promise<{ removed: boolean }> {
|
|
216
|
+
const lines = parseLines(await this.read());
|
|
217
|
+
const kept = lines.filter((entry) => entry.key !== key);
|
|
218
|
+
if (kept.length === lines.length) return { removed: false };
|
|
219
|
+
await this.write(kept.map((entry) => entry.line));
|
|
220
|
+
return { removed: true };
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
private async write(lines: string[]): Promise<void> {
|
|
224
|
+
const text = lines.filter((line) => line !== "").length ? `${lines.join("\n").replace(/\n+$/, "")}\n` : "";
|
|
225
|
+
await this.io.writeFile(this.path, text);
|
|
226
|
+
await this.io.chmod(this.path, 0o600).catch(() => {});
|
|
227
|
+
this.restartRequired = true;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** Default env-file path for a home dir (mirrors config.ts's fallback). */
|
|
232
|
+
export function envFileForHome(home: string): string {
|
|
233
|
+
return join(home, "backend.env");
|
|
234
|
+
}
|
|
@@ -57,6 +57,8 @@ export interface ProjectRecord {
|
|
|
57
57
|
customName?: string;
|
|
58
58
|
/** Free-form filter keys, lowercase and de-duplicated. */
|
|
59
59
|
labels: string[];
|
|
60
|
+
/** Default model for sessions started under this project (Wave 2: per-project settings). */
|
|
61
|
+
model?: { provider: string; modelId: string };
|
|
60
62
|
kind: ProjectKind;
|
|
61
63
|
createdAt: string;
|
|
62
64
|
updatedAt: string;
|
|
@@ -69,6 +71,8 @@ export interface ProjectPatch {
|
|
|
69
71
|
customName?: string;
|
|
70
72
|
/** Replaces the whole list; validated and normalised before it lands. */
|
|
71
73
|
labels?: string[];
|
|
74
|
+
/** Default model for new sessions in this project; `""` clears it back to the device default. */
|
|
75
|
+
model?: { provider: string; modelId: string } | "";
|
|
72
76
|
}
|
|
73
77
|
|
|
74
78
|
/** The on-disk document. `version` exists so a future shape can be migrated instead of discarded. */
|
|
@@ -103,7 +107,11 @@ const describeError = (error: unknown) => (error instanceof Error ? error.messag
|
|
|
103
107
|
const defaultWarn = (message: string, error?: unknown) =>
|
|
104
108
|
console.warn(`[projects] ${message}`, error === undefined ? "" : describeError(error));
|
|
105
109
|
|
|
106
|
-
const clone = (record: ProjectRecord): ProjectRecord => ({
|
|
110
|
+
const clone = (record: ProjectRecord): ProjectRecord => ({
|
|
111
|
+
...record,
|
|
112
|
+
labels: [...record.labels],
|
|
113
|
+
...(record.model ? { model: { ...record.model } } : {}),
|
|
114
|
+
});
|
|
107
115
|
|
|
108
116
|
/** `prj_` + 12 hex: short enough to type in a URL, wide enough that collisions are not a real risk. */
|
|
109
117
|
export function newProjectId(): string {
|
|
@@ -222,6 +230,21 @@ function coerceRecord(raw: unknown, now: string): ProjectRecord {
|
|
|
222
230
|
archivedAt: nonEmptyString(source.archivedAt) ?? null,
|
|
223
231
|
};
|
|
224
232
|
if (customName) record.customName = customName;
|
|
233
|
+
// Per-project default model: parse strictly so a corrupted pair cannot enter
|
|
234
|
+
// the registry, but never drop a good one (caught live: the field allowlist
|
|
235
|
+
// here silently erased every project's model on each device boot).
|
|
236
|
+
const rawModel = source.model;
|
|
237
|
+
if (rawModel !== undefined && rawModel !== null && rawModel !== "") {
|
|
238
|
+
if (
|
|
239
|
+
rawModel &&
|
|
240
|
+
typeof rawModel === "object" &&
|
|
241
|
+
nonEmptyString((rawModel as Record<string, unknown>).provider) &&
|
|
242
|
+
nonEmptyString((rawModel as Record<string, unknown>).modelId)
|
|
243
|
+
) {
|
|
244
|
+
const model = rawModel as { provider: string; modelId: string };
|
|
245
|
+
record.model = { provider: model.provider, modelId: model.modelId };
|
|
246
|
+
}
|
|
247
|
+
}
|
|
225
248
|
return record;
|
|
226
249
|
}
|
|
227
250
|
|
|
@@ -427,6 +450,15 @@ export class ProjectRegistry {
|
|
|
427
450
|
else next.customName = customName;
|
|
428
451
|
}
|
|
429
452
|
if ("labels" in patch) next.labels = normaliseLabels(patch.labels ?? []);
|
|
453
|
+
if ("model" in patch) {
|
|
454
|
+
if (patch.model === "" || patch.model === undefined) delete next.model;
|
|
455
|
+
else {
|
|
456
|
+
const { provider, modelId } = patch.model;
|
|
457
|
+
if (typeof provider !== "string" || !provider.trim() || typeof modelId !== "string" || !modelId.trim())
|
|
458
|
+
throw invalid("model needs a provider and a modelId");
|
|
459
|
+
next.model = { provider: provider.trim(), modelId: modelId.trim() };
|
|
460
|
+
}
|
|
461
|
+
}
|
|
430
462
|
next.updatedAt = this.now();
|
|
431
463
|
staged.set(next.id, next);
|
|
432
464
|
await this.commit(staged);
|
|
@@ -183,11 +183,31 @@ export function v1(
|
|
|
183
183
|
const body = req.body ?? {};
|
|
184
184
|
if (body.customName !== undefined && typeof body.customName !== "string") throw invalid("customName must be a string");
|
|
185
185
|
if (body.labels !== undefined && !Array.isArray(body.labels)) throw invalid("labels must be an array of strings");
|
|
186
|
-
|
|
186
|
+
if (
|
|
187
|
+
body.model !== undefined &&
|
|
188
|
+
body.model !== "" &&
|
|
189
|
+
(typeof body.model?.provider !== "string" || typeof body.model?.modelId !== "string")
|
|
190
|
+
)
|
|
191
|
+
throw invalid('model must be { provider, modelId } or ""');
|
|
192
|
+
res.json(
|
|
193
|
+
await store.updateProject(param(req, "id"), { customName: body.customName, labels: body.labels, model: body.model }),
|
|
194
|
+
);
|
|
187
195
|
}));
|
|
188
196
|
r.post("/projects/:id/archive", route(async (req, res) => res.json(await store.archiveProject(param(req, "id")))));
|
|
189
197
|
r.post("/projects/:id/unarchive", route(async (req, res) => res.json(await store.unarchiveProject(param(req, "id")))));
|
|
190
198
|
|
|
199
|
+
// ---------------------------------------------------------- env vars
|
|
200
|
+
// The daemon's own env file, behind the guarded editor: managed keys are
|
|
201
|
+
// refused, secrets come back masked, and every change needs a restart.
|
|
202
|
+
r.get("/device/env", route(async (_req, res) => res.json(await store.envView())));
|
|
203
|
+
r.post("/device/env", route(async (req, res) => {
|
|
204
|
+
const body = req.body ?? {};
|
|
205
|
+
if (typeof body.key !== "string" || !body.key.trim()) throw invalid("key is required");
|
|
206
|
+
if (typeof body.value !== "string" || !body.value) throw invalid("value is required");
|
|
207
|
+
res.status(201).json(await store.setEnvVar(body.key.trim(), body.value));
|
|
208
|
+
}));
|
|
209
|
+
r.delete("/device/env/:key", route(async (req, res) => res.json(await store.removeEnvVar(param(req, "key")))));
|
|
210
|
+
|
|
191
211
|
// ---------------------------------------------------- notifications
|
|
192
212
|
// Outbound fan-out (webhook/ntfy). Configured here, delivered by the device.
|
|
193
213
|
r.get("/notify/sinks", (_req, res) => res.json({ sinks: store.notifySinkList() }));
|