my-durable 0.0.56 → 0.0.58

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.
@@ -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
 
@@ -42,6 +42,8 @@ export const defaultAwakeIo = (): AwakeIo => ({
42
42
  const child: ChildProcess = nodeSpawn(cmd, args as string[], {
43
43
  stdio: "ignore",
44
44
  detached: false,
45
+ // A keep-awake holder is background machinery: no console window.
46
+ windowsHide: true,
45
47
  });
46
48
  child.unref();
47
49
  return { kill: () => void child.kill("SIGTERM") };
@@ -162,7 +162,9 @@ interface Io {
162
162
 
163
163
  const execDefault = (cmd: string, args: string[]) =>
164
164
  new Promise<{ ok: boolean; output: string; code: number }>((resolve) => {
165
- execFile(cmd, args, { timeout: 30_000 }, (error, stdout, stderr) => {
165
+ // windowsHide: this daemon runs under a supervisor with no terminal — a
166
+ // console window flashing per call is pure noise on Windows.
167
+ execFile(cmd, args, { timeout: 30_000, windowsHide: true }, (error, stdout, stderr) => {
166
168
  const code = (error as { code?: number } | null)?.code ?? 0;
167
169
  resolve({ ok: !error, output: String(stdout ?? "") + String(stderr ?? ""), code });
168
170
  });
@@ -272,6 +274,8 @@ export function startBackendDetached(
272
274
  stdio: ["ignore", fd, fd],
273
275
  env: cleanChildEnv(env),
274
276
  cwd: dirname(dpi),
277
+ // The whole point of this spawn is "no terminal" — never flash a console.
278
+ windowsHide: true,
275
279
  });
276
280
  child.unref();
277
281
  closeSync(fd);
@@ -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 };
@@ -6,6 +6,7 @@ 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,
@@ -43,7 +44,8 @@ const registryFault = (err: unknown): ApiFault | undefined => {
43
44
  err instanceof GraphError ||
44
45
  err instanceof NotifySinkError ||
45
46
  err instanceof ProjectRegistryError ||
46
- err instanceof EnvError
47
+ err instanceof EnvError ||
48
+ err instanceof PiConfigError
47
49
  )
48
50
  return err.code === "not_found" ? notFound(err.message) : invalid(err.message);
49
51
  return undefined;
@@ -20,7 +20,55 @@ const GIT_SLOW_TIMEOUT = 45_000;
20
20
  /** Same-path status within this window returns the cached answer — the UIs
21
21
  * poll, and a 20s status must not restart on every poll tick. */
22
22
  const STATUS_TTL = 5_000;
23
+ /** A FAILED status is cached too, but briefly: without this, a repo git cannot
24
+ * reach re-spawned git on every UI poll tick (935 failures in one user log).
25
+ * Short enough that a fixed path (git installed, drive mounted) recovers on
26
+ * its own; long enough that a poll storm costs one spawn. */
27
+ const STATUS_FAIL_TTL = 15_000;
23
28
  const statusCache = new Map<string, { at: number; s: GitStatus }>();
29
+ const statusFailCache = new Map<string, { at: number; msg: string }>();
30
+ /** One in-flight status per path: N UI clients polling the same repos through
31
+ * /git/status-batch must share ONE git spawn, not N. */
32
+ const statusInFlight = new Map<string, Promise<GitStatus>>();
33
+
34
+ /** Paths as git ARGV: Git-for-Windows' msys layer mangles backslashes inside
35
+ * argv (`D:\source\x` arrives as `D:source?x` → "cannot change to"), while
36
+ * the very same path with forward slashes works. Pure — no fs, no resolution. */
37
+ export function gitPathFor(p: string, platform: NodeJS.Platform): string {
38
+ return platform === "win32" ? p.replace(/\\/g, "/") : p;
39
+ }
40
+
41
+ /** `gitPathFor` against THIS platform — the form every argv path must take. */
42
+ export const gitPath = (p: string): string => gitPathFor(p, process.platform);
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
+
57
+ /** Same, for the `-- <paths...>` lists (stage/discard/commit/unstage/resolve). */
58
+ const gitPaths = (paths: string[]): string[] => paths.map(gitPath);
59
+
60
+ /** Child-process options, exported so a test can assert the Windows console
61
+ * window stays hidden: a daemon that polls git must never flash a terminal. */
62
+ export const GIT_EXEC_OPTS = (timeout: number) => ({ timeout, maxBuffer: 8 * 1024 * 1024, windowsHide: true });
63
+ export const GH_EXEC_OPTS = (cwd: string, timeout: number) => ({ cwd, timeout, maxBuffer: 4 * 1024 * 1024, windowsHide: true });
64
+
65
+ /** Test seam for counting/driving spawns: `node:child_process`'s ESM namespace
66
+ * is not redefinable, so `mock.method` cannot reach `execFile`. Pass nothing
67
+ * to restore the real one. */
68
+ let execFileImpl: typeof execFile = execFile;
69
+ export function setGitExecForTests(fn?: typeof execFile) {
70
+ execFileImpl = fn ?? execFile;
71
+ }
24
72
 
25
73
  /** The ONE stderr that legitimately means "no repo here" — anything else
26
74
  * (git missing, permission, timeout) is a failure we must not flatten into
@@ -34,7 +82,8 @@ export function isNotARepoError(e: unknown): boolean {
34
82
  /** One git call; rejects on non-zero exit with stderr in the message. */
35
83
  export function git(cwd: string, args: string[], timeout = GIT_TIMEOUT): Promise<string> {
36
84
  return new Promise((ok, fail) => {
37
- execFile("git", ["-C", cwd, ...args], { timeout, maxBuffer: 8 * 1024 * 1024 }, (error, stdout, stderr) => {
85
+ // `-C` is ARGV, so the path goes out forward-slashed (see gitPath).
86
+ execFileImpl("git", ["-C", gitPath(cwd), ...args], GIT_EXEC_OPTS(timeout), (error, stdout, stderr) => {
38
87
  if (error) fail(Error(String(stderr || stdout || error.message).trim().slice(0, 400)));
39
88
  // git chats on stderr for worktree add/switch/fetch — keep both.
40
89
  else ok(`${String(stdout)}${String(stdout) && String(stderr) ? "\n" : ""}${String(stderr)}`);
@@ -48,7 +97,8 @@ export function git(cwd: string, args: string[], timeout = GIT_TIMEOUT): Promise
48
97
  export function gh(cwd: string, args: string[], timeout = GIT_TIMEOUT): Promise<string> {
49
98
  return new Promise((ok, fail) => {
50
99
  // gh resolves the repo from cwd (a --repo flag wants a slug, not a path).
51
- execFile("gh", args, { cwd, timeout, maxBuffer: 4 * 1024 * 1024 }, (error, stdout, stderr) => {
100
+ // cwd is a Node spawn option, not argv — Node handles Windows paths here.
101
+ execFileImpl("gh", args, GH_EXEC_OPTS(cwd, timeout), (error, stdout, stderr) => {
52
102
  if (error) fail(Error(String(stderr || stdout || error.message).trim().slice(0, 400)));
53
103
  else ok(String(stdout));
54
104
  });
@@ -116,9 +166,18 @@ export function gitDirtyMarks(): { root: string; at: number }[] {
116
166
  return dirty.slice(-10);
117
167
  }
118
168
 
119
- 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) {
120
176
  const now = Date.now();
121
- for (const [p, c] 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);
179
+ // A repo whose files change must get a fresh ATTEMPT, failures included.
180
+ for (const [p] of statusFailCache) if (p === key || p.startsWith(key + "/")) statusFailCache.delete(p);
122
181
  dirty.push({ root, at: now });
123
182
  dirtyListener?.();
124
183
  }
@@ -169,12 +228,30 @@ function ensureWatcher(root: string) {
169
228
  /** Test hook: the TTL cache would serve a pre-mutation answer. */
170
229
  export function clearGitStatusCache() {
171
230
  statusCache.clear();
231
+ statusFailCache.clear();
172
232
  }
173
233
 
174
- /** Structured status for a folder: everything the UIs show, one call. */
175
- export async function gitStatus(path: string): Promise<GitStatus> {
176
- const cached = statusCache.get(path);
177
- if (cached && Date.now() - cached.at < STATUS_TTL) return cached.s;
234
+ /** Structured status for a folder: everything the UIs show, one call.
235
+ * `now` is injectable so a test can age the caches without sleeping. */
236
+ export async function gitStatus(path: string, now = Date.now()): Promise<GitStatus> {
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);
240
+ const cached = statusCache.get(key);
241
+ if (cached && now - cached.at < STATUS_TTL) return cached.s;
242
+ const failed = statusFailCache.get(key);
243
+ // Same error text as the original failure — the UI still shows WHY.
244
+ if (failed && now - failed.at < STATUS_FAIL_TTL) throw new Error(failed.msg);
245
+ const running = statusInFlight.get(key);
246
+ if (running) return running;
247
+ const p = statusOnce(path, key).finally(() => {
248
+ if (statusInFlight.get(key) === p) statusInFlight.delete(key);
249
+ });
250
+ statusInFlight.set(key, p);
251
+ return p;
252
+ }
253
+
254
+ async function statusOnce(path: string, key: string): Promise<GitStatus> {
178
255
  const out: GitStatus = { repo: false };
179
256
  try {
180
257
  // Reach git at all before trusting any "empty" answer: git missing from
@@ -275,7 +352,8 @@ export async function gitStatus(path: string): Promise<GitStatus> {
275
352
  // silently (checklist fs-auto-refresh, device side).
276
353
  ensureWatcher(root);
277
354
  const wl = wlP.value;
278
- statusCache.set(path, { at: Date.now(), s: out });
355
+ statusCache.set(key, { at: Date.now(), s: out });
356
+ statusFailCache.delete(key);
279
357
  out.worktrees = wl
280
358
  .split("\n\n")
281
359
  .map((b) => b.trim())
@@ -288,7 +366,29 @@ export async function gitStatus(path: string): Promise<GitStatus> {
288
366
  } catch (e) {
289
367
  // Only a GENUINE "not a git repository" is repo:false. Anything else —
290
368
  // git not found, EACCES, timeout — is a real failure the UIs must show.
291
- if (!isNotARepoError(e)) throw new Error(`git failed on the device: ${(e as Error).message.slice(0, 160)}`);
369
+ if (!isNotARepoError(e)) {
370
+ const msg = `git failed on the device: ${(e as Error).message.slice(0, 160)}`;
371
+ // Cache the FAILURE (briefly): the UIs poll, and a path git cannot reach
372
+ // must cost one spawn per TTL, not one per tick.
373
+ const at = Date.now();
374
+ for (const [k, v] of statusFailCache) if (at - v.at >= STATUS_FAIL_TTL) statusFailCache.delete(k);
375
+ statusFailCache.set(key, { at, msg });
376
+ throw new Error(msg);
377
+ }
378
+ // "Not a repository" is an ANSWER, not a failure: cache it exactly like a
379
+ // success (STATUS_TTL). Without this, every UI poll tick re-spawned git for
380
+ // a plain folder — and on Windows each spawn flashes a console window, the
381
+ // "spam terminal" symptom. Sessions routinely live in non-git folders, so
382
+ // this is the common path. Deliberately NOT in statusFailCache: nothing
383
+ // throws here, so the 15s fail TTL must not apply.
384
+ //
385
+ // Recovery when the folder BECOMES a repo: a plain dir has no fs watcher
386
+ // (ensureWatcher runs on the success path only), so markDirty is
387
+ // unreachable for it — the 5s TTL IS the recovery path: `git init` shows
388
+ // up within STATUS_TTL. Do not add a watcher for it.
389
+ // Keyed by the normalized gitPath key, so markDirty/clearGitStatusCache
390
+ // (which clear statusCache by that key) invalidate it too.
391
+ statusCache.set(key, { at: Date.now(), s: out });
292
392
  }
293
393
  return out;
294
394
  }
@@ -419,16 +519,16 @@ export async function gitOp(
419
519
  }
420
520
  case "stage": {
421
521
  if (!files?.length) throw Error("stage needs files");
422
- return { text: (await git(path, ["add", "--", ...files])).trim() || `staged ${files.length} file(s)` };
522
+ return { text: (await git(path, ["add", "--", ...gitPaths(files)])).trim() || `staged ${files.length} file(s)` };
423
523
  }
424
524
  case "discard": {
425
525
  // IntelliJ's Rollback: index AND worktree back to HEAD for these paths.
426
526
  if (!files?.length) throw Error("discard needs files");
427
- return { text: (await git(path, ["checkout", "HEAD", "--", ...files])).trim() || `discarded ${files.length} file(s)` };
527
+ return { text: (await git(path, ["checkout", "HEAD", "--", ...gitPaths(files)])).trim() || `discarded ${files.length} file(s)` };
428
528
  }
429
529
  case "diff-file": {
430
530
  if (!target) throw Error("diff-file needs a file path");
431
- return { text: (await git(path, ["--no-pager", "diff", ...(staged ? ["--cached"] : []), "HEAD", "--", target])).trim() || "no diff" };
531
+ return { text: (await git(path, ["--no-pager", "diff", ...(staged ? ["--cached"] : []), "HEAD", "--", gitPath(target)])).trim() || "no diff" };
432
532
  }
433
533
  case "stash-push":
434
534
  return { text: (await git(path, ["stash", "push", ...(message ? ["-m", message] : [])])).trim() || "stashed" };
@@ -438,10 +538,10 @@ export async function gitOp(
438
538
  // IntelliJ's Unstage: index only, worktree keeps its changes.
439
539
  if (!files?.length) throw Error("unstage needs files");
440
540
  try {
441
- return { text: (await git(path, ["reset", "-q", "HEAD", "--", ...files])).trim() || `unstaged ${files.length} file(s)` };
541
+ return { text: (await git(path, ["reset", "-q", "HEAD", "--", ...gitPaths(files)])).trim() || `unstaged ${files.length} file(s)` };
442
542
  } catch {
443
543
  // unborn branch: HEAD does not resolve yet — reset against the empty tree.
444
- return { text: (await git(path, ["reset", "-q", "--", ...files])).trim() || `unstaged ${files.length} file(s)` };
544
+ return { text: (await git(path, ["reset", "-q", "--", ...gitPaths(files)])).trim() || `unstaged ${files.length} file(s)` };
445
545
  }
446
546
  }
447
547
  case "compare": {
@@ -518,8 +618,8 @@ export async function gitOp(
518
618
  // orca's conflicts section, one click: pick a side, stage the result.
519
619
  if (side !== "ours" && side !== "theirs") throw Error("resolve needs side=ours|theirs");
520
620
  if (!files?.length) throw Error("resolve needs files");
521
- await git(path, ["checkout", `--${side}`, "--", ...files]);
522
- return { text: (await git(path, ["add", "--", ...files])).trim() || `resolved ${files.length} file(s) with --${side}` };
621
+ await git(path, ["checkout", `--${side}`, "--", ...gitPaths(files)]);
622
+ return { text: (await git(path, ["add", "--", ...gitPaths(files)])).trim() || `resolved ${files.length} file(s) with --${side}` };
523
623
  }
524
624
  case "submodule-update":
525
625
  return { text: (await git(path, ["submodule", "update", "--init", "--recursive"], GIT_SLOW_TIMEOUT)).trim() || "submodules up to date" };
@@ -559,7 +659,7 @@ export async function gitOp(
559
659
  // IntelliJ-style: chosen files only, when the caller picked some.
560
660
  if (files?.length) {
561
661
  for (const f of files) if (f.includes("\0") || f === "") throw Error("bad file path");
562
- return { text: (await git(path, ["commit", "-m", msg, "--", ...files])).split("\n")[0]?.trim() ?? "committed" };
662
+ return { text: (await git(path, ["commit", "-m", msg, "--", ...gitPaths(files)])).split("\n")[0]?.trim() ?? "committed" };
563
663
  }
564
664
  return { text: (await git(path, ["commit", "-am", msg])).split("\n")[0]?.trim() ?? "committed" };
565
665
  }
@@ -571,14 +671,14 @@ export async function gitOp(
571
671
  if (!target || !isAbsolute(target)) throw Error("worktree-add needs an absolute target path");
572
672
  if (branch) {
573
673
  if (!safeRef(branch)) throw Error("worktree-add branch name is invalid (letters, digits, ./-_)");
574
- return { text: (await git(path, ["worktree", "add", "-b", branch, target])).trim() };
674
+ return { text: (await git(path, ["worktree", "add", "-b", branch, gitPath(target)])).trim() };
575
675
  }
576
676
  if (!ref || !safeRef(ref)) throw Error("worktree-add needs a branch (new) or ref (existing)");
577
- return { text: (await git(path, ["worktree", "add", target, ref])).trim() };
677
+ return { text: (await git(path, ["worktree", "add", gitPath(target), ref])).trim() };
578
678
  }
579
679
  case "worktree-remove": {
580
680
  if (!target || !isAbsolute(target)) throw Error("worktree-remove needs an absolute path");
581
- return { text: (await git(path, ["worktree", "remove", target])).trim() || `removed ${target}` };
681
+ return { text: (await git(path, ["worktree", "remove", gitPath(target)])).trim() || `removed ${target}` };
582
682
  }
583
683
  }
584
684
  }
@@ -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,6 +250,32 @@ 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
+ 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
+
253
279
  /** Read auth.json strictly: absent → {}, corrupt → REFUSE (pi owns the fix). */
254
280
  function readAuthStrict(dir: string): Record<string, Credential> {
255
281
  const path = join(dir, "auth.json");
@@ -281,7 +307,7 @@ function writeAuthAtomic(dir: string, next: Record<string, Credential>): void {
281
307
 
282
308
  /** Set one api_key. Refuses invalid ids, oversized keys, and oauth entries. */
283
309
  export function writePiApiKey(dir: string, providerId: string, key: string): PiAuthEntry {
284
- if (!PROVIDER_ID.test(providerId)) throw Error(`invalid provider id: ${JSON.stringify(providerId)}`);
310
+ assertProviderId(providerId);
285
311
  if (!key.trim() || key.length > 4096) throw Error("key must be 1–4096 non-whitespace characters");
286
312
  const auth = readAuthStrict(dir);
287
313
  const existing = auth[providerId];
@@ -294,7 +320,7 @@ export function writePiApiKey(dir: string, providerId: string, key: string): PiA
294
320
 
295
321
  /** Remove one api_key entry. Same refusals; returns whether it existed. */
296
322
  export function removePiApiKey(dir: string, providerId: string): boolean {
297
- if (!PROVIDER_ID.test(providerId)) throw Error(`invalid provider id: ${JSON.stringify(providerId)}`);
323
+ assertProviderId(providerId);
298
324
  const auth = readAuthStrict(dir);
299
325
  const existing = auth[providerId];
300
326
  if (existing && existing.type !== "api_key")
@@ -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