aegiscode 6.8.6 → 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.6",
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
@@ -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');
@@ -115,6 +115,34 @@ function createApp(options = {}) {
115
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/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([
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)));
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
+ };
@@ -189,11 +189,12 @@ function createClient(opts = {}) {
189
189
  return headers;
190
190
  }
191
191
 
192
- async function apiPost(path, body, headers) {
192
+ async function apiPost(path, body, headers, opts) {
193
193
  const res = await fetch(`${apiBase}${path}`, {
194
194
  method: 'POST',
195
195
  headers: headers || authHeaders(),
196
196
  body: JSON.stringify(body || {}),
197
+ signal: opts && opts.signal,
197
198
  });
198
199
  return parseResponse(res);
199
200
  }
@@ -371,6 +372,19 @@ function createClient(opts = {}) {
371
372
  return apiPost('/api/verify-api-key', { api_key: apiKey });
372
373
  }
373
374
 
375
+ /**
376
+ * Ask aegis1 for a free device key when the caller has none configured yet
377
+ * (`POST /api/v1/auth/register-device`). Idempotent server-side on
378
+ * `fingerprint` — the same fingerprint always returns the same account's
379
+ * key rather than minting a new one. The account starts at zero token-bank
380
+ * balance: this hands out an account, not free inference, so the existing
381
+ * balance=0 gate on `/api/v1/chat/completions` still applies unchanged.
382
+ * Sends no API key of its own — there isn't one yet.
383
+ */
384
+ async function registerDevice(fingerprint, opts) {
385
+ return apiPost('/api/v1/auth/register-device', { fingerprint }, undefined, opts);
386
+ }
387
+
374
388
  /** Build the OpenAI-style messages array from either a full history or the
375
389
  * single-shot { system, prompt } shorthand.
376
390
  *
@@ -994,6 +1008,7 @@ function createClient(opts = {}) {
994
1008
  },
995
1009
  promptUrl,
996
1010
  verifyApiKey,
1011
+ registerDevice,
997
1012
  chatCompletion,
998
1013
  byokChatCompletion,
999
1014
  listModels,
@@ -0,0 +1,52 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Auto-provision a free aegis1 device key when a host finds no key configured
5
+ * anywhere (env, the shared 0600 store, legacy config.json). One
6
+ * implementation shared by every host (MCP plugin, desktop, CLI) — see
7
+ * client/credentials.js's own header for why that matters here: three copies
8
+ * of the same timeout/endpoint/save logic is how they drift.
9
+ *
10
+ * Calls aegis1's `POST /api/v1/auth/register-device` (see client/aegis.js's
11
+ * `registerDevice`), idempotent per machine fingerprint (client/
12
+ * device-fingerprint.js) so a wiped credential store still resolves back to
13
+ * the same account rather than minting a new, unfunded one.
14
+ *
15
+ * The provisioned account starts at ZERO token-bank balance server-side, and
16
+ * aegis1 additionally requires an upgraded (paid, active) plan to use pooled
17
+ * aegiscloud models at all (nexus_chat_completions' is_pro() gate) — this
18
+ * only unblocks BYOK and account status/settings until the account is funded
19
+ * and/or upgraded. It is account creation, not a grant of free inference.
20
+ */
21
+ const { machineFingerprint } = require('./device-fingerprint.js');
22
+
23
+ const DEVICE_REGISTER_TIMEOUT_MS = 8000;
24
+
25
+ /**
26
+ * @param {object} aegisClient A client from client/aegis.js (createClient()).
27
+ * @param {object} credentials client/credentials.js (or a compatible double).
28
+ * @returns {Promise<{ok: boolean, key: string, error?: Error}>}
29
+ * `ok` is true only when a usable key was obtained AND persisted to the
30
+ * shared store; `aegisClient.setApiKey()` has already been called on
31
+ * success, so the caller's client is immediately usable either way it
32
+ * inspects `ok`.
33
+ */
34
+ async function autoProvisionApiKey(aegisClient, credentials) {
35
+ if (aegisClient.apiKey) return { ok: true, key: aegisClient.apiKey };
36
+ const controller = new AbortController();
37
+ const timer = setTimeout(() => controller.abort(), DEVICE_REGISTER_TIMEOUT_MS);
38
+ try {
39
+ const data = await aegisClient.registerDevice(machineFingerprint(), { signal: controller.signal });
40
+ const key = data && typeof data.api_key === 'string' ? data.api_key.trim() : '';
41
+ if (!key) return { ok: false, key: '' };
42
+ const saved = credentials.saveApiKey(key);
43
+ aegisClient.setApiKey(key);
44
+ return { ok: !!saved.ok, key };
45
+ } catch (err) {
46
+ return { ok: false, key: '', error: err };
47
+ } finally {
48
+ clearTimeout(timer);
49
+ }
50
+ }
51
+
52
+ module.exports = { autoProvisionApiKey, DEVICE_REGISTER_TIMEOUT_MS };
@@ -0,0 +1,63 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * A stable per-machine identifier, used ONLY to ask aegis1 for a free device
5
+ * key (`POST /api/v1/auth/register-device`) when no key is configured yet. It
6
+ * is not a credential itself — the endpoint treats it as an idempotency key,
7
+ * so a wiped `~/.aegiscode` still resolves back to the same aegis1 account
8
+ * (and whatever balance it holds) instead of minting a fresh, unfunded one.
9
+ *
10
+ * Derivation mirrors ae-guix's `getMachineFingerprint()` (main.js) so the two
11
+ * hosts don't invent divergent conventions for the same idea: the OS's own
12
+ * machine identity where one exists, hashed with a purpose-specific prefix so
13
+ * it can never collide with a fingerprint minted for another purpose.
14
+ */
15
+ const crypto = require('node:crypto');
16
+ const os = require('node:os');
17
+
18
+ /** Best-effort OS machine identity. Empty string, never throws, if none is reachable. */
19
+ function readMachineId() {
20
+ try {
21
+ if (process.platform === 'linux') {
22
+ const fs = require('node:fs');
23
+ try {
24
+ return fs.readFileSync('/etc/machine-id', 'utf8').trim();
25
+ } catch {
26
+ return fs.readFileSync('/var/lib/dbus/machine-id', 'utf8').trim();
27
+ }
28
+ }
29
+ if (process.platform === 'darwin') {
30
+ const { execSync } = require('node:child_process');
31
+ const out = execSync('ioreg -rd1 -c IOPlatformExpertDevice', {
32
+ encoding: 'utf8',
33
+ timeout: 3000,
34
+ });
35
+ const m = out.match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/);
36
+ if (m) return m[1];
37
+ }
38
+ if (process.platform === 'win32') {
39
+ const { execSync } = require('node:child_process');
40
+ const out = execSync('reg query HKLM\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid', {
41
+ encoding: 'utf8',
42
+ timeout: 3000,
43
+ });
44
+ const m = out.match(/MachineGuid\s+REG_SZ\s+(\S+)/);
45
+ if (m) return m[1];
46
+ }
47
+ } catch {
48
+ /* no reachable machine id on this host — the caller falls back below */
49
+ }
50
+ return '';
51
+ }
52
+
53
+ /**
54
+ * sha256("aegiscode-plugin-device-v1:" + machine identity), hex.
55
+ *
56
+ * @param {string} [overrideId] - test-only override for the raw machine identity.
57
+ */
58
+ function machineFingerprint(overrideId) {
59
+ const id = overrideId || readMachineId() || `${os.hostname()}:${os.platform()}:${os.arch()}`;
60
+ return crypto.createHash('sha256').update(`aegiscode-plugin-device-v1:${id}`).digest('hex');
61
+ }
62
+
63
+ module.exports = { machineFingerprint, readMachineId };
@@ -13,6 +13,7 @@
13
13
 
