my-durable 0.0.57 → 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.
- package/apps/dpi-backend/scripts/check-contract.mjs +9 -2
- package/apps/dpi-backend/src/env-vars.ts +10 -1
- package/apps/dpi-backend/src/errors.ts +3 -1
- package/apps/dpi-backend/src/git.ts +26 -6
- package/apps/dpi-backend/src/idempotency.ts +47 -1
- package/apps/dpi-backend/src/notify-sinks.ts +42 -8
- package/apps/dpi-backend/src/pi-config.ts +28 -2
- package/apps/dpi-backend/src/routes.ts +6 -2
- package/apps/dpi-backend/src/store.ts +73 -4
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/{index-C9ulm0b-.js → index-DC0Iicch.js} +7 -7
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/{index-C8I93zWz.css → index-DxGrKN6X.css} +1 -1
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/index.html +2 -2
- package/apps/dpi-playground/apps/dpi-playground-fe/src/client/store.ts +28 -4
- package/apps/dpi-playground/apps/dpi-playground-fe/src/components/ModelPicker.vue +13 -4
- package/apps/dpi-playground/apps/dpi-playground-fe/src/components/OfflinePanel.vue +6 -6
- package/apps/dpi-playground/apps/dpi-playground-fe/src/components/TreeRow.vue +20 -6
- package/apps/dpi-sdk/src/node/ops.ts +1 -0
- package/apps/dpi-tui/src/app.ts +109 -24
- package/apps/dpi-tui/src/commands.ts +41 -14
- package/apps/dpi-tui/src/pickers.ts +51 -18
- package/bin/update.mjs +2 -1
- package/package.json +1 -1
- 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
|
-
|
|
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,
|
|
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
|
-
|
|
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;
|
|
@@ -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
|
-
|
|
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
|
-
|
|
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 ===
|
|
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`
|
|
218
|
-
//
|
|
219
|
-
const key =
|
|
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
|
-
/**
|
|
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
|
-
|
|
389
|
-
|
|
390
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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.
|
|
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
|
-
|
|
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
|
|
@@ -61,7 +61,13 @@ import {
|
|
|
61
61
|
type GraphRunRecord,
|
|
62
62
|
type GraphTask,
|
|
63
63
|
} from "./graphs.js";
|
|
64
|
-
import {
|
|
64
|
+
import {
|
|
65
|
+
MAX_SCHEDULE_NAME_LENGTH,
|
|
66
|
+
ScheduleRegistry,
|
|
67
|
+
normaliseCwd,
|
|
68
|
+
type ScheduleCreateInput,
|
|
69
|
+
type ScheduleRecord,
|
|
70
|
+
} from "./schedules.js";
|
|
65
71
|
import {
|
|
66
72
|
listArchived,
|
|
67
73
|
findBundle,
|
|
@@ -255,6 +261,25 @@ export function lockFile(path: string) {
|
|
|
255
261
|
type Opened = { harness: Harness; unlock: () => void; unsubscribe: () => void; jobs: Jobs; addons: Addons };
|
|
256
262
|
type Resolved = { row: SessionRow; h: Harness; c: Conversation };
|
|
257
263
|
|
|
264
|
+
/**
|
|
265
|
+
* Is `cwd` the project root `root` itself, or inside it? Pure and
|
|
266
|
+
* platform-injected (the gitPathFor convention): on win32 backslashes and
|
|
267
|
+
* forward slashes compare equal and drive/path case is folded, while POSIX
|
|
268
|
+
* stays byte-identical (a backslash is a legal filename character there).
|
|
269
|
+
* Trailing slashes are normalized on both sides, and the prefix match is
|
|
270
|
+
* boundary-checked, so `D:/src/repo-other` is NOT under `D:/src/repo`.
|
|
271
|
+
*/
|
|
272
|
+
export function pathsUnder(root: string, cwd: string, platform: NodeJS.Platform = process.platform): boolean {
|
|
273
|
+
const norm = (p: string): string => {
|
|
274
|
+
const slashed = platform === "win32" ? p.replace(/\\/g, "/") : p;
|
|
275
|
+
const trimmed = slashed.length > 1 ? slashed.replace(/\/+$/, "") : slashed;
|
|
276
|
+
return platform === "win32" ? trimmed.toLowerCase() : trimmed;
|
|
277
|
+
};
|
|
278
|
+
const base = norm(root);
|
|
279
|
+
const path = norm(cwd);
|
|
280
|
+
return path === base || path.startsWith(`${base}/`);
|
|
281
|
+
}
|
|
282
|
+
|
|
258
283
|
/**
|
|
259
284
|
* Bounded, secret-free description of the error that failed a Session. It names the error class only: never the
|
|
260
285
|
* cause message, so no SQL values, tokens or transcript can reach a REST error message. The library reports the
|
|
@@ -746,6 +771,30 @@ export class Store {
|
|
|
746
771
|
return (await this.startDirRoots())[0] ?? resolve(this.startDirs[0] ?? homedir());
|
|
747
772
|
}
|
|
748
773
|
|
|
774
|
+
/** Start-dir containment for a would-be session cwd — the rule behind
|
|
775
|
+
* `create` and every schedule record. `~` expands, a relative path resolves
|
|
776
|
+
* against the FIRST start dir (what `create` has always done), and the
|
|
777
|
+
* resolved path must land inside the start-dir roots: the bare `resolve()`
|
|
778
|
+
* in create used to let an absolute cwd override the base entirely, so
|
|
779
|
+
* {"cwd":"/etc"} could root a session — or a schedule's run — outside the
|
|
780
|
+
* sandbox the operator configured. A path that does not exist (a schedule
|
|
781
|
+
* may point at a mount that is offline right now) is judged lexically, like
|
|
782
|
+
* `containedPath`. Read paths never re-check: existing sessions whose cwd
|
|
783
|
+
* predates the rule are not retroactively broken. */
|
|
784
|
+
async assertSessionCwdAllowed(input: string): Promise<void> {
|
|
785
|
+
const expanded = input === "~" ? homedir() : input.startsWith("~/") ? join(homedir(), input.slice(2)) : input;
|
|
786
|
+
const base = this.startDirs[0] ?? homedir();
|
|
787
|
+
let candidate: string;
|
|
788
|
+
try {
|
|
789
|
+
candidate = await realpath(resolve(base, expanded));
|
|
790
|
+
} catch {
|
|
791
|
+
candidate = resolve(base, expanded);
|
|
792
|
+
}
|
|
793
|
+
const roots = await this.startDirRoots();
|
|
794
|
+
if (!this.underRoots(candidate, roots))
|
|
795
|
+
throw invalid(`cwd must live under a start dir (${roots.join(", ") || "none configured on this device"})`);
|
|
796
|
+
}
|
|
797
|
+
|
|
749
798
|
async directories(): Promise<DirListing> {
|
|
750
799
|
const dirs: { name: string; path: string }[] = [];
|
|
751
800
|
for (const root of this.startDirs) {
|
|
@@ -1093,6 +1142,11 @@ export class Store {
|
|
|
1093
1142
|
} catch {
|
|
1094
1143
|
throw invalid(`cwd must be an existing folder on ${this.name}`);
|
|
1095
1144
|
}
|
|
1145
|
+
// Same containment rule as the fs/git routes: the resolve() above lets an
|
|
1146
|
+
// absolute cwd override the start-dir base entirely, which is how
|
|
1147
|
+
// {"cwd":"/etc"} used to root a session outside the sandbox. This is the
|
|
1148
|
+
// single choke point — schedule runs and graph runs create here too.
|
|
1149
|
+
await this.assertSessionCwdAllowed(path);
|
|
1096
1150
|
// Every session roots a project: the registry is the tree's group-by-cwd,
|
|
1097
1151
|
// promoted to an entity you can name, label and archive (paseo model).
|
|
1098
1152
|
const status = await gitStatus(cwd).catch(() => undefined);
|
|
@@ -1169,7 +1223,15 @@ export class Store {
|
|
|
1169
1223
|
|
|
1170
1224
|
rename(row: SessionRow, name: unknown) {
|
|
1171
1225
|
if (typeof name !== "string" || !name.trim()) throw invalid("A name is required");
|
|
1172
|
-
|
|
1226
|
+
const trimmed = name.trim();
|
|
1227
|
+
// Same cap and phrasing as a schedule's name — a display name, not a
|
|
1228
|
+
// description (the old slice(0,100) silently swallowed a 10k paste).
|
|
1229
|
+
if (trimmed.length > MAX_SCHEDULE_NAME_LENGTH)
|
|
1230
|
+
throw invalid(`name is ${trimmed.length} characters; the limit is ${MAX_SCHEDULE_NAME_LENGTH}`);
|
|
1231
|
+
// Control characters never belong in a display name: reject rather than
|
|
1232
|
+
// store verbatim (a newline) or silently truncate at a NUL.
|
|
1233
|
+
if (/[\u0000-\u001f\u007f]/.test(trimmed)) throw invalid("name must not contain control characters");
|
|
1234
|
+
this.catalog.prepare("UPDATE sessions SET name=? WHERE id=?").run(trimmed, row.id);
|
|
1173
1235
|
this.notify();
|
|
1174
1236
|
return this.sessionSummary(this.row(row.id));
|
|
1175
1237
|
}
|
|
@@ -2179,12 +2241,18 @@ export class Store {
|
|
|
2179
2241
|
}
|
|
2180
2242
|
|
|
2181
2243
|
async createSchedule(input: ScheduleCreateInput): Promise<ScheduleView> {
|
|
2244
|
+
// The registry stores cwd as typed (it never stats), so an out-of-sandbox
|
|
2245
|
+
// cwd used to surface only when the run spawned its session. Reject the
|
|
2246
|
+
// POST up front with the same rule Store.create applies.
|
|
2247
|
+
if (typeof input?.cwd === "string" && input.cwd.trim()) await this.assertSessionCwdAllowed(normaliseCwd(input.cwd));
|
|
2182
2248
|
const record = await this.schedules.create(input);
|
|
2183
2249
|
this.notify();
|
|
2184
2250
|
return this.scheduleView(record);
|
|
2185
2251
|
}
|
|
2186
2252
|
|
|
2187
2253
|
async updateSchedule(id: string, patch: SchedulePatchBody): Promise<ScheduleView> {
|
|
2254
|
+
// Same early refusal when a patch repoints the schedule at /etc.
|
|
2255
|
+
if (typeof patch?.cwd === "string" && patch.cwd.trim()) await this.assertSessionCwdAllowed(normaliseCwd(patch.cwd));
|
|
2188
2256
|
const record = await this.schedules.update(id, patch);
|
|
2189
2257
|
this.notify();
|
|
2190
2258
|
return this.scheduleView(record);
|
|
@@ -2298,8 +2366,9 @@ export class Store {
|
|
|
2298
2366
|
private projectForPath(cwd: string): ProjectRecord | undefined {
|
|
2299
2367
|
let best: ProjectRecord | undefined;
|
|
2300
2368
|
for (const project of this.projects.list({ includeArchived: false })) {
|
|
2301
|
-
|
|
2302
|
-
|
|
2369
|
+
// Slash/case-normalized compare (pathsUnder): a session cwd recorded as
|
|
2370
|
+
// `D:\src\repo` must match a project registered as `D:/src/repo`.
|
|
2371
|
+
const isUnder = pathsUnder(project.rootPath, cwd);
|
|
2303
2372
|
if (isUnder && (!best || project.rootPath.length > best.rootPath.length)) best = project;
|
|
2304
2373
|
}
|
|
2305
2374
|
return best;
|