aegiscode 7.0.26 → 7.0.28

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.
Files changed (118) hide show
  1. package/SOURCE-OFFER.txt +9 -0
  2. package/package.json +4 -7
  3. package/scripts/check.mjs +1 -52
  4. package/scripts/demo.mjs +1 -94
  5. package/scripts/predist.mjs +1 -75
  6. package/scripts/runtests.mjs +1 -56
  7. package/scripts/seal-gate.mjs +1 -74
  8. package/src/agents.js +1 -139
  9. package/src/app.js +1 -2957
  10. package/src/art.js +1 -289
  11. package/src/chatflow.js +1 -3023
  12. package/src/checkpoint.js +1 -90
  13. package/src/clipboard.js +1 -424
  14. package/src/cloudsync.js +1 -528
  15. package/src/commands.js +1 -4089
  16. package/src/config.js +1 -581
  17. package/src/connect.js +1 -349
  18. package/src/credentials.js +1 -33
  19. package/src/deps.js +1 -232
  20. package/src/devrun.js +1 -187
  21. package/src/diff.js +1 -333
  22. package/src/diffview.js +1 -296
  23. package/src/engine.js +1 -297
  24. package/src/entitlement.js +1 -355
  25. package/src/events.js +1 -707
  26. package/src/export.js +1 -67
  27. package/src/filepreview.js +1 -153
  28. package/src/fingerprint.js +1 -592
  29. package/src/format.js +1 -259
  30. package/src/fuzzy.js +1 -119
  31. package/src/history.js +1 -423
  32. package/src/init.js +1 -175
  33. package/src/input.js +1 -139
  34. package/src/keys.js +1 -183
  35. package/src/markdown.js +1 -306
  36. package/src/models.js +1 -507
  37. package/src/naming.js +1 -57
  38. package/src/overlays.js +1 -462
  39. package/src/panels.js +1 -1418
  40. package/src/ping.js +1 -226
  41. package/src/presence.js +1 -238
  42. package/src/render.js +1 -516
  43. package/src/screen.js +1 -518
  44. package/src/screens.js +1 -896
  45. package/src/secret.js +1 -59
  46. package/src/securefs.js +1 -359
  47. package/src/settings.js +1 -155
  48. package/src/shared.js +1 -52
  49. package/src/sharedpaths.js +1 -53
  50. package/src/signup.js +1 -156
  51. package/src/summarize.js +1 -95
  52. package/src/sysdiag.js +1 -585
  53. package/src/system.js +1 -40
  54. package/src/theme.js +1 -570
  55. package/src/title.js +1 -220
  56. package/src/todos.js +1 -115
  57. package/src/tokens.js +1 -263
  58. package/src/topup.js +1 -210
  59. package/src/update.js +1 -191
  60. package/vendor/client/aegis.js +1 -2441
  61. package/vendor/client/attest.js +1 -518
  62. package/vendor/client/authorship-key.js +1 -410
  63. package/vendor/client/auto-provision.js +1 -134
  64. package/vendor/client/brain-catalog.js +1 -268
  65. package/vendor/client/byok-catalog.js +1 -199
  66. package/vendor/client/catalog-client.js +1 -487
  67. package/vendor/client/conversation-export.js +1 -177
  68. package/vendor/client/credentials.js +1 -494
  69. package/vendor/client/device-fingerprint.js +1 -141
  70. package/vendor/client/drive-connect.js +1 -110
  71. package/vendor/client/drive-upload.js +1 -234
  72. package/vendor/client/env-file.js +1 -1273
  73. package/vendor/client/fingerprint.js +1 -1064
  74. package/vendor/client/foreign-memory.js +1 -669
  75. package/vendor/client/google-signin.js +1 -133
  76. package/vendor/client/hooks.js +1 -430
  77. package/vendor/client/model-discovery.js +1 -373
  78. package/vendor/client/naming.js +1 -283
  79. package/vendor/client/platform.js +1 -937
  80. package/vendor/client/prefs.js +1 -351
  81. package/vendor/client/presence-constants.js +1 -107
  82. package/vendor/client/presence.js +1 -438
  83. package/vendor/client/record-vault.js +3 -1055
  84. package/vendor/client/session-store.js +1 -575
  85. package/vendor/client/topup.js +1 -297
  86. package/vendor/client/touch.js +1 -458
  87. package/vendor/client/update.js +1 -763
  88. package/vendor/client/user-models.js +1 -381
  89. package/vendor/desktop/lib/local/agents.js +1 -105
  90. package/vendor/desktop/lib/local/attachments.js +1 -276
  91. package/vendor/desktop/lib/local/autonomous.js +1 -1045
  92. package/vendor/desktop/lib/local/claude-pro.js +1 -1028
  93. package/vendor/desktop/lib/local/context.js +1 -125
  94. package/vendor/desktop/lib/local/engine.js +1 -3666
  95. package/vendor/desktop/lib/local/entitlement.js +1 -660
  96. package/vendor/desktop/lib/local/exec-plan.js +1 -269
  97. package/vendor/desktop/lib/local/git-scope.js +1 -228
  98. package/vendor/desktop/lib/local/integrity.js +1 -163
  99. package/vendor/desktop/lib/local/local.js +1 -2145
  100. package/vendor/desktop/lib/local/prompt.js +1 -280
  101. package/vendor/desktop/lib/local/queue.js +1 -560
  102. package/vendor/desktop/lib/local/session-rounds.js +1 -238
  103. package/vendor/desktop/lib/local/shell.js +1 -712
  104. package/vendor/desktop/lib/local/spill.js +1 -75
  105. package/vendor/desktop/lib/local/tools.js +1 -1328
  106. package/vendor/desktop/lib/local/turn-guard.js +1 -300
  107. package/vendor/desktop/lib/local/worktree-lock.js +1 -235
  108. package/vendor/desktop/lib/settings.js +1 -890
  109. package/vendor/desktop/main.js +1 -4890
  110. package/vendor/desktop/renderer/usage.js +1 -1239
  111. package/vendor/hosts/install.js +1 -638
  112. package/vendor/hosts/openai-shim.js +1 -515
  113. package/vendor/hosts/spec.js +1 -164
  114. package/vendor/hosts/targets.js +1 -346
  115. package/vendor/mcp/server.js +1 -221
  116. package/vendor/mcp/tools.js +1 -408
  117. package/vendor/one/src/child.js +1 -285
  118. package/vendor/one/src/permissions.js +1 -383