14
14
  const { createClient } = require('../client/aegis.js');
15
15
  const credentials = require('../client/credentials.js');
16
+ const { autoProvisionApiKey } = require('../client/auto-provision.js');
16
17
  const { createTools } = require('./tools.js');
17
18
 
18
19
  // `~/.aegiscode/.env` read into process.env once, before anything resolves a
@@ -46,7 +47,6 @@ const aegis = createClient(credentials.clientOptions());
46
47
  // (cli/) so the two hosts cannot drift apart. This file owns the JSON-RPC
47
48
  // plumbing and nothing else.
48
49
  const { TOOLS, toolList } = createTools(aegis);
49
- const API_KEY = aegis.apiKey;
50
50
  const API_BASE = aegis.apiBase;
51
51
  const SERVER_NAME = 'aegis';
52
52
  // Keep in sync with .claude-plugin/plugin.json "version".
@@ -67,6 +67,36 @@ function missingKeyText() {
67
67
  ].join('\n');
68
68
  }
69
69
 
70
+ // A tool call with no key configured anywhere gets ONE auto-provision attempt
71
+ // per process, not one per call: `register-device` is rate-limited server-side
72
+ // at 5/hour/IP, and a session that fires several tool calls before the user
73
+ // notices the failure message must not burn through that budget on retries
74
+ // that would fail the same way. Success or failure, this only ever runs once.
75
+ // The provisioning itself (endpoint, fingerprint, timeout) is shared with the
76
+ // desktop app and the CLI — see client/auto-provision.js.
77
+ let provisionAttempted = false;
78
+ async function ensureApiKey() {
79
+ if (aegis.apiKey || provisionAttempted) return;
80
+ provisionAttempted = true;
81
+ const result = await autoProvisionApiKey(aegis, credentials);
82
+ if (result.error) {
83
+ process.stderr.write(`aegis: device auto-registration failed (${result.error.message}) — falling back to manual setup.\n`);
84
+ return;
85
+ }
86
+ if (!result.key) {
87
+ process.stderr.write('aegis: device auto-registration returned no usable key — falling back to manual setup.\n');
88
+ return;
89
+ }
90
+ // Starts at zero token-bank balance by design (see registerDevice()'s doc in
91
+ // client/aegis.js) — this grants an account, not free inference, so the
92
+ // very next call still 402s until the account is funded.
93
+ process.stderr.write(
94
+ 'aegis: no API key was configured — auto-provisioned a free AEGIS account' +
95
+ (result.ok ? ` (key saved to ${credentials.keyStatus().path}).\n` : ' (could not save it — see above).\n') +
96
+ `Fund it at ${aegis.promptUrl('topup', 'device_autoprovision')} or set your own BYOK key with aegis_byok_set.\n`
97
+ );
98
+ }
99
+
70
100
  // ---------------------------------------------------------------------------
71
101
  // JSON-RPC / MCP plumbing
72
102
  // ---------------------------------------------------------------------------
@@ -126,7 +156,8 @@ async function handleMessage(msg) {
126
156
  });
127
157
  return;
128
158
  }
129
- if (!API_KEY) {
159
+ if (!aegis.apiKey) await ensureApiKey();
160
+ if (!aegis.apiKey) {
130
161
  reply(id, {
131
162
  content: [{ type: 'text', text: missingKeyText() }],
132
163
  isError: true,