opencode-self-improvement 0.15.5 → 0.15.6

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/README.md CHANGED
@@ -51,6 +51,8 @@ Daily memory writes publish a complete replacement file under that lock, so conc
51
51
 
52
52
  Memory is stored outside every repository, under `~/.config/opencode/memory` by default (override with `OPENCODE_MEMORY_DIR`). To start over, delete that directory.
53
53
 
54
+ On POSIX systems, new store directories use owner-only `0700` permissions and new files use `0600` (subject to a more restrictive umask). This includes temporary replacements, snapshots, locks, status files, and append-only logs. Accessing an existing store attempts to remove group/other permissions from its root; existing directories and appended/status files are tightened when written, without adding owner permissions. Old descendants are not recursively migrated: a successfully tightened root prevents other users from traversing to them. If directory chmod reports `EPERM`, `EROFS`, `EOPNOTSUPP`, or `ENOSYS` (for example an immutable or foreign-owned root, or a mount without chmod support), reads remain available with the existing permissions: owner-only traversal is not guaranteed. Correct ownership, mount support, or permissions outside the plugin when that privacy guarantee is required. File permission enforcement on writes remains unchanged. Existing ancestors outside the store are left unchanged. A store root that is itself a symlink is refused; configure its real directory instead. These modes do not revoke already-open handles or protect copies/hard links outside the private root. On Windows, privacy depends on the directory's ACL; the plugin does not change Windows ACLs.
55
+
54
56
  ## Options
55
57
 
56
58
  Zero configuration is the default. To tune, use the object form of the plugin entry in `opencode.json(c)`:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-self-improvement",
3
- "version": "0.15.5",
3
+ "version": "0.15.6",
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": {
@@ -5,12 +5,16 @@
5
5
  import { homedir } from "node:os";
6
6
  import { join } from "node:path";
7
7
  import { fileURLToPath } from "node:url";
8
+ import { tightenDirectory } from "../permissions.ts";
8
9
 
