aegiscode 6.8.5 → 6.8.7

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/src/config.js CHANGED
@@ -14,6 +14,7 @@
14
14
 
15
15
  const fs = require('node:fs');
16
16
  const path = require('node:path');
17
+ const { writePrivateFile } = require('./securefs.js');
17
18
 
18
19
  // The data dir is defined once, in the shared credential module, because the
19
20
  // desktop app and the MCP plugin now read and write the same store: a second
@@ -181,11 +182,10 @@ function loadConfig() {
181
182
  function updateConfig(patch) {
182
183
  const next = { ...loadConfig(), ...patch };
183
184
  try {
184
- fs.mkdirSync(aegisDir(), { recursive: true });
185
- // Write atomically-ish: tmp file + rename so a crash can't corrupt it.
186
- const tmp = configPath() + '.tmp';
187
- fs.writeFileSync(tmp, JSON.stringify(next, null, 2) + '\n');
188
- fs.renameSync(tmp, configPath());
185
+ // Atomic (tmp + rename) so a crash can't corrupt it, and written 0600:
186
+ // config.json carries `provider` and `baseURL`, so a group-writable copy is
187
+ // a way for another local account to repoint the session's endpoint.
188
+ writePrivateFile(configPath(), JSON.stringify(next, null, 2) + '\n');
189
189
  } catch (e) {
190
190
  if (process.env.AEGIS_HIST_DEBUG) console.error('[config] write failed:', e);
191
191
  }
@@ -229,10 +229,9 @@ function loadPermissions() {
229
229
  /** Persist permission rules. Returns the saved rules (or the input on failure). */
230
230
  function savePermissions(rules) {
231
231
  try {
232
- fs.mkdirSync(aegisDir(), { recursive: true });
233
- const tmp = permissionsPath() + '.tmp';
234
- fs.writeFileSync(tmp, JSON.stringify(rules, null, 2) + '\n');
235
- fs.renameSync(tmp, permissionsPath());
232
+ // 0600: the rules decide which tools run without a prompt, so a writable
233
+ // copy is a way to pre-approve the next session's tool calls.
234
+ writePrivateFile(permissionsPath(), JSON.stringify(rules, null, 2) + '\n');
236
235
  } catch (e) {
237
236
  if (process.env.AEGIS_HIST_DEBUG) console.error('[permissions] write failed:', e);
238
237
  }
package/src/deps.js CHANGED
@@ -63,6 +63,10 @@ const updatePath = resolveShared(path.join('client', 'update.js'));
63
63
  // must work the SAME queue with the SAME rules (scoped commits included).
64
64
  const queuePath = resolveShared(path.join('desktop', 'lib', 'local', 'queue.js'));
65
65
  const autonomousPath = resolveShared(path.join('desktop', 'lib', 'local', 'autonomous.js'));
66
+ // Auto-provision a free device key when no key is configured anywhere — same
67
+ // module the MCP plugin and the desktop app use, so all three ask aegis1 for
68
+ // the same account on the same machine, with the same timeout.
69
+ const autoProvisionPath = resolveShared(path.join('client', 'auto-provision.js'));
66
70
 
67
71
  const { createClient } = require(clientPath);
68
72
  const { createTools } = require(toolsPath);
@@ -74,6 +78,7 @@ const { buildSystemPrompt } = require(promptPath);
74
78
  const updater = require(updatePath);
75
79
  const queue = require(queuePath);
76
80
  const autonomous = require(autonomousPath);
81
+ const { autoProvisionApiKey } = require(autoProvisionPath);
77
82
 
78
83
  module.exports = {
79
84
  resolveShared,
@@ -90,6 +95,7 @@ module.exports = {
90
95
  updater,
91
96
  queue,
92
97
  autonomous,
93
- paths: { client: clientPath, tools: toolsPath, usage: usagePath, engine: enginePath, settings: settingsPath, agents: agentsPath, prompt: promptPath, update: updatePath, queue: queuePath, autonomous: autonomousPath },
98
+ autoProvisionApiKey,
99
+ paths: { client: clientPath, tools: toolsPath, usage: usagePath, engine: enginePath, settings: settingsPath, agents: agentsPath, prompt: promptPath, update: updatePath, queue: queuePath, autonomous: autonomousPath, autoProvision: autoProvisionPath },
94
100
  roots,
95
101
  };
package/src/diffview.js CHANGED
@@ -142,12 +142,14 @@ function defaultOpen(preview) {
142
142
  }
143
143
 
144
144
  /**
145
- * The summary row: ` ⎿ Update(src/diff.js) +12 -3 · click to view diff`.
145
+ * The summary row: ` ⎿ Update(src/diff.js) +12 -3 · click to view diff`.
146
146
  *
147
147
  * @param {object} preview From diff.js's editPreview().
148
148
  * @param {object} ctx App context (selects the light/dark diff palette).
149
+ * @param {{open?: boolean}} [opts] Whether the block is expanded — flips the
150
+ * hint to "click to collapse", the way the click gesture will read next.
149
151
  */
150
- function diffSummaryRow(preview, ctx) {
152
+ function diffSummaryRow(preview, ctx, opts = {}) {
151
153
  const t = themeOf(ctx);
152
154
  const D = diffOf(ctx);
153
155
  const bits = [` ${t.gray}${GLYPH.hook} ${RESET}`];
@@ -156,6 +158,11 @@ function diffSummaryRow(preview, ctx) {
156
158
  if (preview.dels) bits.push(`${D.delFg} -${preview.dels}${RESET}`);
157
159
  if (!preview.adds && !preview.dels) bits.push(`${t.gray} no line changes${RESET}`);
158
160
  if (preview.misses) bits.push(`${t.gold} ${preview.misses} edit(s) not applied${RESET}`);
161
+ // The affordance, and the only thing that tells the reader this row is
162
+ // clickable — chatflow's clickHits map keys the row painted here. It also
163
+ // mirrors aegiscodex-dev's diffSummaryRow(), which emits the same hint, so
164
+ // the two hosts advertise the same gesture in the same words.
165
+ bits.push(`${DIM} · ${opts.open ? 'click to collapse' : 'click to view diff'}${RESET}`);
159
166
  return bits.join('');
160
167
  }
161
168
 
@@ -175,7 +182,7 @@ function renderDiffBlock(preview, ctx, cols, opts = {}) {
175
182
  const width = Math.max(8, Number(cols) || 80);
176
183
  const D = diffOf(ctx);
177
184
  const t = themeOf(ctx);
178
- const out = [clipRow(diffSummaryRow(preview, ctx), width)];
185
+ const out = [clipRow(diffSummaryRow(preview, ctx, { open: opts.open }), width)];
179
186
  if (!opts.open || !preview || !preview.rows || !preview.rows.length) return out;
180
187
 
181
188
  const rows = markIntraLine(preview.rows.slice(0, MAX_BLOCK_ROWS).map((r) => Object.assign({}, r)));
@@ -0,0 +1,108 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * entitlement.js — the terminal host's binding to the SHARED Pro gate.
5
+ *
6
+ * WHY THIS FILE EXISTS (and why it is six lines of real work). The gate that
7
+ * decides who may spend the fan-out lives in
8
+ * `desktop/lib/local/entitlement.js`, and the CLI has been the leak since the
9
+ * day it landed: `autonomous.js` drives the SAME queue file through the SAME
10
+ * worker, `createWorker` takes a `canFanOut` predicate, and the CLI simply
11
+ * never passed one — so it defaulted to `() => true`. A task queued with
12
+ * `--workers 8` or written into queue.jsonl by hand fans out on the free tier
13
+ * from `ssh box 'aegiscode autonomous proceed'`, costing the multiplier the
14
+ * gate exists to withhold, with no window and nobody to ask.
15
+ *
16
+ * The desktop's own comment named this as a known gap ("the CLI's own drain is
17
+ * a different host with no session to ask"). It had a session — it has the same
18
+ * account key in the same 0600 store, read through the same shared client. It
19
+ * was a wiring omission, not an architectural one.
20
+ *
21
+ * TWO THINGS ARE HOST-SPECIFIC, and both are handled by the shared module's own
22
+ * seams rather than reimplemented here:
23
+ *
24
+ * 1. THE CHANNEL. `host: 'cli'` makes every refusal link
25
+ * `/go/upgrade?s=cli&…`, so a terminal click is filed as a CLI conversion
26
+ * instead of a desktop one. The desktop's literals hardcode `s=desktop`;
27
+ * printing one from the terminal would have quietly moved every CLI
28
+ * conversion into the desktop's column.
29
+ * 2. THE PROBE. The CLI has no Electron session, so it builds the same
30
+ * reading the desktop builds — `verifyApiKey()` for the plan plus
31
+ * `tokenBankBalance()` for the operator's balance — from the shared client
32
+ * directly.
33
+ *
34
+ * Not reimplemented, deliberately: the plan vocabulary, the balance
35
+ * interpretation, the fail-closed rules, the refusal copy, the campaign ids.
36
+ * Two implementations of "is this account paid" is exactly how the terminal and
37
+ * the GUI would come to disagree about who owes money — and the disagreement
38
+ * would spend real money, in whichever host had the looser copy.
39
+ *
40
+ * Wired through `sharedpaths.js` (paths, no eager requires) rather than
41
+ * `deps.js`, because `deps.js` eagerly loads `autonomous.js`, which loads THIS
42
+ * file back: requiring deps.js here would be a require cycle handing one side a
43
+ * half-built exports object. Same reason `sharedpaths.js` was split out.
44
+ */
45
+
46
+ const { resolveShared } = require('./sharedpaths.js');
47
+
48
+ /** The shared decision, resolved by existence (repo checkout or staged tree). */
49
+ function loadModule() {
50
+ // eslint-disable-next-line global-require
51
+ return require(resolveShared('desktop/lib/local/entitlement.js'));
52
+ }
53
+
54
+ /** The shared thin transport, same two-layout resolution as deps.js. */
55
+ function loadClient() {
56
+ // eslint-disable-next-line global-require
57
+ const { createClient } = require(resolveShared('client/aegis.js'));
58
+ const credentials = require('./credentials.js');
59
+ return createClient(credentials.clientOptions({ channel: 'cli' }));
60
+ }
61
+
62
+ /**
63
+ * The account probe, shaped exactly as the desktop builds it.
64
+ *
65
+ * A failed balance call leaves the balance UNKNOWN rather than inventing a
66
+ * zero: an unreadable bank must never manufacture a top-up prompt, and
67
+ * `classifyProbe` fails closed on the unknown anyway. Both calls are read-only
68
+ * and neither writes server-side — the gate observes the operator's number, it
69
+ * never sets one.
70
+ */
71
+ function buildProbe(aegis) {
72
+ if (!aegis || typeof aegis.verifyApiKey !== 'function') return undefined;
73
+ return async () => {
74
+ const verify = await aegis.verifyApiKey();
75
+ const body = verify && typeof verify === 'object' ? { ...verify } : {};
76
+ if (typeof aegis.tokenBankBalance === 'function') {
77
+ try {
78
+ const bank = await aegis.tokenBankBalance();
79
+ if (bank && typeof bank === 'object') {
80
+ if (bank.balance_micros != null) body.balance_micros = bank.balance_micros;
81
+ else if (bank.balance_eur != null) body.balance_eur = bank.balance_eur;
82
+ }
83
+ } catch {
84
+ // Unknown stays unknown — see the docstring above.
85
+ }
86
+ }
87
+ return body;
88
+ };
89
+ }
90
+
91
+ /**
92
+ * The gate for one CLI process, reading the SAME account the desktop reads.
93
+ *
94
+ * `host: 'cli'` is the whole reason campaign links can be trusted from here.
95
+ * Returns the shared gate object: `{ refresh, current, gateFanout }`.
96
+ */
97
+ function createCliEntitlement({ aegis, now, ttlMs } = {}) {
98
+ const mod = loadModule();
99
+ const client = aegis || loadClient();
100
+ return mod.createEntitlement({
101
+ probe: buildProbe(client),
102
+ host: 'cli',
103
+ ...(now ? { now } : {}),
104
+ ...(ttlMs ? { ttlMs } : {}),
105
+ });
106
+ }
107
+
108
+ module.exports = { createCliEntitlement, buildProbe, loadModule };
package/src/events.js CHANGED
@@ -25,6 +25,14 @@ const { decodeEscSequence, decodePlain, KEY } = require('./keys.js');
25
25
 
26
26
  const queue = [];
27
27
  let waiting = [];
28
+
29
+ /**
30
+ * Handed to every parked `nextKey()` waiter when the pump is reset, so a
31
+ * consumer can tell "the stream went away" from "the user pressed nothing".
32
+ * Without it the only way to unblock a waiter is a real keypress, which means a
33
+ * session whose loop is parked on a bare `nextKey()` cannot be stopped at all.
34
+ */
35
+ const STREAM_END = Symbol('aegis.streamEnd');
28
36
  let buffer = '';
29
37
  let seq = '';
30
38
  let escTimer = null;
@@ -261,7 +269,9 @@ function nextKeyTimeout(ms) {
261
269
  }, ms);
262
270
  const wrapper = (key) => {
263
271
  clearTimeout(timer);
264
- resolve(key);
272
+ // A pump reset resolves null, exactly like the timeout path: this call's
273
+ // contract is "a key or null", and STREAM_END is not a key.
274
+ resolve(key === STREAM_END ? null : key);
265
275
  };
266
276
  waiting.push(wrapper);
267
277
  });
@@ -316,7 +326,22 @@ function resetKeyStream() {
316
326
  buffer = '';
317
327
  pasteChunks = [];
318
328
  drainQueue();
329
+ // Resolve — do NOT merely drop — the parked waiters. `waiting = []` on its own
330
+ // leaves every loop sitting on a bare nextKey() parked forever: nothing can
331
+ // ever wake it, so any consumer that leaks the pump becomes unkillable and
332
+ // keeps painting into the stdout it captured. Handing each waiter STREAM_END
333
+ // lets its loop observe the teardown and break. A leaked session's keystrokes
334
+ // also stop landing in the next session's queue, because the queue is cleared
335
+ // here and the stale waiter is gone rather than still attached to it.
336
+ const parked = waiting;
319
337
  waiting = [];
338
+ for (const w of parked) {
339
+ try {
340
+ w(STREAM_END);
341
+ } catch {
342
+ /* waiter already settled */
343
+ }
344
+ }
320
345
  attachedStdin = null;
321
346
  onData = null;
322
347
  suspended = false;
@@ -324,6 +349,7 @@ function resetKeyStream() {
324
349
 
325
350
  module.exports = {
326
351
  KEY,
352
+ STREAM_END,
327
353
  // Exported for `test/cli-marking.test.mjs`: the click/drag/release split is
328
354
  // the half of the marking gesture that is pure decoding, and it is the half
329
355
  // that regressed silently once already (only left presses were named, so a
package/src/history.js CHANGED
@@ -24,6 +24,7 @@ const fs = require('node:fs');
24
24
  const os = require('node:os');
25
25
  const path = require('node:path');
26
26
  const { aegisDir } = require('./config.js');
27
+ const { ensurePrivateDir, writePrivateFile } = require('./securefs.js');
27
28
  const { sessionStore } = require('./shared.js');
28
29
  const { estimateTokens } = require('./tokens.js');
29
30
 
@@ -36,7 +37,7 @@ function historyPath() {
36
37
  }
37
38
 
38
39
  function ensureHistoryDir() {
39
- fs.mkdirSync(path.dirname(historyPath()), { recursive: true });
40
+ ensurePrivateDir(path.dirname(historyPath()));
40
41
  }
41
42
 
42
43
  /**
@@ -95,7 +96,8 @@ function appendHistoryEntries(entries) {
95
96
  const prev = fs.existsSync(p) ? fs.readFileSync(p, 'utf8').split('\n').filter(Boolean) : [];
96
97
  const lines = [...prev, ...list.map((e) => JSON.stringify(e))];
97
98
  const trimmed = lines.slice(Math.max(0, lines.length - HISTORY_LIMIT));
98
- fs.writeFileSync(p, trimmed.join('\n') + '\n');
99
+ // 0600: this file is every prompt and reply the session has ever had.
100
+ writePrivateFile(p, trimmed.join('\n') + '\n');
99
101
  mirrorToSharedStore(list);
100
102
  return list.length;
101
103
  } catch (e) {
@@ -227,7 +229,7 @@ function pruneSessionHistory(sessionId) {
227
229
  .filter((l) => {
228
230
  try { return JSON.parse(l).sessionId !== sessionId; } catch { return true; }
229
231
  });
230
- fs.writeFileSync(p, kept.length ? kept.join('\n') + '\n' : '');
232
+ writePrivateFile(p, kept.length ? kept.join('\n') + '\n' : '');
231
233
  } catch (e) {
232
234
  if (process.env.AEGIS_HIST_DEBUG) console.error('[history] prune failed:', e);
233
235
  }
@@ -0,0 +1,319 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Private files in the data dir (~/.aegiscode) — hardening against a local
5
+ * info-stealer, which is the threat the CLI's own store actually invites.
6
+ *
7
+ * What was wrong: every writer in this CLI used `fs.writeFileSync(p, data)`
8
+ * with no `mode`, and `fs.mkdirSync(dir, { recursive: true })` with no `mode`.
9
+ * Both therefore inherited the process umask, which on a default desktop Linux
10
+ * is 0002 — so the data dir landed at 0775 and every file in it at 0664. On a
11
+ * single-user box that looks harmless. It is not:
12
+ *
13
+ * - 0664 is world-READABLE. history.jsonl is every prompt and every reply the
14
+ * user has ever sent, checkpoints/ is the same in full, and clipboard.txt is
15
+ * verbatim whatever the user last marked and copied. Any other local account
16
+ * — or any process running as one — reads all of it with plain `cat`.
17
+ * - 0664 is group-WRITABLE, and so was the 0775 directory. config.json holds
18
+ * `provider` and `baseURL`, so a second account in the group could repoint
19
+ * the CLI's endpoint at a host it controls and collect the prompts, the
20
+ * completions, and the credentials relayed through it. A writable data dir
21
+ * also lets anyone drop a `permissions.json` that pre-approves the tools
22
+ * they want the next session to run unprompted.
23
+ *
24
+ * Two properties matter beyond the mode bits:
25
+ *
26
+ * - `O_NOFOLLOW` on create. `writeFileSync` follows symlinks, so a symlink
27
+ * planted at `~/.aegiscode/clipboard.txt` pointing at `~/.bashrc` turned a
28
+ * copy gesture into an arbitrary file overwrite. Creating with
29
+ * `O_CREAT|O_EXCL|O_NOFOLLOW` — after unlinking any leftover — fails instead
30
+ * of following, and `O_EXCL` closes the window between the unlink and the
31
+ * open: a symlink raced into place makes the open fail with EEXIST rather
32
+ * than being followed.
33
+ * - `rename`, not truncate, for the atomic path. `renameSync` replaces a
34
+ * planted symlink instead of writing through it, so the atomic writers
35
+ * (config, permissions) are safe even without the O_EXCL dance.
36
+ *
37
+ * Ownership is checked before every chmod and never chmod'ed through a symlink,
38
+ * so a data dir that is deliberately shared (or root-owned) is left alone rather
39
+ * than having its permissions silently rewritten by us. Every helper is
40
+ * best-effort in the same spirit as the rest of this CLI: a hardening step that
41
+ * cannot be applied must not be the reason a session cannot save.
42
+ *
43
+ * Deliberately dependency-free — no `shared.js`, no engine — so it can be
44
+ * required from anything without a cycle, and unit-tested in isolation.
45
+ */
46
+
47
+ const fs = require('node:fs');
48
+ const path = require('node:path');
49
+
50
+ // O_NOFOLLOW is POSIX; on Windows the constant is absent, leaving the mode and
51
+ // rename protections (which do not depend on it) in place.
52
+ const NOFOLLOW = fs.constants.O_NOFOLLOW || 0;
53
+
54
+ /** True when `st` is owned by the current user (always true where getuid is absent). */
55
+ function ownedByUs(st) {
56
+ if (typeof process.getuid !== 'function') return true;
57
+ try { return st.uid === process.getuid(); } catch { return false; }
58
+ }
59
+
60
+ /**
61
+ * Force `p` to `mode`, but only when it is a real file we own.
62
+ * Never follows a symlink (chmod through a link would modify its target) and
63
+ * never returns false for a file that is already correct.
64
+ */
65
+ function chmodPrivate(p, mode = 0o600) {
66
+ try {
67
+ const st = fs.lstatSync(p);
68
+ if (st.isSymbolicLink()) return false;
69
+ if (!ownedByUs(st)) return false;
70
+ if ((st.mode & 0o777) === mode) return true;
71
+ fs.chmodSync(p, mode);
72
+ return true;
73
+ } catch {
74
+ return false;
75
+ }
76
+ }
77
+
78
+ /**
79
+ * `mkdir -p` at 0700, and tighten a directory that already exists.
80
+ * `mkdirSync` ignores `mode` for a directory that is already there, so an
81
+ * install that predates this module keeps its 0775 without the explicit chmod.
82
+ */
83
+ function ensurePrivateDir(dir) {
84
+ try {
85
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
86
+ } catch {
87
+ return false;
88
+ }
89
+ try {
90
+ const st = fs.lstatSync(dir);
91
+ if (st.isSymbolicLink() || !st.isDirectory()) return false;
92
+ if (ownedByUs(st) && (st.mode & 0o077) !== 0) fs.chmodSync(dir, 0o700);
93
+ return true;
94
+ } catch {
95
+ return false;
96
+ }
97
+ }
98
+
99
+ /**
100
+ * Write `data` to `file` with mode 0600, creating the parent dir at 0700.
101
+ *
102
+ * atomic (default) writes `file.tmp` and renames over the target, so a crash
103
+ * cannot truncate a live config and a planted symlink is replaced rather than
104
+ * followed. `{ atomic: false }` truncates in place instead, which is the right
105
+ * shape for a scratch file that is never read concurrently — it still refuses
106
+ * to follow a symlink at `file`.
107
+ *
108
+ * Throws on failure; callers already treat a failed save as non-fatal.
109
+ */
110
+ function writePrivateFile(file, data, opts = {}) {
111
+ const dir = path.dirname(file);
112
+ ensurePrivateDir(dir);
113
+
114
+ const common = fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | NOFOLLOW;
115
+
116
+ if (opts.atomic === false) {
117
+ try { fs.unlinkSync(file); } catch {} // drop a leftover or a planted symlink
118
+ const fd = fs.openSync(file, common, 0o600);
119
+ try {
120
+ fs.fchmodSync(fd, 0o600);
121
+ fs.writeFileSync(fd, data);
122
+ } finally {
123
+ fs.closeSync(fd);
124
+ }
125
+ return true;
126
+ }
127
+
128
+ const tmp = file + '.tmp';
129
+ try { fs.unlinkSync(tmp); } catch {}
130
+ const fd = fs.openSync(tmp, common, 0o600);
131
+ try {
132
+ fs.fchmodSync(fd, 0o600);
133
+ fs.writeFileSync(fd, data);
134
+ } finally {
135
+ fs.closeSync(fd);
136
+ }
137
+ fs.renameSync(tmp, file); // replaces a planted symlink instead of writing through it
138
+ chmodPrivate(file, 0o600);
139
+ return true;
140
+ }
141
+
142
+ /**
143
+ * ---------------------------------------------------------------------------
144
+ * Retroactive repair.
145
+ * ---------------------------------------------------------------------------
146
+ *
147
+ * `writePrivateFile` hardens a path only at the moment it is written, so an
148
+ * install that predates this module keeps its 0664/0775 indefinitely: each
149
+ * writer fixes a file the next time that file happens to change, and nothing
150
+ * ever revisits the rest. On the real store that left `~/.aegiscode` at 0775
151
+ * with config.json, permissions.json, history.jsonl, clipboard.txt and every
152
+ * file under checkpoints/ and indexes/ at 0664 — months of transcripts, plus a
153
+ * group-writable endpoint — readable by any other local account.
154
+ *
155
+ * `repairExposure` walks the data dir once and forces it private. Three details
156
+ * are load-bearing rather than incidental:
157
+ *
158
+ * - The exec bit is PRESERVED, not stripped. This directory is not purely
159
+ * data: `oauth-proxy.js` (0775) and `bin/aegis-cli` (0755) are run from
160
+ * here, so the obvious implementation — a blanket `chmod 0600` — would
161
+ * silently break both. The rule is therefore mode-relative: a directory, or
162
+ * a file the owner may execute, becomes 0700; anything else becomes 0600.
163
+ * Nothing loses a permission it needed; everything loses the ones it did
164
+ * not.
165
+ * - Symlinks are never entered and never chmod'ed through, for the same reason
166
+ * `chmodPrivate` refuses them: a planted link would otherwise make the
167
+ * repair itself the write primitive.
168
+ * - The root directory is the high-value step. At 0700 no other account can
169
+ * traverse into it at all, which covers every file inside — including the
170
+ * executables above whose own modes stay permissive. The per-file pass is
171
+ * defence in depth for the case where the directory is later re-shared,
172
+ * restored from a backup, or a file is copied out of it.
173
+ *
174
+ * The read-only (`auditExposure`) and writing (`repairExposure`) entry points
175
+ * are deliberately separate so `/doctor` can report exposure without changing
176
+ * anything, and only act on an explicit `/doctor fix`.
177
+ */
178
+
179
+ /** Longest path (below the data dir) the repair walk will descend. */
180
+ const MAX_WALK_DEPTH = 4;
181
+
182
+ /** `0775`-style rendering of the permission bits of a `stat`. */
183
+ function fmtMode(mode) {
184
+ return '0' + (mode & 0o777).toString(8).padStart(3, '0');
185
+ }
186
+
187
+ /**
188
+ * The mode a path should hold: 0700 when the owner needs to traverse or execute
189
+ * it (a directory, or a file carrying an owner-exec bit), 0600 otherwise.
190
+ */
191
+ function targetMode(st) {
192
+ if (st.isDirectory()) return 0o700;
193
+ return st.mode & 0o100 ? 0o700 : 0o600;
194
+ }
195
+
196
+ /**
197
+ * Every non-symlink entry under `root`, depth-first, with its lstat.
198
+ * Unreadable directories are skipped rather than thrown on: a repair that
199
+ * cannot see a subtree must still fix the rest of it.
200
+ */
201
+ function scanTree(root) {
202
+ const out = [];
203
+ const walk = (dir, rel, depth) => {
204
+ if (depth > MAX_WALK_DEPTH) return;
205
+ let entries;
206
+ try {
207
+ entries = fs.readdirSync(dir, { withFileTypes: true });
208
+ } catch {
209
+ return;
210
+ }
211
+ for (const e of entries) {
212
+ if (e.isSymbolicLink()) continue; // never followed, never chmod'ed through
213
+ const full = path.join(dir, e.name);
214
+ const childRel = rel ? `${rel}/${e.name}` : e.name;
215
+ let st;
216
+ try {
217
+ st = fs.lstatSync(full);
218
+ } catch {
219
+ continue;
220
+ }
221
+ out.push({ rel: childRel, full, st });
222
+ if (st.isDirectory()) walk(full, childRel, depth + 1);
223
+ }
224
+ };
225
+ walk(root, '', 0);
226
+ return out;
227
+ }
228
+
229
+ /** Does `mode` grant anything to group or other? */
230
+ function exposedBits(mode) {
231
+ return (mode & 0o077) !== 0;
232
+ }
233
+
234
+ /**
235
+ * Report every path in the data dir that is reachable by group or other.
236
+ *
237
+ * Read-only. Returns `{ root, exists, rootMode, exposed, total }` where each
238
+ * entry of `exposed` is `{ rel, mode, kind }` — `rel` is `.` for the root
239
+ * itself, and `kind` is `'dir'` or `'file'`.
240
+ */
241
+ function auditExposure(root) {
242
+ const report = { root, exists: false, rootMode: null, exposed: [], total: 0 };
243
+ let rst;
244
+ try {
245
+ rst = fs.lstatSync(root);
246
+ } catch {
247
+ return report;
248
+ }
249
+ if (rst.isSymbolicLink() || !rst.isDirectory()) return report;
250
+ report.exists = true;
251
+ report.rootMode = fmtMode(rst.mode);
252
+ if (exposedBits(rst.mode)) report.exposed.push({ rel: '.', mode: report.rootMode, kind: 'dir' });
253
+
254
+ const items = scanTree(root);
255
+ report.total = items.length;
256
+ for (const it of items) {
257
+ if (!exposedBits(it.st.mode)) continue;
258
+ report.exposed.push({
259
+ rel: it.rel,
260
+ mode: fmtMode(it.st.mode),
261
+ kind: it.st.isDirectory() ? 'dir' : 'file',
262
+ });
263
+ }
264
+ return report;
265
+ }
266
+
267
+ /**
268
+ * Force every group/world-accessible path in the data dir back to 0700/0600,
269
+ * preserving the owner-exec bit (see the block comment above).
270
+ *
271
+ * Best-effort and idempotent: a path that is already private is left untouched,
272
+ * a path we do not own is reported rather than fought over, and a second run
273
+ * fixes nothing. Returns `{ root, exists, fixed, failed, remaining }`, where
274
+ * `remaining` is the exposure audit taken after the pass — non-empty only when
275
+ * something could not be repaired.
276
+ */
277
+ function repairExposure(root) {
278
+ const report = { root, exists: false, fixed: [], failed: [], remaining: [] };
279
+ let rst;
280
+ try {
281
+ rst = fs.lstatSync(root);
282
+ } catch {
283
+ return report;
284
+ }
285
+ if (rst.isSymbolicLink() || !rst.isDirectory()) return report;
286
+ report.exists = true;
287
+
288
+ const tighten = (full, st, rel) => {
289
+ if (!ownedByUs(st)) {
290
+ report.failed.push({ rel, reason: 'not owned by this user' });
291
+ return;
292
+ }
293
+ const want = targetMode(st);
294
+ try {
295
+ fs.chmodSync(full, want);
296
+ report.fixed.push({ rel, from: fmtMode(st.mode), to: fmtMode(want) });
297
+ } catch (err) {
298
+ report.failed.push({ rel, reason: err.code || String(err) });
299
+ }
300
+ };
301
+
302
+ if (exposedBits(rst.mode)) tighten(root, rst, '.');
303
+ for (const it of scanTree(root)) {
304
+ if (!exposedBits(it.st.mode)) continue;
305
+ tighten(it.full, it.st, it.rel);
306
+ }
307
+
308
+ report.remaining = auditExposure(root).exposed;
309
+ return report;
310
+ }
311
+
312
+ module.exports = {
313
+ ensurePrivateDir,
314
+ writePrivateFile,
315
+ chmodPrivate,
316
+ auditExposure,
317
+ repairExposure,
318
+ fmtMode,
319
+ };