@@ -1,496 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
- // Conveying a modified copy, or running one as a network service, owes the
5
- // corresponding source under this licence (§5/§13) — see LICENSING.md.
6
- 'use strict';
7
-
8
- /**
9
- * credentials.js — the ONE AEGIS account credential store, shared by every
10
- * host in this repo (terminal `aegiscode`, the MCP plugin, the desktop app).
11
- *
12
- * Why it lives in `client/`: this directory is the only tree every host
13
- * already bundles. The MCP plugin ships `mcp/` + `client/` and nothing else, so
14
- * a reader placed here needs no cross-package dependency — which is what the
15
- * alternative (the MCP host requiring `cli/src/credentials.js`) would have
16
- * forced, and why that host used to read `AEGIS_API_KEY` from the environment
17
- * alone while the CLI could save a key to disk. One login, one file, all
18
- * four hosts: that is the point of this module.
19
- *
20
- * Zero dependencies, no host imports. The data dir is resolved here
21
- * (`aegisHome()`) rather than imported from the CLI's config.js, so this file
22
- * runs from a bare `node client/credentials.js` inside the plugin tree.
23
- *
24
- * Resolution order, first hit wins:
25
- *
26
- * 1. `AEGIS_API_KEY` **exported by the launching shell** — so CI and an
27
- * explicit export keep working.
28
- * 2. `credentials.json` in the data dir, mode 0600. The writable store, and
29
- * the record of a key the user deliberately saved (`aegiscode login`, the
30
- * CLI's `/key`, the desktop's Settings pane).
31
- * 3. `AEGIS_API_KEY` from `~/.aegiscode/.env` — the documented place to put a
32
- * key, but a FALLBACK rather than a decision: no save stamp, shared by
33
- * every host, hand-edited. Both rungs read the same variable, which is why
34
- * `isFromEnvFile()` exists — without it a leftover line in that file
35
- * outranked rung 2 forever and a freshly saved key was silently ignored
36
- * while every host reported it as saved. See `resolveApiKey`.
37
- * 4. `config.json`'s `aegiscloud.api_key` / `memory.token` — the shape an
38
- * earlier AEGIS CLI left in the same data dir. Read, never written, and
39
- * never deleted: it is another product's file and the user's key is in
40
- * it. When one is found it is *also* copied into credentials.json so the
41
- * next run reads the 0600 copy, and the status line says the plaintext
42
- * copy is still there rather than silently leaving it.
43
- *
44
- * The key is never printed in full by anything in this repo; callers mask it.
45
- */
46
-
47
- const fs = require('node:fs');
48
- const os = require('node:os');
49
- const path = require('node:path');
50
-
51
- const KEY_ENV = 'AEGIS_API_KEY';
52
- /** Optional override for the memory token (cloud sync's own credential). */
53
- const MEMORY_ENV = 'AEGIS_MEMORY_TOKEN';
54
- const HOME_ENV = 'AEGISCODE_HOME';
55
- const CREDENTIALS_FILE = 'credentials.json';
56
- const CONFIG_FILE = 'config.json';
57
- const FILE_MODE = 0o600;
58
- const DIR_MODE = 0o700;
59
-
60
- /**
61
- * The per-user AEGIS data directory: `$AEGISCODE_HOME` or `~/.aegiscode`.
62
- *
63
- * Every host resolves its data dir through this one function, so the CLI, the
64
- * MCP plugin and the desktop app agree on where memory and credentials live
65
- * instead of each keeping a private store the others cannot see. (The desktop
66
- * still keeps its *settings* — the safeStorage-encrypted key, window state —
67
- * in Electron's userData; only the shared memory + credential files live here.)
68
- */
69
- function aegisHome(env) {
70
- const e = env || process.env;
71
- const override = e && e[HOME_ENV];
72
- if (override && String(override).trim()) return path.resolve(String(override).trim());
73
- return path.join(os.homedir(), '.aegiscode');
74
- }
75
-
76
- function credentialsPath(dir) {
77
- return path.join(dir || aegisHome(), CREDENTIALS_FILE);
78
- }
79
-
80
- function configPath(dir) {
81
- return path.join(dir || aegisHome(), CONFIG_FILE);
82
- }
83
-
84
- /**
85
- * Accept the key in the shapes a user actually pastes it.
86
- *
87
- * Copy-paste from a dashboard, a `.env` line, a shell profile or a chat message
88
- * are all realistic — and pasting `AEGIS_API_KEY=aegis_…` or `"aegis_…"` into a
89
- * prompt that stores the literal string produces an auth failure the user
90
- * cannot see the cause of, because the key *looks* right in the status line.
91
- */
92
- function normalizeApiKey(raw) {
93
- let s = String(raw == null ? '' : raw).trim();
94
- if (!s) return '';
95
- s = s.replace(/^export\s+/i, '').trim();
96
- const assignment = /^[A-Za-z_][A-Za-z0-9_]*\s*=\s*(.+)$/s.exec(s);
97
- if (assignment) s = assignment[1].trim();
98
- s = s.replace(/^["']|["']$/g, '').trim();
99
- s = s.replace(/^Bearer\s+/i, '').trim();
100
- return s;
101
- }
102
-
103
- /**
104
- * Shape check only — no network. Catches the two mistakes that are structural
105
- * (an empty paste, and a wrapped/truncated multi-line paste) so the caller can
106
- * refuse before spending a verification round trip.
107
- *
108
- * `o.label` names the credential in the "too short" message ("AEGIS keys",
109
- * "Anthropic keys", …) — every caller sees the same 16-char floor, worded for
110
- * whichever secret it is collecting. Defaults to 'AEGIS' so the one call site
111
- * this shipped with (the account-key login flow) reads exactly as before.
112
- */
113
- function validateApiKey(raw, o = {}) {
114
- const label = String(o.label || 'AEGIS');
115
- const key = normalizeApiKey(raw);
116
- if (!key) return { ok: false, key, reason: 'empty', message: 'no key given' };
117
- if (/\s/.test(key)) {
118
- return {
119
- ok: false,
120
- key,
121
- reason: 'whitespace',
122
- message: 'that looks like more than one word — paste just the key',
123
- };
124
- }
125
- if (key.length < 16) {
126
- return {
127
- ok: false,
128
- key,
129
- reason: 'too short',
130
- message: `that key is ${key.length} characters — ${label} keys are longer than that`,
131
- };
132
- }
133
- return { ok: true, key, reason: null, message: null };
134
- }
135
-
136
- /** The stored credential object, or {} — never throws on a missing/corrupt file. */
137
- function readCredentials(dir) {
138
- try {
139
- const parsed = JSON.parse(fs.readFileSync(credentialsPath(dir), 'utf8'));
140
- if (parsed && typeof parsed === 'object') return parsed;
141
- } catch {}
142
- return {};
143
- }
144
-
145
- /**
146
- * Merge a patch into the store, creating it 0600 (and tightening an existing
147
- * file that is wider — a key file that a previous run left 0644 is exactly the
148
- * leak this file exists to avoid).
149
- */
150
- function writeCredentials(patch, dir) {
151
- const target = credentialsPath(dir);
152
- const next = { ...readCredentials(dir), ...patch, version: 1 };
153
- try {
154
- fs.mkdirSync(path.dirname(target), { recursive: true, mode: DIR_MODE });
155
- const tmp = target + '.tmp';
156
- fs.writeFileSync(tmp, JSON.stringify(next, null, 2) + '\n', { mode: FILE_MODE });
157
- fs.renameSync(tmp, target);
158
- try {
159
- fs.chmodSync(target, FILE_MODE);
160
- } catch {}
161
- } catch (e) {
162
- if (process.env.AEGIS_HIST_DEBUG) console.error('[credentials] write failed:', e);
163
- return { ok: false, error: e, credentials: next };
164
- }
165
- return { ok: true, credentials: next };
166
- }
167
-
168
- /**
169
- * The key an earlier AEGIS CLI wrote into config.json (the `aegiscloud` /
170
- * `memory` blocks are not ours). Read-only.
171
- */
172
- function readLegacyConfig(dir) {
173
- try {
174
- const parsed = JSON.parse(fs.readFileSync(configPath(dir), 'utf8'));
175
- if (!parsed || typeof parsed !== 'object') return {};
176
- const cloud = parsed.aegiscloud && typeof parsed.aegiscloud === 'object' ? parsed.aegiscloud : {};
177
- const memory = parsed.memory && typeof parsed.memory === 'object' ? parsed.memory : {};
178
- return {
179
- apiKey: normalizeApiKey(cloud.api_key),
180
- memoryToken: String(memory.token || '').trim(),
181
- syncConversations: cloud.syncConversations === true ? true : undefined,
182
- lastVerified: cloud.lastVerified || null,
183
- memorySubscribed: memory.subscribed === true ? true : undefined,
184
- };
185
- } catch {
186
- return {};
187
- }
188
- }
189
-
190
- /** True when config.json still carries a plaintext copy of the account key. */
191
- function legacyKeyOnDisk(dir) {
192
- return !!readLegacyConfig(dir).apiKey;
193
- }
194
-
195
- /**
196
- * Copy a legacy key/token into the 0600 store, once, without touching the file
197
- * it came from. Returns which fields were adopted so the caller can say so.
198
- */
199
- function adoptLegacy(dir) {
200
- const legacy = readLegacyConfig(dir);
201
- const creds = readCredentials(dir);
202
- const patch = {};
203
- if (legacy.apiKey && !creds.aegisApiKey) patch.aegisApiKey = legacy.apiKey;
204
- if (legacy.memoryToken && !creds.memoryToken) patch.memoryToken = legacy.memoryToken;
205
- if (!Object.keys(patch).length) return { adopted: [] };
206
- const written = writeCredentials({ ...patch, adoptedFrom: configPath(dir) }, dir);
207
- if (!written.ok) return { adopted: [] };
208
- return { adopted: Object.keys(patch) };
209
- }
210
-
211
- /**
212
- * Was this environment value put there by `~/.aegiscode/.env`, rather than
213
- * exported by the launching shell?
214
- *
215
- * The env object is passed through: provenance is a property of the object the
216
- * value was loaded INTO, so a caller resolving from an injected `{ env }` (every
217
- * test, and any host that scopes its environment) must be answered about that
218
- * object rather than about `process.env`.
219
- *
220
- * Loaded lazily and defensively: this module is deliberately dependency-free
221
- * (it is copied into hosts that bundle no other file), so an absent env-file
222
- * module simply means "nothing is file-sourced" — which is the pre-existing
223
- * behaviour, not a failure.
224
- */
225
- function fromEnvFile(name, value, env) {
226
- try {
227
- const envFile = require('./env-file.js');
228
- return (
229
- typeof envFile.isFromEnvFile === 'function' &&
230
- envFile.isFromEnvFile(name, value, env ? { env } : undefined)
231
- );
232
- } catch {
233
- return false;
234
- }
235
- }
236
-
237
- /**
238
- * The key to use, and where it came from.
239
- *
240
- * Order, and the one asymmetry that matters:
241
- *
242
- * 1. `AEGIS_API_KEY` **exported by the launching shell** — unchanged, and
243
- * still first, so CI and an explicit `AEGIS_API_KEY=… aegiscode` keep
244
- * working.
245
- * 2. `credentials.json` — a key the user explicitly saved with
246
- * `aegiscode login`, the CLI's `/key`, or the desktop's Settings pane.
247
- * 3. `AEGIS_API_KEY` **from `~/.aegiscode/.env`** — the documented place to
248
- * put a key, but a fallback rather than a decision: it carries no save
249
- * stamp and the file is shared by every host and hand-edited by users.
250
- * 4. `config.json`'s legacy `aegiscloud.api_key`.
251
- *
252
- * Rungs 1 and 3 are the same variable, which is exactly the bug this ordering
253
- * fixes. `env-file.js` copies the file into `process.env` at host start-up, so a
254
- * leftover line — a rotated key that was never cleaned up, a value from an
255
- * older install, a provider row mirrored into the wrong name — became
256
- * indistinguishable from a deliberate export and permanently outranked the file
257
- * the user had just written. The symptom is the one that gets reported as
258
- * "it says the key is saved but it is not using it": `aegiscode login` prints
259
- * `key saved`, the desktop prints `saved (aegis_••••1234)`, `key status` reads
260
- * back the new key — and every request authenticates with the stale one, so the
261
- * account check 401s and nothing names the cause. `env-file.js`'s own contract
262
- * is that the file is "a convenience for the common case, not a way for a stale
263
- * file to shadow an explicit" setting; `isFromEnvFile()` is what makes that
264
- * true for a save as well as for an export.
265
- *
266
- * @returns {{key:string, source:'env'|'credentials'|'envfile'|'config'|'none', from:string}}
267
- */
268
- function resolveApiKey(o = {}) {
269
- const env = o.env || process.env;
270
- const dir = o.dir;
271
- const fromEnv = normalizeApiKey(env && env[KEY_ENV]);
272
- // An explicit export wins outright. A value the env FILE supplied does not:
273
- // it is held back to rung 3 so an explicit save outranks it.
274
- if (fromEnv && !fromEnvFile(KEY_ENV, env && env[KEY_ENV], env)) {
275
- return { key: fromEnv, source: 'env', from: KEY_ENV };
276
- }
277
-
278
- const creds = readCredentials(dir);
279
- const stored = normalizeApiKey(creds.aegisApiKey);
280
- if (stored) return { key: stored, source: 'credentials', from: credentialsPath(dir) };
281
-
282
- if (fromEnv) return { key: fromEnv, source: 'envfile', from: envFileLabel(env, dir) };
283
-
284
- const legacy = readLegacyConfig(dir).apiKey;
285
- if (legacy) return { key: legacy, source: 'config', from: configPath(dir) };
286
-
287
- return { key: '', source: 'none', from: '' };
288
- }
289
-
290
- /** Whether any credential is available (env, store or legacy config). */
291
- function hasApiKey(o = {}) {
292
- return !!resolveApiKey(o).key;
293
- }
294
-
295
- /**
296
- * Persist a key.
297
- *
298
- * @returns {{ok:boolean, key:string, path:string, error?:Error, message?:string}}
299
- */
300
- function saveApiKey(raw, dir) {
301
- const v = validateApiKey(raw);
302
- if (!v.ok) return { ok: false, key: v.key, path: credentialsPath(dir), message: v.message };
303
- const written = writeCredentials({ aegisApiKey: v.key, savedAt: new Date().toISOString() }, dir);
304
- if (!written.ok) {
305
- return {
306
- ok: false,
307
- key: v.key,
308
- path: credentialsPath(dir),
309
- error: written.error,
310
- message: `could not write ${credentialsPath(dir)}`,
311
- };
312
- }
313
- return { ok: true, key: v.key, path: credentialsPath(dir) };
314
- }
315
-
316
- /**
317
- * Remove the stored key (and nothing else — the memory token stays, since a
318
- * key rotation should not silently unsubscribe cloud memory). config.json is
319
- * never touched: another product writes it.
320
- */
321
- function clearApiKey(dir) {
322
- const had = !!normalizeApiKey(readCredentials(dir).aegisApiKey);
323
- const written = writeCredentials({ aegisApiKey: '', adoptedFrom: '' }, dir);
324
- return { cleared: had, ok: written.ok, path: credentialsPath(dir) };
325
- }
326
-
327
- /** The memory token cloud sync authenticates with, from store or legacy. */
328
- function resolveMemoryToken(o = {}) {
329
- const env = o.env || process.env;
330
- const dir = o.dir;
331
- const fromEnv = String((env && env[MEMORY_ENV]) || '').trim();
332
- if (fromEnv) return { token: fromEnv, source: 'env' };
333
- const creds = readCredentials(dir);
334
- const stored = String(creds.memoryToken || '').trim();
335
- if (stored) return { token: stored, source: 'credentials' };
336
- const legacy = readLegacyConfig(dir).memoryToken;
337
- if (legacy) return { token: legacy, source: 'config' };
338
- return { token: '', source: 'none' };
339
- }
340
-
341
- function saveMemoryToken(token, extra = {}, dir) {
342
- return writeCredentials({ memoryToken: String(token || '').trim(), ...extra }, dir);
343
- }
344
-
345
- function clearMemoryToken(dir) {
346
- return writeCredentials({ memoryToken: '', memorySubscribed: false }, dir);
347
- }
348
-
349
- /**
350
- * Everything a status screen or a `doctor` line needs about the credential,
351
- * without ever exposing the key itself.
352
- */
353
- function keyStatus(o = {}) {
354
- const dir = o.dir;
355
- const { key, source, from } = resolveApiKey(o);
356
- const creds = readCredentials(dir);
357
- let mode = null;
358
- try {
359
- mode = fs.statSync(credentialsPath(dir)).mode & 0o777;
360
- } catch {}
361
- return {
362
- configured: !!key,
363
- key,
364
- source,
365
- from,
366
- path: credentialsPath(dir),
367
- fileMode: mode == null ? null : '0' + mode.toString(8),
368
- stored: !!normalizeApiKey(creds.aegisApiKey),
369
- legacyPlaintext: legacyKeyOnDisk(dir),
370
- verifiedAt: creds.verifiedAt || null,
371
- account: creds.account || null,
372
- memoryToken: !!resolveMemoryToken(o).token,
373
- memorySource: resolveMemoryToken(o).source,
374
- };
375
- }
376
-
377
- /**
378
- * Client options for `createClient`: the resolved key plus the stored memory
379
- * token, so a restart does not re-exchange for a token it already has.
380
- */
381
- function clientOptions(o = {}) {
382
- const { key } = resolveApiKey(o);
383
- const { token } = resolveMemoryToken(o);
384
- const opts = {};
385
- // Set explicitly, even when empty: `createClient` only re-checks its own
386
- // (real, ambient) process.env when `apiKey`/`memoryToken` are `undefined`.
387
- // Omitting an empty result here was indistinguishable from "not resolved
388
- // yet" and let that fallback see the real environment's key even when an
389
- // injected `o.env`/`o.dir` (tests, a hosted agent, a `--base` against a
390
- // staging account — the reason this function takes them at all) had
391
- // already and correctly resolved to "no key".
392
- opts.apiKey = key;
393
- opts.memoryToken = token;
394
- // The host names itself so upgrade prompts raised inside the shared client
395
- // are attributed to the right product. Unset means desktop, which matches
396
- // createClient's own default.
397
- if (o.channel) opts.channel = o.channel;
398
- return opts;
399
- }
400
-
401
- /** Human label for a resolution source, for status lines. */
402
- const SOURCE_LABEL = {
403
- env: `${KEY_ENV}`,
404
- credentials: 'saved key file',
405
- envfile: `~/.aegiscode/.env (${KEY_ENV})`,
406
- config: 'config.json (aegis CLI)',
407
- none: 'not set',
408
- };
409
-
410
- /**
411
- * The env file a value came from, for the `envfile` status line. Resolved
412
- * through env-file.js when it is present so the answer is the real path
413
- * (`$AEGISCODE_HOME/.env` included) rather than a guess.
414
- */
415
- function envFileLabel(env, dir) {
416
- try {
417
- const envFile = require('./env-file.js');
418
- if (typeof envFile.envFileFor === 'function') return envFile.envFileFor(dir);
419
- } catch {}
420
- return envFileForFallback(dir);
421
- }
422
-
423
- /** `~/.aegiscode/.env`, built here so the label survives a host that ships no
424
- * env-file module (same rule aegisHome() exists for). */
425
- function envFileForFallback(dir) {
426
- return path.join(dir || aegisHome(), '.env');
427
- }
428
-
429
- function sourceLabel(source) {
430
- return SOURCE_LABEL[source] || SOURCE_LABEL.none;
431
- }
432
-
433
- /**
434
- * Prefer the most recently saved key between a host's own copy and this file.
435
- *
436
- * The desktop keeps its key encrypted via Electron safeStorage, which is a
437
- * better place for it than a 0600 file — but only one of the two can be in
438
- * force, and picking wrong is silent: the user rotates their key with
439
- * `aegiscode login`, the app keeps presenting an old string it saved last week,
440
- * and every call 401s with a key that looks right in Settings.
441
- *
442
- * Both sides stamp `savedAt`, so the rule is simply "the newest write wins",
443
- * with the host's own copy breaking a tie (it is encrypted). A missing stamp on
444
- * either side loses to a present one; equal keys always resolve to the host's.
445
- *
446
- * @returns {{key:string, source:'host'|'shared'|'none', sharedAt:number, hostAt:number}}
447
- */
448
- function preferNewest(storedKey, storedAt, o = {}) {
449
- const ownKey = normalizeApiKey(storedKey);
450
- const ownAt = Date.parse(storedAt || '') || 0;
451
- const shared = readCredentials(o.dir);
452
- const sharedKey = normalizeApiKey(shared.aegisApiKey);
453
- const sharedAt = Date.parse(shared.savedAt || '') || 0;
454
-
455
- if (!sharedKey) return { key: ownKey, source: ownKey ? 'host' : 'none', sharedAt, hostAt: ownAt };
456
- if (!ownKey) return { key: sharedKey, source: 'shared', sharedAt, hostAt: ownAt };
457
- if (ownKey === sharedKey) return { key: ownKey, source: 'host', sharedAt, hostAt: ownAt };
458
- return sharedAt > ownAt
459
- ? { key: sharedKey, source: 'shared', sharedAt, hostAt: ownAt }
460
- : { key: ownKey, source: 'host', sharedAt, hostAt: ownAt };
461
- }
462
-
463
- /** One line telling the user how to supply a key, used by every error path. */
464
- const HOW_TO_SET = 'run `aegiscode login` (or /key inside a session) to save one';
465
-
466
- module.exports = {
467
- KEY_ENV,
468
- MEMORY_ENV,
469
- HOME_ENV,
470
- CREDENTIALS_FILE,
471
- CONFIG_FILE,
472
- aegisHome,
473
- credentialsPath,
474
- configPath,
475
- normalizeApiKey,
476
- validateApiKey,
477
- readCredentials,
478
- writeCredentials,
479
- readLegacyConfig,
480
- legacyKeyOnDisk,
481
- adoptLegacy,
482
- resolveApiKey,
483
- hasApiKey,
484
- fromEnvFile,
485
- envFileForFallback,
486
- saveApiKey,
487
- clearApiKey,
488
- resolveMemoryToken,
489
- saveMemoryToken,
490
- clearMemoryToken,
491
- keyStatus,
492
- clientOptions,
493
- preferNewest,
494
- sourceLabel,
495
- HOW_TO_SET,
496
- };
3
+ const e=require("node:fs"),n=require("node:os"),r=require("node:path"),o="AEGIS_API_KEY",t="AEGIS_MEMORY_TOKEN",i="AEGISCODE_HOME",s="credentials.json",c="config.json";function a(e){const o=e||process.env,t=o&&o[i];return t&&String(t).trim()?r.resolve(String(t).trim()):r.join(n.homedir(),".aegiscode")}function u(e){return r.join(e||a(),s)}function y(e){return r.join(e||a(),c)}function l(e){let n=String(null==e?"":e).trim();if(!n)return"";n=n.replace(/^export\s+/i,"").trim();const r=/^[A-Za-z_][A-Za-z0-9_]*\s*=\s*(.+)$/s.exec(n);return r&&(n=r[1].trim()),n=n.replace(/^["']|["']$/g,"").trim(),n=n.replace(/^Bearer\s+/i,"").trim(),n}function m(e,n={}){const r=String(n.label||"AEGIS"),o=l(e);return o?/\s/.test(o)?{ok:!1,key:o,reason:"whitespace",message:"that looks like more than one word — paste just the key"}:o.length<16?{ok:!1,key:o,reason:"too short",message:`that key is ${o.length} characters — ${r} keys are longer than that`}:{ok:!0,key:o,reason:null,message:null}:{ok:!1,key:o,reason:"empty",message:"no key given"}}function k(n){try{const r=JSON.parse(e.readFileSync(u(n),"utf8"));if(r&&"object"==typeof r)return r}catch{}return{}}function f(n,o){const t=u(o),i={...k(o),...n,version:1};try{e.mkdirSync(r.dirname(t),{recursive:!0,mode:448});const n=t+".tmp";e.writeFileSync(n,JSON.stringify(i,null,2)+"\n",{mode:384}),e.renameSync(n,t);try{e.chmodSync(t,384)}catch{}}catch(e){return process.env.AEGIS_HIST_DEBUG&&console.error("[credentials] write failed:",e),{ok:!1,error:e,credentials:i}}return{ok:!0,credentials:i}}function d(n){try{const r=JSON.parse(e.readFileSync(y(n),"utf8"));if(!r||"object"!=typeof r)return{};const o=r.aegiscloud&&"object"==typeof r.aegiscloud?r.aegiscloud:{},t=r.memory&&"object"==typeof r.memory?r.memory:{};return{apiKey:l(o.api_key),memoryToken:String(t.token||"").trim(),syncConversations:!0===o.syncConversations||void 0,lastVerified:o.lastVerified||null,memorySubscribed:!0===t.subscribed||void 0}}catch{return{}}}function p(e){return!!d(e).apiKey}function g(e,n,r){try{const o=require("./env-file.js");return"function"==typeof o.isFromEnvFile&&o.isFromEnvFile(e,n,r?{env:r}:void 0)}catch{return!1}}function h(e={}){const n=e.env||process.env,r=e.dir,t=l(n&&n[o]);if(t&&!g(o,n&&n[o],n))return{key:t,source:"env",from:o};const i=l(k(r).aegisApiKey);if(i)return{key:i,source:"credentials",from:u(r)};if(t)return{key:t,source:"envfile",from:S(0,r)};const s=d(r).apiKey;return s?{key:s,source:"config",from:y(r)}:{key:"",source:"none",from:""}}function v(e={}){const n=e.env||process.env,r=e.dir,o=String(n&&n[t]||"").trim();if(o)return{token:o,source:"env"};const i=k(r),s=String(i.memoryToken||"").trim();if(s)return{token:s,source:"credentials"};const c=d(r).memoryToken;return c?{token:c,source:"config"}:{token:"",source:"none"}}const A={env:`${o}`,credentials:"saved key file",envfile:`~/.aegiscode/.env (${o})`,config:"config.json (aegis CLI)",none:"not set"};function S(e,n){try{const e=require("./env-file.js");if("function"==typeof e.envFileFor)return e.envFileFor(n)}catch{}return E(n)}function E(e){return r.join(e||a(),".env")}module.exports={KEY_ENV:o,MEMORY_ENV:t,HOME_ENV:i,CREDENTIALS_FILE:s,CONFIG_FILE:c,aegisHome:a,credentialsPath:u,configPath:y,normalizeApiKey:l,validateApiKey:m,readCredentials:k,writeCredentials:f,readLegacyConfig:d,legacyKeyOnDisk:p,adoptLegacy:function(e){const n=d(e),r=k(e),o={};return n.apiKey&&!r.aegisApiKey&&(o.aegisApiKey=n.apiKey),n.memoryToken&&!r.memoryToken&&(o.memoryToken=n.memoryToken),Object.keys(o).length&&f({...o,adoptedFrom:y(e)},e).ok?{adopted:Object.keys(o)}:{adopted:[]}},resolveApiKey:h,hasApiKey:function(e={}){return!!h(e).key},fromEnvFile:g,envFileForFallback:E,saveApiKey:function(e,n){const r=m(e);if(!r.ok)return{ok:!1,key:r.key,path:u(n),message:r.message};const o=f({aegisApiKey:r.key,savedAt:(new Date).toISOString()},n);return o.ok?{ok:!0,key:r.key,path:u(n)}:{ok:!1,key:r.key,path:u(n),error:o.error,message:`could not write ${u(n)}`}},clearApiKey:function(e){return{cleared:!!l(k(e).aegisApiKey),ok:f({aegisApiKey:"",adoptedFrom:""},e).ok,path:u(e)}},resolveMemoryToken:v,saveMemoryToken:function(e,n={},r){return f({memoryToken:String(e||"").trim(),...n},r)},clearMemoryToken:function(e){return f({memoryToken:"",memorySubscribed:!1},e)},keyStatus:function(n={}){const r=n.dir,{key:o,source:t,from:i}=h(n),s=k(r);let c=null;try{c=511&e.statSync(u(r)).mode}catch{}return{configured:!!o,key:o,source:t,from:i,path:u(r),fileMode:null==c?null:"0"+c.toString(8),stored:!!l(s.aegisApiKey),legacyPlaintext:p(r),verifiedAt:s.verifiedAt||null,account:s.account||null,memoryToken:!!v(n).token,memorySource:v(n).source}},clientOptions:function(e={}){const{key:n}=h(e),{token:r}=v(e),o={};return o.apiKey=n,o.memoryToken=r,e.channel&&(o.channel=e.channel),o},preferNewest:function(e,n,r={}){const o=l(e),t=Date.parse(n||"")||0,i=k(r.dir),s=l(i.aegisApiKey),c=Date.parse(i.savedAt||"")||0;return s?o?o===s?{key:o,source:"host",sharedAt:c,hostAt:t}:c>t?{key:s,source:"shared",sharedAt:c,hostAt:t}:{key:o,source:"host",sharedAt:c,hostAt:t}:{key:s,source:"shared",sharedAt:c,hostAt:t}:{key:o,source:o?"host":"none",sharedAt:c,hostAt:t}},sourceLabel:function(e){return A[e]||A.none},HOW_TO_SET:"run `aegiscode login` (or /key inside a session) to save one"};
@@ -1,143 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
- // Conveying a modified copy, or running one as a network service, owes the
5
- // corresponding source under this licence (§5/§13) — see LICENSING.md.
6
- 'use strict';
7
-
8
- /**
9
- * A stable per-machine identifier, used ONLY to ask aegis1 for a free device
10
- * key (`POST /api/v1/auth/register-device`) when no key is configured yet. It
11
- * is not a credential itself — the endpoint treats it as an idempotency key,
12
- * so a wiped `~/.aegiscode` still resolves back to the same aegis1 account
13
- * (and whatever balance it holds) instead of minting a fresh, unfunded one.
14
- *
15
- * Derivation mirrors ae-guix's `getMachineFingerprint()` (main.js) so the two
16
- * hosts don't invent divergent conventions for the same idea: the OS's own
17
- * machine identity where one exists, hashed with a purpose-specific prefix so
18
- * it can never collide with a fingerprint minted for another purpose.
19
- */
20
- const crypto = require('node:crypto');
21
- const os = require('node:os');
22
- const fs = require('node:fs');
23
- const path = require('node:path');
24
-
25
- /**
26
- * Where a per-install random id is persisted when the OS exposes no machine
27
- * identity at all. Deliberately inside the same private store as the
28
- * credentials, so `readMachineId()`-less hosts (minimal Linux containers
29
- * without /etc/machine-id, hardened images, some CI runners) still get a
30
- * collision-resistant fingerprint instead of a guessable one — while the
31
- * credential store as a whole remains the single thing a wipe destroys.
32
- */
33
- function installIdPath() {
34
- const home = process.env.AEGISCODEX_HOME || path.join(os.homedir(), '.aegiscode');
35
- return path.join(home, 'install-id');
36
- }
37
-
38
- /** Best-effort OS machine identity. Empty string, never throws, if none is reachable. */
39
- function readMachineId() {
40
- try {
41
- if (process.platform === 'linux') {
42
- const fs = require('node:fs');
43
- try {
44
- return fs.readFileSync('/etc/machine-id', 'utf8').trim();
45
- } catch {
46
- return fs.readFileSync('/var/lib/dbus/machine-id', 'utf8').trim();
47
- }
48
- }
49
- if (process.platform === 'darwin') {
50
- const { execSync } = require('node:child_process');
51
- const out = execSync('ioreg -rd1 -c IOPlatformExpertDevice', {
52
- encoding: 'utf8',
53
- timeout: 3000,
54
- });
55
- const m = out.match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/);
56
- if (m) return m[1];
57
- }
58
- if (process.platform === 'win32') {
59
- const { execSync } = require('node:child_process');
60
- const out = execSync('reg query HKLM\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid', {
61
- encoding: 'utf8',
62
- timeout: 3000,
63
- });
64
- const m = out.match(/MachineGuid\s+REG_SZ\s+(\S+)/);
65
- if (m) return m[1];
66
- }
67
- } catch {
68
- /* no reachable machine id on this host — the caller falls back below */
69
- }
70
- return '';
71
- }
72
-
73
- /**
74
- * A random 128-bit id persisted 0600 in the private store, minted on first
75
- * need. Distinct from the machine identity: it survives a credential wipe
76
- * only if the store itself survives, which is exactly the guarantee we can
77
- * honestly make on a host that reports no machine id at all.
78
- *
79
- * @returns {string} hex id, or '' if the store is not writable.
80
- */
81
- function persistedInstallId() {
82
- const file = installIdPath();
83
- const read = () => {
84
- try {
85
- const v = fs.readFileSync(file, 'utf8').trim();
86
- return /^[0-9a-f]{32}$/.test(v) ? v : '';
87
- } catch {
88
- return '';
89
- }
90
- };
91
- const existing = read();
92
- if (existing) return existing;
93
- try {
94
- const fresh = crypto.randomBytes(16).toString('hex');
95
- fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
96
- fs.writeFileSync(file, fresh, { mode: 0o600, flag: 'wx' });
97
- return fresh;
98
- } catch {
99
- // Lost a race with a concurrent host process, or the store is read-only.
100
- return read();
101
- }
102
- }
103
-
104
- /**
105
- * sha256("aegiscode-plugin-device-v1:" + machine identity), hex.
106
- *
107
- * Identity precedence, strongest first:
108
- * 1. an explicit override (test-only),
109
- * 2. the OS machine identity (`readMachineId()`),
110
- * 3. a persisted random install id,
111
- * 4. `hostname:platform:arch` — last resort, kept only so this never throws.
112
- *
113
- * Only step 4 is guessable by a third party; steps 2 and 3 are both per-host
114
- * unique.
115
- *
116
- * @param {string} [overrideId] - test-only override for the raw machine identity.
117
- */
118
- function machineFingerprint(overrideId) {
119
- return crypto
120
- .createHash('sha256')
121
- .update(`aegiscode-plugin-device-v1:${machineIdentity(overrideId).id}`)
122
- .digest('hex');
123
- }
124
-
125
- /** @returns {{kind: 'override'|'machine-id'|'install-id'|'hostname', id: string}} */
126
- function machineIdentity(overrideId) {
127
- if (overrideId) return { kind: 'override', id: String(overrideId) };
128
- const machine = readMachineId();
129
- if (machine) return { kind: 'machine-id', id: machine };
130
- const install = persistedInstallId();
131
- if (install) return { kind: 'install-id', id: install };
132
- return {
133
- kind: 'hostname',
134
- id: `${os.hostname()}:${os.platform()}:${os.arch()}`,
135
- };
136
- }
137
-
138
- module.exports = {
139
- machineFingerprint,
140
- machineIdentity,
141
- readMachineId,
142
- persistedInstallId,
143
- };
3
+ "use strict";const crypto=require("node:crypto"),os=require("node:os"),fs=require("node:fs"),path=require("node:path");function installIdPath(){const e=process.env.AEGISCODEX_HOME||path.join(os.homedir(),".aegiscode");return path.join(e,"install-id")}function readMachineId(){try{if("linux"===process.platform){const e=require("node:fs");try{return e.readFileSync("/etc/machine-id","utf8").trim()}catch{return e.readFileSync("/var/lib/dbus/machine-id","utf8").trim()}}if("darwin"===process.platform){const{execSync:e}=require("node:child_process"),t=e("ioreg -rd1 -c IOPlatformExpertDevice",{encoding:"utf8",timeout:3e3}).match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/);if(t)return t[1]}if("win32"===process.platform){const{execSync:e}=require("node:child_process"),t=e("reg query HKLM\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid",{encoding:"utf8",timeout:3e3}).match(/MachineGuid\s+REG_SZ\s+(\S+)/);if(t)return t[1]}}catch{}return""}function persistedInstallId(){const e=installIdPath(),t=()=>{try{const t=fs.readFileSync(e,"utf8").trim();return/^[0-9a-f]{32}$/.test(t)?t:""}catch{return""}},r=t();if(r)return r;try{const t=crypto.randomBytes(16).toString("hex");return fs.mkdirSync(path.dirname(e),{recursive:!0,mode:448}),fs.writeFileSync(e,t,{mode:384,flag:"wx"}),t}catch{return t()}}function machineFingerprint(e){return crypto.createHash("sha256").update(`aegiscode-plugin-device-v1:${machineIdentity(e).id}`).digest("hex")}function machineIdentity(e){if(e)return{kind:"override",id:String(e)};const t=readMachineId();if(t)return{kind:"machine-id",id:t};const r=persistedInstallId();return r?{kind:"install-id",id:r}:{kind:"hostname",id:`${os.hostname()}:${os.platform()}:${os.arch()}`}}module.exports={machineFingerprint:machineFingerprint,machineIdentity:machineIdentity,readMachineId:readMachineId,persistedInstallId:persistedInstallId};