my-durable 0.0.57 → 0.0.59

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.
Files changed (32) hide show
  1. package/apps/dpi-backend/scripts/check-contract.mjs +9 -2
  2. package/apps/dpi-backend/src/env-vars.ts +10 -1
  3. package/apps/dpi-backend/src/errors.ts +71 -2
  4. package/apps/dpi-backend/src/gc-cli.ts +24 -17
  5. package/apps/dpi-backend/src/gc.ts +3 -1
  6. package/apps/dpi-backend/src/git.ts +26 -6
  7. package/apps/dpi-backend/src/idempotency.ts +47 -1
  8. package/apps/dpi-backend/src/notify-sinks.ts +42 -8
  9. package/apps/dpi-backend/src/pi-config.ts +43 -8
  10. package/apps/dpi-backend/src/routes.ts +6 -2
  11. package/apps/dpi-backend/src/store.ts +285 -18
  12. package/apps/dpi-backend/src/tunnel.ts +24 -2
  13. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/{index-C9ulm0b-.js → index-DC0Iicch.js} +7 -7
  14. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/{index-C8I93zWz.css → index-DxGrKN6X.css} +1 -1
  15. package/apps/dpi-playground/apps/dpi-playground-fe/dist/index.html +2 -2
  16. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/store.ts +28 -4
  17. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/ModelPicker.vue +13 -4
  18. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/OfflinePanel.vue +6 -6
  19. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/TreeRow.vue +20 -6
  20. package/apps/dpi-playground/apps/dpi-playground-hub/src/main.ts +67 -29
  21. package/apps/dpi-playground/apps/dpi-playground-hub/src/mux.ts +13 -2
  22. package/apps/dpi-playground/apps/dpi-playground-hub/src/shares.ts +7 -1
  23. package/apps/dpi-sdk/src/node/ops.ts +1 -0
  24. package/apps/dpi-tui/src/app.ts +217 -49
  25. package/apps/dpi-tui/src/commands.ts +57 -22
  26. package/apps/dpi-tui/src/pickers.ts +55 -18
  27. package/apps/dpi-tui/src/scroll.ts +59 -0
  28. package/apps/dpi-tui/src/views.ts +17 -2
  29. package/apps/dpi-tui/src/wrap.ts +42 -0
  30. package/bin/update.mjs +2 -1
  31. package/package.json +1 -1
  32. package/scripts/verify.mjs +7 -0
@@ -19,7 +19,10 @@ const WORK = join(backend, ".contract-negative");
19
19
 
20
20
  const checkerSource = readFileSync(CHECKER, "utf8");
21
21
  const apiSource = readFileSync(join(SDK_SRC, "api.ts"), "utf8");
22
- const tsc = join(backend, "node_modules/.bin/tsc");
22
+ // `node_modules/.bin/tsc` is a POSIX sh shim — not executable on win32. Run
23
+ // the real JS entry through the CURRENT node instead: same TypeScript, no
24
+ // shell, works on every platform.
25
+ const tsc = join(backend, "node_modules", "typescript", "bin", "tsc");
23
26
 
