opencode-self-improvement 0.15.21 → 0.15.23
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/package.json +1 -1
- package/src/store/files/deletions.ts +10 -0
- package/src/tools/schema.ts +9 -0
- package/src/viewer/mutate.ts +8 -0
- package/src/viewer/page.html +17 -5
- package/src/viewer/server.ts +345 -29
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-self-improvement",
|
|
3
|
-
"version": "0.15.
|
|
3
|
+
"version": "0.15.23",
|
|
4
4
|
"description": "Durable memory for opencode: remember facts, decisions, and commands across sessions, plus a one-command per-repo setup (/repo-init).",
|
|
5
5
|
"main": "index.ts",
|
|
6
6
|
"exports": {
|
|
@@ -28,6 +28,16 @@ export async function logDeletion(
|
|
|
28
28
|
// stamp writes no stamp here — the legacy global path, unchanged.
|
|
29
29
|
repo: memory.repo,
|
|
30
30
|
repoPath: memory.repoPath,
|
|
31
|
+
// #207: the visibility- and provenance-bearing metadata survives here
|
|
32
|
+
// too. tags carry the quarantine marker, so a restore that reads this
|
|
33
|
+
// line cannot silently release quarantine; issue and kw keep provenance
|
|
34
|
+
// and recall aliases alive; status keeps an open thread open. Comma-
|
|
35
|
+
// joined scalars match the memory line, and a row without them writes
|
|
36
|
+
// nothing — the legacy fallback the restore documents.
|
|
37
|
+
tags: memory.tags?.length ? memory.tags.join(",") : undefined,
|
|
38
|
+
kw: memory.kw?.length ? memory.kw.join(",") : undefined,
|
|
39
|
+
issue: memory.issue,
|
|
40
|
+
status: memory.status,
|
|
31
41
|
reason: redactSecrets(reason),
|
|
32
42
|
}),
|
|
33
43
|
);
|
package/src/tools/schema.ts
CHANGED
|
@@ -244,7 +244,16 @@ export const UnrejectBody = z.object({
|
|
|
244
244
|
// repo/repoPath (#129): the origin stamp of the DELETED row, replayed from the
|
|
245
245
|
// audit line so a restore-entry keeps the row's original visibility instead of
|
|
246
246
|
// silently landing global. Both absent = the documented legacy global restore.
|
|
247
|
+
// ts (#207): identity of the deleted row. The server resolves the row's
|
|
248
|
+
// metadata (tags/kw/issue/status, and the origin stamp) from the deletion
|
|
249
|
+
// audit line itself — by ts when present, falling back to type/scope/content
|
|
250
|
+
// when that ts matches no audit line, else directly by type/scope/content —
|
|
251
|
+
// so the client can neither launder a quarantined row into an injectable one
|
|
252
|
+
// nor forge a provenance the audit does not carry. The client-replay fallback
|
|
253
|
+
// above applies only to rows the audit does not carry at all. The metadata
|
|
254
|
+
// fields are deliberately NOT in this schema.
|
|
247
255
|
export const RestoreEntryBody = z.object({
|
|
256
|
+
ts: isoTs.optional(),
|
|
248
257
|
type: z.enum(TYPES),
|
|
249
258
|
scope: memoryField.min(1),
|
|
250
259
|
content: z.string().min(1),
|
package/src/viewer/mutate.ts
CHANGED
|
@@ -209,6 +209,14 @@ async function audit(
|
|
|
209
209
|
// legacy/unstamped case — restore leaves it global, as documented.
|
|
210
210
|
repo: mem.repo,
|
|
211
211
|
repoPath: mem.repoPath,
|
|
212
|
+
// #207: tags (which carry quarantine), kw, issue and status survive the
|
|
213
|
+
// same way, so restoring a deleted row cannot silently release
|
|
214
|
+
// quarantine or drop provenance. Absent metadata writes nothing — the
|
|
215
|
+
// legacy fallback the restore path documents.
|
|
216
|
+
tags: mem.tags?.length ? mem.tags.join(",") : undefined,
|
|
217
|
+
kw: mem.kw?.length ? mem.kw.join(",") : undefined,
|
|
218
|
+
issue: mem.issue,
|
|
219
|
+
status: mem.status,
|
|
212
220
|
// Same write-boundary rule as evidence (#128): an audit reason is
|
|
213
221
|
// human prose and must not persist a recognized credential.
|
|
214
222
|
reason: redactSecrets(reason),
|
package/src/viewer/page.html
CHANGED
|
@@ -228,6 +228,12 @@ function render() {
|
|
|
228
228
|
: m.superseded_by ? "superseded" : m.quarantined ? "quarantined" : "active";
|
|
229
229
|
const stBadge = status === "superseded" ? badge("status-superseded", "superseded \u2192 " + m.superseded_by.slice(0,8))
|
|
230
230
|
: badge("status-" + status, status);
|
|
231
|
+
// #207: a deleted row that was quarantined must SAY so next to its
|
|
232
|
+
// deleted badge — restore keeps the quarantine, and the operator must
|
|
233
|
+
// see both facts before clicking.
|
|
234
|
+
const stCell = kind === "deleted" && m.quarantined
|
|
235
|
+
? stBadge + " " + badge("status-quarantined", "quarantined")
|
|
236
|
+
: stBadge;
|
|
231
237
|
const actions = kind === "blocked"
|
|
232
238
|
? `<button class="btn warn" data-action="unblock" data-ts="${esc(m.ts)}" title="Restore this memory to the read paths">unblock</button>`
|
|
233
239
|
: kind === "deleted"
|
|
@@ -241,7 +247,7 @@ function render() {
|
|
|
241
247
|
<td>${badge("type", m.type)}</td>
|
|
242
248
|
<td>${badge("scope", m.scope)}</td>
|
|
243
249
|
<td class="content">${esc(m.content)}</td>
|
|
244
|
-
<td>${
|
|
250
|
+
<td>${stCell}</td>
|
|
245
251
|
<td class="actions">${actions}</td>
|
|
246
252
|
</tr>`;
|
|
247
253
|
}).join("");
|
|
@@ -357,16 +363,21 @@ async function unreject(ch) {
|
|
|
357
363
|
} catch (e) { toast(String(e.message), true); }
|
|
358
364
|
}
|
|
359
365
|
|
|
360
|
-
function restoreEntry(type, scope, content, repo, repoPath) {
|
|
366
|
+
function restoreEntry(ts, type, scope, content, repo, repoPath, quarantined) {
|
|
361
367
|
askModal(
|
|
362
368
|
"Restore deleted memory?",
|
|
363
|
-
|
|
369
|
+
quarantined
|
|
370
|
+
? "This entry is QUARANTINED. The restore re-adds it STILL QUARANTINED — withheld from recall and injection until you release quarantine deliberately."
|
|
371
|
+
: "Re-adds this entry to memory from its audit record.",
|
|
364
372
|
"Restore",
|
|
365
373
|
async () => {
|
|
366
374
|
try {
|
|
367
375
|
// The audit line's origin stamp rides along (#129): a restore keeps the
|
|
368
376
|
// row's ORIGINAL visibility instead of silently landing global.
|
|
369
|
-
|
|
377
|
+
// #207: the deleted ts keys the server-side audit lookup, so tags,
|
|
378
|
+
// keywords, issue and status come back from the store's record — this
|
|
379
|
+
// page cannot launder a quarantined row into an injectable one.
|
|
380
|
+
await api("/api/restore-entry", { ts, type, scope, content, repo: repo || undefined, repoPath: repoPath || undefined });
|
|
370
381
|
toast("restored to memory");
|
|
371
382
|
await refresh();
|
|
372
383
|
} catch (e) { toast(String(e.message), true); }
|
|
@@ -392,7 +403,8 @@ $("rows").addEventListener("click", (e) => {
|
|
|
392
403
|
else if (action === "un-reject") unreject(btn.dataset.ch);
|
|
393
404
|
else if (action === "restore-deleted") {
|
|
394
405
|
const { type, scope, content, repo, repoPath } = btn.dataset;
|
|
395
|
-
|
|
406
|
+
const m = DATA.deleted.find((d) => d.ts === ts);
|
|
407
|
+
restoreEntry(ts, type, scope, content, repo, repoPath, !!m?.quarantined);
|
|
396
408
|
}
|
|
397
409
|
});
|
|
398
410
|
|
package/src/viewer/server.ts
CHANGED
|
@@ -4,8 +4,21 @@
|
|
|
4
4
|
// through the same loadAll() used by recall/inject (so blocked entries are
|
|
5
5
|
// hidden), and all mutations are non-destructive (snapshot + audit + supersede).
|
|
6
6
|
// I2: serves only file data; never writes into any repo.
|
|
7
|
+
// #223: a non-loopback bind or allowed host mints a startup token (0600, in
|
|
8
|
+
// the store root) and every request must present it; loopback stays open.
|
|
7
9
|
import { basename, join } from "node:path";
|
|
10
|
+
import {
|
|
11
|
+
closeSync,
|
|
12
|
+
constants,
|
|
13
|
+
linkSync,
|
|
14
|
+
openSync,
|
|
15
|
+
readFileSync,
|
|
16
|
+
renameSync,
|
|
17
|
+
rmSync,
|
|
18
|
+
statSync,
|
|
19
|
+
} from "node:fs";
|
|
8
20
|
import { isIP } from "node:net";
|
|
21
|
+
import { randomBytes, timingSafeEqual } from "node:crypto";
|
|
9
22
|
import { serve, type Server } from "bun";
|
|
10
23
|
import { z, type ZodTypeAny } from "zod";
|
|
11
24
|
import {
|
|
@@ -26,6 +39,7 @@ import { blockedEntries } from "../store/blocklist.ts";
|
|
|
26
39
|
import { listSnapshots, restoreSnapshot } from "../store/undo.ts";
|
|
27
40
|
import { appendMemory } from "../store/files/append.ts";
|
|
28
41
|
import { loadAll, memoryFiles } from "../store/files/load.ts";
|
|
42
|
+
import { type MemoryStatus } from "../store/model/memory.ts";
|
|
29
43
|
import { parseLine } from "../core/logfmt/format.ts";
|
|
30
44
|
import { readLines } from "../core/logfmt/read.ts";
|
|
31
45
|
import { releaseQuarantinedMemory } from "./mutate.ts";
|
|
@@ -43,6 +57,7 @@ import {
|
|
|
43
57
|
} from "./mutate.ts";
|
|
44
58
|
import { tombstones } from "../store/tombstones/tombstone.ts";
|
|
45
59
|
import { assertViewerWriteAllowed } from "./rejections.ts";
|
|
60
|
+
import { preparePrivateFile } from "../core/permissions.ts";
|
|
46
61
|
|
|
47
62
|
const PAGE = join(import.meta.dir, "page.html");
|
|
48
63
|
const HOST = process.env.OPENCODE_VIEWER_HOST || "127.0.0.1";
|
|
@@ -97,8 +112,167 @@ function isLoopbackHostname(name: string): boolean {
|
|
|
97
112
|
return host === "::1" || host === "0:0:0:0:0:0:0:1";
|
|
98
113
|
}
|
|
99
114
|
|
|
100
|
-
|
|
101
|
-
|
|
115
|
+
// #223: exposure without authentication was the defect — with a non-loopback
|
|
116
|
+
// bind (or an allowed non-loopback name) every read and mutation was open HTTP
|
|
117
|
+
// for the whole LAN. A token is now minted at startup and every request must
|
|
118
|
+
// present it: the Host/Origin layer stays as the CSRF defence it always was,
|
|
119
|
+
// but it is no longer the only thing between the LAN and the store.
|
|
120
|
+
const TOKEN_FILE = "viewer.token";
|
|
121
|
+
const TOKEN_COOKIE = "osi-viewer";
|
|
122
|
+
const TOKEN_SHAPE = /^[0-9a-f]{64}$/;
|
|
123
|
+
|
|
124
|
+
function tokenPath(): string {
|
|
125
|
+
return join(memoryRoot(), TOKEN_FILE);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// Reuse a token already in the file so a restart does not invalidate URLs a
|
|
129
|
+
// human has open (and two viewers sharing a store share one token); mint a
|
|
130
|
+
// fresh one otherwise. Concurrent first starts — same process or separate
|
|
131
|
+
// processes — must agree on ONE token (F1, #223 review): the claim is an
|
|
132
|
+
// atomic hard-link of a fully-written 0600 temp, so exactly one starter's
|
|
133
|
+
// content lands at the path (link(2) refuses an existing target), and every
|
|
134
|
+
// loser reads back the winner's complete token instead of overwriting the
|
|
135
|
+
// file with its own.
|
|
136
|
+
//
|
|
137
|
+
// F1 residual (#223 review round 2): the hard-link claim solves an ABSENT
|
|
138
|
+
// file, not a CORRUPT one — two starters that both read the same corrupt
|
|
139
|
+
// winner used to replace it unconditionally, disagreeing on Linux and
|
|
140
|
+
// throwing EPERM on Windows. Recovery is now serialized twice over: within
|
|
141
|
+
// one process every mint runs through this promise chain, so the second
|
|
142
|
+
// starter re-reads the repaired file instead of racing the repair; across
|
|
143
|
+
// processes an O_EXCL lock file elects one repairman and the others adopt
|
|
144
|
+
// its token. A replacement is never unconditional.
|
|
145
|
+
//
|
|
146
|
+
// F3 (#223 review round 2): the reuse path must enforce the 0600 contract
|
|
147
|
+
// too. preparePrivateFile tightens an existing file to owner-only (keeping
|
|
148
|
+
// owner bits, refusing a final-component symlink), so a token file left
|
|
149
|
+
// world-readable is repaired before it is accepted — restoring what the
|
|
150
|
+
// round-1 early return bypassed.
|
|
151
|
+
let mintTail: Promise<unknown> = Promise.resolve();
|
|
152
|
+
|
|
153
|
+
function mintViewerToken(): Promise<string> {
|
|
154
|
+
const run = mintTail.then(() => mintTokenOnce());
|
|
155
|
+
mintTail = run.catch(() => {});
|
|
156
|
+
return run;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function readToken(path: string): string {
|
|
160
|
+
try {
|
|
161
|
+
return readFileSync(path, "utf8").trim();
|
|
162
|
+
} catch {
|
|
163
|
+
return "";
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
async function mintTokenOnce(): Promise<string> {
|
|
168
|
+
const path = tokenPath();
|
|
169
|
+
const prior = readToken(path);
|
|
170
|
+
if (TOKEN_SHAPE.test(prior)) {
|
|
171
|
+
preparePrivateFile(path);
|
|
172
|
+
return prior;
|
|
173
|
+
}
|
|
174
|
+
const token = randomBytes(32).toString("hex");
|
|
175
|
+
const tmp = `${path}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
|
|
176
|
+
try {
|
|
177
|
+
preparePrivateFile(tmp);
|
|
178
|
+
await Bun.write(tmp, token);
|
|
179
|
+
try {
|
|
180
|
+
linkSync(tmp, path);
|
|
181
|
+
} catch (err) {
|
|
182
|
+
if ((err as NodeJS.ErrnoException).code !== "EEXIST") throw err;
|
|
183
|
+
const winner = readToken(path);
|
|
184
|
+
if (TOKEN_SHAPE.test(winner)) return winner;
|
|
185
|
+
return await recoverCorruptToken(path, tmp, token);
|
|
186
|
+
}
|
|
187
|
+
return token;
|
|
188
|
+
} finally {
|
|
189
|
+
rmSync(tmp, { force: true });
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// Repair a corrupt token file under an O_EXCL lock (F1 residual, #223
|
|
194
|
+
// review): exactly one starter replaces the file, the rest adopt its token.
|
|
195
|
+
// The lock also keeps Windows from renaming onto a file a rival starter is
|
|
196
|
+
// mid-read — the observed EPERM. A holder that crashes must not wedge every
|
|
197
|
+
// later start, so a lock older than the wait window is stolen and retried.
|
|
198
|
+
const RECOVER_WAIT_MS = 5_000;
|
|
199
|
+
const RECOVER_STALE_MS = 15_000;
|
|
200
|
+
|
|
201
|
+
async function recoverCorruptToken(
|
|
202
|
+
path: string,
|
|
203
|
+
tmp: string,
|
|
204
|
+
token: string,
|
|
205
|
+
): Promise<string> {
|
|
206
|
+
const lock = path + ".recover";
|
|
207
|
+
const deadline = Date.now() + RECOVER_WAIT_MS;
|
|
208
|
+
for (;;) {
|
|
209
|
+
let held = false;
|
|
210
|
+
try {
|
|
211
|
+
closeSync(
|
|
212
|
+
openSync(
|
|
213
|
+
lock,
|
|
214
|
+
constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL,
|
|
215
|
+
0o600,
|
|
216
|
+
),
|
|
217
|
+
);
|
|
218
|
+
held = true;
|
|
219
|
+
const settled = readToken(path);
|
|
220
|
+
if (TOKEN_SHAPE.test(settled)) return settled;
|
|
221
|
+
renameSync(tmp, path);
|
|
222
|
+
return token;
|
|
223
|
+
} catch (err) {
|
|
224
|
+
if (held || (err as NodeJS.ErrnoException).code !== "EEXIST") throw err;
|
|
225
|
+
const waiting = readToken(path);
|
|
226
|
+
if (TOKEN_SHAPE.test(waiting)) return waiting;
|
|
227
|
+
if (Date.now() < deadline) {
|
|
228
|
+
await Bun.sleep(25);
|
|
229
|
+
continue;
|
|
230
|
+
}
|
|
231
|
+
let stale = true;
|
|
232
|
+
try {
|
|
233
|
+
stale = Date.now() - statSync(lock).mtimeMs > RECOVER_STALE_MS;
|
|
234
|
+
} catch {
|
|
235
|
+
stale = true;
|
|
236
|
+
}
|
|
237
|
+
if (!stale) throw err;
|
|
238
|
+
rmSync(lock, { force: true });
|
|
239
|
+
} finally {
|
|
240
|
+
if (held) rmSync(lock, { force: true });
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function tokenMatches(candidate: string, expected: string): boolean {
|
|
246
|
+
const a = Buffer.from(candidate);
|
|
247
|
+
const b = Buffer.from(expected);
|
|
248
|
+
return a.length === b.length && timingSafeEqual(a, b);
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// No decodeURIComponent: the cookie is a fixed-hex token we mint and set
|
|
252
|
+
// verbatim, and decoding junk like `osi-viewer=%` throws URIError on the
|
|
253
|
+
// auth path — a 500 where a malformed credential must simply be refused
|
|
254
|
+
// (N1, #223 review). The raw value cannot match, so it falls through to 401.
|
|
255
|
+
function cookieValue(req: Request, name: string): string | null {
|
|
256
|
+
for (const part of (req.headers.get("cookie") ?? "").split(";")) {
|
|
257
|
+
const eq = part.indexOf("=");
|
|
258
|
+
if (eq !== -1 && part.slice(0, eq).trim() === name)
|
|
259
|
+
return part.slice(eq + 1).trim();
|
|
260
|
+
}
|
|
261
|
+
return null;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
function exposureWarning(path: string): string {
|
|
265
|
+
return (
|
|
266
|
+
"[memory-viewer] WARNING: non-loopback hosts are allowed. Every request " +
|
|
267
|
+
"must present the startup-minted token (Authorization: Bearer, the " +
|
|
268
|
+
TOKEN_COOKIE +
|
|
269
|
+
" cookie, or ?token= on /); requests without it are refused with 401. " +
|
|
270
|
+
"Token: " +
|
|
271
|
+
path +
|
|
272
|
+
" (mode 0600). Plain HTTP still exposes the token on the wire — use " +
|
|
273
|
+
"only on a network you trust."
|
|
274
|
+
);
|
|
275
|
+
}
|
|
102
276
|
|
|
103
277
|
function rejectRequest(req: Request, url: URL, port: number): Response | null {
|
|
104
278
|
if (
|
|
@@ -130,6 +304,50 @@ interface Row {
|
|
|
130
304
|
// restore-entry round trip can restore the row's ORIGINAL visibility.
|
|
131
305
|
repo?: string;
|
|
132
306
|
repoPath?: string;
|
|
307
|
+
// #207: the deleted row's metadata, read back from the audit line, so the
|
|
308
|
+
// deleted-entry UI can show WHAT is being restored — in particular whether
|
|
309
|
+
// it is quarantined. Only deletion rows carry these; blocked rows do not.
|
|
310
|
+
tags?: string[];
|
|
311
|
+
kw?: string[];
|
|
312
|
+
issue?: string;
|
|
313
|
+
status?: string;
|
|
314
|
+
quarantined?: boolean;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
// Comma-joined scalars back into arrays, the inverse of the audit write.
|
|
318
|
+
function splitScalar(value: unknown): string[] | undefined {
|
|
319
|
+
return typeof value === "string" && value
|
|
320
|
+
? value.split(",").filter(Boolean)
|
|
321
|
+
: undefined;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
// The metadata a deletion audit line carries for the deleted row (#207).
|
|
325
|
+
// Kept out of the client contract: restore resolves it here, from the store's
|
|
326
|
+
// own record, rather than trusting replayed bytes.
|
|
327
|
+
interface DeletionMeta {
|
|
328
|
+
tags?: string[];
|
|
329
|
+
kw?: string[];
|
|
330
|
+
issue?: string;
|
|
331
|
+
status?: MemoryStatus;
|
|
332
|
+
repo?: string;
|
|
333
|
+
repoPath?: string;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
function auditMeta(f: NonNullable<ReturnType<typeof parseLine>>): DeletionMeta {
|
|
337
|
+
const tags = splitScalar(f.tags);
|
|
338
|
+
const kw = splitScalar(f.kw);
|
|
339
|
+
return {
|
|
340
|
+
...(tags ? { tags } : {}),
|
|
341
|
+
...(kw ? { kw } : {}),
|
|
342
|
+
...(typeof f.issue === "string" && f.issue ? { issue: f.issue } : {}),
|
|
343
|
+
...(f.status === "open" || f.status === "settled"
|
|
344
|
+
? { status: f.status }
|
|
345
|
+
: {}),
|
|
346
|
+
...(typeof f.repo === "string" && f.repo ? { repo: f.repo } : {}),
|
|
347
|
+
...(typeof f.repoPath === "string" && f.repoPath
|
|
348
|
+
? { repoPath: f.repoPath }
|
|
349
|
+
: {}),
|
|
350
|
+
};
|
|
133
351
|
}
|
|
134
352
|
|
|
135
353
|
// Deleted entries live only in the audit log (their memory line was removed),
|
|
@@ -139,17 +357,58 @@ async function deletedRows(): Promise<Row[]> {
|
|
|
139
357
|
return lines
|
|
140
358
|
.map((l) => parseLine(l))
|
|
141
359
|
.filter((f): f is NonNullable<typeof f> => f !== null)
|
|
142
|
-
.map((f) =>
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
:
|
|
152
|
-
|
|
360
|
+
.map((f) => {
|
|
361
|
+
const meta = auditMeta(f);
|
|
362
|
+
return {
|
|
363
|
+
ts: String(f.original_ts ?? f.ts ?? ""),
|
|
364
|
+
type: String(f.type ?? ""),
|
|
365
|
+
scope: String(f.scope ?? ""),
|
|
366
|
+
content: String(f.content ?? ""),
|
|
367
|
+
reason: String(f.reason ?? ""),
|
|
368
|
+
...meta,
|
|
369
|
+
// #207: the operator must SEE that a deleted row was quarantined —
|
|
370
|
+
// restoring it must not read as a way to release quarantine.
|
|
371
|
+
...(meta.tags
|
|
372
|
+
? { quarantined: isQuarantined({ tags: meta.tags }) }
|
|
373
|
+
: {}),
|
|
374
|
+
};
|
|
375
|
+
});
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
// The authoritative record of what a deleted row carried, keyed by the deleted
|
|
379
|
+
// row's ts (#207). The LAST matching line wins: a row edited then deleted has
|
|
380
|
+
// its newest state last, and that is the state a restore re-adds. Lines
|
|
381
|
+
// written before #207 carry no metadata — the documented fallback.
|
|
382
|
+
async function deletionAuditFor(ts: string): Promise<DeletionMeta | undefined> {
|
|
383
|
+
let found: DeletionMeta | undefined;
|
|
384
|
+
for (const line of await readLines(deletionsFile())) {
|
|
385
|
+
const f = parseLine(line);
|
|
386
|
+
if (!f || f.original_ts !== ts) continue;
|
|
387
|
+
found = auditMeta(f);
|
|
388
|
+
}
|
|
389
|
+
return found;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
// Same record, keyed by the deleted row's identity instead of its ts (#207 F2).
|
|
393
|
+
// A restore request that omits ts is a legacy REQUEST, not a legacy record:
|
|
394
|
+
// if the audit carries a matching line, that line is still the authoritative
|
|
395
|
+
// copy of what the row carried, and resolving it here closes the laundering
|
|
396
|
+
// path (omitting ts must not restore a known quarantined row as injectable).
|
|
397
|
+
// Only when NO line matches — a client older than the viewer, or a row whose
|
|
398
|
+
// deletion predates the audit — does the route fall back to client replay.
|
|
399
|
+
async function deletionAuditByRow(
|
|
400
|
+
type: string,
|
|
401
|
+
scope: string,
|
|
402
|
+
content: string,
|
|
403
|
+
): Promise<DeletionMeta | undefined> {
|
|
404
|
+
let found: DeletionMeta | undefined;
|
|
405
|
+
for (const line of await readLines(deletionsFile())) {
|
|
406
|
+
const f = parseLine(line);
|
|
407
|
+
if (!f || f.type !== type || f.scope !== scope || f.content !== content)
|
|
408
|
+
continue;
|
|
409
|
+
found = auditMeta(f);
|
|
410
|
+
}
|
|
411
|
+
return found;
|
|
153
412
|
}
|
|
154
413
|
|
|
155
414
|
// Blocked entries are still on disk but hidden by the blocklist; scan every
|
|
@@ -178,10 +437,20 @@ async function blockedRows(): Promise<Row[]> {
|
|
|
178
437
|
export interface ViewerServer {
|
|
179
438
|
server: Server<any>;
|
|
180
439
|
url: string;
|
|
440
|
+
/** The minted token when exposure requires auth; null on a loopback-only bind. */
|
|
441
|
+
token: string | null;
|
|
181
442
|
}
|
|
182
443
|
|
|
183
444
|
export async function startViewer(port: number = PORT): Promise<ViewerServer> {
|
|
184
445
|
const page = await Bun.file(PAGE).text();
|
|
446
|
+
// The same condition that used to only warn now switches authentication on:
|
|
447
|
+
// if any allowed name can be reached from another machine, the token is
|
|
448
|
+
// mandatory for every request, reads included (the store is the blast
|
|
449
|
+
// radius of a read too). Loopback-only binds keep the token-free flow.
|
|
450
|
+
const exposed = [...allowedHostnames()].some(
|
|
451
|
+
(host) => !isLoopbackHostname(host),
|
|
452
|
+
);
|
|
453
|
+
const viewerToken = exposed ? await mintViewerToken() : null;
|
|
185
454
|
const server = serve({
|
|
186
455
|
hostname: HOST,
|
|
187
456
|
port,
|
|
@@ -207,13 +476,36 @@ export async function startViewer(port: number = PORT): Promise<ViewerServer> {
|
|
|
207
476
|
}
|
|
208
477
|
const rejected = rejectRequest(req, url, server.port ?? port);
|
|
209
478
|
if (rejected) return rejected;
|
|
479
|
+
if (viewerToken !== null) {
|
|
480
|
+
// Bearer header or cookie on every path; the raw ?token= is accepted
|
|
481
|
+
// on / only, as the bootstrap a human pastes once. The page's own
|
|
482
|
+
// fetches are same-origin and carry the cookie, so the token never
|
|
483
|
+
// has to appear in an API URL (or in a log line).
|
|
484
|
+
const auth = req.headers.get("authorization");
|
|
485
|
+
const bearer =
|
|
486
|
+
auth && /^Bearer /i.test(auth) ? auth.slice(7).trim() : null;
|
|
487
|
+
const cookie = cookieValue(req, TOKEN_COOKIE);
|
|
488
|
+
const bootstrap =
|
|
489
|
+
url.pathname === "/" ? url.searchParams.get("token") : null;
|
|
490
|
+
// Validate every presentation instead of taking the first PRESENT
|
|
491
|
+
// one (F2, #223 review): a stale cookie from before a supported
|
|
492
|
+
// token regeneration must not shadow the freshly printed bootstrap
|
|
493
|
+
// URL. A request with no valid credential is still refused.
|
|
494
|
+
const accepted =
|
|
495
|
+
(bearer !== null && tokenMatches(bearer, viewerToken)) ||
|
|
496
|
+
(cookie !== null && tokenMatches(cookie, viewerToken)) ||
|
|
497
|
+
(bootstrap !== null && tokenMatches(bootstrap, viewerToken));
|
|
498
|
+
if (!accepted) return error("viewer authentication required", 401);
|
|
499
|
+
}
|
|
210
500
|
if (url.pathname === "/") {
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
501
|
+
const headers: Record<string, string> = {
|
|
502
|
+
...SECURITY_HEADERS,
|
|
503
|
+
"content-type": "text/html; charset=utf-8",
|
|
504
|
+
};
|
|
505
|
+
if (viewerToken !== null)
|
|
506
|
+
headers["set-cookie"] =
|
|
507
|
+
`${TOKEN_COOKIE}=${viewerToken}; HttpOnly; SameSite=Strict; Path=/`;
|
|
508
|
+
return new Response(page, { headers });
|
|
217
509
|
}
|
|
218
510
|
if (req.method === "GET" && url.pathname === "/api/data") {
|
|
219
511
|
return loaded().then(
|
|
@@ -228,10 +520,14 @@ export async function startViewer(port: number = PORT): Promise<ViewerServer> {
|
|
|
228
520
|
});
|
|
229
521
|
const bound = server.port ?? port;
|
|
230
522
|
// Warn after binding; wildcard binds (0.0.0.0 and ::) are non-loopback too.
|
|
231
|
-
if (
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
523
|
+
if (exposed) console.warn(exposureWarning(tokenPath()));
|
|
524
|
+
return {
|
|
525
|
+
server,
|
|
526
|
+
url: viewerToken
|
|
527
|
+
? `http://${HOST}:${bound}/?token=${viewerToken}`
|
|
528
|
+
: `http://${HOST}:${bound}/`,
|
|
529
|
+
token: viewerToken,
|
|
530
|
+
};
|
|
235
531
|
}
|
|
236
532
|
|
|
237
533
|
async function loaded(): Promise<Record<string, unknown>> {
|
|
@@ -371,16 +667,36 @@ async function restoreEntryRoute(
|
|
|
371
667
|
body: z.infer<typeof RestoreEntryBody>,
|
|
372
668
|
): Promise<Response> {
|
|
373
669
|
await assertViewerWriteAllowed(body.content);
|
|
374
|
-
//
|
|
375
|
-
//
|
|
376
|
-
//
|
|
377
|
-
//
|
|
670
|
+
// #207: every field that controls visibility or provenance is resolved from
|
|
671
|
+
// the audit line itself — the store's own record — so a restore cannot
|
|
672
|
+
// silently release quarantine (the quarantine tags come back with the row;
|
|
673
|
+
// releasing it stays the deliberate, reason-required release-quarantine
|
|
674
|
+
// action), cannot drop import provenance, and a client-forged repo stamp
|
|
675
|
+
// loses to the authoritative one. With ts the lookup is by row identity, and
|
|
676
|
+
// a ts that matches no audit line still resolves by type/scope/content
|
|
677
|
+
// before any fallback: an unknown explicit ts is an unresolved identity, not
|
|
678
|
+
// permission to replay (F2 residual). Without ts the lookup is by
|
|
679
|
+
// type/scope/content directly. Either way, omitting or missing ts cannot
|
|
680
|
+
// launder a KNOWN quarantined row back to injectable (F2). The client-replay
|
|
681
|
+
// fallback (#129 origin stamp, no metadata) survives only for rows the audit
|
|
682
|
+
// does not carry at all — a legacy record, not a legacy request.
|
|
683
|
+
const src =
|
|
684
|
+
(body.ts && (await deletionAuditFor(body.ts))) ||
|
|
685
|
+
(await deletionAuditByRow(body.type, body.scope, body.content));
|
|
378
686
|
const t = await appendMemory({
|
|
379
687
|
type: body.type,
|
|
380
688
|
scope: body.scope,
|
|
381
689
|
content: body.content,
|
|
382
|
-
|
|
383
|
-
|
|
690
|
+
...(src
|
|
691
|
+
? {
|
|
692
|
+
tags: src.tags,
|
|
693
|
+
kw: src.kw,
|
|
694
|
+
issue: src.issue,
|
|
695
|
+
status: src.status,
|
|
696
|
+
repo: src.repo,
|
|
697
|
+
repoPath: src.repoPath,
|
|
698
|
+
}
|
|
699
|
+
: { repo: body.repo, repoPath: body.repoPath }),
|
|
384
700
|
});
|
|
385
701
|
return json({ restored: t });
|
|
386
702
|
}
|