my-durable 0.0.69 → 0.0.71
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 +17 -1
- package/apps/dpi-backend/src/daemon.ts +4 -1
- package/apps/dpi-backend/src/git.ts +3 -1
- package/apps/dpi-backend/src/host-guard.ts +56 -0
- package/apps/dpi-backend/src/main.ts +11 -5
- package/apps/dpi-backend/src/pair-page.ts +15 -4
- package/apps/dpi-backend/src/store.ts +33 -2
- package/apps/dpi-backend/src/telegram.ts +36 -2
- 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 +3 -0
- package/apps/dpi-playground/apps/dpi-playground-hub/src/main.ts +13 -0
- package/apps/dpi-playground/apps/dpi-playground-hub/src/pairing.ts +31 -5
- package/apps/dpi-playground/apps/dpi-playground-hub/src/proxy.ts +13 -2
- package/apps/dpi-playground/apps/dpi-playground-hub/src/transport.ts +14 -0
- 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/drivers.ts +14 -1
- package/apps/dpi-sdk/src/protocol/tunnel.ts +3 -1
- package/apps/dpi-tui/src/app.ts +17 -13
- package/apps/dpi-tui/src/commands.ts +2 -1
- package/apps/dpi-tui/src/main.ts +3 -1
- package/apps/dpi-tui/src/pickers.ts +12 -11
- package/apps/dpi-tui/src/welcome.ts +2 -1
- package/deploy/Caddyfile +5 -2
- 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
|
}
|
|
@@ -361,6 +361,7 @@ export function readZipEntries(data: Uint8Array): ZipArchiveEntry[] {
|
|
|
361
361
|
}
|
|
362
362
|
|
|
363
363
|
const entries: ZipArchiveEntry[] = [];
|
|
364
|
+
let totalDeclared = 0;
|
|
364
365
|
let p = centralOffset;
|
|
365
366
|
for (let i = 0; i < count; i += 1) {
|
|
366
367
|
if (p + 46 > eocd) throw bad(`central directory entry ${i} overruns the archive`);
|
|
@@ -378,6 +379,15 @@ export function readZipEntries(data: Uint8Array): ZipArchiveEntry[] {
|
|
|
378
379
|
}
|
|
379
380
|
const name = buf.toString("utf8", p + 46, p + 46 + nameLength);
|
|
380
381
|
validateEntryName(name);
|
|
382
|
+
// R15 (run-2 h8): the WHOLE archive may never promise more than the
|
|
383
|
+
// backup ceiling — a pile of individually-legal entries must not add up
|
|
384
|
+
// to an unbounded restore either. Entry 0 is the writer's own manifest,
|
|
385
|
+
// which the write-side budget (walkHome) never counts, so a ceiling-sized
|
|
386
|
+
// home must stay restorable (R15 cold review P2-1).
|
|
387
|
+
if (i > 0 || name !== "manifest.json") totalDeclared += uncompressedSize;
|
|
388
|
+
if (totalDeclared > MAX_BACKUP_BYTES) {
|
|
389
|
+
throw bad(`archive declares more than ${MAX_BACKUP_BYTES} bytes of entries`);
|
|
390
|
+
}
|
|
381
391
|
|
|
382
392
|
if (localOffset + 30 > buf.length || buf.readUInt32LE(localOffset) !== LOCAL_SIG) {
|
|
383
393
|
throw bad(`local header for ${name} is corrupt`);
|
|
@@ -390,8 +400,14 @@ export function readZipEntries(data: Uint8Array): ZipArchiveEntry[] {
|
|
|
390
400
|
let out: Buffer;
|
|
391
401
|
if (method === 0) out = buf.subarray(start, start + compressedSize);
|
|
392
402
|
else if (method === 8) {
|
|
403
|
+
// R15 (run-2 h8): a hostile "backup" can declare a tiny uncompressedSize
|
|
404
|
+
// while the deflate stream expands ~1000x — the old check ran only AFTER
|
|
405
|
+
// the full allocation. Cap the inflate itself: the entry may never
|
|
406
|
+
// produce more than the smaller of its declared size (cross-checked
|
|
407
|
+
// right below anyway) and the backup ceiling.
|
|
408
|
+
const declaredCap = Math.min(Math.max(uncompressedSize, 1), MAX_BACKUP_BYTES);
|
|
393
409
|
try {
|
|
394
|
-
out = inflateRawSync(buf.subarray(start, start + compressedSize));
|
|
410
|
+
out = inflateRawSync(buf.subarray(start, start + compressedSize), { maxOutputLength: declaredCap });
|
|
395
411
|
} catch (error) {
|
|
396
412
|
throw bad(`cannot inflate ${name} (${describeError(error)})`);
|
|
397
413
|
}
|
|
@@ -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
|
|
@@ -428,7 +428,9 @@ export type GitOp =
|
|
|
428
428
|
| "pr-comment";
|
|
429
429
|
|
|
430
430
|
/** Plain string an arg may never contain — we build argv ourselves anyway. */
|
|
431
|
-
|
|
431
|
+
// R16 (run-2 h6): a leading dash would turn the ref into a git OPTION
|
|
432
|
+
// (`push -u origin --mirror`); refuse the whole ref instead.
|
|
433
|
+
const safeRef = (s: string) => /^[\w./@+-]+$/.test(s) && !s.startsWith("-") && !s.includes("..");
|
|
432
434
|
|
|
433
435
|
/** Run one whitelisted git operation. Every arg is ours; callers only pick names. */
|
|
434
436
|
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")
|
|
@@ -62,7 +62,18 @@ export const PAIR_PAGE_HTML = `<!doctype html>
|
|
|
62
62
|
var statusEl = document.getElementById("status");
|
|
63
63
|
var meta = document.getElementById("meta");
|
|
64
64
|
var H = { "content-type": "application/json", "x-dpi-pair": "1" };
|
|
65
|
-
|
|
65
|
+
// R15 (run-2 h1): the enrollment page renders HUB-CONTROLLED text here
|
|
66
|
+
// (lastError, error.message from the offer the operator pasted) — that is a
|
|
67
|
+
// remote principal, so the status line must be text-only. The page's own
|
|
68
|
+
// static strings stopped needing markup at the same time.
|
|
69
|
+
function say(text, cls) {
|
|
70
|
+
statusEl.textContent = "";
|
|
71
|
+
if (!text) return;
|
|
72
|
+
var span = document.createElement("span");
|
|
73
|
+
if (cls) span.className = cls;
|
|
74
|
+
span.textContent = text;
|
|
75
|
+
statusEl.appendChild(span);
|
|
76
|
+
}
|
|
66
77
|
// The hub handoff link put the offer in THIS page's fragment.
|
|
67
78
|
if (location.hash.indexOf("#offer=") === 0) offerEl.value = location.href;
|
|
68
79
|
function poll() {
|
|
@@ -70,8 +81,8 @@ export const PAIR_PAGE_HTML = `<!doctype html>
|
|
|
70
81
|
.then(function (r) { return r.json(); })
|
|
71
82
|
.then(function (s) {
|
|
72
83
|
render(s);
|
|
73
|
-
if (s.state === "pairing") { say(
|
|
74
|
-
else if (s.state === "paired") say("paired — credential saved. You can close this page and open
|
|
84
|
+
if (s.state === "pairing") { say("⠿ waiting for approval on the hub…", "spin warn"); setTimeout(poll, 2000); }
|
|
85
|
+
else if (s.state === "paired") say("paired — credential saved. You can close this page and open dpi tui.", "ok");
|
|
75
86
|
})
|
|
76
87
|
.catch(function () { setTimeout(poll, 3000); });
|
|
77
88
|
}
|
|
@@ -101,7 +112,7 @@ export const PAIR_PAGE_HTML = `<!doctype html>
|
|
|
101
112
|
if (!o.ok) { say((o.b && o.b.error && o.b.error.message) || "refused", "err"); go.disabled = false; return; }
|
|
102
113
|
poll();
|
|
103
114
|
})
|
|
104
|
-
.catch(function () { say("cannot reach the local backend — is
|
|
115
|
+
.catch(function () { say("cannot reach the local backend — is dpi device running?", "err"); go.disabled = false; });
|
|
105
116
|
});
|
|
106
117
|
load();
|
|
107
118
|
})();
|
|
@@ -984,14 +984,39 @@ export class Store {
|
|
|
984
984
|
|
|
985
985
|
/** A caller-supplied path that must stay inside the start dirs: `~` expands,
|
|
986
986
|
* symlinks resolve, and anything outside answers 400 `invalid`. A path that
|
|
987
|
-
* does not exist is judged
|
|
987
|
+
* does not exist is judged by its deepest EXISTING ancestor (R15, run-2 h6):
|
|
988
|
+
* a not-yet-existing tail spelled under an in-start-dir symlink must not
|
|
989
|
+
* pass a lexical prefix check — walk dirname until realpath succeeds,
|
|
990
|
+
* re-append the missing tail, then judge that (git worktree-add targets
|
|
991
|
+
* never exist, so the old lexical fallback was the branch every
|
|
992
|
+
* worktree-add took). */
|
|
988
993
|
async containedPath(input: string): Promise<string> {
|
|
989
994
|
const expanded = input === "~" ? homedir() : input.startsWith("~/") ? join(homedir(), input.slice(2)) : input;
|
|
990
995
|
let candidate: string;
|
|
991
996
|
try {
|
|
992
997
|
candidate = await realpath(resolve(expanded));
|
|
993
998
|
} catch {
|
|
994
|
-
|
|
999
|
+
// Not yet existing: resolve the deepest existing ancestor so symlink
|
|
1000
|
+
// components are honored, then re-append the missing tail verbatim.
|
|
1001
|
+
const absolute = resolve(expanded);
|
|
1002
|
+
const tail: string[] = [];
|
|
1003
|
+
let current = absolute;
|
|
1004
|
+
let resolvedAncestor: string | undefined;
|
|
1005
|
+
for (let depth = 0; depth < 64; depth++) {
|
|
1006
|
+
const parent = dirname(current);
|
|
1007
|
+
if (parent === current) break;
|
|
1008
|
+
tail.unshift(current.slice(parent.length + 1));
|
|
1009
|
+
current = parent;
|
|
1010
|
+
try {
|
|
1011
|
+
resolvedAncestor = await realpath(current);
|
|
1012
|
+
break;
|
|
1013
|
+
} catch {}
|
|
1014
|
+
}
|
|
1015
|
+
// Fail CLOSED on exhaustion (R15 cold review P1-2): when no existing
|
|
1016
|
+
// ancestor was found at all, judging the raw spelling lexically would
|
|
1017
|
+
// resurrect the exact symlink escape this walk exists to close.
|
|
1018
|
+
if (resolvedAncestor === undefined) throw invalid("path must live under a start dir");
|
|
1019
|
+
candidate = join(resolvedAncestor, ...tail);
|
|
995
1020
|
}
|
|
996
1021
|
if (!this.underRoots(candidate, await this.startDirRoots())) throw invalid("path must live under a start dir");
|
|
997
1022
|
return candidate;
|
|
@@ -1254,12 +1279,18 @@ export class Store {
|
|
|
1254
1279
|
}
|
|
1255
1280
|
|
|
1256
1281
|
async createGraph(body: Record<string, unknown>): Promise<GraphRecord> {
|
|
1282
|
+
// R16 (run-2 h6 parity): sessions refuse a bad cwd up-front; graphs ran
|
|
1283
|
+
// confined only at run time. Same rule at mutation time.
|
|
1284
|
+
if (typeof body?.cwd === "string" && body.cwd.trim())
|
|
1285
|
+
await this.assertSessionCwdAllowed(normaliseCwd(body.cwd));
|
|
1257
1286
|
const created = await this.graphs.create(body as never);
|
|
1258
1287
|
this.notify();
|
|
1259
1288
|
return created;
|
|
1260
1289
|
}
|
|
1261
1290
|
|
|
1262
1291
|
async updateGraph(id: string, body: Record<string, unknown>): Promise<GraphRecord> {
|
|
1292
|
+
if (typeof body?.cwd === "string" && body.cwd.trim())
|
|
1293
|
+
await this.assertSessionCwdAllowed(normaliseCwd(body.cwd));
|
|
1263
1294
|
const updated = await this.graphs.update(id, body as never);
|
|
1264
1295
|
this.notify();
|
|
1265
1296
|
return updated;
|
|
@@ -395,6 +395,9 @@ export class TelegramBridge {
|
|
|
395
395
|
return bridge;
|
|
396
396
|
}
|
|
397
397
|
|
|
398
|
+
/** Last registry text this process loaded or wrote (R15 h14 foreign-writer sync). */
|
|
399
|
+
private registryText: string | null = null;
|
|
400
|
+
|
|
398
401
|
/** True while the poll loop is scheduled or in flight. */
|
|
399
402
|
get running(): boolean {
|
|
400
403
|
return this.runningValue;
|
|
@@ -509,6 +512,7 @@ export class TelegramBridge {
|
|
|
509
512
|
const main = await this.readRegistry(this.filePath);
|
|
510
513
|
if (main.ok) {
|
|
511
514
|
this.adopt(main.file);
|
|
515
|
+
this.registryText = main.text ?? null;
|
|
512
516
|
this.mainIsGood = true;
|
|
513
517
|
return;
|
|
514
518
|
}
|
|
@@ -539,7 +543,9 @@ export class TelegramBridge {
|
|
|
539
543
|
|
|
540
544
|
private async readRegistry(
|
|
541
545
|
path: string,
|
|
542
|
-
): Promise<
|
|
546
|
+
): Promise<
|
|
547
|
+
{ ok: true; file: TelegramRegistryFile; text?: string } | { ok: false; missing: boolean; text?: string; error?: unknown }
|
|
548
|
+
> {
|
|
543
549
|
if (!(await this.io.exists(path))) return { ok: false, missing: true };
|
|
544
550
|
let text: string;
|
|
545
551
|
try {
|
|
@@ -548,7 +554,7 @@ export class TelegramBridge {
|
|
|
548
554
|
return { ok: false, missing: false, error };
|
|
549
555
|
}
|
|
550
556
|
try {
|
|
551
|
-
return { ok: true, file: coerceRegistry(JSON.parse(text), this.now()) };
|
|
557
|
+
return { ok: true, file: coerceRegistry(JSON.parse(text), this.now()), text };
|
|
552
558
|
} catch (error) {
|
|
553
559
|
return { ok: false, missing: false, text, error };
|
|
554
560
|
}
|
|
@@ -583,6 +589,31 @@ export class TelegramBridge {
|
|
|
583
589
|
this.codes = file.codes.map((code) => ({ ...code }));
|
|
584
590
|
}
|
|
585
591
|
|
|
592
|
+
/**
|
|
593
|
+
* R15 (run-2 h14): the `dpi telegram` CLI is a designed second writer of the
|
|
594
|
+
* registry file. Before authorizing ANY update, re-read the file and adopt
|
|
595
|
+
* foreign changes (bindings removed/added by the CLI, its minted codes), so
|
|
596
|
+
* a revocation takes effect on the live bridge and is never resurrected by
|
|
597
|
+
* the next offset persist. The ack offset only ever moves forward.
|
|
598
|
+
*/
|
|
599
|
+
private async syncForeign(): Promise<boolean> {
|
|
600
|
+
try {
|
|
601
|
+
if (!(await this.io.exists(this.filePath))) return true;
|
|
602
|
+
const text = await this.io.readFile(this.filePath);
|
|
603
|
+
if (text === this.registryText) return true; // still our own last write
|
|
604
|
+
const file = coerceRegistry(JSON.parse(text), this.now());
|
|
605
|
+
this.adopt({ ...file, offset: Math.max(this.offset, file.offset) });
|
|
606
|
+
this.registryText = text;
|
|
607
|
+
return true;
|
|
608
|
+
} catch (error) {
|
|
609
|
+
// Fail CLOSED (R15 cold review P3-1): with an unreadable/unparseable
|
|
610
|
+
// registry the in-memory bindings cannot be trusted to reflect the
|
|
611
|
+
// operator's intent — authorize nothing until the file is healthy.
|
|
612
|
+
this.warn(`could not re-read ${this.filePath} before dispatch; skipping the update`, error);
|
|
613
|
+
return false;
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
|
|
586
617
|
/** Stage → persist → swap. A failed write leaves memory exactly as it was. */
|
|
587
618
|
private commit(apply: (draft: TelegramRegistryFile) => void): Promise<void> {
|
|
588
619
|
return this.run(async () => {
|
|
@@ -620,6 +651,7 @@ export class TelegramBridge {
|
|
|
620
651
|
const payload = `${JSON.stringify(draft satisfies TelegramRegistryFile, null, 2)}\n`;
|
|
621
652
|
await this.io.writeFile(this.filePath, payload);
|
|
622
653
|
await this.io.chmod(this.filePath, 0o600);
|
|
654
|
+
this.registryText = payload;
|
|
623
655
|
this.mainIsGood = true;
|
|
624
656
|
}
|
|
625
657
|
|
|
@@ -691,9 +723,11 @@ export class TelegramBridge {
|
|
|
691
723
|
|
|
692
724
|
/** Acknowledge first (persist the new offset), then handle. Never both-half-heartedly. */
|
|
693
725
|
private async handle(update: TelegramUpdate): Promise<void> {
|
|
726
|
+
const synced = await this.syncForeign();
|
|
694
727
|
await this.commit((draft) => {
|
|
695
728
|
draft.offset = Math.max(draft.offset, update.updateId + 1);
|
|
696
729
|
});
|
|
730
|
+
if (!synced) return; // acknowledged, but NOT authorized on stale state
|
|
697
731
|
if (!update.message) return; // non-message or non-text: acknowledged, ignored
|
|
698
732
|
await this.dispatch(
|
|
699
733
|
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,9 @@ 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): a requireTls-denied GET /share/<token> lands the FULL
|
|
109
|
+
// capability token in audit path samples — the token IS the share secret.
|
|
110
|
+
out = out.replace(/(\/share\/)[A-Za-z0-9_-]{20,32}(?![A-Za-z0-9_-])/g, "$1<redacted>");
|
|
108
111
|
// Credential material without its prefix (slices, echo): 43-char base64url runs.
|
|
109
112
|
out = out.replace(/(?<![A-Za-z0-9_-])[A-Za-z0-9_-]{43}(?![A-Za-z0-9_-])/g, "<redacted>");
|
|
110
113
|
// Pairing codes as standalone values ("code":"AB2C7DEF" / "ABCD2345EF67") but not ordinary words.
|
|
@@ -605,6 +605,19 @@ if (args.includes("--dev")) {
|
|
|
605
605
|
},
|
|
606
606
|
}),
|
|
607
607
|
);
|
|
608
|
+
// R15 (run-2 h12): unmatched /share/ paths (empty, multi-segment) must get
|
|
609
|
+
// the share 404 page — NOT fall through to the SPA fallback, which serves
|
|
610
|
+
// the operator app shell to anyone the edge exempted for /share/*.
|
|
611
|
+
app.get("/share/{*rest}", (_req, res) => {
|
|
612
|
+
res.status(404);
|
|
613
|
+
res.set("Cache-Control", "no-cache");
|
|
614
|
+
res.set("Content-Type", "text/html; charset=utf-8");
|
|
615
|
+
// Same lockdown as the /share/:token 404 — renderShareNotFound is
|
|
616
|
+
// inline-styled, so the shell CSP (style-src 'self') must not apply.
|
|
617
|
+
res.set("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'");
|
|
618
|
+
res.set("X-Frame-Options", "DENY");
|
|
619
|
+
res.send(renderShareNotFound());
|
|
620
|
+
});
|
|
608
621
|
app.get("/{*path}", (req, res, next) => {
|
|
609
622
|
// A path that names a file is an asset that does not exist, not a page of the app.
|
|
610
623
|
if (extname(req.path)) return void next();
|
|
@@ -275,7 +275,7 @@ export class PairingService {
|
|
|
275
275
|
}
|
|
276
276
|
|
|
277
277
|
/** Mint a single-use code entry (shared by the admin and device-initiated flows). */
|
|
278
|
-
private mintEntry(actor: "admin" | "device"): CodeEntry {
|
|
278
|
+
private mintEntry(actor: "admin" | "device", audit = true): CodeEntry {
|
|
279
279
|
const now = this.now();
|
|
280
280
|
let code = "";
|
|
281
281
|
do {
|
|
@@ -290,15 +290,25 @@ export class PairingService {
|
|
|
290
290
|
cancelled: false,
|
|
291
291
|
...(actor === "device" ? { deviceMinted: true as const } : {}),
|
|
292
292
|
};
|
|
293
|
+
// R15 (run-2 h11b): for the UNAUTH device surface the persistent audit row
|
|
294
|
+
// is written only when the mint SURVIVES — a failed anonymous attempt
|
|
295
|
+
// already leaves an aggregated denial record (failWindows) and its RAM
|
|
296
|
+
// slot is recycled instantly, so appending here let an anonymous flood
|
|
297
|
+
// persist one append-only row per request at per-IP rates only. Successful
|
|
298
|
+
// mints stay bounded by the RAM caps (100 live device codes, 5-7 min TTL).
|
|
299
|
+
if (audit) this.auditCodeCreated(entry, actor);
|
|
300
|
+
this.codes.set(entry.codeId, entry);
|
|
301
|
+
this.byCode.set(code, entry.codeId);
|
|
302
|
+
return entry;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
private auditCodeCreated(entry: CodeEntry, actor: "admin" | "device"): void {
|
|
293
306
|
this.deps.audit.append({
|
|
294
307
|
actor,
|
|
295
308
|
action: "pair.code_created",
|
|
296
309
|
outcome: "ok",
|
|
297
310
|
detail: { codeId: entry.codeId, expiresAt: entry.expiresAt, ...(actor === "device" ? { initiated: "device" } : {}) },
|
|
298
311
|
});
|
|
299
|
-
this.codes.set(entry.codeId, entry);
|
|
300
|
-
this.byCode.set(code, entry.codeId);
|
|
301
|
-
return entry;
|
|
302
312
|
}
|
|
303
313
|
|
|
304
314
|
/** POST /api/pair/code (admin) — mint a fresh single-use code. */
|
|
@@ -348,7 +358,7 @@ export class PairingService {
|
|
|
348
358
|
if (request?.type !== "pair.device-request" || !checkPairingDto(PairDeviceRequestSchema, request))
|
|
349
359
|
return this.fail(400, "invalid", "pair.device-request body failed schema validation");
|
|
350
360
|
|
|
351
|
-
const entry = this.mintEntry("device");
|
|
361
|
+
const entry = this.mintEntry("device", false);
|
|
352
362
|
const started = this.start({ ...(request as object), type: "pair.request", v: 1, code: entry.code }, address);
|
|
353
363
|
if (!started.ok) {
|
|
354
364
|
// The enrollment never existed: drop the code so a failed request leaves nothing behind.
|
|
@@ -356,6 +366,7 @@ export class PairingService {
|
|
|
356
366
|
this.byCode.delete(entry.code);
|
|
357
367
|
return started;
|
|
358
368
|
}
|
|
369
|
+
this.auditCodeCreated(entry, "device");
|
|
359
370
|
return this.ok({
|
|
360
371
|
type: "pair.device-ack",
|
|
361
372
|
v: 1,
|
|
@@ -516,6 +527,21 @@ export class PairingService {
|
|
|
516
527
|
return this.fail(409, "code_in_use", "This code is reserved for another enrollment");
|
|
517
528
|
if (existing.cancelled) return this.fail(410, "enrollment_cancelled", "Enrollment cancelled");
|
|
518
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
|
+
}
|
|
519
545
|
return this.ok({
|
|
520
546
|
type: "pair.challenge",
|
|
521
547
|
v: 1,
|
|
@@ -66,7 +66,16 @@ 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
|
+
if (k.length > 256)
|
|
76
|
+
throw new DpiError("invalid", "idempotency-key longer than 256 chars", 400);
|
|
77
|
+
return k;
|
|
78
|
+
})(),
|
|
70
79
|
body: req.body ?? {},
|
|
71
80
|
},
|
|
72
81
|
closed.signal,
|
|
@@ -124,7 +133,9 @@ export function proxy(
|
|
|
124
133
|
const disposition = isZip
|
|
125
134
|
? `attachment; filename="${stem}.zip"`
|
|
126
135
|
: 'attachment; filename="device-response.bin"';
|
|
127
|
-
|
|
136
|
+
// R16 (run-2 h4): the zip LABEL is hub-authored — a chunk-sourced
|
|
137
|
+
// contentType has no length bound, so never reflect it verbatim.
|
|
138
|
+
res.type(isZip ? "application/zip" : "application/octet-stream")
|
|
128
139
|
.set("Content-Disposition", disposition)
|
|
129
140
|
.send(payload);
|
|
130
141
|
}
|
|
@@ -8,6 +8,8 @@
|
|
|
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 { REST_PATH_PREFIX } from "../../../../dpi-sdk/src/protocol/limits.js";
|
|
11
13
|
import type { Frame } from "../../../../dpi-sdk/src/api.js";
|
|
12
14
|
import type { DeviceRow } from "../../../../dpi-sdk/src/node/registry.js";
|
|
13
15
|
|
|
@@ -77,6 +79,18 @@ export class LanTransport implements DeviceTransport {
|
|
|
77
79
|
|
|
78
80
|
async request(input: TransportRequest, signal: AbortSignal): Promise<TransportResponse> {
|
|
79
81
|
if (!this.available) throw new DpiError("unauthorized", "LAN device has no URL/token", 0);
|
|
82
|
+
// R16 (run-2 h4 parity): the tunnel dispatcher runs the REST allowlist on
|
|
83
|
+
// every request; the LAN leg must not be the weaker twin — same principal
|
|
84
|
+
// today, but drift here would surface as a hub-frontend-only capability.
|
|
85
|
+
// The tunnel contract carries the /v1 prefix; this leg's paths are already
|
|
86
|
+
// prefix-stripped, so re-attach it for the shared validator.
|
|
87
|
+
const allow = validateRestRequest({
|
|
88
|
+
method: input.method,
|
|
89
|
+
path: input.path.startsWith(REST_PATH_PREFIX)
|
|
90
|
+
? input.path
|
|
91
|
+
: `${REST_PATH_PREFIX}${input.path}`,
|
|
92
|
+
});
|
|
93
|
+
if (!allow.ok) throw new DpiError("invalid", allow.error ?? "path not allowed", 400);
|
|
80
94
|
const timeout = AbortSignal.timeout(REST_TIMEOUT_MS);
|
|
81
95
|
const effective = signal ? AbortSignal.any([signal, timeout]) : timeout;
|
|
82
96
|
const hasBody = !["GET", "HEAD", "DELETE"].includes(input.method);
|
|
@@ -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 };
|
|
@@ -110,6 +110,9 @@ 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`);
|
|
113
116
|
const home = shPath(device.homeDir);
|
|
114
117
|
const body = [
|
|
115
118
|
`DPI_DEVICE_NAME=${device.id}`,
|
|
@@ -120,7 +123,13 @@ async function writeEnv(device: NetDevice, ctx: DriverContext, rotate = false) {
|
|
|
120
123
|
const v = local[k] ?? process.env[k];
|
|
121
124
|
return v && !/[\n\r]/.test(v) ? [`${k}=${v}`] : [];
|
|
122
125
|
}),
|
|
123
|
-
|
|
126
|
+
// R16 (run-2 h12): env_keys secrets already refuse [\n\r]; plain env:
|
|
127
|
+
// entries get the same guard — a multiline YAML value would inject extra
|
|
128
|
+
// KEY=VALUE lines into backend.env (incl. a duplicate DPI_TOKEN, last
|
|
129
|
+
// wins). Misconfigured values are skipped, mirroring the env_keys branch.
|
|
130
|
+
...Object.entries(device.env).flatMap(([k, v]) =>
|
|
131
|
+
typeof v === "string" && v && !/[\n\r]/.test(v) ? [`${k}=${v}`] : [],
|
|
132
|
+
),
|
|
124
133
|
].join("\n");
|
|
125
134
|
const mkStartDirs = device.startDirs.map((r) => `mkdir -p "${shPath(r)}"`).join("\n");
|
|
126
135
|
await exec(
|
|
@@ -145,6 +154,10 @@ echo "env ok"`,
|
|
|
145
154
|
function fill(template: string, values: Record<string, string>) {
|
|
146
155
|
return template.replace(/__([A-Z_]+)__/g, (m, key: string) => {
|
|
147
156
|
if (!(key in values)) throw Error(`Template placeholder ${m} has no value`);
|
|
157
|
+
// R16 (run-2 h12): these values land in a root-owned systemd unit / a
|
|
158
|
+
// LaunchAgent plist — a newline would inject whole new directives.
|
|
159
|
+
if (/[\n\r]/.test(values[key]))
|
|
160
|
+
throw Error(`Template value for ${key} contains a newline`);
|
|
148
161
|
return values[key];
|
|
149
162
|
});
|
|
150
163
|
}
|
|
@@ -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
|
@@ -708,7 +708,7 @@ export class App {
|
|
|
708
708
|
this.input!.value = "/";
|
|
709
709
|
} else if (data === "f") this.beginInput("filter", "filter ❯ ");
|
|
710
710
|
else if (data === "n") this.beginInput("new", "new session › ");
|
|
711
|
-
else if (data === "x") this.beginInput("kill", `reset ${this.sessionSummary()?.name ?? "context"}? y/n`);
|
|
711
|
+
else if (data === "x") this.beginInput("kill", `reset ${sanitizeTerminal(this.sessionSummary()?.name ?? "context")}? y/n`);
|
|
712
712
|
else if (data === "g") this.setView("herd");
|
|
713
713
|
else if (data === "N") this.setView("network");
|
|
714
714
|
else if (data === "L") this.setView("log");
|
|
@@ -1062,7 +1062,9 @@ export class App {
|
|
|
1062
1062
|
)}${c.muted(". Reattach:")}\n just tui attach ${target}\n\n`,
|
|
1063
1063
|
);
|
|
1064
1064
|
}
|
|
1065
|
-
process.exit(0)
|
|
1065
|
+
// Under `node --test` a process.exit(0) in teardown would swallow assertion
|
|
1066
|
+
// failures of the very tests that drive this class (R15 cold review P1-1).
|
|
1067
|
+
if (!process.env.NODE_TEST_CONTEXT) process.exit(0);
|
|
1066
1068
|
}
|
|
1067
1069
|
|
|
1068
1070
|
private reattachRef() {
|
|
@@ -1153,7 +1155,7 @@ export class App {
|
|
|
1153
1155
|
const session = this.sessions.find((x) => x.id === this.sessionId);
|
|
1154
1156
|
const right =
|
|
1155
1157
|
this.view === "agent" && session
|
|
1156
|
-
? `${this.device.id}:${session.name}:${this.agentId ?? 1}`
|
|
1158
|
+
? `${sanitizeTerminal(this.device.id)}:${sanitizeTerminal(session.name)}:${this.agentId ?? 1}`
|
|
1157
1159
|
: this.view === "agent"
|
|
1158
1160
|
? "no workspace"
|
|
1159
1161
|
: "j/k move · ↵ open";
|
|
@@ -1218,10 +1220,10 @@ export class App {
|
|
|
1218
1220
|
// the web shows a banner — the TUI used to show a healthy branch chip
|
|
1219
1221
|
// while the repo was mid-merge with conflicts.
|
|
1220
1222
|
const gitChip = g?.repo
|
|
1221
|
-
? ` ${c.muted("⎇")} ${c.text(g.branch ?? g.head ?? "")}${(g.staged ?? 0) + (g.unstaged ?? 0) + (g.untracked ?? 0) ? c.warn(` ±${(g.staged ?? 0) + (g.unstaged ?? 0) + (g.untracked ?? 0)}`) : ""}${g.merge ? c.err(gitStateSuffix(g)) : g.detached ? c.warn(gitStateSuffix(g)) : ""}`
|
|
1223
|
+
? ` ${c.muted("⎇")} ${c.text(sanitizeTerminal(g.branch ?? g.head ?? ""))}${(g.staged ?? 0) + (g.unstaged ?? 0) + (g.untracked ?? 0) ? c.warn(` ±${(g.staged ?? 0) + (g.unstaged ?? 0) + (g.untracked ?? 0)}`) : ""}${g.merge ? c.err(gitStateSuffix(g)) : g.detached ? c.warn(gitStateSuffix(g)) : ""}`
|
|
1222
1224
|
: "";
|
|
1223
1225
|
lines.push(
|
|
1224
|
-
`${c.muted(this.device.id)} ${c.muted("›")} ${c.text(session?.name ?? "—")} ${c.muted("›")} ${c.bold(`#${this.agentId ?? 1}`)}${gitChip} ` +
|
|
1226
|
+
`${c.muted(sanitizeTerminal(this.device.id))} ${c.muted("›")} ${c.text(sanitizeTerminal(session?.name ?? "—"))} ${c.muted("›")} ${c.bold(`#${this.agentId ?? 1}`)}${gitChip} ` +
|
|
1225
1227
|
`${STATE_COLOR[state](STATE_GLYPH[state] + " " + (this.busy() ? "working" : "idle"))} ` +
|
|
1226
1228
|
// Catalog miss renders "?" not "—" (R5 finding 5): unknown window ≠ no usage.
|
|
1227
1229
|
`${c.muted("ctx")} ${ctx === undefined ? c.muted("?") : c.accent(rep("█", filled)) + c.muted(rep("░", barW - filled)) + " " + c.muted(`${ctx}%`)}`,
|
|
@@ -1271,7 +1273,9 @@ export class App {
|
|
|
1271
1273
|
const s = this.model.state;
|
|
1272
1274
|
// Display-width loop wrap (R5 finding 1): the old single-split leaked the
|
|
1273
1275
|
// remainder of every overlong line to pi-tui's hard clip. See wrap.ts.
|
|
1274
|
-
|
|
1276
|
+
// R15 (run-2 h15): transcript payloads are model/tool-controlled — the
|
|
1277
|
+
// sanitize happens HERE, at the data boundary, before any styling/wrap.
|
|
1278
|
+
const wrap = (text: string, indent = " ") => wrapByColumn(sanitizeTerminal(text), w, indent);
|
|
1275
1279
|
if (this.tab === "transcript") {
|
|
1276
1280
|
const lines: string[] = [];
|
|
1277
1281
|
let turn = 0;
|
|
@@ -1288,15 +1292,15 @@ export class App {
|
|
|
1288
1292
|
else if (b.type === "text") lines.push(...wrap(b.text));
|
|
1289
1293
|
else if (b.type === "tool") {
|
|
1290
1294
|
const glyph = b.call.status === "error" ? c.err("✗") : b.call.status === "running" ? c.warn("◐") : c.ok("✓");
|
|
1291
|
-
const args = JSON.stringify(b.call.args ?? {}) || "";
|
|
1292
|
-
lines.push(` ${glyph} ${c.bold(b.call.name)} ${c.muted(this.expand ? args.slice(0, w - 8) : args.slice(0, Math.max(10, w - 20)))}`);
|
|
1295
|
+
const args = sanitizeTerminal(JSON.stringify(b.call.args ?? {}) || "");
|
|
1296
|
+
lines.push(` ${glyph} ${c.bold(sanitizeTerminal(b.call.name))} ${c.muted(this.expand ? args.slice(0, w - 8) : args.slice(0, Math.max(10, w - 20)))}`);
|
|
1293
1297
|
const out = b.call.output ?? b.call.result ?? "";
|
|
1294
1298
|
if (typeof out === "string" && out)
|
|
1295
1299
|
for (const l of (this.expand ? out.split("\n") : out.split("\n").slice(0, 6)))
|
|
1296
|
-
lines.push(` ${c.muted(l.slice(0, w - 6))}`);
|
|
1300
|
+
lines.push(` ${c.muted(sanitizeTerminal(l).slice(0, w - 6))}`);
|
|
1297
1301
|
}
|
|
1298
1302
|
}
|
|
1299
|
-
if (item.error) lines.push(` ${c.err(item.error.slice(0, w - 4))}`);
|
|
1303
|
+
if (item.error) lines.push(` ${c.err(sanitizeTerminal(item.error).slice(0, w - 4))}`);
|
|
1300
1304
|
lines.push("");
|
|
1301
1305
|
}
|
|
1302
1306
|
}
|
|
@@ -1307,7 +1311,7 @@ export class App {
|
|
|
1307
1311
|
const lines: string[] = [];
|
|
1308
1312
|
for (const item of s.inbox)
|
|
1309
1313
|
lines.push(
|
|
1310
|
-
` ${c.warn("◆")} ${c.text(`${item.mode === "steer" ? "steer" : "queued"}: ${(item.content ?? "context update").replace(/\s+/g, " ").slice(0, w - 20)}`)}`,
|
|
1314
|
+
` ${c.warn("◆")} ${c.text(`${item.mode === "steer" ? "steer" : "queued"}: ${sanitizeTerminal(item.content ?? "context update").replace(/\s+/g, " ").slice(0, w - 20)}`)}`,
|
|
1311
1315
|
);
|
|
1312
1316
|
const bg = this.agentId === undefined ? [] : this.session.backgroundTasks(this.agentId);
|
|
1313
1317
|
for (const t of bg) lines.push(` ${c.accent("◐")} ${c.text(String(t).slice(0, w - 6))}`);
|
|
@@ -1325,7 +1329,7 @@ export class App {
|
|
|
1325
1329
|
for (const [name, n] of [...counts.entries()].sort((a, b) => b[1] - a[1])) {
|
|
1326
1330
|
const barW = 16;
|
|
1327
1331
|
const filled = Math.round((n / max) * barW);
|
|
1328
|
-
lines.push(` ${c.text(name.padEnd(14))} ${c.muted(rep("▮", filled))}${c.muted(rep("▯", barW - filled))} ${c.muted(String(n))}`);
|
|
1332
|
+
lines.push(` ${c.text(sanitizeTerminal(name).padEnd(14))} ${c.muted(rep("▮", filled))}${c.muted(rep("▯", barW - filled))} ${c.muted(String(n))}`);
|
|
1329
1333
|
}
|
|
1330
1334
|
if (!counts.size) lines.push(c.muted(" no tool calls yet"));
|
|
1331
1335
|
return lines;
|
|
@@ -1371,7 +1375,7 @@ export class App {
|
|
|
1371
1375
|
if (this.filter)
|
|
1372
1376
|
lines.push(c.warn(` filter: ${this.filter} · ${rows.length}/${this.events.length} shown — esc clears`));
|
|
1373
1377
|
const visible = h - lines.length;
|
|
1374
|
-
for (const e of rows.slice(-visible)) lines.push(` ${c.muted(e.at)} ${c.accent(e.glyph)} ${c.text(e.text.slice(0, w - 18))}`);
|
|
1378
|
+
for (const e of rows.slice(-visible)) lines.push(` ${c.muted(e.at)} ${c.accent(e.glyph)} ${c.text(sanitizeTerminal(e.text).slice(0, w - 18))}`);
|
|
1375
1379
|
return lines;
|
|
1376
1380
|
}
|
|
1377
1381
|
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
import type { SlashCommand } from "@earendil-works/pi-tui";
|
|
3
3
|
import { THINKING_LEVELS, type ThinkingLevel } from "../../dpi-sdk/src/api.ts";
|
|
4
4
|
import type { App } from "./app.ts";
|
|
5
|
+
import { sanitizeTerminal } from "./sanitize.ts";
|
|
5
6
|
import { Panel, pickAgent, pickDevice, pickModel, pickSession, pickThinking } from "./pickers.ts";
|
|
6
7
|
import { parsePairArgs, runPairing } from "./pairing.ts";
|
|
7
8
|
import { gitStateSuffix } from "./views.ts";
|
|
@@ -242,7 +243,7 @@ export async function runCommand(app: App, text: string): Promise<boolean> {
|
|
|
242
243
|
new Panel(
|
|
243
244
|
() => [
|
|
244
245
|
c.bold(c.accent("dpi-tui")),
|
|
245
|
-
c.muted(`${app.device.id} │ ${app.device.url}`),
|
|
246
|
+
c.muted(`${sanitizeTerminal(app.device.id)} │ ${sanitizeTerminal(app.device.url)}`),
|
|
246
247
|
"",
|
|
247
248
|
...KEYS.map(([k, d]) => `${c.secondary(k.padEnd(11))} ${d}`),
|
|
248
249
|
"",
|
package/apps/dpi-tui/src/main.ts
CHANGED
|
@@ -13,6 +13,7 @@ import { syncConfigToRegistry, tryLoadNetworkConfig } from "../../dpi-sdk/src/no
|
|
|
13
13
|
import { App, type DeviceRef } from "./app.ts";
|
|
14
14
|
import { pickDevice } from "./pickers.ts";
|
|
15
15
|
import { emptyDeviceInfo, resolveStartupAction, showWelcome, WELCOME_DEVICE } from "./welcome.ts";
|
|
16
|
+
import { sanitizeTerminal } from "./sanitize.ts";
|
|
16
17
|
|
|
17
18
|
const USAGE = `usage: dpi-tui [device[:session[:agent]]] [options]
|
|
18
19
|
dpi-tui --url <url> --token <token> [--save <id>]
|
|
@@ -213,10 +214,11 @@ if (startup.kind === "welcome") {
|
|
|
213
214
|
hubEnv,
|
|
214
215
|
),
|
|
215
216
|
{
|
|
216
|
-
notice:
|
|
217
|
+
notice: sanitizeTerminal(
|
|
217
218
|
isDpiError(e) && e.code === "unauthorized"
|
|
218
219
|
? `${device.id}: token rejected by ${device.url}`
|
|
219
220
|
: `${device.id} is offline at ${device.url} (${(e as Error).message})`,
|
|
221
|
+
),
|
|
220
222
|
},
|
|
221
223
|
);
|
|
222
224
|
}
|
|
@@ -13,6 +13,7 @@ import {
|
|
|
13
13
|
} from "@earendil-works/pi-tui";
|
|
14
14
|
import { THINKING_LEVELS, type ThinkingLevel } from "../../dpi-sdk/src/api.ts";
|
|
15
15
|
import { agentTree, type TreeNode } from "../../dpi-sdk/src/models.ts";
|
|
16
|
+
import { sanitizeTerminal } from "./sanitize.ts";
|
|
16
17
|
import type { App } from "./app.ts";
|
|
17
18
|
import { c, selectTheme } from "./theme.ts";
|
|
18
19
|
|
|
@@ -259,15 +260,15 @@ export class Panel extends Box {
|
|
|
259
260
|
export async function pickSession(app: App) {
|
|
260
261
|
const tree = await app.client.tree();
|
|
261
262
|
const items: SelectItem[] = [
|
|
262
|
-
{ value: "+new", label: "+ New session", description: `choose a directory on ${app.device.id}` },
|
|
263
|
+
{ value: "+new", label: "+ New session", description: `choose a directory on ${sanitizeTerminal(app.device.id)}` },
|
|
263
264
|
...tree.sessions.map((s) => ({
|
|
264
265
|
value: s.id,
|
|
265
|
-
label: s.name,
|
|
266
|
-
description: `${s.cwd.split("/").slice(-2).join("/")} │ ${s.agents.length} agent${s.agents.length === 1 ? "" : "s"}${s.busy ? " │ working" : ""}`,
|
|
266
|
+
label: sanitizeTerminal(s.name),
|
|
267
|
+
description: `${sanitizeTerminal(s.cwd.split("/").slice(-2).join("/"))} │ ${s.agents.length} agent${s.agents.length === 1 ? "" : "s"}${s.busy ? " │ working" : ""}`,
|
|
267
268
|
})),
|
|
268
269
|
];
|
|
269
270
|
app.overlay(
|
|
270
|
-
new Picker(`Sessions on ${app.device.id}`, items, (item) => {
|
|
271
|
+
new Picker(`Sessions on ${sanitizeTerminal(app.device.id)}`, items, (item) => {
|
|
271
272
|
app.closeOverlay();
|
|
272
273
|
if (item.value === "+new") return void newSession(app);
|
|
273
274
|
const s = tree.sessions.find((x) => x.id === item.value)!;
|
|
@@ -343,12 +344,12 @@ export function walkDirs(app: App, path: string): Promise<string | undefined | n
|
|
|
343
344
|
app.setPending(null);
|
|
344
345
|
if (!listing) return done(null);
|
|
345
346
|
const items: SelectItem[] = [
|
|
346
|
-
...(listing.path ? [{ value: `use:${listing.path}`, label: `✓ Use ${listing.path}` }] : []),
|
|
347
|
+
...(listing.path ? [{ value: `use:${listing.path}`, label: `✓ Use ${sanitizeTerminal(listing.path)}` }] : []),
|
|
347
348
|
...(listing.path ? [{ value: listing.parent ?? "", label: listing.parent ? ".." : "⌂ start dirs" }] : []),
|
|
348
|
-
...listing.dirs.map((d) => ({ value: d.path, label: `${d.name}/` })),
|
|
349
|
+
...listing.dirs.map((d) => ({ value: d.path, label: `${sanitizeTerminal(d.name)}/` })),
|
|
349
350
|
];
|
|
350
351
|
app.overlay(
|
|
351
|
-
new Picker(`Working directory on ${app.device.name}`, items, (item) => {
|
|
352
|
+
new Picker(`Working directory on ${sanitizeTerminal(app.device.name)}`, items, (item) => {
|
|
352
353
|
app.closeOverlay();
|
|
353
354
|
if (item.value.startsWith("use:")) done(item.value.slice(4));
|
|
354
355
|
else void step(item.value);
|
|
@@ -366,8 +367,8 @@ function chooseModel(app: App, current?: string) {
|
|
|
366
367
|
return new Promise<(typeof app.info.models)[number] | undefined>((done) => {
|
|
367
368
|
const models = app.info.models;
|
|
368
369
|
const picker = new Picker(
|
|
369
|
-
`Model (${app.device.name})`,
|
|
370
|
-
models.map((m) => ({ value: `${m.provider}/${m.id}`, label: m.name, description: `${m.tier} │ ${m.provider}` })),
|
|
370
|
+
`Model (${sanitizeTerminal(app.device.name)})`,
|
|
371
|
+
models.map((m) => ({ value: `${m.provider}/${m.id}`, label: sanitizeTerminal(m.name), description: `${sanitizeTerminal(m.tier)} │ ${sanitizeTerminal(m.provider)}` })),
|
|
371
372
|
(item) => {
|
|
372
373
|
app.closeOverlay();
|
|
373
374
|
done(models.find((m) => `${m.provider}/${m.id}` === item.value));
|
|
@@ -436,7 +437,7 @@ export function pickAgent(app: App) {
|
|
|
436
437
|
const icon = a.kind === "fork" ? "⑂" : a.kind === "subagent" ? "↳" : "◆";
|
|
437
438
|
rows.push({
|
|
438
439
|
value: String(a.id),
|
|
439
|
-
label: `${" ".repeat(depth)}${icon} ${a.name}${a.busy ? " ●" : ""}`,
|
|
440
|
+
label: `${" ".repeat(depth)}${icon} ${sanitizeTerminal(a.name)}${a.busy ? " ●" : ""}`,
|
|
440
441
|
description: [a.kind === "fork" ? `fork @ #${a.forkedAt}` : a.kind, a.background ? `${a.background} bg` : ""]
|
|
441
442
|
.filter(Boolean)
|
|
442
443
|
.join(" │ "),
|
|
@@ -445,7 +446,7 @@ export function pickAgent(app: App) {
|
|
|
445
446
|
}
|
|
446
447
|
};
|
|
447
448
|
walk(agentTree(app.device.id, summary, false), 0);
|
|
448
|
-
const picker = new Picker(`Agents in ${summary.name}`, rows, (item) => {
|
|
449
|
+
const picker = new Picker(`Agents in ${sanitizeTerminal(summary.name)}`, rows, (item) => {
|
|
449
450
|
app.closeOverlay();
|
|
450
451
|
void app.attach(summary.id, Number(item.value));
|
|
451
452
|
}, () => app.closeOverlay());
|
|
@@ -21,6 +21,7 @@ import type { App, DeviceRef } from "./app.ts";
|
|
|
21
21
|
import { Picker } from "./pickers.ts";
|
|
22
22
|
import { parsePairArgs, runPairing, type PairArgs } from "./pairing.ts";
|
|
23
23
|
import { c } from "./theme.ts";
|
|
24
|
+
import { sanitizeTerminal } from "./sanitize.ts";
|
|
24
25
|
|
|
25
26
|
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
|
26
27
|
|
|
@@ -277,7 +278,7 @@ export class WelcomePicker extends Picker {
|
|
|
277
278
|
export function showWelcome(app: App, opts: { notice?: string } = {}) {
|
|
278
279
|
const devices = app.registry?.list() ?? [];
|
|
279
280
|
const subtitle = opts.notice
|
|
280
|
-
? c.err(opts.notice)
|
|
281
|
+
? c.err(sanitizeTerminal(opts.notice))
|
|
281
282
|
: c.muted("This is the app — connect a device to get started:");
|
|
282
283
|
let picked = false; // an action was chosen: closing the overlay is a step, not a quit
|
|
283
284
|
app.overlay(
|
package/deploy/Caddyfile
CHANGED
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
# exempt (exact path+method): GET /healthz · POST /api/pair/start ·
|
|
13
13
|
# POST /api/pair/verify · POST /api/pair/request (device-initiated
|
|
14
14
|
# enrollment — the device holds no Basic credential by design) ·
|
|
15
|
-
# GET /share
|
|
15
|
+
# GET /share/<token> (public capability page — the 20-32-char token IS the boundary; R15 narrowed the matcher to the token shape) ·
|
|
16
16
|
# GET /api/tunnel (WS upgrade) — everything else — including WRONG METHODS
|
|
17
17
|
# on the exempt paths — requires HTTP Basic auth, and the Authorization
|
|
18
18
|
# header is STRIPPED before the hub so device tokens and admin credentials
|
|
@@ -77,7 +77,10 @@ https://{$DPI_PUBLIC_HOST} {
|
|
|
77
77
|
}
|
|
78
78
|
@share {
|
|
79
79
|
method GET
|
|
80
|
-
|
|
80
|
+
# R15 (run-2 h12): exempt ONLY the token-shaped share page (mirrors
|
|
81
|
+
# shares.ts isToken) — a bare /share/* wildcard also exempted the hub's
|
|
82
|
+
# SPA fallback, serving the operator app shell anonymously.
|
|
83
|
+
path_regexp ^/share/[A-Za-z0-9_-]{20,32}$
|
|
81
84
|
}
|
|
82
85
|
@healthz {
|
|
83
86
|
method GET
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "my-durable",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.71",
|
|
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": {
|