24
27
  const tsconfig = {
25
28
  compilerOptions: {
@@ -95,7 +98,11 @@ function prepare(directory, api) {
95
98
  }
96
99
 
97
100
  function compile(directory) {
98
- const result = spawnSync(tsc, ["--noEmit", "-p", "tsconfig.json"], { cwd: directory, encoding: "utf8" });
101
+ const result = spawnSync(process.execPath, [tsc, "--noEmit", "-p", "tsconfig.json"], {
102
+ cwd: directory,
103
+ encoding: "utf8",
104
+ windowsHide: true,
105
+ });
99
106
  return { status: result.status ?? 1, output: `${result.stdout ?? ""}${result.stderr ?? ""}` };
100
107
  }
101
108
 
@@ -120,7 +120,10 @@ const isSecret = (key: string) => SECRET_KEY.test(key);
120
120
  */
121
121
  function parseLines(text: string): Array<{ key?: string; value?: string; line: string }> {
122
122
  if (text === "") return [];
123
- const raw = text.split("\n");
123
+ // CRLF-tolerant: a file edited in Notepad carries \r at every line end —
124
+ // splitting on \n alone would leave it glued to every VALUE (`KEY=abc\r`
125
+ // reads as the key "abc\r", silently corrupting API keys).
126
+ const raw = text.split(/\r?\n/);
124
127
  if (raw.length > 1 && raw[raw.length - 1] === "") raw.pop();
125
128
  return raw.map((line) => {
126
129
  const m = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(line);
@@ -213,6 +216,12 @@ export class EnvFileEditor {
213
216
 
214
217
  /** Remove one key's line. Only file-sourced keys can be removed. */
215
218
  async unset(key: string): Promise<{ removed: boolean }> {
219
+ // Same guard as set(): a managed key has its own dedicated setting (token,
220
+ // port, start dirs, …) — deleting its line from a remote browser locks the
221
+ // operator out just as surely as overwriting it (the set-side guard alone
222
+ // left DELETE /device/env/DPI_TOKEN a working bypass).
223
+ if ((READONLY_KEYS as readonly string[]).includes(key))
224
+ throw invalid(`${key} has its own setting (port, host, start_dirs, …); change that instead`);
216
225
  const lines = parseLines(await this.read());
217
226
  const kept = lines.filter((entry) => entry.key !== key);
218
227
  if (kept.length === lines.length) return { removed: false };
@@ -1,11 +1,12 @@
1
1
  import type { ErrorRequestHandler } from "express";
2
- import { ConversationBusy, SessionFailed } from "@earendil-works/pi-durable";
2
+ import { ConversationBusy, SessionFailed, StorageRequestError } from "@earendil-works/pi-durable";
3
3
  import type { ErrorCode } from "../../dpi-sdk/src/api.js";
4
4
  import { ScheduleRegistryError } from "./schedules.js";
5
5
  import { GraphError } from "./graphs.js";
6
6
  import { NotifySinkError } from "./notify-sinks.js";
7
7
  import { ProjectRegistryError } from "./projects.js";
8
8
  import { EnvError } from "./env-vars.js";
9
+ import { PiConfigError } from "./pi-config.js";
9
10
 
10
11
  const STATUS: Record<ErrorCode, number> = {
11
12
  unauthorized: 401,
@@ -35,6 +36,58 @@ export class ApiFault extends Error {
35
36
  export const invalid = (message: string) => new ApiFault("invalid", message);
36
37
  export const notFound = (message: string) => new ApiFault("not_found", message);
37
38
 
39
+ /**
40
+ * SQLite faults, mapped to bounded client-facing text (R5 finding 5): node:sqlite
41
+ * reports plain Errors with `code: "ERR_SQLITE_ERROR"` and a numeric `errcode`
42
+ * (5=BUSY, 6=LOCKED, 8=READONLY, 11=CORRUPT, 26=NOTADB). The raw message
43
+ * ("database is locked", "no such column: …") must never reach a client.
44
+ */
45
+ const SQLITE_BUSY = 5;
46
+ const SQLITE_LOCKED = 6;
47
+ const SQLITE_CORRUPT = 11;
48
+ const SQLITE_NOTADB = 26;
49
+
50
+ const sqliteCode = (err: unknown): string | undefined =>
51
+ err instanceof Error ? (err as { code?: unknown }).code as string | undefined : undefined;
52
+
53
+ export const isSqliteError = (err: unknown): err is Error & { errcode?: number } =>
54
+ sqliteCode(err) === "ERR_SQLITE_ERROR" && err instanceof Error;
55
+
56
+ const sqliteErrcode = (err: Error & { errcode?: number }): number | undefined =>
57
+ typeof err.errcode === "number" ? err.errcode : undefined;
58
+
59
+ /** True when a failure means "another connection holds the database" — retryable, not fatal. */
60
+ export const isStorageBusy = (err: unknown): boolean => {
61
+ if (!isSqliteError(err)) return false;
62
+ const errcode = sqliteErrcode(err);
63
+ return errcode === SQLITE_BUSY || errcode === SQLITE_LOCKED || /database (is|table is) locked/i.test(err.message);
64
+ };
65
+
66
+ /** The one retryable storage fault (R5 finding 1): 503, temporary, no sqlite internals. */
67
+ export const storageBusyFault = (): ApiFault =>
68
+ new ApiFault("unavailable", "The device's storage is busy; this failure is temporary — retry shortly");
69
+
70
+ /** True when the database FILE itself is unreadable (corrupt header / not a database / foreign format). */
71
+ export const isUnreadableStorage = (err: unknown): boolean => {
72
+ if (!isSqliteError(err)) return false;
73
+ const errcode = sqliteErrcode(err);
74
+ return (
75
+ errcode === SQLITE_CORRUPT ||
76
+ errcode === SQLITE_NOTADB ||
77
+ /file is not a database|disk image is malformed|unsupported file format/i.test(err.message)
78
+ );
79
+ };
80
+
81
+ /** Map any sqlite error to a bounded typed fault; the raw message never leaves the server. */
82
+ const sqliteFault = (err: Error & { errcode?: number }): ApiFault => {
83
+ if (isStorageBusy(err)) return storageBusyFault();
84
+ if (isUnreadableStorage(err))
85
+ return new ApiFault("unavailable", "The device's storage is unreadable; restart the device to quarantine the corrupt file and rebuild");
86
+ if (/^no such (table|column):/i.test(err.message) || /^unknown column/i.test(err.message))
87
+ return new ApiFault("unavailable", "The device's storage schema does not match this build; restart the device to migrate");
88
+ return new ApiFault("unavailable", "A storage operation failed; retry, or restart the device if it persists");
89
+ };
90
+
38
91
  /** Typed registry failures carry their own 4xx code (`invalid`/`not_found`) — map them
39
92
  * to the matching status with the message intact, instead of a 500 "internal". */
40
93
  const registryFault = (err: unknown): ApiFault | undefined => {
@@ -43,7 +96,8 @@ const registryFault = (err: unknown): ApiFault | undefined => {
43
96
  err instanceof GraphError ||
44
97
  err instanceof NotifySinkError ||
45
98
  err instanceof ProjectRegistryError ||
46
- err instanceof EnvError
99
+ err instanceof EnvError ||
100
+ err instanceof PiConfigError
47
101
  )
48
102
  return err.code === "not_found" ? notFound(err.message) : invalid(err.message);
49
103
  return undefined;
@@ -57,9 +111,24 @@ export const errorMiddleware: ErrorRequestHandler = (err, req, res, _next) => {
57
111
  else if (err instanceof SessionFailed)
58
112
  fault = new ApiFault("unavailable", "The session failed and is closed; it is unavailable until reopened");
59
113
  else if (err instanceof ConversationBusy) fault = new ApiFault("busy", "The agent is busy and the input asked to be rejected while busy");
114
+ // pi-durable's typed "this storage READ was malformed" class (a cursor from
115
+ // another scan, an unknown id): caller error whatever the message text. The
116
+ // old mapping keyed on the message-prefix regex below, so only "Invalid…"
117
+ // wordings scored 400 and any other message leaked as a 500 with raw
118
+ // internal text.
119
+ else if (err instanceof StorageRequestError) fault = invalid(err.message);
60
120
  else if (err?.type === "entity.parse.failed") fault = invalid("Body must be valid JSON");
61
121
  else if (err?.type === "entity.too.large") fault = invalid("Body too large");
122
+ // SQLite faults get a bounded typed shape (R5 finding 5) — before any message
123
+ // regex could touch them, and with the full error still logged server-side.
124
+ else if (isSqliteError(err)) {
125
+ console.error(`[dpi-backend] ${req.method} ${req.path}: storage error:`, err.stack);
126
+ fault = sqliteFault(err);
127
+ }
62
128
  else if (/App State changed while you were editing/.test(String(err?.message))) fault = new ApiFault("conflict", err.message);
129
+ // Message-prefix fallback for dpi-sdk's app-state validation Errors
130
+ // (dpi-sdk/src/app-state.ts throws plain Error with no class of its own).
131
+ // Typed classes are mapped above by instanceof — nothing else relies on this.
63
132
  else if (err instanceof Error && /^(Field|Invalid|Use a JSON Pointer|Increment|The state root|State path|Parent must|Value must|Reserved field|App State must|State is too)/.test(err.message))
64
133
  fault = invalid(err.message);
65
134
  else {
@@ -90,24 +90,31 @@ export async function gcCli(args: GcArgs, io: GcIo = defaultGcIo()): Promise<num
90
90
  const archiveDir = join(resolveDataDir(argv, io), "archive");
91
91
  const options = { closedBeforeDays: days, now: io.now() };
92
92
 
93
- if (!apply) {
94
- const plan = await gcPlan(archiveDir, options);
95
- io.print(`archive ${archiveDir}`);
96
- io.print(`keep last ${days}d — ${plan.total.count} archived session(s), ${humanBytes(plan.total.bytes)}`);
97
- if (!plan.candidates.length) {
98
- io.print("nothing to delete.");
99
- } else {
100
- io.print(`would delete ${plan.candidates.length} session(s), ${humanBytes(plan.candidateBytes)}:`);
101
- for (const candidate of plan.candidates.slice(0, 20))
102
- io.print(` ${candidate.sessionId.slice(0, 8)} ${candidate.ageDays}d old ${humanBytes(candidate.bytes)}`);
103
- if (plan.candidates.length > 20) io.print(` … and ${plan.candidates.length - 20} more`);
104
- io.print("re-run with --yes to delete.");
93
+ // The plan/apply calls live inside the pretty-error path (R5 finding 6): a bad
94
+ // cutoff or unreadable archive used to escape as a raw stack trace.
95
+ try {
96
+ if (!apply) {
97
+ const plan = await gcPlan(archiveDir, options);
98
+ io.print(`archive ${archiveDir}`);
99
+ io.print(`keep last ${argv[at + 1]} — ${plan.total.count} archived session(s), ${humanBytes(plan.total.bytes)}`);
100
+ if (!plan.candidates.length) {
101
+ io.print("nothing to delete.");
102
+ } else {
103
+ io.print(`would delete ${plan.candidates.length} session(s), ${humanBytes(plan.candidateBytes)}:`);
104
+ for (const candidate of plan.candidates.slice(0, 20))
105
+ io.print(` ${candidate.sessionId.slice(0, 8)} ${candidate.ageDays}d old ${humanBytes(candidate.bytes)}`);
106
+ if (plan.candidates.length > 20) io.print(` … and ${plan.candidates.length - 20} more`);
107
+ io.print("re-run with --yes to delete.");
108
+ }
109
+ for (const skip of plan.skipped) io.printErr(`skipped ${skip.name}: ${skip.reason}`);
110
+ return 0;
105
111
  }
106
- for (const skip of plan.skipped) io.printErr(`skipped ${skip.name}: ${skip.reason}`);
112
+
113
+ const { removed, bytes } = await gcApply(archiveDir, options);
114
+ io.print(`deleted ${removed.length} archived session(s), ${humanBytes(bytes)} freed.`);
107
115
  return 0;
116
+ } catch (e) {
117
+ io.printErr(`dpi gc: ${e instanceof Error ? e.message : String(e)}`);
118
+ return 2;
108
119
  }
109
-
110
- const { removed, bytes } = await gcApply(archiveDir, options);
111
- io.print(`deleted ${removed.length} archived session(s), ${humanBytes(bytes)} freed.`);
112
- return 0;
113
120
  }
@@ -78,7 +78,9 @@ export async function archivedEntries(archiveDir: string): Promise<{ entries: Ar
78
78
  export async function gcPlan(archiveDir: string, options: { closedBeforeDays: number; now?: number }): Promise<GcPlan> {
79
79
  const now = options.now ?? Date.now();
80
80
  const days = options.closedBeforeDays;
81
- if (!Number.isFinite(days) || days < 1) throw new Error(`closedBeforeDays must be at least 1, got ${String(days)}`);
81
+ // Sub-day cutoffs are legal (R5 finding 6): the CLI advertises 90m/12h and
82
+ // parseDuration delivers them as fractional days. Only non-positive values refuse.
83
+ if (!Number.isFinite(days) || days <= 0) throw new Error(`closedBeforeDays must be positive, got ${String(days)}`);
82
84
  const { entries, skipped } = await archivedEntries(archiveDir);
83
85
  const cutoff = now - days * 86_400_000;
84
86
  const candidates = entries
@@ -41,6 +41,19 @@ export function gitPathFor(p: string, platform: NodeJS.Platform): string {
41
41
  /** `gitPathFor` against THIS platform — the form every argv path must take. */
42
42
  export const gitPath = (p: string): string => gitPathFor(p, process.platform);
43
43
 
44
+ /**
45
+ * Cache-map key for a repo path: ONE entry per repo, not per spelling. Like
46
+ * `gitPathFor` it forward-slashes on win32, plus trailing-slash strip and case
47
+ * fold — `D:\\x`, `d:/x/` and `D:/x` are the same repo, and the status caches,
48
+ * the single-flight map and markDirty only dedupe if every spelling lands on
49
+ * the same key. NOT for argv (case must survive there) — cache maps only.
50
+ */
51
+ export function cacheKey(p: string, platform: NodeJS.Platform = process.platform): string {
52
+ const slashed = platform === "win32" ? p.replace(/\\/g, "/") : p;
53
+ const trimmed = slashed.length > 1 ? slashed.replace(/\/+$/, "") : slashed;
54
+ return platform === "win32" ? trimmed.toLowerCase() : trimmed;
55
+ }
56
+
44
57
  /** Same, for the `-- <paths...>` lists (stage/discard/commit/unstage/resolve). */
45
58
  const gitPaths = (paths: string[]): string[] => paths.map(gitPath);
46
59
 
@@ -153,11 +166,18 @@ export function gitDirtyMarks(): { root: string; at: number }[] {
153
166
  return dirty.slice(-10);
154
167
  }
155
168
 
156
- function markDirty(root: string) {
169
+ /**
170
+ * Drop every cached status at or under this repo root (the fs watcher's dirty
171
+ * mark; exported as a test seam like clearGitStatusCache). The comparisons run
172
+ * on canonical `cacheKey`s, so a root git printed as `D:\repo` invalidates an
173
+ * entry cached as `d:/repo` — and `d:/repo-other` survives untouched.
174
+ */
175
+ export function markDirty(root: string) {
157
176
  const now = Date.now();
158
- for (const [p] of statusCache) if (p === root || p.startsWith(root + "/") || p.startsWith(root + "\\")) statusCache.delete(p);
177
+ const key = cacheKey(root);
178
+ for (const [p] of statusCache) if (p === key || p.startsWith(key + "/")) statusCache.delete(p);
159
179
  // A repo whose files change must get a fresh ATTEMPT, failures included.
160
- for (const [p] of statusFailCache) if (p === root || p.startsWith(root + "/") || p.startsWith(root + "\\")) statusFailCache.delete(p);
180
+ for (const [p] of statusFailCache) if (p === key || p.startsWith(key + "/")) statusFailCache.delete(p);
161
181
  dirty.push({ root, at: now });
162
182
  dirtyListener?.();
163
183
  }
@@ -214,9 +234,9 @@ export function clearGitStatusCache() {
214
234
  /** Structured status for a folder: everything the UIs show, one call.
215
235
  * `now` is injectable so a test can age the caches without sleeping. */
216
236
  export async function gitStatus(path: string, now = Date.now()): Promise<GitStatus> {
217
- // One key per repo, not per spelling: `D:\\x` and `D:/x` are the same repo,
218
- // and single-flight only dedupes if both land on the same entry.
219
- const key = gitPath(path);
237
+ // One key per repo, not per spelling: `D:\\x`, `d:/x/` and `D:/x` land on
238
+ // the SAME entry (cacheKey), so single-flight dedupes every spelling.
239
+ const key = cacheKey(path);
220
240
  const cached = statusCache.get(key);
221
241
  if (cached && now - cached.at < STATUS_TTL) return cached.s;
222
242
  const failed = statusFailCache.get(key);
@@ -1,8 +1,24 @@
1
1
  import type { RequestHandler } from "express";
2
2
  import type { Store } from "./store.js";
3
3
 
4
- /** Replays the stored response for a repeated `Idempotency-Key` on create routes. */
4
+ /** The rendered response of the request that owns an Idempotency-Key mid-flight. */
5
+ type Outcome = { status: number; body: unknown };
6
+
7
+ /**
8
+ * Replays the stored response for a repeated `Idempotency-Key` on create routes.
9
+ *
10
+ * Two layers:
11
+ * - after the first request with a key finishes, `store.replay` answers every
12
+ * later one from the `requests` table;
13
+ * - WHILE it is still rendering, same-key requests share its outcome instead
14
+ * of racing into N duplicates (6 concurrent creates used to make 6
15
+ * sessions: the remember-then-replay row only lands when the winner is
16
+ * done). Same pattern as git.ts's `statusInFlight` — a per-key promise map,
17
+ * not a lock file.
18
+ */
5
19
  export function idempotent(store: Store): RequestHandler {
20
+ // Per-middleware (per Store) so concurrent app instances never share flights.
21
+ const inFlight = new Map<string, Promise<Outcome>>();
6
22
  return (req, res, next) => {
7
23
  const key = req.get("idempotency-key");
8
24
  if (!key) return next();
@@ -10,8 +26,38 @@ export function idempotent(store: Store): RequestHandler {
10
26
  const route = `${req.method} ${req.baseUrl}${req.path}`;
11
27
  const stored = store.replay(key, route);
12
28
  if (stored) return void res.status(stored.status).set("Idempotent-Replay", "true").json(stored.body);
29
+ const flightKey = `${route}\u0000${key}`;
30
+ const running = inFlight.get(flightKey);
31
+ if (running) {
32
+ // A loser waits for the winner's outcome: a stored success replays with
33
+ // the header; a failure is handed over as-is (nothing was remembered, so
34
+ // the caller may still retry the key).
35
+ void running.then((done) => {
36
+ if (done.status < 400) res.set("Idempotent-Replay", "true");
37
+ res.status(done.status).json(done.body);
38
+ }, next);
39
+ return;
40
+ }
41
+ let settle!: (outcome: Outcome) => void;
42
+ let fail!: (error: Error) => void;
43
+ const flight: Promise<Outcome> = new Promise<Outcome>((ok, no) => {
44
+ settle = ok;
45
+ fail = no;
46
+ }).finally(() => {
47
+ if (inFlight.get(flightKey) === flight) inFlight.delete(flightKey);
48
+ });
49
+ // The winner never awaits `flight`; without this a winner that dies without
50
+ // rendering would surface as an unhandled rejection.
51
+ flight.catch(() => {});
52
+ inFlight.set(flightKey, flight);
53
+ // A client that disconnects before the response must release same-key
54
+ // waiters, not hang them forever.
55
+ res.once("close", () => {
56
+ if (!res.writableEnded) fail(new Error("the request holding this Idempotency-Key ended without a response"));
57
+ });
13
58
  const json = res.json.bind(res);
14
59
  res.json = (body: unknown) => {
60
+ settle({ status: res.statusCode, body });
15
61
  if (res.statusCode < 400) store.remember(key, route, res.statusCode, body);
16
62
  return json(body);
17
63
  };
@@ -121,6 +121,11 @@ export interface SinkRecord {
121
121
  lastError?: string;
122
122
  /** HTTP status of that attempt; absent when the request never got a response. */
123
123
  lastStatus?: number;
124
+ /** The per-sink grant this record was created (or last patched) with — a LAN
125
+ * sink must survive its own patches: re-validating the SAME url on a later
126
+ * PATCH reuses this flag instead of 400ing. Pointing the sink at a NEW url
127
+ * is judged like a fresh create: env default or an explicit opt-in. */
128
+ allowPrivateHosts?: boolean;
124
129
  }
125
130
 
126
131
  /** The on-disk document. `version` exists so a future shape can be migrated instead of discarded. */
@@ -385,12 +390,9 @@ function validateInput(
385
390
  if (!input || typeof input !== "object") throw invalid("sink input is required");
386
391
  if (!isKind(input.kind)) throw invalid(`kind must be "webhook" or "ntfy"`);
387
392
  const kind = input.kind;
388
- const url = normaliseSinkUrl(input.url, { allowPrivateHosts: options.allowPrivateHosts === true });
389
- if (kind === "ntfy") {
390
- // ntfy publishes to <server>/<topic>; a bare server URL would 404 on every event.
391
- const path = new URL(url).pathname.replace(/^\/+|\/+$/g, "");
392
- if (!path) throw invalid(`ntfy url must include the topic: https://ntfy.sh/<topic>`);
393
- }
393
+ // Scalar fields first, so a patch that carries both a bad label and a url
394
+ // problem reports the label — the field the caller can fix without deciding
395
+ // the url question again.
394
396
  if (input.enabled !== undefined && typeof input.enabled !== "boolean") {
395
397
  throw invalid("enabled must be true or false");
396
398
  }
@@ -400,8 +402,14 @@ function validateInput(
400
402
  if (input.priority !== undefined && kind !== "ntfy") throw invalid("priority is ntfy-only");
401
403
  if (input.tags !== undefined && kind !== "ntfy") throw invalid("tags are ntfy-only");
402
404
  const label = normaliseLabel(input.label);
403
- const priority = input.priority;
404
405
  const tags = normaliseTags(input.tags);
406
+ const priority = input.priority;
407
+ const url = normaliseSinkUrl(input.url, { allowPrivateHosts: options.allowPrivateHosts === true });
408
+ if (kind === "ntfy") {
409
+ // ntfy publishes to <server>/<topic>; a bare server URL would 404 on every event.
410
+ const path = new URL(url).pathname.replace(/^\/+|\/+$/g, "");
411
+ if (!path) throw invalid(`ntfy url must include the topic: https://ntfy.sh/<topic>`);
412
+ }
405
413
  return {
406
414
  kind,
407
415
  url,
@@ -447,6 +455,7 @@ function coerceRecord(raw: unknown, now: number): SinkRecord | undefined {
447
455
  if (label) record.label = label;
448
456
  if (source.kind === "ntfy" && isPriority(source.priority)) record.priority = source.priority;
449
457
  if (tags) record.tags = tags;
458
+ if (source.allowPrivateHosts === true) record.allowPrivateHosts = true;
450
459
  if (typeof source.lastDeliveryAt === "number") record.lastDeliveryAt = source.lastDeliveryAt;
451
460
  if (typeof source.lastStatus === "number") record.lastStatus = source.lastStatus;
452
461
  const lastError = nonEmptyString(source.lastError);
@@ -598,6 +607,10 @@ export class NotifySinks {
598
607
  while (staged.has(id)) id = newSinkId();
599
608
  const now = this.now();
600
609
  const record: SinkRecord = { id, ...fields, createdAt: now, updatedAt: now };
610
+ // Remember the per-request grant on the record: it is what lets later
611
+ // patches of the SAME url re-validate instead of 400ing (the env default
612
+ // needs no record — it applies on its own).
613
+ if (options.allowPrivateHosts === true) record.allowPrivateHosts = true;
601
614
  staged.set(record.id, record);
602
615
  await this.commit(staged);
603
616
  return clone(record);
@@ -632,9 +645,30 @@ export class NotifySinks {
632
645
  else if (existing.priority) merged.priority = existing.priority;
633
646
  if ("tags" in patch) merged.tags = patch.tags;
634
647
  else if (existing.tags) merged.tags = existing.tags;
635
- const fields = validateInput(merged, { allowPrivateHosts: this.allowPrivateHosts || options.allowPrivateHosts === true });
648
+ // The grant persisted at create re-validates the sink's OWN url on every
649
+ // patch — {"label":"x"} on a LAN sink must not 400. A NEW url is judged
650
+ // like a fresh create: env default or an explicit per-request opt-in
651
+ // (B5), so the flag is not a one-time skeleton key for future hosts.
652
+ let urlUnchanged = true;
653
+ if (patch.url !== undefined) {
654
+ try {
655
+ urlUnchanged = normaliseSinkUrl(patch.url, { allowPrivateHosts: true }) === existing.url;
656
+ } catch {
657
+ urlUnchanged = false; // the real validation below reports why
658
+ }
659
+ }
660
+ const fields = validateInput(merged, {
661
+ allowPrivateHosts:
662
+ this.allowPrivateHosts ||
663
+ options.allowPrivateHosts === true ||
664
+ (existing.allowPrivateHosts === true && urlUnchanged),
665
+ });
636
666
  const next: SinkRecord = { ...existing, ...fields, id: existing.id, createdAt: existing.createdAt };
637
667
  next.updatedAt = this.now();
668
+ // An explicit opt-in on this patch re-grants the record (for its new url);
669
+ // otherwise the create-time grant rides along untouched.
670
+ if (options.allowPrivateHosts === true || existing.allowPrivateHosts === true) next.allowPrivateHosts = true;
671
+ else delete next.allowPrivateHosts;
638
672
  // A field that validation dropped (empty label, no tags) must not linger from the old record.
639
673
  if (!fields.label) delete next.label;
640
674
  if (!fields.priority) delete next.priority;
@@ -250,7 +250,35 @@ export function piAuthView(auth: Record<string, Credential>, modelsJson: PiModel
250
250
 
251
251
  const PROVIDER_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
252
252
 
253
- /** Read auth.json strictly: absent → {}, corrupt → REFUSE (pi owns the fix). */
253
+ export type PiConfigErrorCode = "invalid" | "not_found";
254
+
255
+ /** Typed failure so routes can answer 400 (`invalid`) or 404 (`not_found`)
256
+ * without string matching — a hostile provider id (path-traversal shape,
257
+ * spaces, unicode) is caller error, not a 500 with a stack. */
258
+ export class PiConfigError extends Error {
259
+ readonly code: PiConfigErrorCode;
260
+
261
+ constructor(code: PiConfigErrorCode, message: string) {
262
+ super(message);
263
+ this.name = "PiConfigError";
264
+ this.code = code;
265
+ }
266
+ }
267
+
268
+ /** Provider ids reach a filename key in pi's auth.json, so anything outside
269
+ * PROVIDER_ID — including `../` shapes, spaces and non-ASCII — is refused
270
+ * before any file is touched. */
271
+ function assertProviderId(providerId: string): void {
272
+ if (!PROVIDER_ID.test(providerId))
273
+ throw new PiConfigError(
274
+ "invalid",
275
+ `invalid provider id: ${JSON.stringify(providerId)} (use 1–64 characters of letters, digits, dot, dash or underscore)`,
276
+ );
277
+ }
278
+
279
+ /** Read auth.json strictly: absent → {}, corrupt → REFUSE (pi owns the fix).
280
+ * Typed PiConfigError: the device refusing to touch pi's broken file is a
281
+ * caller-facing 4xx with the plain words, not a 500 with a stack. */
254
282
  function readAuthStrict(dir: string): Record<string, Credential> {
255
283
  const path = join(dir, "auth.json");
256
284
  if (!existsSync(path)) return {};
@@ -258,10 +286,10 @@ function readAuthStrict(dir: string): Record<string, Credential> {
258
286
  try {
259
287
  parsed = JSON.parse(readFileSync(path, "utf8"));
260
288
  } catch {
261
- throw Error("auth.json is not valid JSON — fix it with pi, the device will not rewrite it");
289
+ throw new PiConfigError("invalid", "auth.json is not valid JSON — fix it with pi, the device will not rewrite it");
262
290
  }
263
291
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
264
- throw Error("auth.json has an unexpected shape — fix it with pi, the device will not rewrite it");
292
+ throw new PiConfigError("invalid", "auth.json has an unexpected shape — fix it with pi, the device will not rewrite it");
265
293
  return parsed as Record<string, Credential>;
266
294
  }
267
295
 
@@ -279,14 +307,18 @@ function writeAuthAtomic(dir: string, next: Record<string, Credential>): void {
279
307
  renameSync(tmp, path);
280
308
  }
281
309
 
282
- /** Set one api_key. Refuses invalid ids, oversized keys, and oauth entries. */
310
+ /** Set one api_key. Refuses invalid ids, oversized keys, and oauth entries
311
+ * (typed: an oauth conflict is caller error → 4xx, never a 500). */
283
312
  export function writePiApiKey(dir: string, providerId: string, key: string): PiAuthEntry {
284
- if (!PROVIDER_ID.test(providerId)) throw Error(`invalid provider id: ${JSON.stringify(providerId)}`);
313
+ assertProviderId(providerId);
285
314
  if (!key.trim() || key.length > 4096) throw Error("key must be 1–4096 non-whitespace characters");
286
315
  const auth = readAuthStrict(dir);
287
316
  const existing = auth[providerId];
288
317
  if (existing && existing.type !== "api_key")
289
- throw Error(`${providerId} uses an interactive pi login (${existing.type}) — edit it with pi, not here`);
318
+ throw new PiConfigError(
319
+ "invalid",
320
+ `${providerId} uses an interactive pi login (${existing.type}) — edit it with pi, not here`,
321
+ );
290
322
  const credential: ApiKeyCredential = { type: "api_key", key };
291
323
  writeAuthAtomic(dir, { ...auth, [providerId]: credential });
292
324
  return { providerId, type: "api_key", source: existing ? "auth.json" : "auth.json", masked: maskPiKey(key) };
@@ -294,11 +326,14 @@ export function writePiApiKey(dir: string, providerId: string, key: string): PiA
294
326
 
295
327
  /** Remove one api_key entry. Same refusals; returns whether it existed. */
296
328
  export function removePiApiKey(dir: string, providerId: string): boolean {
297
- if (!PROVIDER_ID.test(providerId)) throw Error(`invalid provider id: ${JSON.stringify(providerId)}`);
329
+ assertProviderId(providerId);
298
330
  const auth = readAuthStrict(dir);
299
331
  const existing = auth[providerId];
300
332
  if (existing && existing.type !== "api_key")
301
- throw Error(`${providerId} uses an interactive pi login (${existing.type}) — edit it with pi, not here`);
333
+ throw new PiConfigError(
334
+ "invalid",
335
+ `${providerId} uses an interactive pi login (${existing.type}) — edit it with pi, not here`,
336
+ );
302
337
  if (!existing) return false;
303
338
  const next = { ...auth };
304
339
  delete next[providerId];
@@ -10,7 +10,7 @@ import type { DevicePairing } from "./pairing.js";
10
10
 
11
11
  type Async = (req: Request, res: Response) => Promise<unknown>;
12
12
  const route = (fn: Async) => (req: Request, res: Response, next: NextFunction) => fn(req, res).catch(next);
13
- import { gitOp, gitStatus, gitStatusBatch, isNotARepoError, type GitOp } from "./git.ts";
13
+ import { gitOp, gitStatus, gitStatusBatch, isNotARepoError, type GitOp } from "./git.js";
14
14
  const GIT_OPS: GitOp[] = ["diff", "log", "log-list", "fetch", "pull", "push", "switch", "branch", "commit", "stage", "unstage", "discard", "diff-file", "stash-push", "stash-pop", "compare", "merge-abort", "show-files", "ignore", "checkpoint", "checkpoints", "rewind", "resolve", "submodule-update", "pr-create", "pr-list", "pr-merge", "pr-checks", "pr-comment", "worktree-list", "worktree-add", "worktree-remove"];
15
15
 
16
16
  interface Locals {
@@ -42,7 +42,11 @@ export function v1(
42
42
  connector?: { status(): unknown },
43
43
  stop?: () => void,
44
44
  ) {
45
- const r = Router();
45
+ // caseSensitive: the hub tunnel's allowlist is lowercase-exact, so the
46
+ // device-local surface must not be looser than what can actually reach it
47
+ // (/V1/DEVICE used to answer 200 over loopback and 404 through the tunnel).
48
+ // Every client (sdk/TUI/web) speaks lowercase — verified against sdk client.ts.
49
+ const r = Router({ caseSensitive: true });
46
50
  const create = idempotent(store);
47
51
  // `dpi device stop`: graceful local shutdown (token-authed like every /v1
48
52
  // route). The response flushes BEFORE the daemon tears down so the caller