my-durable 0.0.70 → 0.0.72
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/archived.ts +12 -8
- package/apps/dpi-backend/src/backup.ts +7 -1
- package/apps/dpi-backend/src/daemon.ts +4 -1
- package/apps/dpi-backend/src/git.ts +37 -3
- package/apps/dpi-backend/src/host-guard.ts +56 -0
- package/apps/dpi-backend/src/main.ts +11 -5
- package/apps/dpi-backend/src/store.ts +30 -1
- package/apps/dpi-backend/src/telegram.ts +43 -3
- package/apps/dpi-playground/apps/dpi-playground-fe/src/client/export-bundle.ts +8 -2
- package/apps/dpi-playground/apps/dpi-playground-hub/src/audit.ts +18 -0
- package/apps/dpi-playground/apps/dpi-playground-hub/src/monitor.ts +12 -2
- package/apps/dpi-playground/apps/dpi-playground-hub/src/pairing.ts +15 -0
- package/apps/dpi-playground/apps/dpi-playground-hub/src/proxy.ts +18 -2
- package/apps/dpi-playground/apps/dpi-playground-hub/src/transport.ts +60 -2
- package/apps/dpi-playground/apps/dpi-playground-hub/src/tunnel-transport.ts +15 -2
- package/apps/dpi-sdk/src/node/chunk.ts +10 -3
- package/apps/dpi-sdk/src/node/config.ts +23 -5
- package/apps/dpi-sdk/src/node/drivers.ts +25 -2
- package/apps/dpi-sdk/src/protocol/tunnel.ts +3 -1
- package/apps/dpi-tui/src/app.ts +8 -6
- package/apps/dpi-tui/src/commands.ts +3 -3
- package/apps/dpi-tui/src/main.ts +3 -1
- package/apps/dpi-tui/src/pairing.ts +9 -8
- package/apps/dpi-tui/src/welcome.ts +1 -1
- package/package.json +1 -1
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
*
|
|
25
25
|
* No express, no Store import: the leader wires routes and store calls.
|
|
26
26
|
*/
|
|
27
|
-
import { chmodSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
|
|
27
|
+
import { chmodSync, lstatSync, readFileSync, readdirSync, statSync, writeFileSync, type Dirent } from "node:fs";
|
|
28
28
|
import { mkdir, rename, stat } from "node:fs/promises";
|
|
29
29
|
import { basename, join } from "node:path";
|
|
30
30
|
import { DatabaseSync } from "node:sqlite";
|
|
@@ -179,19 +179,23 @@ function bundleStats(bundleDir: string): { turns: number; lastMessageAt: number
|
|
|
179
179
|
}
|
|
180
180
|
|
|
181
181
|
/** Recursive size of a bundle dir; 0 when unreadable. Symlinks are not followed (lstat-free stat on entries we can read). */
|
|
182
|
-
function dirBytes(dir: string): number {
|
|
182
|
+
function dirBytes(dir: string, depth = 0): number {
|
|
183
|
+
// R16 (run-2 h8): listArchived must never throw — statSync FOLLOWS symlinks,
|
|
184
|
+
// so a planted symlink loop (a->b, b->a) blew the stack. Lstat never
|
|
185
|
+
// follows; the depth cap bounds hostile deep trees. Symlinked entries are
|
|
186
|
+
// skipped (not sizeable), matching gc.ts.
|
|
183
187
|
let total = 0;
|
|
184
|
-
let
|
|
188
|
+
let entries: Dirent[];
|
|
185
189
|
try {
|
|
186
|
-
|
|
190
|
+
entries = readdirSync(dir, { withFileTypes: true });
|
|
187
191
|
} catch {
|
|
188
192
|
return 0;
|
|
189
193
|
}
|
|
190
|
-
|
|
194
|
+
if (depth >= 64) return total;
|
|
195
|
+
for (const e of entries) {
|
|
191
196
|
try {
|
|
192
|
-
|
|
193
|
-
if (
|
|
194
|
-
else if (s.isFile()) total += s.size;
|
|
197
|
+
if (e.isDirectory()) total += dirBytes(join(dir, e.name), depth + 1);
|
|
198
|
+
else if (e.isFile()) total += lstatSync(join(dir, e.name)).size;
|
|
195
199
|
} catch {
|
|
196
200
|
// broken symlink / vanished entry: not sizeable, not fatal
|
|
197
201
|
}
|
|
@@ -53,6 +53,8 @@ const describeError = (error: unknown) => (error instanceof Error ? error.messag
|
|
|
53
53
|
|
|
54
54
|
/** The in-memory zip build is capped so `createBackup` cannot balloon the device's RAM. */
|
|
55
55
|
export const MAX_BACKUP_BYTES = 256 * 1024 * 1024;
|
|
56
|
+
/** R17: how much of an entry-0 manifest may ride free of the total cap (real manifests are ~150 bytes). */
|
|
57
|
+
const MANIFEST_ALLOWANCE_BYTES = 64 * 1024;
|
|
56
58
|
/** `ensurePrivateDir` (dpi-sdk) is synchronous and not injectable; the io carries the same 0700/0600 rule instead. */
|
|
57
59
|
const DIR_MODE = 0o700;
|
|
58
60
|
const FILE_MODE = 0o600;
|
|
@@ -383,8 +385,12 @@ export function readZipEntries(data: Uint8Array): ZipArchiveEntry[] {
|
|
|
383
385
|
// backup ceiling — a pile of individually-legal entries must not add up
|
|
384
386
|
// to an unbounded restore either. Entry 0 is the writer's own manifest,
|
|
385
387
|
// which the write-side budget (walkHome) never counts, so a ceiling-sized
|
|
386
|
-
// home must stay restorable (R15 cold review P2-1).
|
|
388
|
+
// home must stay restorable (R15 cold review P2-1). R17 (run-3 h2): the
|
|
389
|
+
// exemption is now BOUNDED to a manifest-plausible allowance (the real
|
|
390
|
+
// manifest is a fixed ~150-byte shape) — a hostile entry-0 declaring the
|
|
391
|
+
// full 256 MiB used to ride free and double the retained ceiling.
|
|
387
392
|
if (i > 0 || name !== "manifest.json") totalDeclared += uncompressedSize;
|
|
393
|
+
else totalDeclared += Math.max(0, uncompressedSize - MANIFEST_ALLOWANCE_BYTES);
|
|
388
394
|
if (totalDeclared > MAX_BACKUP_BYTES) {
|
|
389
395
|
throw bad(`archive declares more than ${MAX_BACKUP_BYTES} bytes of entries`);
|
|
390
396
|
}
|
|
@@ -94,8 +94,11 @@ export function cleanChildEnv(env: Record<string, string | undefined>): NodeJS.P
|
|
|
94
94
|
const q = (s: string) => `"${s.replaceAll('"', "")}"`;
|
|
95
95
|
|
|
96
96
|
export function systemdUnit(o: { node: string; dpi: string; env: Record<string, string> }): string {
|
|
97
|
+
// R16 (run-2 h12): a CR/LF inside a value would start a new unit directive;
|
|
98
|
+
// collapse to spaces (the daemon writes its own managed values, but the unit
|
|
99
|
+
// file is the trust boundary — sanitize at the sink).
|
|
97
100
|
const envLines = Object.entries(o.env)
|
|
98
|
-
.map(([k, v]) => `Environment="${k}=${v.replaceAll('"', "")}"`)
|
|
101
|
+
.map(([k, v]) => `Environment="${k}=${v.replaceAll('"', "").replace(/[\r\n]+/g, " ")}"`)
|
|
99
102
|
.join("\n");
|
|
100
103
|
return `[Unit]
|
|
101
104
|
Description=Durable Pi device daemon
|
|
@@ -59,8 +59,40 @@ const gitPaths = (paths: string[]): string[] => paths.map(gitPath);
|
|
|
59
59
|
|
|
60
60
|
/** Child-process options, exported so a test can assert the Windows console
|
|
61
61
|
* window stays hidden: a daemon that polls git must never flash a terminal. */
|
|
62
|
-
|
|
63
|
-
|
|
62
|
+
/**
|
|
63
|
+
* R17 (run-3 h1 hardening): git/gh children run -C agent-writable repos where
|
|
64
|
+
* hooks/config are plantable. The daemon's process.env carries DPI_TOKEN
|
|
65
|
+
* (loadEnvFile) which shellEnv deliberately strips from agent processes —
|
|
66
|
+
* mirror that allowlist here so the token (and any future backend.env secret)
|
|
67
|
+
* never rides into repo-controlled hook environments.
|
|
68
|
+
*/
|
|
69
|
+
const CHILD_ENV_ALLOWLIST = ["PATH", "HOME", "USER", "SHELL", "TMPDIR", "LANG", "TERM", "GIT_SSH_COMMAND", "SSH_AUTH_SOCK"];
|
|
70
|
+
// execFile `env` REPLACES the whole environment, and on win32 git/gh resolve
|
|
71
|
+
// home (USERPROFILE chain), config (APPDATA), temp (TEMP/TMP) and TLS
|
|
72
|
+
// (SystemRoot) from these — without them commit identity and gh auth break.
|
|
73
|
+
const WIN32_CHILD_ENV_ALLOWLIST = [
|
|
74
|
+
...CHILD_ENV_ALLOWLIST,
|
|
75
|
+
"SYSTEMROOT", "SYSTEMDRIVE", "COMSPEC", "PATHEXT",
|
|
76
|
+
"TEMP", "TMP", "USERPROFILE", "HOMEDRIVE", "HOMEPATH",
|
|
77
|
+
"APPDATA", "LOCALAPPDATA", "PROGRAMFILES", "PROGRAMDATA",
|
|
78
|
+
];
|
|
79
|
+
const childEnv = (): NodeJS.ProcessEnv => {
|
|
80
|
+
const allow = process.platform === "win32" ? WIN32_CHILD_ENV_ALLOWLIST : CHILD_ENV_ALLOWLIST;
|
|
81
|
+
return Object.fromEntries(allow.flatMap((k) => (process.env[k] ? [[k, process.env[k]]] : [])));
|
|
82
|
+
}
|
|
83
|
+
export const GIT_EXEC_OPTS = (timeout: number) => ({
|
|
84
|
+
timeout,
|
|
85
|
+
maxBuffer: 8 * 1024 * 1024,
|
|
86
|
+
windowsHide: true,
|
|
87
|
+
env: childEnv(),
|
|
88
|
+
});
|
|
89
|
+
export const GH_EXEC_OPTS = (cwd: string, timeout: number) => ({
|
|
90
|
+
cwd,
|
|
91
|
+
timeout,
|
|
92
|
+
maxBuffer: 4 * 1024 * 1024,
|
|
93
|
+
windowsHide: true,
|
|
94
|
+
env: childEnv(),
|
|
95
|
+
});
|
|
64
96
|
|
|
65
97
|
/** Test seam for counting/driving spawns: `node:child_process`'s ESM namespace
|
|
66
98
|
* is not redefinable, so `mock.method` cannot reach `execFile`. Pass nothing
|
|
@@ -428,7 +460,9 @@ export type GitOp =
|
|
|
428
460
|
| "pr-comment";
|
|
429
461
|
|
|
430
462
|
/** Plain string an arg may never contain — we build argv ourselves anyway. */
|
|
431
|
-
|
|
463
|
+
// R16 (run-2 h6): a leading dash would turn the ref into a git OPTION
|
|
464
|
+
// (`push -u origin --mirror`); refuse the whole ref instead.
|
|
465
|
+
const safeRef = (s: string) => /^[\w./@+-]+$/.test(s) && !s.startsWith("-") && !s.includes("..");
|
|
432
466
|
|
|
433
467
|
/** Run one whitelisted git operation. Every arg is ours; callers only pick names. */
|
|
434
468
|
export async function gitOp(
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import type { RequestHandler } from "express";
|
|
2
|
+
import { hostname, networkInterfaces } from "node:os";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Operator-supplied extra Host spellings (comma-separated, name or name:port;
|
|
6
|
+
* a bare name inherits our port). Rebind-safe by construction: the operator
|
|
7
|
+
* typed these names for THIS device.
|
|
8
|
+
*/
|
|
9
|
+
export function extraHosts(port: number, env: NodeJS.ProcessEnv = process.env): string[] {
|
|
10
|
+
const raw = env.DPI_EXTRA_HOSTS ?? "";
|
|
11
|
+
return raw
|
|
12
|
+
.split(",")
|
|
13
|
+
.map((h) => h.trim().toLowerCase())
|
|
14
|
+
.filter(Boolean)
|
|
15
|
+
.map((h) => (h.includes(":") || h.startsWith("[") ? h : `${h}:${port}`));
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* R16 (run-2 h1 NV close): the enrollment surface is unauthenticated, and its
|
|
20
|
+
* x-dpi-pair custom header only forces a CORS preflight on FOREIGN origins —
|
|
21
|
+
* a DNS-rebind page (evil.com re-resolving to this device's LAN IP:port) makes
|
|
22
|
+
* every fetch same-origin from the browser's point of view, so the preflight
|
|
23
|
+
* guard does not see it. The Host header survives rebinding untouched: it
|
|
24
|
+
* still says evil.com. Mirror the hub's 421 guard (guard.ts): only hosts this
|
|
25
|
+
* device actually serves may talk to the unauthenticated routes.
|
|
26
|
+
*/
|
|
27
|
+
export function hostAllowlist(port: number, env: NodeJS.ProcessEnv = process.env): Set<string> {
|
|
28
|
+
const short = hostname().toLowerCase().replace(/\.local$/, "");
|
|
29
|
+
const hosts = new Set([
|
|
30
|
+
`localhost:${port}`,
|
|
31
|
+
`127.0.0.1:${port}`,
|
|
32
|
+
`[::1]:${port}`,
|
|
33
|
+
`${short}:${port}`,
|
|
34
|
+
// mDNS spelling resolves to this machine itself — rebind-safe (the Pi
|
|
35
|
+
// access style: pi.local:4780/pair must not 421).
|
|
36
|
+
`${short}.local:${port}`,
|
|
37
|
+
...extraHosts(port, env),
|
|
38
|
+
]);
|
|
39
|
+
for (const addresses of Object.values(networkInterfaces()))
|
|
40
|
+
for (const a of addresses ?? []) {
|
|
41
|
+
if (a.family === "IPv4") hosts.add(`${a.address}:${port}`);
|
|
42
|
+
else if (a.family === "IPv6") hosts.add(`[${a.address}]:${port}`);
|
|
43
|
+
}
|
|
44
|
+
return hosts;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function hostGuard(allowed: Set<string>): RequestHandler {
|
|
48
|
+
return (req, res, next) => {
|
|
49
|
+
const host = (req.headers.host ?? "").toLowerCase();
|
|
50
|
+
if (!allowed.has(host))
|
|
51
|
+
return void res
|
|
52
|
+
.status(421)
|
|
53
|
+
.json({ error: { code: "invalid", message: `Unknown Host header: ${host}` } });
|
|
54
|
+
next();
|
|
55
|
+
};
|
|
56
|
+
}
|
|
@@ -9,6 +9,7 @@ import { loadConfig, deviceHome } from "./config.js";
|
|
|
9
9
|
import { Store, PACKAGE_VERSION } from "./store.js";
|
|
10
10
|
import { installCrashHandlers } from "./crash.js";
|
|
11
11
|
import { bearerAuth } from "./auth.js";
|
|
12
|
+
import { hostAllowlist, hostGuard } from "./host-guard.js";
|
|
12
13
|
import { errorMiddleware } from "./errors.js";
|
|
13
14
|
import { v1 } from "./routes.js";
|
|
14
15
|
import { DevicePairing } from "./pairing.js";
|
|
@@ -73,10 +74,15 @@ crashStore = store;
|
|
|
73
74
|
|
|
74
75
|
const app = express();
|
|
75
76
|
app.disable("x-powered-by");
|
|
76
|
-
|
|
77
|
+
// R16 (run-2 h1): DNS rebinding makes the enrollment surface same-origin from
|
|
78
|
+
// the browser's view, defeating the x-dpi-pair preflight guard. Only hosts
|
|
79
|
+
// this device serves (loopback + own interfaces, all with our port) may talk
|
|
80
|
+
// to anything unauthenticated; everything else is misdirected.
|
|
81
|
+
const unauthHostGuard = hostGuard(hostAllowlist(config.port));
|
|
82
|
+
app.get("/healthz", unauthHostGuard, (_req, res) => res.json({ ok: true }));
|
|
77
83
|
// The base URL is what people type first; a JSON 404 reads like a broken
|
|
78
84
|
// daemon. Land them on the one real page (unpaired: enroll; paired: status).
|
|
79
|
-
app.get("/", (_req, res) => res.redirect("/pair"));
|
|
85
|
+
app.get("/", unauthHostGuard, (_req, res) => res.redirect("/pair"));
|
|
80
86
|
const pairing = new DevicePairing(store, config.home, config.name, process.env.DPI_HUB_URL, {
|
|
81
87
|
// Forced hub change (P-5): once the new pairing is persisted the OLD
|
|
82
88
|
// connector is stopped — never two live tunnels for one device, and the old
|
|
@@ -115,8 +121,8 @@ const pairEnrollGuard = (req: Request, res: Response, next: NextFunction) => {
|
|
|
115
121
|
.json({ error: { code: "forbidden", message: "missing x-dpi-pair header" } });
|
|
116
122
|
next();
|
|
117
123
|
};
|
|
118
|
-
app.get("/pair", (_req, res) => res.type("html").send(PAIR_PAGE_HTML));
|
|
119
|
-
app.get("/v1/pair-enroll", pairEnrollGuard, (_req, res) => {
|
|
124
|
+
app.get("/pair", unauthHostGuard, (_req, res) => res.type("html").send(PAIR_PAGE_HTML));
|
|
125
|
+
app.get("/v1/pair-enroll", unauthHostGuard, pairEnrollGuard, (_req, res) => {
|
|
120
126
|
const s = pairing.status();
|
|
121
127
|
res.json({
|
|
122
128
|
state: s.state,
|
|
@@ -126,7 +132,7 @@ app.get("/v1/pair-enroll", pairEnrollGuard, (_req, res) => {
|
|
|
126
132
|
lastError: s.lastError,
|
|
127
133
|
});
|
|
128
134
|
});
|
|
129
|
-
app.post("/v1/pair-enroll", pairEnrollGuard, express.json({ limit: "8kb" }), (req, res) => {
|
|
135
|
+
app.post("/v1/pair-enroll", unauthHostGuard, pairEnrollGuard, express.json({ limit: "8kb" }), (req, res) => {
|
|
130
136
|
void (async () => {
|
|
131
137
|
const s = pairing.status();
|
|
132
138
|
if (s.state === "paired")
|
|
@@ -80,6 +80,7 @@ import { NotifySinks, type DeliveryResult, type SinkInput, type SinkRecord } fro
|
|
|
80
80
|
import { zipSync, EXPORT_RAW_LIMIT_BYTES, type ZipEntry } from "./zip.js";
|
|
81
81
|
import { salvageFailureNote, salvageSessionDb } from "./salvage.js";
|
|
82
82
|
import { mkdirSync, writeFileSync, readFileSync, unlinkSync, readdirSync, renameSync, statSync } from "node:fs";
|
|
83
|
+
import { lstat } from "node:fs/promises";
|
|
83
84
|
import { ensurePrivateDir } from "../../dpi-sdk/src/node/private-dir.js";
|
|
84
85
|
import { join, dirname, relative, resolve, sep } from "node:path";
|
|
85
86
|
import { homedir, hostname, platform } from "node:os";
|
|
@@ -1016,7 +1017,29 @@ export class Store {
|
|
|
1016
1017
|
// ancestor was found at all, judging the raw spelling lexically would
|
|
1017
1018
|
// resurrect the exact symlink escape this walk exists to close.
|
|
1018
1019
|
if (resolvedAncestor === undefined) throw invalid("path must live under a start dir");
|
|
1019
|
-
|
|
1020
|
+
// R17 (run-3 h1): lstat every re-appended tail component. The walk only
|
|
1021
|
+
// calls realpath, which cannot see a DANGLING symlink — a link component
|
|
1022
|
+
// pointing at a nonexistent path would ride the tail verbatim and be
|
|
1023
|
+
// judged lexically. Any symlink in the tail is resolved-and-rejudged;
|
|
1024
|
+
// a dangling one is refused (fail closed on what the walk cannot see).
|
|
1025
|
+
let walked = resolvedAncestor;
|
|
1026
|
+
for (const part of tail) {
|
|
1027
|
+
const next = join(walked, part);
|
|
1028
|
+
let isLink = false;
|
|
1029
|
+
try {
|
|
1030
|
+
isLink = (await lstat(next)).isSymbolicLink();
|
|
1031
|
+
} catch {
|
|
1032
|
+
isLink = false; // plain missing component: fine, the path is new
|
|
1033
|
+
}
|
|
1034
|
+
if (isLink) {
|
|
1035
|
+
const linked = await realpath(next).catch(() => undefined);
|
|
1036
|
+
if (linked === undefined) throw invalid("path must live under a start dir"); // dangling link: refuse
|
|
1037
|
+
walked = linked; // existing link target: continue the walk from truth
|
|
1038
|
+
} else {
|
|
1039
|
+
walked = next;
|
|
1040
|
+
}
|
|
1041
|
+
}
|
|
1042
|
+
candidate = walked;
|
|
1020
1043
|
}
|
|
1021
1044
|
if (!this.underRoots(candidate, await this.startDirRoots())) throw invalid("path must live under a start dir");
|
|
1022
1045
|
return candidate;
|
|
@@ -1279,12 +1302,18 @@ export class Store {
|
|
|
1279
1302
|
}
|
|
1280
1303
|
|
|
1281
1304
|
async createGraph(body: Record<string, unknown>): Promise<GraphRecord> {
|
|
1305
|
+
// R16 (run-2 h6 parity): sessions refuse a bad cwd up-front; graphs ran
|
|
1306
|
+
// confined only at run time. Same rule at mutation time.
|
|
1307
|
+
if (typeof body?.cwd === "string" && body.cwd.trim())
|
|
1308
|
+
await this.assertSessionCwdAllowed(normaliseCwd(body.cwd));
|
|
1282
1309
|
const created = await this.graphs.create(body as never);
|
|
1283
1310
|
this.notify();
|
|
1284
1311
|
return created;
|
|
1285
1312
|
}
|
|
1286
1313
|
|
|
1287
1314
|
async updateGraph(id: string, body: Record<string, unknown>): Promise<GraphRecord> {
|
|
1315
|
+
if (typeof body?.cwd === "string" && body.cwd.trim())
|
|
1316
|
+
await this.assertSessionCwdAllowed(normaliseCwd(body.cwd));
|
|
1288
1317
|
const updated = await this.graphs.update(id, body as never);
|
|
1289
1318
|
this.notify();
|
|
1290
1319
|
return updated;
|
|
@@ -182,7 +182,7 @@ export interface TelegramRegistryFile {
|
|
|
182
182
|
codes: TelegramBindCode[];
|
|
183
183
|
}
|
|
184
184
|
|
|
185
|
-
export type TelegramBridgeErrorCode = "invalid";
|
|
185
|
+
export type TelegramBridgeErrorCode = "invalid" | "registry_changed";
|
|
186
186
|
|
|
187
187
|
/** Typed failure for the mutation paths (`bind`) so a UI can answer without string matching. */
|
|
188
188
|
export class TelegramBridgeError extends Error {
|
|
@@ -465,6 +465,11 @@ export class TelegramBridge {
|
|
|
465
465
|
targetId = sessionId;
|
|
466
466
|
}
|
|
467
467
|
return this.run(async () => {
|
|
468
|
+
// R17 (run-3 h4): the CLI is the SECOND writer — re-read the registry
|
|
469
|
+
// (adopt foreign state) before snapshotting, so a daemon commit that
|
|
470
|
+
// landed since open() is not clobbered by our persist CAS.
|
|
471
|
+
if (!(await this.syncForeign()))
|
|
472
|
+
throw new TelegramBridgeError("registry_changed", `registry ${this.filePath} is missing/unreadable; refusing to bind`);
|
|
468
473
|
const now = this.now();
|
|
469
474
|
const draft = this.snapshot();
|
|
470
475
|
draft.codes = draft.codes.filter((code) => Date.parse(code.expiresAt) > now); // prune the dead ones
|
|
@@ -486,6 +491,8 @@ export class TelegramBridge {
|
|
|
486
491
|
/** Remove the first binding whose chat id starts with `chatPrefix`; returns the chat id, or undefined when none matched. */
|
|
487
492
|
async unbind(chatPrefix: string): Promise<number | undefined> {
|
|
488
493
|
return this.run(async () => {
|
|
494
|
+
// R17 (run-3 h4): same second-writer discipline as bind().
|
|
495
|
+
if (!(await this.syncForeign())) return undefined;
|
|
489
496
|
const draft = this.snapshot();
|
|
490
497
|
const hit = draft.chats.find((binding) => String(binding.chatId).startsWith(chatPrefix));
|
|
491
498
|
if (hit === undefined) return undefined;
|
|
@@ -598,7 +605,23 @@ export class TelegramBridge {
|
|
|
598
605
|
*/
|
|
599
606
|
private async syncForeign(): Promise<boolean> {
|
|
600
607
|
try {
|
|
601
|
-
|
|
608
|
+
// R17 (run-3 h4): an ABSENT registry is either a FRESH device (we have
|
|
609
|
+
// never known a registry: registryText null — load()'s "fresh device"
|
|
610
|
+
// semantics) or the operator revoking by removal while the daemon runs
|
|
611
|
+
// (or an unreadable file: exists() maps every stat failure to absent).
|
|
612
|
+
// Fresh → adopt the empty state and continue (bind works, no bindings
|
|
613
|
+
// exist to authorize anything). Known-then-gone → fail CLOSED: no
|
|
614
|
+
// dispatch on stale memory, and no persist either — a commit would
|
|
615
|
+
// resurrect the deleted file with the revoked bindings.
|
|
616
|
+
if (!(await this.io.exists(this.filePath))) {
|
|
617
|
+
if (this.registryText === null) {
|
|
618
|
+
this.adopt({ version: TELEGRAM_REGISTRY_VERSION, offset: this.offset, chats: [], codes: [] });
|
|
619
|
+
return true; // fresh: nothing to adopt, nothing to clobber
|
|
620
|
+
}
|
|
621
|
+
this.mainIsGood = false; // an absent main must not be "refreshed" into .bak
|
|
622
|
+
this.warn(`registry ${this.filePath} vanished; skipping the update (no dispatch, no persist)`);
|
|
623
|
+
return false;
|
|
624
|
+
}
|
|
602
625
|
const text = await this.io.readFile(this.filePath);
|
|
603
626
|
if (text === this.registryText) return true; // still our own last write
|
|
604
627
|
const file = coerceRegistry(JSON.parse(text), this.now());
|
|
@@ -609,6 +632,7 @@ export class TelegramBridge {
|
|
|
609
632
|
// Fail CLOSED (R15 cold review P3-1): with an unreadable/unparseable
|
|
610
633
|
// registry the in-memory bindings cannot be trusted to reflect the
|
|
611
634
|
// operator's intent — authorize nothing until the file is healthy.
|
|
635
|
+
this.mainIsGood = false; // the next persist must NOT bake these bytes into .bak
|
|
612
636
|
this.warn(`could not re-read ${this.filePath} before dispatch; skipping the update`, error);
|
|
613
637
|
return false;
|
|
614
638
|
}
|
|
@@ -639,6 +663,22 @@ export class TelegramBridge {
|
|
|
639
663
|
* new bytes through the io's atomic write, then 0600.
|
|
640
664
|
*/
|
|
641
665
|
private async persist(draft: TelegramRegistryFile): Promise<void> {
|
|
666
|
+
// R17 (run-3 h4): the registry has TWO writers (daemon + dpi telegram
|
|
667
|
+
// CLI). Write-after-read validation: if the file's bytes changed since we
|
|
668
|
+
// last saw them, our snapshot is stale — writing it would clobber the
|
|
669
|
+
// foreign commit (un-spend a code, revert a /stop). Fail loudly instead.
|
|
670
|
+
if (this.registryText !== null && (await this.io.exists(this.filePath))) {
|
|
671
|
+
const current = await this.io.readFile(this.filePath);
|
|
672
|
+
if (current !== this.registryText) {
|
|
673
|
+
this.mainIsGood = false;
|
|
674
|
+
throw new TelegramBridgeError(
|
|
675
|
+
"registry_changed",
|
|
676
|
+
`registry changed under us (foreign write); re-open or retry — refusing to clobber ${this.filePath}`,
|
|
677
|
+
);
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
// registryText === null means no known baseline (fresh device or the
|
|
681
|
+
// load()-time recovery rewrite) — those writes are legitimate.
|
|
642
682
|
if (this.mainIsGood && (await this.io.exists(this.filePath))) {
|
|
643
683
|
try {
|
|
644
684
|
const previous = await this.io.readFile(this.filePath);
|
|
@@ -724,10 +764,10 @@ export class TelegramBridge {
|
|
|
724
764
|
/** Acknowledge first (persist the new offset), then handle. Never both-half-heartedly. */
|
|
725
765
|
private async handle(update: TelegramUpdate): Promise<void> {
|
|
726
766
|
const synced = await this.syncForeign();
|
|
767
|
+
if (!synced) return; // acknowledged (Telegram will redeliver), NOT authorized and NOT persisted — a stale snapshot must never become file truth again
|
|
727
768
|
await this.commit((draft) => {
|
|
728
769
|
draft.offset = Math.max(draft.offset, update.updateId + 1);
|
|
729
770
|
});
|
|
730
|
-
if (!synced) return; // acknowledged, but NOT authorized on stale state
|
|
731
771
|
if (!update.message) return; // non-message or non-text: acknowledged, ignored
|
|
732
772
|
await this.dispatch(
|
|
733
773
|
update.message.chatId,
|
|
@@ -22,8 +22,14 @@ export type BundleTarget = Ref<{
|
|
|
22
22
|
export function downloadBundle(r: BundleFile) {
|
|
23
23
|
const a = document.createElement("a");
|
|
24
24
|
// slice() normalizes the buffer to a plain ArrayBuffer (BlobPart typing, TS 5.7).
|
|
25
|
-
|
|
26
|
-
a
|
|
25
|
+
// R16 (run-2 h13): the device is untrusted at the operator origin — the FE
|
|
26
|
+
// authors the label itself (mirrors hub delta-6): zip MIME is a literal and
|
|
27
|
+
// the filename is charset-folded, extension-stripped is unnecessary (the
|
|
28
|
+
// honest device contract is *.bundle.zip) but the cap keeps it sane.
|
|
29
|
+
let stem = (r.filename || "device-response").replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 80) || "device-response";
|
|
30
|
+
if (/\.zip$/i.test(r.filename) && !/\.zip$/i.test(stem)) stem = `${stem.slice(0, 76)}.zip`;
|
|
31
|
+
a.href = URL.createObjectURL(new Blob([r.bytes.slice()], { type: "application/zip" }));
|
|
32
|
+
a.download = stem;
|
|
27
33
|
a.click();
|
|
28
34
|
URL.revokeObjectURL(a.href);
|
|
29
35
|
}
|
|
@@ -105,6 +105,24 @@ export function scrubSecrets(value: string): string {
|
|
|
105
105
|
out = out.replace(/([?&]code=)[A-Za-z0-9_-]+/g, "$1<redacted>");
|
|
106
106
|
// v2 offer links: the secret IS the #offer= fragment payload — redact it wherever a URL shows up.
|
|
107
107
|
out = out.replace(/(#offer=)[A-Za-z0-9_-]+/g, "$1<redacted>");
|
|
108
|
+
// R16 (run-2 h7) + R17 (run-3 h10): a denied request lands the FULL share
|
|
109
|
+
// capability token in audit path samples — the token IS the secret. The
|
|
110
|
+
// prefix spelling is ATTACKER-CONTROLLED (/share/, /api/shares/, /Share/,
|
|
111
|
+
// /%73hare/...), so anchor on a *share-shaped* path segment (case-blind,
|
|
112
|
+
// percent-encoding tolerated) followed by the 20-32-char token run — not on
|
|
113
|
+
// any one literal prefix. Bare 20-32-char values elsewhere (audit enums
|
|
114
|
+
// like "foreign_subscription") stay readable.
|
|
115
|
+
out = out.replace(
|
|
116
|
+
/(\/[a-z0-9%]*shares?\/)[A-Za-z0-9_-]{20,32}(?![A-Za-z0-9_-])/gi,
|
|
117
|
+
"$1<redacted>",
|
|
118
|
+
);
|
|
119
|
+
// Encoded spellings (/%73hare/) hide the literal "share" — any
|
|
120
|
+
// percent-bearing path segment followed by a token-shaped run is treated
|
|
121
|
+
// the same.
|
|
122
|
+
out = out.replace(
|
|
123
|
+
/(\/[^\s"']*%[^\s"']*\/)[A-Za-z0-9_-]{20,32}(?![A-Za-z0-9_-])/gi,
|
|
124
|
+
"$1<redacted>",
|
|
125
|
+
);
|
|
108
126
|
// Credential material without its prefix (slices, echo): 43-char base64url runs.
|
|
109
127
|
out = out.replace(/(?<![A-Za-z0-9_-])[A-Za-z0-9_-]{43}(?![A-Za-z0-9_-])/g, "<redacted>");
|
|
110
128
|
// Pairing codes as standalone values ("code":"AB2C7DEF" / "ABCD2345EF67") but not ordinary words.
|
|
@@ -226,10 +226,20 @@ export class DeviceMonitor {
|
|
|
226
226
|
continue;
|
|
227
227
|
}
|
|
228
228
|
try {
|
|
229
|
+
// R17 (run-3 h8): abort the losing probe — a timed-out fetch keeps
|
|
230
|
+
// buffering (up to REST_TIMEOUT_MS) while the backoff loop starts the
|
|
231
|
+
// next one, multiplying an unbounded read. The per-probe controller
|
|
232
|
+
// also stops reading the moment the race is lost.
|
|
233
|
+
const probeCtl = new AbortController();
|
|
234
|
+
const onOuterAbort = () => probeCtl.abort();
|
|
235
|
+
signal?.addEventListener("abort", onOuterAbort, { once: true });
|
|
229
236
|
const probe = await Promise.race([
|
|
230
|
-
transport.request({ method: "GET", path: "/v1/device" }, signal),
|
|
237
|
+
transport.request({ method: "GET", path: "/v1/device" }, probeCtl.signal),
|
|
231
238
|
sleep(6_000, signal).then(() => null),
|
|
232
|
-
])
|
|
239
|
+
]).finally(() => {
|
|
240
|
+
signal?.removeEventListener("abort", onOuterAbort);
|
|
241
|
+
probeCtl.abort();
|
|
242
|
+
});
|
|
233
243
|
if (probe === null) throw new DpiError("offline", `Probe timeout for ${device.url}`);
|
|
234
244
|
if (probe.status === 401)
|
|
235
245
|
throw new DpiError("unauthorized", "Device rejected the token", 401);
|
|
@@ -527,6 +527,21 @@ export class PairingService {
|
|
|
527
527
|
return this.fail(409, "code_in_use", "This code is reserved for another enrollment");
|
|
528
528
|
if (existing.cancelled) return this.fail(410, "enrollment_cancelled", "Enrollment cancelled");
|
|
529
529
|
if (now >= live.expiresAt) return this.fail(410, "code_expired", "Pairing code expired");
|
|
530
|
+
// R16 (run-2 h2 hardening): the dead window. A proof that arrives after
|
|
531
|
+
// NONCE_TTL is refused forever (verify() re-checks the TTL against the
|
|
532
|
+
// ORIGINAL nonceIssuedAt) while the code stays live for minutes — an
|
|
533
|
+
// unverified enrollment could never complete. Same-identity re-entry is
|
|
534
|
+
// exactly the retry signal: mint a fresh nonce for an unverified,
|
|
535
|
+
// unconsumed, stale ceremony. Verified/consumed enrollments keep their
|
|
536
|
+
// nonce (idempotent answer; a consumed nonce is terminal by design).
|
|
537
|
+
if (
|
|
538
|
+
existing.verifiedAt === undefined &&
|
|
539
|
+
!existing.nonceConsumed &&
|
|
540
|
+
now - existing.nonceIssuedAt > NONCE_TTL_MS
|
|
541
|
+
) {
|
|
542
|
+
existing.nonce = randomBytes(32).toString("base64url");
|
|
543
|
+
existing.nonceIssuedAt = now;
|
|
544
|
+
}
|
|
530
545
|
return this.ok({
|
|
531
546
|
type: "pair.challenge",
|
|
532
547
|
v: 1,
|
|
@@ -66,7 +66,21 @@ export function proxy(
|
|
|
66
66
|
{
|
|
67
67
|
method: req.method,
|
|
68
68
|
path,
|
|
69
|
-
|
|
69
|
+
// R16 (run-2 h4): bound the forwarded key to the device schema cap —
|
|
70
|
+
// an over-long key would be schema-rejected on the device and drop
|
|
71
|
+
// the tunnel into reconnect churn. Refuse it cleanly at the edge.
|
|
72
|
+
idempotencyKey: (() => {
|
|
73
|
+
const k = req.get("idempotency-key");
|
|
74
|
+
if (k === undefined) return undefined;
|
|
75
|
+
// R17 (run-3 h8): an EMPTY key would suppress the R9 auto-key
|
|
76
|
+
// derivation and then drop as falsy at frame build — the mutation
|
|
77
|
+
// goes out with NO dedup key at all. Refuse it like the over-long.
|
|
78
|
+
if (k.trim() === "")
|
|
79
|
+
throw new DpiError("invalid", "idempotency-key must not be empty", 400);
|
|
80
|
+
if (k.length > 256)
|
|
81
|
+
throw new DpiError("invalid", "idempotency-key longer than 256 chars", 400);
|
|
82
|
+
return k;
|
|
83
|
+
})(),
|
|
70
84
|
body: req.body ?? {},
|
|
71
85
|
},
|
|
72
86
|
closed.signal,
|
|
@@ -124,7 +138,9 @@ export function proxy(
|
|
|
124
138
|
const disposition = isZip
|
|
125
139
|
? `attachment; filename="${stem}.zip"`
|
|
126
140
|
: 'attachment; filename="device-response.bin"';
|
|
127
|
-
|
|
141
|
+
// R16 (run-2 h4): the zip LABEL is hub-authored — a chunk-sourced
|
|
142
|
+
// contentType has no length bound, so never reflect it verbatim.
|
|
143
|
+
res.type(isZip ? "application/zip" : "application/octet-stream")
|
|
128
144
|
.set("Content-Disposition", disposition)
|
|
129
145
|
.send(payload);
|
|
130
146
|
}
|
|
@@ -8,6 +8,11 @@
|
|
|
8
8
|
*/
|
|
9
9
|
import { DpiClient } from "../../../../dpi-sdk/src/client.js";
|
|
10
10
|
import { DpiError } from "../../../../dpi-sdk/src/errors.js";
|
|
11
|
+
import { validateRestRequest } from "../../../../dpi-sdk/src/protocol/tunnel.js";
|
|
12
|
+
import {
|
|
13
|
+
LOGICAL_MESSAGE_MAX_BYTES,
|
|
14
|
+
REST_PATH_PREFIX,
|
|
15
|
+
} from "../../../../dpi-sdk/src/protocol/limits.js";
|
|
11
16
|
import type { Frame } from "../../../../dpi-sdk/src/api.js";
|
|
12
17
|
import type { DeviceRow } from "../../../../dpi-sdk/src/node/registry.js";
|
|
13
18
|
|
|
@@ -77,6 +82,18 @@ export class LanTransport implements DeviceTransport {
|
|
|
77
82
|
|
|
78
83
|
async request(input: TransportRequest, signal: AbortSignal): Promise<TransportResponse> {
|
|
79
84
|
if (!this.available) throw new DpiError("unauthorized", "LAN device has no URL/token", 0);
|
|
85
|
+
// R16 (run-2 h4 parity): the tunnel dispatcher runs the REST allowlist on
|
|
86
|
+
// every request; the LAN leg must not be the weaker twin — same principal
|
|
87
|
+
// today, but drift here would surface as a hub-frontend-only capability.
|
|
88
|
+
// The tunnel contract carries the /v1 prefix; this leg's paths are already
|
|
89
|
+
// prefix-stripped, so re-attach it for the shared validator.
|
|
90
|
+
const allow = validateRestRequest({
|
|
91
|
+
method: input.method,
|
|
92
|
+
path: input.path.startsWith(REST_PATH_PREFIX)
|
|
93
|
+
? input.path
|
|
94
|
+
: `${REST_PATH_PREFIX}${input.path}`,
|
|
95
|
+
});
|
|
96
|
+
if (!allow.ok) throw new DpiError("invalid", allow.error ?? "path not allowed", 400);
|
|
80
97
|
const timeout = AbortSignal.timeout(REST_TIMEOUT_MS);
|
|
81
98
|
const effective = signal ? AbortSignal.any([signal, timeout]) : timeout;
|
|
82
99
|
const hasBody = !["GET", "HEAD", "DELETE"].includes(input.method);
|
|
@@ -96,11 +113,19 @@ export class LanTransport implements DeviceTransport {
|
|
|
96
113
|
if (signal?.aborted) throw cause;
|
|
97
114
|
throw new DpiError("offline", `Cannot reach ${this.client.baseUrl}`, 0, { cause });
|
|
98
115
|
}
|
|
99
|
-
|
|
116
|
+
// R17 (run-3 h8): size parity with the tunnel leg — the device connector
|
|
117
|
+
// caps its own fetches (16 MiB textual / binary cap) and reassembly
|
|
118
|
+
// budgets bound the tunnel; this leg used to buffer arrayBuffer() with NO
|
|
119
|
+
// cap, so a hostile LAN peer (or compromised device) could OOM the whole
|
|
120
|
+
// hub process. Mirror the connector's capped reader.
|
|
100
121
|
const ct = response.headers.get("content-type") ?? undefined;
|
|
122
|
+
const textual = ct === undefined || TEXTUAL_CT_RE.test(ct);
|
|
123
|
+
const capped = await readBodyCapped(response, textual ? LOGICAL_MESSAGE_MAX_BYTES : BINARY_RESPONSE_MAX_BYTES);
|
|
124
|
+
if (!capped.ok)
|
|
125
|
+
throw new DpiError("invalid", `device answer exceeds ${textual ? "16 MiB" : "12 MB"}`, 413);
|
|
126
|
+
const raw = capped.bytes;
|
|
101
127
|
// Textual responses keep the legacy plain-string shape; binaries are base64-flagged
|
|
102
128
|
// so the proxy can serve bytes byte-exact (R8 binary passthrough).
|
|
103
|
-
const textual = ct === undefined || TEXTUAL_CT_RE.test(ct);
|
|
104
129
|
return {
|
|
105
130
|
status: response.status,
|
|
106
131
|
contentType: ct,
|
|
@@ -134,3 +159,36 @@ export function transportFor(
|
|
|
134
159
|
if (row.transport === "tunnel") return tunnel ? tunnel.dispatcherFor(row) : undefined;
|
|
135
160
|
return new LanTransport(row);
|
|
136
161
|
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* R17 (run-3 h8): the binary cap mirrors the device connector's own reader
|
|
165
|
+
* (tunnel.ts uses 12_000_000 — aligned exactly so a binary that passes one
|
|
166
|
+
* leg never surprises the other).
|
|
167
|
+
*/
|
|
168
|
+
const BINARY_RESPONSE_MAX_BYTES = 12_000_000;
|
|
169
|
+
|
|
170
|
+
async function readBodyCapped(
|
|
171
|
+
res: Response,
|
|
172
|
+
cap: number,
|
|
173
|
+
): Promise<{ ok: true; bytes: Buffer } | { ok: false }> {
|
|
174
|
+
const declared = Number(res.headers.get("content-length"));
|
|
175
|
+
if (Number.isFinite(declared) && declared > cap) {
|
|
176
|
+
await res.body?.cancel().catch(() => {});
|
|
177
|
+
return { ok: false };
|
|
178
|
+
}
|
|
179
|
+
if (!res.body) return { ok: true, bytes: Buffer.alloc(0) };
|
|
180
|
+
const reader = res.body.getReader();
|
|
181
|
+
const parts: Uint8Array[] = [];
|
|
182
|
+
let total = 0;
|
|
183
|
+
for (;;) {
|
|
184
|
+
const { done, value } = await reader.read();
|
|
185
|
+
if (done) break;
|
|
186
|
+
total += value.byteLength;
|
|
187
|
+
if (total > cap) {
|
|
188
|
+
await reader.cancel().catch(() => {});
|
|
189
|
+
return { ok: false };
|
|
190
|
+
}
|
|
191
|
+
parts.push(value);
|
|
192
|
+
}
|
|
193
|
+
return { ok: true, bytes: Buffer.concat(parts) };
|
|
194
|
+
}
|
|
@@ -339,7 +339,17 @@ export class TunnelDispatcher {
|
|
|
339
339
|
idempotentReplay?: unknown;
|
|
340
340
|
}
|
|
341
341
|
| undefined;
|
|
342
|
-
|
|
342
|
+
// R16 (run-2 h3): mirror the inline plain-frame schema caps here — the
|
|
343
|
+
// chunked envelope carries no TypeBox schema, so without this a
|
|
344
|
+
// device could deliver a 1xx/300-599-fractional status or an
|
|
345
|
+
// unbounded contentType string (proxy would reflect it verbatim into
|
|
346
|
+
// a response header).
|
|
347
|
+
if (
|
|
348
|
+
typeof env?.status !== "number" ||
|
|
349
|
+
!Number.isInteger(env.status) ||
|
|
350
|
+
env.status < 200 ||
|
|
351
|
+
env.status > 599
|
|
352
|
+
) {
|
|
343
353
|
p?.resolve({
|
|
344
354
|
status: 502,
|
|
345
355
|
body: {
|
|
@@ -350,7 +360,10 @@ export class TunnelDispatcher {
|
|
|
350
360
|
}
|
|
351
361
|
p?.resolve({
|
|
352
362
|
status: env.status,
|
|
353
|
-
contentType:
|
|
363
|
+
contentType:
|
|
364
|
+
typeof env.contentType === "string" && env.contentType.length <= 256
|
|
365
|
+
? env.contentType
|
|
366
|
+
: undefined,
|
|
354
367
|
body: env.body,
|
|
355
368
|
...(env.bodyEncoding === "base64" ? { bodyEncoding: "base64" as const } : {}),
|
|
356
369
|
...(env.bodyEncoding === "base64"
|
|
@@ -31,7 +31,9 @@ const ENVELOPE_OVERHEAD_BYTES = 256;
|
|
|
31
31
|
|
|
32
32
|
export type ChunkCorrelation =
|
|
33
33
|
| { kind: "tunnel-data"; subscriptionId: string; sub: string }
|
|
34
|
-
|
|
34
|
+
// R16: chunked rest-REQUESTS are a dead direction (removed from DEVICE_TO_HUB
|
|
35
|
+
// and never hub->device) — the correlation surface is rest-response only.
|
|
36
|
+
| { kind: "rest-response"; reqId: string };
|
|
35
37
|
|
|
36
38
|
const correlationKey = (c: ChunkCorrelation) =>
|
|
37
39
|
c.kind === "tunnel-data" ? `data:${c.subscriptionId}` : `${c.kind}:${c.reqId}`;
|
|
@@ -232,10 +234,15 @@ export class ChunkReassembler {
|
|
|
232
234
|
*/
|
|
233
235
|
feed(chunk: TunnelChunk, owns: (correlation: ChunkCorrelation) => boolean): AssemblyOutcome {
|
|
234
236
|
if (chunk.type !== "tunnel-chunk") return { ok: false, error: "chunk: not a chunk frame" };
|
|
235
|
-
|
|
237
|
+
// R16: chunk.kind "rest-request" is a dead direction (direction assert
|
|
238
|
+
// rejects it upstream) — narrow here so the type stays honest.
|
|
239
|
+
const correlation: ChunkCorrelation | null =
|
|
236
240
|
chunk.kind === "tunnel-data"
|
|
237
241
|
? { kind: "tunnel-data", subscriptionId: chunk.subscriptionId, sub: chunk.sub }
|
|
238
|
-
:
|
|
242
|
+
: chunk.kind === "rest-response"
|
|
243
|
+
? { kind: "rest-response", reqId: chunk.reqId }
|
|
244
|
+
: null;
|
|
245
|
+
if (!correlation) return { ok: false, error: "chunk: unsupported chunk kind" };
|
|
239
246
|
const key = correlationKey(correlation);
|
|
240
247
|
const envelope = validateChunkEnvelope(chunk);
|
|
241
248
|
if (!envelope.ok) return { ok: false, error: envelope.error };
|
|
@@ -99,6 +99,16 @@ export function parseNetworkConfig(text: string, file = NETWORK_FILE): NetworkCo
|
|
|
99
99
|
if (!DEVICE_KINDS.includes(kind)) throw Error(`${where}.kind must be one of ${DEVICE_KINDS.join(", ")}`);
|
|
100
100
|
const port = Number(d.port ?? 4780);
|
|
101
101
|
if (!Number.isInteger(port) || port < 1 || port > 65535) throw Error(`${where}.port is invalid`);
|
|
102
|
+
// R17 (run-3 h12): these scalars reach generated shell scripts, backend.env
|
|
103
|
+
// lines and unit/plist content — a newline injected env lines (duplicate
|
|
104
|
+
// DPI_TOKEN/DPI_START_DIRS, last-wins at daemon boot) and quote/$/backtick
|
|
105
|
+
// executed command substitution inside the double-quoted script segments.
|
|
106
|
+
// Refuse control characters and shell metacharacters at parse time.
|
|
107
|
+
const pathish = (v: string, field: string) => {
|
|
108
|
+
if (/[\n\r\0]/.test(v)) throw Error(`${where}.${field} must be a single line`);
|
|
109
|
+
if (/["'`$\\]/.test(v)) throw Error(`${where}.${field} must not contain quotes, $ or backslash`);
|
|
110
|
+
return v;
|
|
111
|
+
};
|
|
102
112
|
const device: NetDevice = {
|
|
103
113
|
id,
|
|
104
114
|
name: typeof d.name === "string" ? d.name : id,
|
|
@@ -106,10 +116,10 @@ export function parseNetworkConfig(text: string, file = NETWORK_FILE): NetworkCo
|
|
|
106
116
|
url: "",
|
|
107
117
|
port,
|
|
108
118
|
node: Number(d.node ?? 24),
|
|
109
|
-
codeDir: typeof d.code_dir === "string" ? d.code_dir : "~/dpi",
|
|
110
|
-
homeDir: typeof d.home_dir === "string" ? d.home_dir : "~/.dpi",
|
|
111
|
-
startDirs: d.start_dirs === undefined ? [DEFAULT_START_DIR] : strList(d.start_dirs, `${where}.start_dirs`),
|
|
112
|
-
host: d.host === undefined ? (kind === "local" ? "127.0.0.1" : "0.0.0.0") : str(d.host, `${where}.host`),
|
|
119
|
+
codeDir: pathish(typeof d.code_dir === "string" ? d.code_dir : "~/dpi", "code_dir"),
|
|
120
|
+
homeDir: pathish(typeof d.home_dir === "string" ? d.home_dir : "~/.dpi", "home_dir"),
|
|
121
|
+
startDirs: d.start_dirs === undefined ? [DEFAULT_START_DIR] : strList(d.start_dirs, `${where}.start_dirs`).map((r: string) => pathish(r, "start_dirs")),
|
|
122
|
+
host: d.host === undefined ? (kind === "local" ? "127.0.0.1" : "0.0.0.0") : pathish(str(d.host, `${where}.host`), "host"),
|
|
113
123
|
envKeys: d.env_keys === undefined ? [] : strList(d.env_keys, `${where}.env_keys`),
|
|
114
124
|
env: {},
|
|
115
125
|
...(typeof d.token_env === "string" ? { tokenEnv: d.token_env } : {}),
|
|
@@ -119,7 +129,15 @@ export function parseNetworkConfig(text: string, file = NETWORK_FILE): NetworkCo
|
|
|
119
129
|
if (d.service !== "launchd" && d.service !== "systemd") throw Error(`${where}.service must be launchd or systemd`);
|
|
120
130
|
device.service = d.service;
|
|
121
131
|
}
|
|
122
|
-
if (kind === "ssh")
|
|
132
|
+
if (kind === "ssh") {
|
|
133
|
+
const target = str(d.ssh, `${where}.ssh`);
|
|
134
|
+
// R17 (run-3 h12): the ssh scalar is a leading argv element — a leading
|
|
135
|
+
// dash would be parsed as an ssh OPTION (e.g. -oProxyCommand=…). Accept
|
|
136
|
+
// only a user@host[:port] shape.
|
|
137
|
+
if (!/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+(:\d+)?$/.test(target))
|
|
138
|
+
throw Error(`${where}.ssh must be user@host[:port] (no options, no metacharacters)`);
|
|
139
|
+
device.ssh = target;
|
|
140
|
+
}
|
|
123
141
|
if (kind === "exe-dev") {
|
|
124
142
|
device.vm = str(d.vm, `${where}.vm`);
|
|
125
143
|
if (!/^[a-z0-9][a-z0-9-]{1,62}$/.test(device.vm)) throw Error(`${where}.vm is not a valid exe.dev name`);
|
|
@@ -110,6 +110,14 @@ async function writeEnv(device: NetDevice, ctx: DriverContext, rotate = false) {
|
|
|
110
110
|
const local = localEnv(ctx.config);
|
|
111
111
|
const missing = device.envKeys.filter((k) => !(local[k] ?? process.env[k]));
|
|
112
112
|
if (missing.length) ctx.log(`warning: ${missing.join(", ")} not found in ${join(ctx.config.root, ".env")} or the environment`);
|
|
113
|
+
for (const [k, v] of Object.entries(device.env))
|
|
114
|
+
if (typeof v !== "string" || !v || /[\n\r]/.test(v))
|
|
115
|
+
ctx.log(`warning: device ${device.id} env ${k} has no value or contains a newline — skipped`);
|
|
116
|
+
// R17 (run-3 h12): config.ts rejects CR/LF in these at parse; the sink
|
|
117
|
+
// guards too so a future field can never reintroduce the line-injection.
|
|
118
|
+
for (const [k, v] of [["DPI_HOST", device.host], ["DPI_START_DIRS", device.startDirs.join(":")]] as const)
|
|
119
|
+
if (/[\n\r]/.test(v))
|
|
120
|
+
throw Error(`device ${device.id}: ${k} value contains a newline — refusing to write backend.env`);
|
|
113
121
|
const home = shPath(device.homeDir);
|
|
114
122
|
const body = [
|
|
115
123
|
`DPI_DEVICE_NAME=${device.id}`,
|
|
@@ -120,7 +128,13 @@ async function writeEnv(device: NetDevice, ctx: DriverContext, rotate = false) {
|
|
|
120
128
|
const v = local[k] ?? process.env[k];
|
|
121
129
|
return v && !/[\n\r]/.test(v) ? [`${k}=${v}`] : [];
|
|
122
130
|
}),
|
|
123
|
-
|
|
131
|
+
// R16 (run-2 h12): env_keys secrets already refuse [\n\r]; plain env:
|
|
132
|
+
// entries get the same guard — a multiline YAML value would inject extra
|
|
133
|
+
// KEY=VALUE lines into backend.env (incl. a duplicate DPI_TOKEN, last
|
|
134
|
+
// wins). Misconfigured values are skipped, mirroring the env_keys branch.
|
|
135
|
+
...Object.entries(device.env).flatMap(([k, v]) =>
|
|
136
|
+
typeof v === "string" && v && !/[\n\r]/.test(v) ? [`${k}=${v}`] : [],
|
|
137
|
+
),
|
|
124
138
|
].join("\n");
|
|
125
139
|
const mkStartDirs = device.startDirs.map((r) => `mkdir -p "${shPath(r)}"`).join("\n");
|
|
126
140
|
await exec(
|
|
@@ -145,6 +159,10 @@ echo "env ok"`,
|
|
|
145
159
|
function fill(template: string, values: Record<string, string>) {
|
|
146
160
|
return template.replace(/__([A-Z_]+)__/g, (m, key: string) => {
|
|
147
161
|
if (!(key in values)) throw Error(`Template placeholder ${m} has no value`);
|
|
162
|
+
// R16 (run-2 h12): these values land in a root-owned systemd unit / a
|
|
163
|
+
// LaunchAgent plist — a newline would inject whole new directives.
|
|
164
|
+
if (/[\n\r]/.test(values[key]))
|
|
165
|
+
throw Error(`Template value for ${key} contains a newline`);
|
|
148
166
|
return values[key];
|
|
149
167
|
});
|
|
150
168
|
}
|
|
@@ -169,7 +187,12 @@ async function installService(device: NetDevice, ctx: DriverContext) {
|
|
|
169
187
|
};
|
|
170
188
|
const deployDir = join(ctx.config.root, "apps/dpi-backend/deploy");
|
|
171
189
|
if (device.service === "launchd") {
|
|
172
|
-
|
|
190
|
+
// R17 (run-3 h12): plist is XML — escape & and < in the values (mirrors
|
|
191
|
+
// daemon.ts launchdPlist) so no new element can be forged.
|
|
192
|
+
const xmlValues = Object.fromEntries(
|
|
193
|
+
Object.entries(values).map(([k, v]) => [k, v.replaceAll("&", "&").replaceAll("<", "<")]),
|
|
194
|
+
);
|
|
195
|
+
const plist = fill(readFileSync(join(deployDir, "dpi-backend.plist"), "utf8"), xmlValues);
|
|
173
196
|
await exec(
|
|
174
197
|
device,
|
|
175
198
|
`P="$HOME/Library/LaunchAgents/${SERVICE_LABEL}.plist"
|
|
@@ -306,7 +306,9 @@ const DEVICE_TO_HUB = new Set([
|
|
|
306
306
|
"tunnel-chunk:tunnel-data",
|
|
307
307
|
"rest-response",
|
|
308
308
|
"tunnel-chunk:rest-response",
|
|
309
|
-
|
|
309
|
+
// R16 (run-2 h3): no producer exists for a chunked rest-request device->hub
|
|
310
|
+
// (route() ignored it silently). Removed instead of dead-allowed: a future
|
|
311
|
+
// device sending one is now an audited direction violation, not drift.
|
|
310
312
|
]);
|
|
311
313
|
|
|
312
314
|
function messageKey(msg: { type: string; action?: string; kind?: string }): string {
|
package/apps/dpi-tui/src/app.ts
CHANGED
|
@@ -653,7 +653,9 @@ export class App {
|
|
|
653
653
|
|
|
654
654
|
/** A long fetch (dirs on a cold tunnel) holds the message line with a ◌ note. */
|
|
655
655
|
setPending(text: string | null) {
|
|
656
|
-
|
|
656
|
+
// R17 (run-3 h5): pending notes interpolate device-sourced paths/names
|
|
657
|
+
// (walkDirs/newSession feed them) — sanitize at the chokepoint.
|
|
658
|
+
this.pendingNote = text === null ? null : sanitizeTerminal(text);
|
|
657
659
|
this.requestRender();
|
|
658
660
|
}
|
|
659
661
|
|
|
@@ -1231,7 +1233,7 @@ export class App {
|
|
|
1231
1233
|
lines.push(
|
|
1232
1234
|
AGENT_TABS.map((t) => (t.id === this.tab ? c.inverse(c.bold(` ${t.label} `)) : c.muted(` ${t.label} `))).join(
|
|
1233
1235
|
c.muted("│"),
|
|
1234
|
-
) + c.muted(rep(" ", Math.max(0, w - 62))) + c.muted(this.model.state.agent.model?.modelId?.split("/").pop() ?? ""),
|
|
1236
|
+
) + c.muted(rep(" ", Math.max(0, w - 62))) + c.muted(sanitizeTerminal(this.model.state.agent.model?.modelId?.split("/").pop() ?? "")),
|
|
1235
1237
|
);
|
|
1236
1238
|
lines.push(c.muted(rep(box.h, w)));
|
|
1237
1239
|
const inner = h - 3;
|
|
@@ -1355,12 +1357,12 @@ export class App {
|
|
|
1355
1357
|
// config tab
|
|
1356
1358
|
const model = this.model.state.agent.model;
|
|
1357
1359
|
const lines = [
|
|
1358
|
-
` ${c.muted("model")} ${c.text(model?.modelId ?? "—")}`,
|
|
1359
|
-
` ${c.muted("provider")} ${c.muted(model?.provider ?? "—")}`,
|
|
1360
|
+
` ${c.muted("model")} ${c.text(sanitizeTerminal(model?.modelId ?? "—"))}`,
|
|
1361
|
+
` ${c.muted("provider")} ${c.muted(sanitizeTerminal(model?.provider ?? "—"))}`,
|
|
1360
1362
|
` ${c.muted("thinking")} ${c.text(String(this.model.state.agent.thinkingLevel ?? "low"))} ${c.muted("(y cycles)")}`,
|
|
1361
1363
|
"",
|
|
1362
|
-
` ${c.muted("device")} ${c.text(this.device.id)} ${c.muted(this.device.url)}`,
|
|
1363
|
-
` ${c.muted("start dirs")} ${c.muted(this.info.startDirs.join(", ").slice(0, w - 18) || "—")}`,
|
|
1364
|
+
` ${c.muted("device")} ${c.text(sanitizeTerminal(this.device.id))} ${c.muted(sanitizeTerminal(this.device.url))}`,
|
|
1365
|
+
` ${c.muted("start dirs")} ${c.muted(sanitizeTerminal(this.info.startDirs.join(", ")).slice(0, w - 18) || "—")}`,
|
|
1364
1366
|
];
|
|
1365
1367
|
return lines;
|
|
1366
1368
|
}
|
|
@@ -194,7 +194,7 @@ export async function runCommand(app: App, text: string): Promise<boolean> {
|
|
|
194
194
|
// not skip that gate (R4 finding 4: the palette entry used to wipe the
|
|
195
195
|
// context unconditionally). A typed handoff note carries its own intent.
|
|
196
196
|
if (!arg) {
|
|
197
|
-
const ok = await app.prompt(`Reset ${app.sessionSummary()?.name ?? "context"}? y/n`, "");
|
|
197
|
+
const ok = await app.prompt(`Reset ${sanitizeTerminal(app.sessionSummary()?.name ?? "context")}? y/n`, "");
|
|
198
198
|
if (ok === undefined || !ok.trim().toLowerCase().startsWith("y"))
|
|
199
199
|
return app.flash("reset cancelled"), true;
|
|
200
200
|
}
|
|
@@ -227,11 +227,11 @@ export async function runCommand(app: App, text: string): Promise<boolean> {
|
|
|
227
227
|
app.overlay(
|
|
228
228
|
new Panel(() => {
|
|
229
229
|
const tasks = app.session.state.tasks;
|
|
230
|
-
const lines = [c.bold(c.accent(`Live tasks in ${app.sessionSummary()?.name ?? "session"}`)), ""];
|
|
230
|
+
const lines = [c.bold(c.accent(`Live tasks in ${sanitizeTerminal(app.sessionSummary()?.name ?? "session")}`)), ""];
|
|
231
231
|
if (!tasks.length) lines.push(c.muted("No live tasks."));
|
|
232
232
|
for (const t of tasks)
|
|
233
233
|
lines.push(
|
|
234
|
-
`${t.background ? c.secondary("◌ bg") : c.warn("● fg")} #${t.id} ${t.kind} ${c.muted(`agent #${t.conversationId} │ ${t.state.status}${t.state.phase ? `/${t.state.phase}` : ""}`)}`,
|
|
234
|
+
`${t.background ? c.secondary("◌ bg") : c.warn("● fg")} #${t.id} ${sanitizeTerminal(t.kind)} ${c.muted(sanitizeTerminal(`agent #${t.conversationId} │ ${t.state.status}${t.state.phase ? `/${t.state.phase}` : ""}`))}`,
|
|
235
235
|
);
|
|
236
236
|
lines.push("", c.muted("esc close"));
|
|
237
237
|
return lines;
|
package/apps/dpi-tui/src/main.ts
CHANGED
|
@@ -55,7 +55,9 @@ export function isValidConnectUrl(candidate: string): boolean {
|
|
|
55
55
|
}
|
|
56
56
|
|
|
57
57
|
function fail(message: string): never {
|
|
58
|
-
|
|
58
|
+
// R17 (run-3 h5): device-supplied strings (catalog lists, DpiError text)
|
|
59
|
+
// reach stderr here — sanitize for consistency with the frame boundaries.
|
|
60
|
+
process.stderr.write(`${sanitizeTerminal(message)}\n`);
|
|
59
61
|
process.exit(1);
|
|
60
62
|
}
|
|
61
63
|
|
|
@@ -16,6 +16,7 @@ import type { App } from "./app.ts";
|
|
|
16
16
|
import { wrapTextWithAnsi } from "@earendil-works/pi-tui";
|
|
17
17
|
import { Panel } from "./pickers.ts";
|
|
18
18
|
import { c } from "./theme.ts";
|
|
19
|
+
import { sanitizeTerminal } from "./sanitize.ts";
|
|
19
20
|
|
|
20
21
|
export interface PairArgs {
|
|
21
22
|
code?: string;
|
|
@@ -151,25 +152,25 @@ export function pairingViewLines(
|
|
|
151
152
|
hubOrigin?: string,
|
|
152
153
|
): string[] {
|
|
153
154
|
const lines: string[] = [c.bold(c.accent("Pair this device"))];
|
|
154
|
-
if (hubOrigin) lines.push(c.muted(`hub: ${hubOrigin}`));
|
|
155
|
+
if (hubOrigin) lines.push(c.muted(`hub: ${sanitizeTerminal(hubOrigin)}`));
|
|
155
156
|
if (!status) {
|
|
156
|
-
lines.push(c.muted(note));
|
|
157
|
+
lines.push(c.muted(sanitizeTerminal(note)));
|
|
157
158
|
return lines.flatMap((line) => wrapTextWithAnsi(line, Math.max(1, width)));
|
|
158
159
|
}
|
|
159
|
-
lines.push(c.muted(`device: ${status.deviceName ?? status.deviceUid ?? "?"} · uid ${status.deviceUid ?? "?"}`));
|
|
160
|
+
lines.push(c.muted(sanitizeTerminal(`device: ${status.deviceName ?? status.deviceUid ?? "?"} · uid ${status.deviceUid ?? "?"}`)));
|
|
160
161
|
lines.push("");
|
|
161
162
|
lines.push(c.bold("key fingerprint (compare with the hub wizard):"));
|
|
162
|
-
for (const line of wrapFingerprint(status.fingerprint, width)) lines.push(` ${c.secondary(line)}`);
|
|
163
|
+
for (const line of wrapFingerprint(status.fingerprint, width)) lines.push(` ${c.secondary(sanitizeTerminal(line))}`);
|
|
163
164
|
lines.push("");
|
|
164
165
|
if (status.pending) {
|
|
165
166
|
lines.push(c.warn("Awaiting approval on the hub…"));
|
|
166
|
-
if (status.pending.note) lines.push(c.muted(` ${status.pending.note}`));
|
|
167
|
+
if (status.pending.note) lines.push(c.muted(` ${sanitizeTerminal(status.pending.note)}`));
|
|
167
168
|
} else if (status.lastError) {
|
|
168
|
-
lines.push(c.err(describePairingError(status.lastError)));
|
|
169
|
+
lines.push(c.err(sanitizeTerminal(describePairingError(status.lastError))));
|
|
169
170
|
if (status.state === "paired")
|
|
170
|
-
lines.push(c.muted(`Existing pairing to ${status.hubOrigin} is unchanged.`));
|
|
171
|
+
lines.push(c.muted(sanitizeTerminal(`Existing pairing to ${status.hubOrigin} is unchanged.`)));
|
|
171
172
|
} else if (status.state === "paired") {
|
|
172
|
-
lines.push(c.ok(`Paired to ${status.hubOrigin} (generation ${status.generation}).`));
|
|
173
|
+
lines.push(c.ok(sanitizeTerminal(`Paired to ${status.hubOrigin} (generation ${status.generation}).`)));
|
|
173
174
|
lines.push(c.muted("The connector keeps the tunnel up; /pair again to re-pair."));
|
|
174
175
|
} else if (status.state === "revoked") {
|
|
175
176
|
lines.push(c.warn("Revoked on the hub. /pair CODE to pair again."));
|
|
@@ -426,7 +426,7 @@ async function welcomeLocal(app: App) {
|
|
|
426
426
|
const id = suggestDeviceId(probe.info.hostname, probe.info.name);
|
|
427
427
|
stepPicker(
|
|
428
428
|
app,
|
|
429
|
-
`Local backend: ${probe.info.name || probe.info.hostname || url}`,
|
|
429
|
+
`Local backend: ${sanitizeTerminal(probe.info.name || probe.info.hostname || url)}`,
|
|
430
430
|
[{ value: "open", label: `Save as "${id}" and open`, description: `${url} │ token from DPI_TOKEN / backend.env` }],
|
|
431
431
|
// local.token was read BEFORE a first boot may have written backend.env —
|
|
432
432
|
// re-resolve, the file exists now.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "my-durable",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.72",
|
|
4
4
|
"description": "Durable Pi — the durable agent network: hub web UI, device backend daemon, TUI admin and the shared SDK, packaged as one runnable monorepo install",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|