9
10
  export function memoryRoot(): string {
10
- return (
11
+ const root = (
11
12
  process.env.OPENCODE_MEMORY_DIR ||
12
13
  join(homedir(), ".config", "opencode", "memory")
13
14
  );
15
+ // Protect old stores even on read-only use; do not create an absent store.
16
+ tightenDirectory(root);
17
+ return root;
14
18
  }
15
19
 
16
20
  // Where the plugin mirrors its own slash command (/repo-init). Written once at
@@ -2,18 +2,21 @@
2
2
  // Minimal logfmt reader/writer shared by the durable store and the evidence
3
3
  // log. Field order is preserved on write so chains are diffable.
4
4
  import { dirname } from "node:path";
5
- import { appendFile, mkdir, rename, stat, unlink } from "node:fs/promises";
5
+ import { mkdir, open, rename, stat, unlink } from "node:fs/promises";
6
+ import { constants } from "node:fs";
7
+ import { tightenDirectory } from "../permissions.ts";
6
8
  import { IS_WINDOWS } from "./format.ts";
7
9
 
8
10
  export async function ensureDir(path: string): Promise<void> {
9
- await mkdir(path, { recursive: true });
11
+ await mkdir(path, { recursive: true, mode: 0o700 });
12
+ tightenDirectory(path);
10
13
  }
11
14
 
12
15
  export async function appendLog(file: string, line: string): Promise<void> {
13
16
  await ensureDir(dirname(file));
14
17
  const next = line.endsWith("\n") ? line : line + "\n";
15
18
  // One O_APPEND write: read-modify-write loses rows under concurrent
16
- // appenders (20 concurrent appends left 2 on disk). appendFile's "a" flag is
19
+ // appenders (20 concurrent appends left 2 on disk). The handle uses
17
20
  // O_APPEND|O_CREAT — atomic small writes on local POSIX filesystems,
18
21
  // covering interleaved async tasks in the service AND a second process
19
22
  // (the viewer) appending the same day file. Do NOT "simplify" back to
@@ -21,7 +24,13 @@ export async function appendLog(file: string, line: string): Promise<void> {
21
24
  // Appending is safe against other appenders only. Callers writing a file that
22
25
  // is ALSO rewritten whole (a daily memory file, the blocklist) hold the store
23
26
  // lock around this — see lock.ts.
24
- await appendFile(file, next);
27
+ const handle = await open(file, constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | (constants.O_NOFOLLOW ?? 0), 0o600);
28
+ try {
29
+ if (!IS_WINDOWS) await handle.chmod((await handle.stat()).mode & 0o600);
30
+ await handle.appendFile(next);
31
+ } finally {
32
+ await handle.close();
33
+ }
25
34
  }
26
35
 
27
36
  // A change-detection token for one file: any append, rewrite or replacement
@@ -57,11 +66,15 @@ export async function writeAtomic(file: string, content: string, since?: string)
57
66
  // name would let one call replace the bytes another call's anchored publish
58
67
  // is retrying. Keep separate temps even when the caller holds a lock.
59
68
  const tmp = `${file}.${process.pid}.${++tmpSeq}.tmp`;
69
+ let claimed = false;
60
70
  try {
71
+ const handle = await open(tmp, "wx", 0o600);
72
+ claimed = true;
73
+ await handle.close();
61
74
  await Bun.write(tmp, content);
62
75
  await handoverRename(tmp, file, since);
63
76
  } catch (err) {
64
- await unlink(tmp).catch(() => undefined);
77
+ if (claimed) await unlink(tmp).catch(() => undefined);
65
78
  throw err;
66
79
  }
67
80
  }
@@ -0,0 +1,47 @@
1
+ // POSIX modes protect local store data, not Windows ACLs. Never follow a
2
+ // final-component link while tightening permissions, or add owner access that
3
+ // an operator deliberately removed (e.g. a read-only store).
4
+ import { closeSync, constants, fchmodSync, fstatSync, mkdirSync, openSync } from "node:fs";
5
+ import { dirname } from "node:path";
6
+
7
+ export function tightenDirectory(path: string): void {
8
+ if (process.platform === "win32") return;
9
+ let fd: number;
10
+ try {
11
+ fd = openSync(path, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
12
+ } catch (err) {
13
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return;
14
+ throw err;
15
+ }
16
+ try {
17
+ const mode = fstatSync(fd).mode & 0o7777;
18
+ const privateMode = mode & 0o700;
19
+ if (mode !== privateMode) {
20
+ try {
21
+ fchmodSync(fd, privateMode);
22
+ } catch (err) {
23
+ // A readable store may be immutable, foreign-owned, or on a mount
24
+ // without chmod support. Keep reads available without claiming that
25
+ // its existing permissions were tightened. Open-time refusals above
26
+ // remain policy errors; unexpected I/O failures still propagate.
27
+ const code = (err as NodeJS.ErrnoException).code;
28
+ if (!code || !["EPERM", "EROFS", "EOPNOTSUPP", "ENOSYS"].includes(code)) throw err;
29
+ }
30
+ }
31
+ } finally {
32
+ closeSync(fd);
33
+ }
34
+ }
35
+
36
+ // Status publication keeps its existing Bun.write scheduling. Claim/tighten
37
+ // the file before that write, without first exposing its contents at 0644.
38
+ export function preparePrivateFile(path: string): void {
39
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
40
+ tightenDirectory(dirname(path));
41
+ const fd = openSync(path, constants.O_WRONLY | constants.O_CREAT | (constants.O_NOFOLLOW ?? 0), 0o600);
42
+ try {
43
+ if (process.platform !== "win32") fchmodSync(fd, fstatSync(fd).mode & 0o600);
44
+ } finally {
45
+ closeSync(fd);
46
+ }
47
+ }
@@ -101,7 +101,7 @@ async function resolveExportTarget(file: string | undefined): Promise<string> {
101
101
  // existing link long before this runs, so the only way to test O_NOFOLLOW
102
102
  // without racing is to call the writer directly.
103
103
  export async function writeExport(path: string, text: string, exclusive = false): Promise<void> {
104
- await mkdir(dirname(path), { recursive: true });
104
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
105
105
  // exclusive = a default destination WE chose: create it or fail, never
106
106
  // silently replace another export's file. An explicit caller-supplied
107
107
  // `file` keeps the historical O_TRUNC replace (backup workflows rewrite
@@ -13,6 +13,7 @@
13
13
  //
14
14
  // Scope of v2: same-machine reads. Against a REMOTE server the terminal panel
15
15
  // sees no status files (it says so) — the RPC surface is the planned follow-up.
16
+ import { preparePrivateFile } from "../core/permissions.ts";
16
17
  import { readFile } from "node:fs/promises";
17
18
  import type { Attribution } from "../inject/attribution.ts";
18
19
  import { captureLag, ledgerIsYoung, rowsPerDay } from "./metrics.ts";
@@ -123,6 +124,7 @@ export const SESSION_FILE_CAP = 32;
123
124
 
124
125
  export async function writeJson(path: string, p: StatusPayload): Promise<boolean> {
125
126
  try {
127
+ preparePrivateFile(path);
126
128
  await Bun.write(path, JSON.stringify(p, null, 2) + "\n");
127
129
  return true;
128
130
  } catch {
@@ -64,10 +64,14 @@ async function pruneStatusDir(): Promise<void> {
64
64
  // Best-effort by design: a status write must never break injection. Writes the
65
65
  // per-session file (primary) AND the global latest file (fallback).
66
66
  export async function writeStatus(p: StatusPayload): Promise<void> {
67
- await writeJson(statusFile(), p);
68
- if (typeof p.sessionID === "string" && p.sessionID) {
69
- await writeJson(sessionStatusFile(p.sessionID), p);
70
- await pruneStatusDir();
67
+ try {
68
+ await writeJson(statusFile(), p);
69
+ if (typeof p.sessionID === "string" && p.sessionID) {
70
+ await writeJson(sessionStatusFile(p.sessionID), p);
71
+ await pruneStatusDir();
72
+ }
73
+ } catch {
74
+ // Resolving an existing root can also fail its permission check.
71
75
  }
72
76
  }
73
77
 
@@ -77,26 +81,34 @@ export async function writeStatus(p: StatusPayload): Promise<void> {
77
81
  * Without one: the global latest file.
78
82
  */
79
83
  export async function readStatus(sessionID?: string): Promise<StatusPayload | null> {
80
- if (sessionID) return readJson(sessionStatusFile(sessionID));
81
- return readJson(statusFile());
84
+ try {
85
+ if (sessionID) return await readJson(sessionStatusFile(sessionID));
86
+ return await readJson(statusFile());
87
+ } catch {
88
+ return null; // an inaccessible root is also "no data"
89
+ }
82
90
  }
83
91
 
84
92
  // Newest-first last `limit` write_blocked evidence rows, scanning today and
85
93
  // yesterday so a block just before midnight stays visible.
86
94
  export async function blockedRecent(limit = 6): Promise<BlockedRow[]> {
87
- const today = dateStr();
88
- const yesterday = new Date(Date.now() - 86_400_000).toISOString().split("T")[0]!;
89
- const rows: BlockedRow[] = [];
90
- for (const day of [yesterday, today]) {
91
- for (const line of await readLines(join(evidenceDir(), `${day}.logfmt`))) {
92
- const f = parseLine(line);
93
- if (!f || f.ev !== "write_blocked") continue;
94
- rows.push({
95
- ts: String(f.ts ?? day),
96
- sid: String(f.sid ?? "?"),
97
- reason: String(f.reason ?? "?"),
98
- });
95
+ try {
96
+ const today = dateStr();
97
+ const yesterday = new Date(Date.now() - 86_400_000).toISOString().split("T")[0]!;
98
+ const rows: BlockedRow[] = [];
99
+ for (const day of [yesterday, today]) {
100
+ for (const line of await readLines(join(evidenceDir(), `${day}.logfmt`))) {
101
+ const f = parseLine(line);
102
+ if (!f || f.ev !== "write_blocked") continue;
103
+ rows.push({
104
+ ts: String(f.ts ?? day),
105
+ sid: String(f.sid ?? "?"),
106
+ reason: String(f.reason ?? "?"),
107
+ });
108
+ }
99
109
  }
110
+ return rows.slice(-limit).reverse();
111
+ } catch {
112
+ return []; // A refused root is no status data, not an unhandled panel refresh.
100
113
  }
101
- return rows.slice(-limit).reverse();
102
114
  }
@@ -58,7 +58,7 @@ async function claimSnapshot(file: string): Promise<string> {
58
58
  for (;;) {
59
59
  const snap = join(snapshotDir(), `${stamp}-${basename(file)}`);
60
60
  try {
61
- const handle = await open(snap, "wx");
61
+ const handle = await open(snap, "wx", 0o600);
62
62
  await handle.close();
63
63
  return snap;
64
64
  } catch (err) {
package/src/store/lock.ts CHANGED
@@ -21,7 +21,8 @@
21
21
  // Readers take NO lock: publishers hand over the new file with a rename
22
22
  // (writeAtomic in logfmt.ts), so a reader always sees a complete store, never
23
23
  // the middle of a rewrite.
24
- import { mkdir, open, stat, unlink } from "node:fs/promises";
24
+ import { open, stat, unlink } from "node:fs/promises";
25
+ import { ensureDir } from "../core/logfmt/publish.ts";
25
26
  import { basename, dirname } from "node:path";
26
27
  import { record } from "../evidence/record.ts";
27
28
 
@@ -140,7 +141,7 @@ export async function holdFileLock<T>(
140
141
  budgetMs: number,
141
142
  now: () => number = Date.now,
142
143
  ): Promise<T> {
143
- await mkdir(dirname(lockPath), { recursive: true });
144
+ await ensureDir(dirname(lockPath));
144
145
  const token = `${process.pid}-${Math.random().toString(36).slice(2)}`;
145
146
  const started = now();
146
147
  let backoff = MIN_BACKOFF_MS;
@@ -155,7 +156,7 @@ export async function holdFileLock<T>(
155
156
  let everSawHolder = false;
156
157
  for (;;) {
157
158
  try {
158
- const handle = await open(lockPath, "wx");
159
+ const handle = await open(lockPath, "wx", 0o600);
159
160
  try {
160
161
  await handle.write(token);
161
162
  } finally {