opencode-self-improvement 0.15.21 → 0.15.22
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/viewer/server.ts +222 -12
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-self-improvement",
|
|
3
|
-
"version": "0.15.
|
|
3
|
+
"version": "0.15.22",
|
|
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": {
|
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 {
|
|
@@ -43,6 +56,7 @@ import {
|
|
|
43
56
|
} from "./mutate.ts";
|
|
44
57
|
import { tombstones } from "../store/tombstones/tombstone.ts";
|
|
45
58
|
import { assertViewerWriteAllowed } from "./rejections.ts";
|
|
59
|
+
import { preparePrivateFile } from "../core/permissions.ts";
|
|
46
60
|
|
|
47
61
|
const PAGE = join(import.meta.dir, "page.html");
|
|
48
62
|
const HOST = process.env.OPENCODE_VIEWER_HOST || "127.0.0.1";
|
|
@@ -97,8 +111,167 @@ function isLoopbackHostname(name: string): boolean {
|
|
|
97
111
|
return host === "::1" || host === "0:0:0:0:0:0:0:1";
|
|
98
112
|
}
|
|
99
113
|
|
|
100
|
-
|
|
101
|
-
|
|
114
|
+
// #223: exposure without authentication was the defect — with a non-loopback
|
|
115
|
+
// bind (or an allowed non-loopback name) every read and mutation was open HTTP
|
|
116
|
+
// for the whole LAN. A token is now minted at startup and every request must
|
|
117
|
+
// present it: the Host/Origin layer stays as the CSRF defence it always was,
|
|
118
|
+
// but it is no longer the only thing between the LAN and the store.
|
|
119
|
+
const TOKEN_FILE = "viewer.token";
|
|
120
|
+
const TOKEN_COOKIE = "osi-viewer";
|
|
121
|
+
const TOKEN_SHAPE = /^[0-9a-f]{64}$/;
|
|
122
|
+
|
|
123
|
+
function tokenPath(): string {
|
|
124
|
+
return join(memoryRoot(), TOKEN_FILE);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// Reuse a token already in the file so a restart does not invalidate URLs a
|
|
128
|
+
// human has open (and two viewers sharing a store share one token); mint a
|
|
129
|
+
// fresh one otherwise. Concurrent first starts — same process or separate
|
|
130
|
+
// processes — must agree on ONE token (F1, #223 review): the claim is an
|
|
131
|
+
// atomic hard-link of a fully-written 0600 temp, so exactly one starter's
|
|
132
|
+
// content lands at the path (link(2) refuses an existing target), and every
|
|
133
|
+
// loser reads back the winner's complete token instead of overwriting the
|
|
134
|
+
// file with its own.
|
|
135
|
+
//
|
|
136
|
+
// F1 residual (#223 review round 2): the hard-link claim solves an ABSENT
|
|
137
|
+
// file, not a CORRUPT one — two starters that both read the same corrupt
|
|
138
|
+
// winner used to replace it unconditionally, disagreeing on Linux and
|
|
139
|
+
// throwing EPERM on Windows. Recovery is now serialized twice over: within
|
|
140
|
+
// one process every mint runs through this promise chain, so the second
|
|
141
|
+
// starter re-reads the repaired file instead of racing the repair; across
|
|
142
|
+
// processes an O_EXCL lock file elects one repairman and the others adopt
|
|
143
|
+
// its token. A replacement is never unconditional.
|
|
144
|
+
//
|
|
145
|
+
// F3 (#223 review round 2): the reuse path must enforce the 0600 contract
|
|
146
|
+
// too. preparePrivateFile tightens an existing file to owner-only (keeping
|
|
147
|
+
// owner bits, refusing a final-component symlink), so a token file left
|
|
148
|
+
// world-readable is repaired before it is accepted — restoring what the
|
|
149
|
+
// round-1 early return bypassed.
|
|
150
|
+
let mintTail: Promise<unknown> = Promise.resolve();
|
|
151
|
+
|
|
152
|
+
function mintViewerToken(): Promise<string> {
|
|
153
|
+
const run = mintTail.then(() => mintTokenOnce());
|
|
154
|
+
mintTail = run.catch(() => {});
|
|
155
|
+
return run;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function readToken(path: string): string {
|
|
159
|
+
try {
|
|
160
|
+
return readFileSync(path, "utf8").trim();
|
|
161
|
+
} catch {
|
|
162
|
+
return "";
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
async function mintTokenOnce(): Promise<string> {
|
|
167
|
+
const path = tokenPath();
|
|
168
|
+
const prior = readToken(path);
|
|
169
|
+
if (TOKEN_SHAPE.test(prior)) {
|
|
170
|
+
preparePrivateFile(path);
|
|
171
|
+
return prior;
|
|
172
|
+
}
|
|
173
|
+
const token = randomBytes(32).toString("hex");
|
|
174
|
+
const tmp = `${path}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
|
|
175
|
+
try {
|
|
176
|
+
preparePrivateFile(tmp);
|
|
177
|
+
await Bun.write(tmp, token);
|
|
178
|
+
try {
|
|
179
|
+
linkSync(tmp, path);
|
|
180
|
+
} catch (err) {
|
|
181
|
+
if ((err as NodeJS.ErrnoException).code !== "EEXIST") throw err;
|
|
182
|
+
const winner = readToken(path);
|
|
183
|
+
if (TOKEN_SHAPE.test(winner)) return winner;
|
|
184
|
+
return await recoverCorruptToken(path, tmp, token);
|
|
185
|
+
}
|
|
186
|
+
return token;
|
|
187
|
+
} finally {
|
|
188
|
+
rmSync(tmp, { force: true });
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// Repair a corrupt token file under an O_EXCL lock (F1 residual, #223
|
|
193
|
+
// review): exactly one starter replaces the file, the rest adopt its token.
|
|
194
|
+
// The lock also keeps Windows from renaming onto a file a rival starter is
|
|
195
|
+
// mid-read — the observed EPERM. A holder that crashes must not wedge every
|
|
196
|
+
// later start, so a lock older than the wait window is stolen and retried.
|
|
197
|
+
const RECOVER_WAIT_MS = 5_000;
|
|
198
|
+
const RECOVER_STALE_MS = 15_000;
|
|
199
|
+
|
|
200
|
+
async function recoverCorruptToken(
|
|
201
|
+
path: string,
|
|
202
|
+
tmp: string,
|
|
203
|
+
token: string,
|
|
204
|
+
): Promise<string> {
|
|
205
|
+
const lock = path + ".recover";
|
|
206
|
+
const deadline = Date.now() + RECOVER_WAIT_MS;
|
|
207
|
+
for (;;) {
|
|
208
|
+
let held = false;
|
|
209
|
+
try {
|
|
210
|
+
closeSync(
|
|
211
|
+
openSync(
|
|
212
|
+
lock,
|
|
213
|
+
constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL,
|
|
214
|
+
0o600,
|
|
215
|
+
),
|
|
216
|
+
);
|
|
217
|
+
held = true;
|
|
218
|
+
const settled = readToken(path);
|
|
219
|
+
if (TOKEN_SHAPE.test(settled)) return settled;
|
|
220
|
+
renameSync(tmp, path);
|
|
221
|
+
return token;
|
|
222
|
+
} catch (err) {
|
|
223
|
+
if (held || (err as NodeJS.ErrnoException).code !== "EEXIST") throw err;
|
|
224
|
+
const waiting = readToken(path);
|
|
225
|
+
if (TOKEN_SHAPE.test(waiting)) return waiting;
|
|
226
|
+
if (Date.now() < deadline) {
|
|
227
|
+
await Bun.sleep(25);
|
|
228
|
+
continue;
|
|
229
|
+
}
|
|
230
|
+
let stale = true;
|
|
231
|
+
try {
|
|
232
|
+
stale = Date.now() - statSync(lock).mtimeMs > RECOVER_STALE_MS;
|
|
233
|
+
} catch {
|
|
234
|
+
stale = true;
|
|
235
|
+
}
|
|
236
|
+
if (!stale) throw err;
|
|
237
|
+
rmSync(lock, { force: true });
|
|
238
|
+
} finally {
|
|
239
|
+
if (held) rmSync(lock, { force: true });
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
function tokenMatches(candidate: string, expected: string): boolean {
|
|
245
|
+
const a = Buffer.from(candidate);
|
|
246
|
+
const b = Buffer.from(expected);
|
|
247
|
+
return a.length === b.length && timingSafeEqual(a, b);
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// No decodeURIComponent: the cookie is a fixed-hex token we mint and set
|
|
251
|
+
// verbatim, and decoding junk like `osi-viewer=%` throws URIError on the
|
|
252
|
+
// auth path — a 500 where a malformed credential must simply be refused
|
|
253
|
+
// (N1, #223 review). The raw value cannot match, so it falls through to 401.
|
|
254
|
+
function cookieValue(req: Request, name: string): string | null {
|
|
255
|
+
for (const part of (req.headers.get("cookie") ?? "").split(";")) {
|
|
256
|
+
const eq = part.indexOf("=");
|
|
257
|
+
if (eq !== -1 && part.slice(0, eq).trim() === name)
|
|
258
|
+
return part.slice(eq + 1).trim();
|
|
259
|
+
}
|
|
260
|
+
return null;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function exposureWarning(path: string): string {
|
|
264
|
+
return (
|
|
265
|
+
"[memory-viewer] WARNING: non-loopback hosts are allowed. Every request " +
|
|
266
|
+
"must present the startup-minted token (Authorization: Bearer, the " +
|
|
267
|
+
TOKEN_COOKIE +
|
|
268
|
+
" cookie, or ?token= on /); requests without it are refused with 401. " +
|
|
269
|
+
"Token: " +
|
|
270
|
+
path +
|
|
271
|
+
" (mode 0600). Plain HTTP still exposes the token on the wire — use " +
|
|
272
|
+
"only on a network you trust."
|
|
273
|
+
);
|
|
274
|
+
}
|
|
102
275
|
|
|
103
276
|
function rejectRequest(req: Request, url: URL, port: number): Response | null {
|
|
104
277
|
if (
|
|
@@ -178,10 +351,20 @@ async function blockedRows(): Promise<Row[]> {
|
|
|
178
351
|
export interface ViewerServer {
|
|
179
352
|
server: Server<any>;
|
|
180
353
|
url: string;
|
|
354
|
+
/** The minted token when exposure requires auth; null on a loopback-only bind. */
|
|
355
|
+
token: string | null;
|
|
181
356
|
}
|
|
182
357
|
|
|
183
358
|
export async function startViewer(port: number = PORT): Promise<ViewerServer> {
|
|
184
359
|
const page = await Bun.file(PAGE).text();
|
|
360
|
+
// The same condition that used to only warn now switches authentication on:
|
|
361
|
+
// if any allowed name can be reached from another machine, the token is
|
|
362
|
+
// mandatory for every request, reads included (the store is the blast
|
|
363
|
+
// radius of a read too). Loopback-only binds keep the token-free flow.
|
|
364
|
+
const exposed = [...allowedHostnames()].some(
|
|
365
|
+
(host) => !isLoopbackHostname(host),
|
|
366
|
+
);
|
|
367
|
+
const viewerToken = exposed ? await mintViewerToken() : null;
|
|
185
368
|
const server = serve({
|
|
186
369
|
hostname: HOST,
|
|
187
370
|
port,
|
|
@@ -207,13 +390,36 @@ export async function startViewer(port: number = PORT): Promise<ViewerServer> {
|
|
|
207
390
|
}
|
|
208
391
|
const rejected = rejectRequest(req, url, server.port ?? port);
|
|
209
392
|
if (rejected) return rejected;
|
|
393
|
+
if (viewerToken !== null) {
|
|
394
|
+
// Bearer header or cookie on every path; the raw ?token= is accepted
|
|
395
|
+
// on / only, as the bootstrap a human pastes once. The page's own
|
|
396
|
+
// fetches are same-origin and carry the cookie, so the token never
|
|
397
|
+
// has to appear in an API URL (or in a log line).
|
|
398
|
+
const auth = req.headers.get("authorization");
|
|
399
|
+
const bearer =
|
|
400
|
+
auth && /^Bearer /i.test(auth) ? auth.slice(7).trim() : null;
|
|
401
|
+
const cookie = cookieValue(req, TOKEN_COOKIE);
|
|
402
|
+
const bootstrap =
|
|
403
|
+
url.pathname === "/" ? url.searchParams.get("token") : null;
|
|
404
|
+
// Validate every presentation instead of taking the first PRESENT
|
|
405
|
+
// one (F2, #223 review): a stale cookie from before a supported
|
|
406
|
+
// token regeneration must not shadow the freshly printed bootstrap
|
|
407
|
+
// URL. A request with no valid credential is still refused.
|
|
408
|
+
const accepted =
|
|
409
|
+
(bearer !== null && tokenMatches(bearer, viewerToken)) ||
|
|
410
|
+
(cookie !== null && tokenMatches(cookie, viewerToken)) ||
|
|
411
|
+
(bootstrap !== null && tokenMatches(bootstrap, viewerToken));
|
|
412
|
+
if (!accepted) return error("viewer authentication required", 401);
|
|
413
|
+
}
|
|
210
414
|
if (url.pathname === "/") {
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
415
|
+
const headers: Record<string, string> = {
|
|
416
|
+
...SECURITY_HEADERS,
|
|
417
|
+
"content-type": "text/html; charset=utf-8",
|
|
418
|
+
};
|
|
419
|
+
if (viewerToken !== null)
|
|
420
|
+
headers["set-cookie"] =
|
|
421
|
+
`${TOKEN_COOKIE}=${viewerToken}; HttpOnly; SameSite=Strict; Path=/`;
|
|
422
|
+
return new Response(page, { headers });
|
|
217
423
|
}
|
|
218
424
|
if (req.method === "GET" && url.pathname === "/api/data") {
|
|
219
425
|
return loaded().then(
|
|
@@ -228,10 +434,14 @@ export async function startViewer(port: number = PORT): Promise<ViewerServer> {
|
|
|
228
434
|
});
|
|
229
435
|
const bound = server.port ?? port;
|
|
230
436
|
// Warn after binding; wildcard binds (0.0.0.0 and ::) are non-loopback too.
|
|
231
|
-
if (
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
437
|
+
if (exposed) console.warn(exposureWarning(tokenPath()));
|
|
438
|
+
return {
|
|
439
|
+
server,
|
|
440
|
+
url: viewerToken
|
|
441
|
+
? `http://${HOST}:${bound}/?token=${viewerToken}`
|
|
442
|
+
: `http://${HOST}:${bound}/`,
|
|
443
|
+
token: viewerToken,
|
|
444
|
+
};
|
|
235
445
|
}
|
|
236
446
|
|
|
237
447
|
async function loaded(): Promise<Record<string, unknown>> {
|