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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "aegiscode",
3
3
  "productName": "AEGIS Code",
4
- "version": "6.8.5",
4
+ "version": "6.8.7",
5
5
  "description": "aegiscode — the command-line version of AEGIS Desktop. The shared tool surface in your shell, over the same thin transport and tool registry as the MCP plugin and the desktop app. Ships transport + UI only; no brain.",
6
6
  "author": {
7
7
  "name": "AEGIS Code",
@@ -27,7 +27,7 @@
27
27
  "predist": "node scripts/predist.mjs",
28
28
  "prepublishOnly": "npm run predist",
29
29
  "check": "node --check bin/aegiscode.js && for f in src/*.js; do node --check \"$f\" || exit 1; done && node --check scripts/predist.mjs",
30
- "test": "for f in ../test/cli-*.test.mjs; do node \"$f\" || exit 1; done"
30
+ "test": "node scripts/runtests.mjs"
31
31
  },
32
32
  "keywords": [
33
33
  "aegis",
@@ -50,6 +50,11 @@ const FILES = [
50
50
  // comments in this array: test/packaging.test.mjs parses it by pairing single
51
51
  // quotes, and one stray one silently swallows the next real entry.)
52
52
  'client/env-file.js',
53
+ // Auto-provision a free device key when no key is configured anywhere —
54
+ // shared with the desktop app and the MCP plugin so all three ask aegis1
55
+ // for the same account on the same machine.
56
+ 'client/auto-provision.js',
57
+ 'client/device-fingerprint.js',
53
58
  'mcp/tools.js',
54
59
  // The stdio MCP server itself — the process every editor config written by
55
60
  // `aegiscode mcp install` points at. Staging the registry without it ships a
@@ -116,6 +121,13 @@ const FILES = [
116
121
  // both sit above; `queue.js` requires only node builtins.
117
122
  'desktop/lib/local/queue.js',
118
123
  'desktop/lib/local/autonomous.js',
124
+ // The shared Pro gate. `autonomous.js` requires `src/entitlement.js` at load
125
+ // time, and that module locates this file by EXISTENCE through
126
+ // `resolveShared` — never by a fallback copy — so a vendor tree missing it
127
+ // throws before the CLI can print its usage, the same failure class as 6.5.6.
128
+ // The module requires nothing at all: the account probe is injected by the
129
+ // caller, which is why staging it alone is enough.
130
+ 'desktop/lib/local/entitlement.js',
119
131
  ];
120
132
 
121
133
  function main() {
@@ -0,0 +1,54 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Run every `test/cli-*.test.mjs` and report all of them.
4
+ *
5
+ * This replaces `for f in …; do node "$f" || exit 1; done`. That loop stops at
6
+ * the first failure, and since the files run in glob (alphabetical) order, one
7
+ * broken file silently hides every file after it — `cli-click` sorts 5th of 28,
8
+ * so a single failure there meant 23 test files had not run at all while the
9
+ * command still looked like "the suite".
10
+ *
11
+ * Failures are collected, each file's own output is streamed through, and the
12
+ * summary names what failed. Exit is non-zero if anything failed, so CI and
13
+ * `npm test` still gate on it.
14
+ */
15
+ import { readdirSync } from 'node:fs';
16
+ import { spawnSync } from 'node:child_process';
17
+ import { dirname, join, resolve } from 'node:path';
18
+ import { fileURLToPath } from 'node:url';
19
+
20
+ const here = dirname(fileURLToPath(import.meta.url));
21
+ const testDir = resolve(here, '..', '..', 'test');
22
+
23
+ const files = readdirSync(testDir)
24
+ .filter((f) => /^cli-.*\.test\.mjs$/.test(f))
25
+ .sort();
26
+
27
+ if (files.length === 0) {
28
+ process.stderr.write(`no cli-*.test.mjs found in ${testDir}\n`);
29
+ process.exit(1);
30
+ }
31
+
32
+ const failed = [];
33
+ const passed = [];
34
+
35
+ for (const f of files) {
36
+ const full = join(testDir, f);
37
+ process.stdout.write(`\n── ${f} ${'─'.repeat(Math.max(0, 60 - f.length))}\n`);
38
+ const res = spawnSync(process.execPath, [full], { stdio: 'inherit' });
39
+ if (res.status === 0) {
40
+ passed.push(f);
41
+ } else {
42
+ failed.push({ f, status: res.status, signal: res.signal });
43
+ }
44
+ }
45
+
46
+ process.stdout.write(`\n${'═'.repeat(64)}\n`);
47
+ process.stdout.write(`cli suite: ${passed.length}/${files.length} files passed\n`);
48
+ if (failed.length) {
49
+ process.stdout.write(`\nFAILED (${failed.length}):\n`);
50
+ for (const { f, status, signal } of failed) {
51
+ process.stdout.write(` ✗ ${f}${signal ? ` (signal ${signal})` : ` (exit ${status})`}\n`);
52
+ }
53
+ process.exit(1);
54
+ }
package/src/app.js CHANGED
@@ -21,7 +21,7 @@
21
21
  const readline = require('node:readline');
22
22
  const os = require('node:os');
23
23
  const { randomUUID } = require('node:crypto');
24
- const { createTools, createClient, usageTokens, usageBuckets, buildSystemPrompt } = require('./deps.js');
24
+ const { createTools, createClient, usageTokens, usageBuckets, buildSystemPrompt, autoProvisionApiKey } = require('./deps.js');
25
25
  const { createEngine, HOST_CLASSES, DEFAULT_CLASS, byokNamespace } = require('./engine.js');
26
26
  const { GLYPH, VERBS, themeOf, RESET, THEME_TABLE } = require('./theme.js');
27
27
  const { LiveRegion, termWidth, w } = require('./screen.js');
@@ -112,9 +112,37 @@ function createApp(options = {}) {
112
112
  // survive a new shell, and until it is *stored* every one of those launches
113
113
  // is "no key" with no in-band way to set one. An injected client keeps
114
114
  // whatever key it was built with.
115
- const client = options.client || createClient(credentials.clientOptions());
115
+ const client = options.client || createClient(credentials.clientOptions({ channel: 'cli' }));
116
116
  const { TOOLS, toolList } = options.tools || createTools(client);
117
117
 
118
+ // With no key configured anywhere, ask aegis1 for a free device key before
119
+ // ever showing "no key" — same shared helper (client/auto-provision.js) the
120
+ // MCP plugin and the desktop app use, so all three ask for the same account
121
+ // on the same machine. One attempt per `createApp()` instance, not one per
122
+ // call: register-device is rate-limited server-side, and a session that
123
+ // fires several turns before noticing a failure must not retry the same
124
+ // failing call each time. The provisioned account starts at zero
125
+ // token-bank balance and still needs an upgraded plan for pooled
126
+ // aegiscloud models (aegis1's is_pro() gate) — this only unblocks BYOK and
127
+ // account status/settings, never silently free inference.
128
+ let provisionAttempted = false;
129
+ async function ensureApiKey() {
130
+ if (client.apiKey || provisionAttempted) return;
131
+ provisionAttempted = true;
132
+ const result = await autoProvisionApiKey(client, credentials);
133
+ if (result.key) {
134
+ emit(
135
+ render.renderNotice(
136
+ ctx(),
137
+ 'info',
138
+ `no AEGIS key was configured — auto-provisioned a free account` +
139
+ (result.ok ? ` (saved to ${credentials.credentialsPath()})` : ' (could not save it — reconfigure with /key)') +
140
+ `. Fund it at ${client.promptUrl('topup', 'device_autoprovision')} or run /byok to use your own key.`
141
+ )
142
+ );
143
+ }
144
+ }
145
+
118
146
  // Tool-approval gate (exec/writeFile/editFile confirm before running).
119
147
  // Read per call, so /permissions and /yolo take effect on the very next tool
120
148
  // round rather than needing a restart. The mode is read LIVE from the
@@ -875,6 +903,7 @@ function createApp(options = {}) {
875
903
  emit(render.renderNotice(ctx(), 'warn', 'nothing to ask — give /ask a prompt'));
876
904
  return;
877
905
  }
906
+ if (!client.apiKey) await ensureApiKey();
878
907
  if (!client.apiKey) {
879
908
  emit(
880
909
  render.renderNotice(
@@ -950,6 +979,7 @@ function createApp(options = {}) {
950
979
  async function runTool(name, args) {
951
980
  const tool = TOOLS[name];
952
981
  if (!tool) throw new Error(`unknown tool: ${name}`);
982
+ if (!client.apiKey) await ensureApiKey();
953
983
  if (!client.apiKey) {
954
984
  throw new Error(`no AEGIS account key — ${credentials.HOW_TO_SET}`);
955
985
  }
@@ -1775,6 +1805,10 @@ function createApp(options = {}) {
1775
1805
  if (tty) {
1776
1806
  restorePrefs();
1777
1807
  adoptLegacyKeyOnce();
1808
+ // Give aegis1 a chance to auto-provision a free device key BEFORE
1809
+ // deciding whether onboarding needs to ask for one — a fresh install
1810
+ // should never be prompted for a key it can get on its own.
1811
+ if (!client.apiKey) await ensureApiKey();
1778
1812
  // Onboarding runs in the normal buffer, before the session takes the
1779
1813
  // alternate screen — the reference's order. A declined trust check must
1780
1814
  // abort: the reference returns without ever reaching `session(ctx)`.
package/src/autonomous.js CHANGED
@@ -136,12 +136,26 @@ function printRunReport(ran, io) {
136
136
  */
137
137
  function buildEngine({ io, quiet = false }) {
138
138
  const credentials = require('./credentials.js');
139
- const client = require('./deps.js').createClient(credentials.clientOptions());
139
+ const client = require('./deps.js').createClient(credentials.clientOptions({ channel: 'cli' }));
140
140
  if (!client.apiKey) {
141
- return { error: `no AEGIS account key — ${credentials.HOW_TO_SET}, or set $${credentials.KEY_ENV}` };
141
+ return { error: `no AEGIS account key — ${credentials.HOW_TO_SET}, or set ${credentials.KEY_ENV}` };
142
142
  }
143
143
  const engine = createEngine({ client, getConfirmMode: () => false });
144
- return { client, engine };
144
+ // The Pro gate (Phase 7). Built from the SAME shared decision the desktop
145
+ // uses, bound to this host's channel so a refusal links `?s=cli` and not
146
+ // `?s=desktop` — see cli/src/entitlement.js. Passed to the worker below as
147
+ // `canFanOut`, which is the seam the shared worker already had and this host
148
+ // never supplied (so it defaulted to "yes" and the fan-out was free here).
149
+ let entitlement = null;
150
+ try {
151
+ entitlement = require('./entitlement.js').createCliEntitlement({ aegis: client });
152
+ } catch {
153
+ // A gate that cannot be built must not be a gate that says yes. The worker
154
+ // fails closed on a missing predicate (`safeCanFanOut`), so leaving this
155
+ // null clamps the drain to single passes rather than spending the fan-out.
156
+ entitlement = null;
157
+ }
158
+ return { client, engine, entitlement };
145
159
  }
146
160
 
147
161
  /** A progress sink for a headless drain: one line per step, never a chat delta. */
@@ -169,6 +183,14 @@ function progressSink(io, { json }) {
169
183
  io.stdout.write(`aegiscode: PLAN.md status list healed for phase(s) ${event.phases.join(', ')}\n`);
170
184
  return;
171
185
  }
186
+ // `note` is how the shared worker reports the fan-out clamp ("this task ran
187
+ // as a single pass"). It was emitted and then dropped on the floor here,
188
+ // which made the gate invisible from the terminal: a drain that silently
189
+ // ran one worker looked identical to one that was entitled to eight.
190
+ if (event.type === 'note' && event.note) {
191
+ io.stderr.write(` ⓘ ${event.note}\n`);
192
+ return;
193
+ }
172
194
  if (event.type === 'recovered') {
173
195
  io.stdout.write(`aegiscode: re-queued task(s) ${event.ids.join(', ')} from a dead worker\n`);
174
196
  }
@@ -277,11 +299,79 @@ async function runQueueCommand(command, argv, io = {}) {
277
299
  stderr.write(`aegiscode autonomous: ${built.error}\n`);
278
300
  return 2;
279
301
  }
302
+ // Read the gate BEFORE the first task, not lazily per task. A snapshot that
303
+ // was never refreshed reads as `unresolved`, which `current()` reports as
304
+ // free — so a PRO account would have its fan-out quietly clamped to a single
305
+ // pass for the whole drain. That is the gate failing in the direction that
306
+ // takes the paid feature away from the paying customer, so one awaited read
307
+ // happens up front and the rest of the drain answers from the cached
308
+ // snapshot (TTL a minute — see DEFAULT_TTL_MS; a drain must not probe per
309
+ // task).
310
+ if (built.entitlement) {
311
+ try {
312
+ await built.entitlement.refresh();
313
+ } catch {
314
+ // Unreachable leaves the snapshot unresolved, i.e. free. Fail-closed is
315
+ // the right direction: the alternative lets a network blip hand out the
316
+ // paid fan-out.
317
+ }
318
+ }
280
319
  const worker = autonomous.createQueueWorker({
281
320
  engine: built.engine,
282
321
  env: process.env,
283
322
  log: progressSink(out, { json }),
323
+ // THE SEAM THIS HOST NEVER SUPPLIED. `createQueueWorker` defaults this to
324
+ // `() => true`, so until now a fan-out asked for in the terminal — or
325
+ // written into queue.jsonl by hand, or left there by another host's older
326
+ // build — spent the multiplier the gate exists to withhold, with no window
327
+ // and nobody to ask. The shared worker already clamps it (`safeCanFanOut`),
328
+ // and a throwing predicate already fails closed; a gate that could not be
329
+ // BUILT at all must read the same way, hence the explicit null → false.
330
+ canFanOut: () => {
331
+ if (!built.entitlement) return false;
332
+ try {
333
+ const snap = built.entitlement.current();
334
+ return Boolean(snap && snap.entitled === true);
335
+ } catch {
336
+ return false;
337
+ }
338
+ },
284
339
  });
340
+ // One promotion per drain, not one per task: the clamp note fires for every
341
+ // fanned-out task, and repeating a checkout link eight times in a log is
342
+ // spam, not promotion. Printed only for a READ WE ACTUALLY TRUST —
343
+ // `degraded` is the module's flag for "we did not get a real answer"
344
+ // (timeout, unparseable body, missing plan field), and an upsell printed on
345
+ // the strength of a timeout is a guess wearing a price tag. `unresolved` is
346
+ // the same rule one level up: the boot snapshot, which nobody asked.
347
+ if (built.entitlement) {
348
+ try {
349
+ const snap = built.entitlement.current();
350
+ if (snap && snap.entitled === false && snap.degraded === false && snap.refusal) {
351
+ stderr.write(`aegiscode autonomous: ${snap.refusal}\n`);
352
+ // The ask, in the message, as an example to write — not as a feature
353
+ // name to decode. `autonomously` is the word the drain actually reads
354
+ // (queue.js stores the inverse as `singlePass`), so the terminal shows
355
+ // the sentence to type.
356
+ stderr.write(' ↳ write tasks like: Do X autonomously\n');
357
+ // HOW to unlock, and it names BOTH routes because there are two:
358
+ // `entitlement.js` sets `entitled = pro || banked`, where the bank is
359
+ // the operator's own lever (aegis1 admin `add_funds`). Printing only
360
+ // "upgrade" would send a user with an empty bank to the plan page when
361
+ // topping up is the action that clears their wall — `snap.wall` is the
362
+ // module's own word for which wall this is, so the line follows it
363
+ // instead of guessing.
364
+ stderr.write(
365
+ snap.wall === 'balance'
366
+ ? ' ↳ unlock: top up the Token Bank, or upgrade to Pro\n'
367
+ : ' ↳ unlock: Pro, or any Token Bank balance\n'
368
+ );
369
+ if (snap.upgradeUrl) stderr.write(` ${snap.upgradeUrl}\n`);
370
+ }
371
+ } catch {
372
+ // A snapshot that cannot be read prints nothing — same rule as above.
373
+ }
374
+ }
285
375
  const commit = args.flags.commit ? true : undefined;
286
376
  const onSigint = () => {
287
377
  // Ctrl-C stops the RUNNING turn, not the process: the task is settled back
package/src/chatflow.js CHANGED
@@ -41,7 +41,7 @@ const {
41
41
  selectionRange, selectionText, applySelection,
42
42
  } = require('./screen.js');
43
43
  const {
44
- KEY, attachKeyStream, nextKey, nextKeyTimeout, requeueKeys, resetKeyStream,
44
+ KEY, STREAM_END, attachKeyStream, nextKey, nextKeyTimeout, requeueKeys, resetKeyStream,
45
45
  isKeyStreamSuspended,
46
46
  } = require('./events.js');
47
47
  const { GLYPH, VERBS, DONE_VERBS, BOLD, BOLD_OFF, themeOf } = require('./theme.js');
@@ -771,9 +771,12 @@ async function runSession(host) {
771
771
  let suggestionIdx = 0;
772
772
  let scroll = 0;
773
773
  let anchorEnd = null;
774
- // Screen row (1-based, as the mouse reports it) → the transcript row painted
775
- // there. Rebuilt on every frame so it follows scrolling; a click reads it to
776
- // find which edit block to toggle.
774
+ // Grid row (0-based, as the frame indexes `lines`) → the transcript message
775
+ // painted there, tool rows only. Rebuilt on every frame so it follows
776
+ // scrolling; a click reads it to find which edit block to toggle. The wire's
777
+ // 1-based row is converted once, in mouseGesture(), so both sides of this map
778
+ // speak grid rows — keying it by screen row instead (the `1 +` that used to
779
+ // read `2 +`) toggles the row ABOVE the one the reader clicked.
777
780
  const clickHits = new Map();
778
781
  // ── mouse marking (text selection) ────────────────────────────────────────
779
782
  // The terminal's own selection can't see the alternate screen, so a drag is
@@ -825,10 +828,11 @@ async function runSession(host) {
825
828
  const view = transcriptLines(transcript, { cols, rows, scroll, anchorEnd }, ctx, Date.now(), lineCache);
826
829
  scroll = view.scroll;
827
830
  anchorEnd = view.anchorEnd;
828
- // The header is frame line 0 (screen row 1), so the transcript window starts
829
- // at screen row 2; each painted line carries its source row in view.owners.
831
+ // The header is frame line 0 (grid row 0), so the transcript window's first
832
+ // painted line is grid row 1; each painted line carries its source row in
833
+ // view.owners.
830
834
  clickHits.clear();
831
- for (let i = 0; i < view.lines.length; i++) clickHits.set(2 + i, view.owners[i]);
835
+ for (let i = 0; i < view.lines.length; i++) clickHits.set(1 + i, view.owners[i]);
832
836
  for (const l of view.lines) lines.push(l);
833
837
  // Exactly `avail` transcript rows, so the frame is exactly `rows` lines:
834
838
  // header(1) + transcript(avail) + spinner/effort + rule + input + rule +
@@ -1329,13 +1333,14 @@ async function runSession(host) {
1329
1333
  };
1330
1334
 
1331
1335
  /**
1332
- * Toggle the edit block painted on a screen row. Split out of the click
1333
- * branch so the gesture resolver can call it for a press that never swept a
1334
- * cell — the click path and the marking path must agree on what a click is.
1336
+ * Toggle the edit block painted at a grid row (0-based — the same row
1337
+ * mouseGesture() resolves from the wire). Split out of the click branch so
1338
+ * the gesture resolver can call it for a press that never swept a cell — the
1339
+ * click path and the marking path must agree on what a click is.
1335
1340
  * Returns true when a block was toggled.
1336
1341
  */
1337
- const toggleAtRow = (screenRow) => {
1338
- const msg = clickHits.get(screenRow);
1342
+ const toggleAtRow = (row) => {
1343
+ const msg = clickHits.get(row);
1339
1344
  if (msg && msg.diff) {
1340
1345
  msg.diffOpen = !msg.diffOpen;
1341
1346
  return true;
@@ -1360,9 +1365,12 @@ async function runSession(host) {
1360
1365
  // collapse the moment the reader tried to select its contents.
1361
1366
  //
1362
1367
  // Coordinates arrive 1-based on the wire and grid rows are 0-based, hence the
1363
- // -1 on both axes. Selection is read from `frameLines` (the last painted
1364
- // grid), NOT the transcript, so the copied cells are the ones the reader
1365
- // pointed at.
1368
+ // -1 on both axes. `cell.row` is also the key toggleAtRow() looks up in
1369
+ // clickHits, which buildFrame() fills from the same 0-based frame, so the two
1370
+ // conversions have to agree: a map built one row off toggles the row above the
1371
+ // one the reader clicked, with everything else still looking right.
1372
+ // Selection is read from `frameLines` (the last painted grid), NOT the
1373
+ // transcript, so the copied cells are the ones the reader pointed at.
1366
1374
  const mouseGesture = (key) => {
1367
1375
  const cell = { col: key.col - 1, row: key.row - 1 };
1368
1376
  if (key.name === 'click') { pendingClick = cell; return false; }
@@ -2015,6 +2023,12 @@ async function runSession(host) {
2015
2023
  while (!ended) {
2016
2024
  const key = await nextKey();
2017
2025
  if (ended) break;
2026
+ // The pump was reset underneath us (another session tore down, or a
2027
+ // child-process handover): stop looping rather than spinning on a
2028
+ // stream that no longer exists. Without this a session parked on
2029
+ // nextKey() at reset time never wakes, and the loop outlives its
2030
+ // terminal — repainting into whatever stdout it captured.
2031
+ if (key === STREAM_END) break;
2018
2032
  try {
2019
2033
  await handleKey(key);
2020
2034
  } catch (err) {
package/src/checkpoint.js CHANGED
@@ -13,6 +13,7 @@
13
13
  const fs = require('node:fs');
14
14
  const path = require('node:path');
15
15
  const { aegisDir } = require('./config.js');
16
+ const { ensurePrivateDir, writePrivateFile } = require('./securefs.js');
16
17
 
17
18
  const CHECKPOINT_LIMIT = 8;
18
19
 
@@ -26,7 +27,7 @@ function checkpointsPath(sessionId) {
26
27
  */
27
28
  function snapshotCheckpoint(sessionId, transcript) {
28
29
  try {
29
- fs.mkdirSync(path.dirname(checkpointsPath(sessionId)), { recursive: true });
30
+ ensurePrivateDir(path.dirname(checkpointsPath(sessionId)));
30
31
  const entry = {
31
32
  ts: new Date().toISOString(),
32
33
  depth: transcript.length,
@@ -37,7 +38,8 @@ function snapshotCheckpoint(sessionId, transcript) {
37
38
  const prev = fs.existsSync(p) ? fs.readFileSync(p, 'utf8').split('\n').filter(Boolean) : [];
38
39
  const lines = [...prev, JSON.stringify(entry)];
39
40
  const trimmed = lines.slice(Math.max(0, lines.length - CHECKPOINT_LIMIT));
40
- fs.writeFileSync(p, trimmed.join('\n') + '\n');
41
+ // 0600: a checkpoint is the full transcript at a point in time.
42
+ writePrivateFile(p, trimmed.join('\n') + '\n');
41
43
  return lines.length - 1; // index into the trimmed list
42
44
  } catch {
43
45
  return -1;
package/src/clipboard.js CHANGED
@@ -7,6 +7,10 @@
7
7
  * clipboard availability. Set AEGISCODE_NO_CLIPBOARD=1 to force the file
8
8
  * fallback (used by tests and headless setups).
9
9
  *
10
+ * The tools are resolved with `resolveTrustedTool` rather than by name, and the
11
+ * fallback file is written 0600 with O_NOFOLLOW — see those functions for what
12
+ * each defends against. Set AEGISCODE_TRUST_PATH=0 to opt out of the PATH check.
13
+ *
10
14
  * Ported from the upstream engine reference (ESM → CommonJS). The data dir
11
15
  * comes from the shared `aegisDir()` helper and the force-fallback env var was
12
16
  * renamed AEGISCODEX_NO_CLIPBOARD → AEGISCODE_NO_CLIPBOARD.
@@ -16,6 +20,7 @@ const { spawnSync } = require('node:child_process');
16
20
  const fs = require('node:fs');
17
21
  const path = require('node:path');
18
22
  const { aegisDir } = require('./config.js');
23
+ const { writePrivateFile } = require('./securefs.js');
19
24
 
20
25
  const TOOLS = [
21
26
  { name: 'pbcopy', cmd: 'pbcopy', args: [], test: () => process.platform === 'darwin' },
@@ -25,13 +30,76 @@ const TOOLS = [
25
30
  { name: 'clip', cmd: 'clip', args: [], test: () => process.platform === 'win32' },
26
31
  ];
27
32
 
28
- function toolAvailable(cmd) {
29
- // `sh` doesn't exist on Windows — use `where` there, `command -v` on POSIX.
30
- const isWin = process.platform === 'win32';
31
- const r = isWin
32
- ? spawnSync('where', [cmd], { encoding: 'utf8', timeout: 3000, windowsHide: true })
33
- : spawnSync('sh', ['-c', `command -v ${cmd}`], { encoding: 'utf8', timeout: 3000 });
34
- return !r.error && r.status === 0;
33
+ /**
34
+ * Is `dir` a directory a second local account could write into?
35
+ *
36
+ * This is the whole check behind the PATH hardening below. A clipboard tool is
37
+ * handed the complete text of whatever the user copied — which in this CLI is
38
+ * usually model output, sometimes containing code, paths, or a secret the user
39
+ * was about to paste into a browser. `spawnSync('wl-copy', …)` resolves that
40
+ * name against `$PATH`, so whoever owns an earlier PATH entry than the real
41
+ * binary owns every byte the user copies: drop a `wl-copy` in a group-writable
42
+ * `~/.local/bin`, or rely on `/tmp` or `.` being in PATH, and the text arrives
43
+ * at the attacker instead of the clipboard.
44
+ *
45
+ * A directory is trusted only when it is not group- or world-writable AND is
46
+ * owned by root or by us. `/tmp` fails on the first test; `~/bin` that the user
47
+ * owns and left at 0755 passes.
48
+ */
49
+ function dirIsTrusted(dir) {
50
+ try {
51
+ const st = fs.statSync(dir);
52
+ if (!st.isDirectory()) return false;
53
+ if (st.mode & 0o022) return false;
54
+ if (typeof process.getuid === 'function' && st.uid !== 0 && st.uid !== process.getuid()) return false;
55
+ return true;
56
+ } catch {
57
+ return false;
58
+ }
59
+ }
60
+
61
+ /**
62
+ * Resolve `cmd` to an absolute path we are willing to execute, or null.
63
+ *
64
+ * Replaces the old `sh -c 'command -v <cmd>'` availability probe: that check
65
+ * answered "is this name on PATH?" when the question that matters is "is the
66
+ * binary PATH would pick one I trust?". Answering the second subsumes the
67
+ * first, and does it without a shell in the loop.
68
+ *
69
+ * Every candidate must survive: a PATH entry that is absolute, trusted, and not
70
+ * the empty string or `.` (both of which mean the current directory); a real
71
+ * file that is executable, not group/world-writable, and owned by root or us;
72
+ * and a realpath whose own directory is trusted too, so a link in a good
73
+ * directory cannot redirect execution into a bad one.
74
+ */
75
+ function resolveTrustedTool(cmd) {
76
+ const entries = String(process.env.PATH || '').split(path.delimiter);
77
+ for (const raw of entries) {
78
+ const dir = String(raw).trim();
79
+ if (!dir || !path.isAbsolute(dir)) continue; // '' and '.' mean "the cwd"
80
+ if (!dirIsTrusted(dir)) continue;
81
+
82
+ const full = path.join(dir, cmd);
83
+ let real;
84
+ try {
85
+ real = fs.realpathSync(full); // throws on ENOENT and on a symlink loop
86
+ } catch {
87
+ continue;
88
+ }
89
+ let st;
90
+ try {
91
+ st = fs.statSync(real);
92
+ } catch {
93
+ continue;
94
+ }
95
+ if (!st.isFile()) continue;
96
+ if (!(st.mode & 0o111)) continue; // not executable
97
+ if (st.mode & 0o022) continue; // group/world-writable binary
98
+ if (typeof process.getuid === 'function' && st.uid !== 0 && st.uid !== process.getuid()) continue;
99
+ if (!dirIsTrusted(path.dirname(real))) continue; // the realpath may leave `dir`
100
+ return real;
101
+ }
102
+ return null;
35
103
  }
36
104
 
37
105
  /**
@@ -40,23 +108,31 @@ function toolAvailable(cmd) {
40
108
  */
41
109
  function copyToClipboard(text) {
42
110
  const forced = process.env.AEGISCODE_NO_CLIPBOARD === '1';
111
+ // AEGISCODE_TRUST_PATH=0 restores the old "whatever PATH resolves" behaviour
112
+ // for a user whose tool legitimately lives in a group-writable prefix (an
113
+ // unusual but real layout). Secure by default; the hatch is documented in the
114
+ // module header rather than being the default.
115
+ const trustPath = process.env.AEGISCODE_TRUST_PATH !== '0';
43
116
  if (!forced) {
44
117
  for (const t of TOOLS) {
45
118
  if (!t.test()) continue;
46
- if (!toolAvailable(t.cmd)) continue;
47
- const r = spawnSync(t.cmd, t.args, { input: String(text), encoding: 'utf8', timeout: 4000 });
119
+ const exe = trustPath ? resolveTrustedTool(t.cmd) : t.cmd;
120
+ if (!exe) continue; // not installed, or installed somewhere untrusted
121
+ const r = spawnSync(exe, t.args, { input: String(text), encoding: 'utf8', timeout: 4000 });
48
122
  if (!r.error && r.status === 0) return { ok: true, via: `tool:${t.name}` };
49
123
  }
50
124
  }
51
- // Fallback: write to the data dir and report the path.
125
+ // Fallback: write to the data dir and report the path. 0600 + O_NOFOLLOW via
126
+ // securefs — this file holds whatever the user last marked, and neither the
127
+ // mode nor a planted symlink may let it double as a way to read or overwrite
128
+ // something else.
52
129
  try {
53
- fs.mkdirSync(aegisDir(), { recursive: true });
54
130
  const p = path.join(aegisDir(), 'clipboard.txt');
55
- fs.writeFileSync(p, String(text), 'utf8');
131
+ writePrivateFile(p, String(text), { atomic: false });
56
132
  return { ok: true, via: 'file', path: p };
57
133
  } catch {
58
134
  return { ok: false, via: 'none' };
59
135
  }
60
136
  }
61
137
 
62
- module.exports = { copyToClipboard };
138
+ module.exports = { copyToClipboard, resolveTrustedTool: resolveTrustedTool };
package/src/commands.js CHANGED
@@ -52,9 +52,10 @@ const panels = require('./panels.js');
52
52
  const overlays = require('./overlays.js');
53
53
  const {
54
54
  updateConfig, loadConfig, loadPermissions, savePermissions, addPermissionRule,
55
- DEFAULT_PERMISSIONS, permissionsPath, configPath,
55
+ DEFAULT_PERMISSIONS, permissionsPath, configPath, aegisDir,
56
56
  memoryPersistState, setMemoryPersist,
57
57
  } = require('./config.js');
58
+ const { auditExposure, repairExposure } = require('./securefs.js');
58
59
  const { copyToClipboard } = require('./clipboard.js');
59
60
  const { snapshotCheckpoint, listCheckpoints, loadCheckpoint } = require('./checkpoint.js');
60
61
  const { signupUrl, goUrl } = require('./signup.js');
@@ -1251,9 +1252,15 @@ const COMMANDS = [
1251
1252
  },
1252
1253
  },
1253
1254
  {
1254
- name: 'doctor', hint: '', category: 'support',
1255
+ name: 'doctor', args: ['action'], hint: '[fix]', category: 'support',
1255
1256
  desc: 'Run diagnostic checks on this environment',
1256
- handler: async (c) => {
1257
+ handler: async (c, args) => {
1258
+ const action = ((args && args.action) || '').toLowerCase();
1259
+ if (action && action !== 'fix') {
1260
+ note(c, 'Usage: /doctor [fix] — "fix" re-tightens the data dir to 0700/0600');
1261
+ c.render();
1262
+ return true;
1263
+ }
1257
1264
  const checks = [];
1258
1265
  const ok = (label, good, detail) => checks.push([good, label, detail]);
1259
1266
  ok('Node', true, process.version);
@@ -1275,6 +1282,43 @@ const COMMANDS = [
1275
1282
  ok('plaintext key', false, `a copy also sits in ${configPath()} (another AEGIS CLI) — /key re-saves it to ${ks.path}`);
1276
1283
  }
1277
1284
  ok('config path', true, configPath());
1285
+ // The store sits at 0775/0664 on any install older than securefs.js —
1286
+ // every file that has not happened to be rewritten since. Report that
1287
+ // always, but repair only when asked: a diagnostic that silently rewrites
1288
+ // the user's directory is a surprise, not a fix.
1289
+ const dataDir = aegisDir();
1290
+ let repaired = null;
1291
+ if (action === 'fix') repaired = repairExposure(dataDir);
1292
+ const audit = auditExposure(dataDir);
1293
+ if (!audit.exists) {
1294
+ ok('data dir', true, `${dataDir} (not created yet)`);
1295
+ } else {
1296
+ const shown = audit.exposed.slice(0, 4).map((e) => `${e.rel} ${e.mode}`).join(', ');
1297
+ ok(
1298
+ 'data dir',
1299
+ audit.exposed.length === 0,
1300
+ audit.exposed.length === 0
1301
+ ? `${dataDir} (${audit.rootMode}, all private)`
1302
+ : `${dataDir} (${audit.rootMode}) — ${audit.exposed.length} path(s) group/world-accessible: ` +
1303
+ `${shown}${audit.exposed.length > 4 ? ', …' : ''} — run /doctor fix`
1304
+ );
1305
+ }
1306
+ if (repaired) {
1307
+ const sample = repaired.fixed
1308
+ .slice(0, 3)
1309
+ .map((f) => `${f.rel} ${f.from}→${f.to}`)
1310
+ .join(', ');
1311
+ ok(
1312
+ 'repair',
1313
+ repaired.remaining.length === 0,
1314
+ repaired.remaining.length === 0
1315
+ ? repaired.fixed.length
1316
+ ? `tightened ${repaired.fixed.length} path(s) — ${sample}${repaired.fixed.length > 3 ? ', …' : ''}`
1317
+ : 'already private, nothing to tighten'
1318
+ : `${repaired.remaining.length} path(s) still exposed — ` +
1319
+ repaired.failed.map((f) => `${f.rel}: ${f.reason}`).join(', ')
1320
+ );
1321
+ }
1278
1322
  const lines = [[span(C.gold + BOLD, 'Doctor'), span(BOLD_OFF, '')], [span(C.gray, '─'.repeat(30))]];
1279
1323
  for (const [good, label, detail] of checks) {
1280
1324
  lines.push([