aegisone 1.0.21 → 1.0.23

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 (226) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +1 -1
  3. package/SOURCE-OFFER.txt +9 -0
  4. package/bin/aegis.js +1 -322
  5. package/package.json +4 -2
  6. package/scripts/bump.mjs +1 -211
  7. package/scripts/bundle.js +1 -129
  8. package/scripts/predist.mjs +1 -939
  9. package/src/child.js +1 -285
  10. package/src/dispatch.js +1 -269
  11. package/src/doctor.js +1 -639
  12. package/src/host.js +1 -111
  13. package/src/permissions.js +1 -369
  14. package/src/probes.js +1 -159
  15. package/src/release.js +1 -409
  16. package/vendor/cli/bin/aegiscode.js +2 -914
  17. package/vendor/cli/package.json +3 -2
  18. package/vendor/cli/scripts/check.mjs +1 -52
  19. package/vendor/cli/scripts/demo.mjs +1 -94
  20. package/vendor/cli/scripts/predist.mjs +1 -75
  21. package/vendor/cli/scripts/runtests.mjs +1 -56
  22. package/vendor/cli/scripts/seal-gate.mjs +1 -74
  23. package/vendor/cli/src/agents.js +1 -139
  24. package/vendor/cli/src/app.js +1 -2932
  25. package/vendor/cli/src/art.js +1 -289
  26. package/vendor/cli/src/autonomous.js +1 -515
  27. package/vendor/cli/src/caps.js +1 -879
  28. package/vendor/cli/src/chatflow.js +1 -3008
  29. package/vendor/cli/src/checkpoint.js +1 -90
  30. package/vendor/cli/src/clipboard.js +1 -424
  31. package/vendor/cli/src/cloudsync.js +1 -528
  32. package/vendor/cli/src/commands.js +1 -3987
  33. package/vendor/cli/src/config.js +1 -581
  34. package/vendor/cli/src/connect.js +1 -349
  35. package/vendor/cli/src/credentials.js +1 -33
  36. package/vendor/cli/src/deps.js +1 -232
  37. package/vendor/cli/src/devrun.js +1 -187
  38. package/vendor/cli/src/diff.js +1 -333
  39. package/vendor/cli/src/diffview.js +1 -296
  40. package/vendor/cli/src/engine.js +1 -297
  41. package/vendor/cli/src/entitlement.js +1 -355
  42. package/vendor/cli/src/events.js +1 -707
  43. package/vendor/cli/src/export.js +1 -67
  44. package/vendor/cli/src/fingerprint.js +1 -592
  45. package/vendor/cli/src/format.js +1 -259
  46. package/vendor/cli/src/fuzzy.js +1 -119
  47. package/vendor/cli/src/gate.js +1 -55
  48. package/vendor/cli/src/history.js +1 -401
  49. package/vendor/cli/src/init.js +1 -175
  50. package/vendor/cli/src/input.js +1 -139
  51. package/vendor/cli/src/keys.js +1 -183
  52. package/vendor/cli/src/limits.js +1 -190
  53. package/vendor/cli/src/markdown.js +1 -306
  54. package/vendor/cli/src/mcp.js +1 -694
  55. package/vendor/cli/src/models.js +1 -487
  56. package/vendor/cli/src/naming.js +1 -229
  57. package/vendor/cli/src/overlays.js +1 -461
  58. package/vendor/cli/src/panels.js +1 -1418
  59. package/vendor/cli/src/permissions.js +1 -290
  60. package/vendor/cli/src/ping.js +1 -226
  61. package/vendor/cli/src/presence.js +1 -238
  62. package/vendor/cli/src/provenance.js +2 -182
  63. package/vendor/cli/src/render.js +1 -515
  64. package/vendor/cli/src/screen.js +1 -518
  65. package/vendor/cli/src/screens.js +1 -896
  66. package/vendor/cli/src/secret.js +1 -59
  67. package/vendor/cli/src/securefs.js +1 -359
  68. package/vendor/cli/src/settings.js +1 -155
  69. package/vendor/cli/src/shared.js +1 -52
  70. package/vendor/cli/src/sharedpaths.js +1 -53
  71. package/vendor/cli/src/signup.js +1 -156
  72. package/vendor/cli/src/summarize.js +1 -95
  73. package/vendor/cli/src/sysdiag.js +1 -585
  74. package/vendor/cli/src/system.js +1 -40
  75. package/vendor/cli/src/theme.js +1 -570
  76. package/vendor/cli/src/title.js +1 -220
  77. package/vendor/cli/src/todos.js +1 -115
  78. package/vendor/cli/src/tokens.js +1 -263
  79. package/vendor/cli/src/topup.js +1 -210
  80. package/vendor/cli/src/update.js +1 -181
  81. package/vendor/cli/vendor/client/aegis.js +1 -2054
  82. package/vendor/cli/vendor/client/attest.js +1 -442
  83. package/vendor/cli/vendor/client/authorship-key.js +1 -410
  84. package/vendor/cli/vendor/client/auto-provision.js +1 -134
  85. package/vendor/cli/vendor/client/brain-catalog.js +1 -268
  86. package/vendor/cli/vendor/client/byok-catalog.js +1 -230
  87. package/vendor/cli/vendor/client/credentials.js +1 -494
  88. package/vendor/cli/vendor/client/device-fingerprint.js +1 -141
  89. package/vendor/cli/vendor/client/drive-connect.js +1 -85
  90. package/vendor/cli/vendor/client/drive-upload.js +1 -174
  91. package/vendor/cli/vendor/client/env-file.js +1 -1273
  92. package/vendor/cli/vendor/client/fingerprint.js +1 -1064
  93. package/vendor/cli/vendor/client/foreign-memory.js +1 -669
  94. package/vendor/cli/vendor/client/google-signin.js +1 -125
  95. package/vendor/cli/vendor/client/hooks.js +1 -430
  96. package/vendor/cli/vendor/client/model-discovery.js +1 -330
  97. package/vendor/cli/vendor/client/platform.js +1 -937
  98. package/vendor/cli/vendor/client/prefs.js +1 -351
  99. package/vendor/cli/vendor/client/presence-constants.js +1 -107
  100. package/vendor/cli/vendor/client/presence.js +1 -438
  101. package/vendor/cli/vendor/client/record-vault.js +3 -1055
  102. package/vendor/cli/vendor/client/session-store.js +1 -548
  103. package/vendor/cli/vendor/client/topup.js +1 -297
  104. package/vendor/cli/vendor/client/touch.js +1 -458
  105. package/vendor/cli/vendor/client/update.js +1 -704
  106. package/vendor/cli/vendor/client/user-models.js +1 -381
  107. package/vendor/cli/vendor/desktop/lib/local/agents.js +1 -105
  108. package/vendor/cli/vendor/desktop/lib/local/autonomous.js +1 -1045
  109. package/vendor/cli/vendor/desktop/lib/local/claude-pro.js +1 -993
  110. package/vendor/cli/vendor/desktop/lib/local/context.js +1 -95
  111. package/vendor/cli/vendor/desktop/lib/local/engine.js +1 -3228
  112. package/vendor/cli/vendor/desktop/lib/local/entitlement.js +1 -654
  113. package/vendor/cli/vendor/desktop/lib/local/git-scope.js +1 -228
  114. package/vendor/cli/vendor/desktop/lib/local/local.js +1 -2135
  115. package/vendor/cli/vendor/desktop/lib/local/prompt.js +1 -275
  116. package/vendor/cli/vendor/desktop/lib/local/queue.js +1 -560
  117. package/vendor/cli/vendor/desktop/lib/local/session-rounds.js +1 -208
  118. package/vendor/cli/vendor/desktop/lib/local/shell.js +1 -680
  119. package/vendor/cli/vendor/desktop/lib/local/tools.js +1 -1238
  120. package/vendor/cli/vendor/desktop/lib/local/turn-guard.js +1 -300
  121. package/vendor/cli/vendor/desktop/lib/local/worktree-lock.js +1 -235
  122. package/vendor/cli/vendor/desktop/lib/settings.js +1 -890
  123. package/vendor/cli/vendor/desktop/renderer/usage.js +1 -1239
  124. package/vendor/cli/vendor/hosts/install.js +1 -638
  125. package/vendor/cli/vendor/hosts/openai-shim.js +1 -515
  126. package/vendor/cli/vendor/hosts/spec.js +1 -164
  127. package/vendor/cli/vendor/hosts/targets.js +1 -346
  128. package/vendor/cli/vendor/mcp/server.js +1 -221
  129. package/vendor/cli/vendor/mcp/tools.js +1 -408
  130. package/vendor/cli/vendor/one/src/child.js +1 -285
  131. package/vendor/cli/vendor/one/src/permissions.js +1 -369
  132. package/vendor/desktop/bin/aegis.js +1 -32
  133. package/vendor/desktop/lib/account-key.js +1 -56
  134. package/vendor/desktop/lib/auto.js +1 -430
  135. package/vendor/desktop/lib/avatar/companion.js +1 -698
  136. package/vendor/desktop/lib/avatar/cosmetics.js +1 -532
  137. package/vendor/desktop/lib/avatar/events.js +1 -344
  138. package/vendor/desktop/lib/avatar/holder-turn.js +1 -350
  139. package/vendor/desktop/lib/avatar/holders.js +1 -612
  140. package/vendor/desktop/lib/avatar/identity.js +1 -641
  141. package/vendor/desktop/lib/avatar/level.js +1 -368
  142. package/vendor/desktop/lib/avatar/mirror.js +1 -524
  143. package/vendor/desktop/lib/avatar/persona.js +1 -388
  144. package/vendor/desktop/lib/avatar/profile.js +1 -977
  145. package/vendor/desktop/lib/avatar/register.js +1 -307
  146. package/vendor/desktop/lib/avatar/store.js +1 -472
  147. package/vendor/desktop/lib/avatar/tiers.js +1 -38
  148. package/vendor/desktop/lib/avatar/transfer.js +1 -415
  149. package/vendor/desktop/lib/avatar/turn.js +1 -216
  150. package/vendor/desktop/lib/avatar/voice.js +1 -328
  151. package/vendor/desktop/lib/avatar/xp.js +1 -404
  152. package/vendor/desktop/lib/deep-link.js +1 -120
  153. package/vendor/desktop/lib/fingerprint.js +2 -347
  154. package/vendor/desktop/lib/google-connect.js +1 -169
  155. package/vendor/desktop/lib/local/agents.js +1 -105
  156. package/vendor/desktop/lib/local/autonomous.js +1 -1045
  157. package/vendor/desktop/lib/local/claude-pro.js +1 -993
  158. package/vendor/desktop/lib/local/context.js +1 -95
  159. package/vendor/desktop/lib/local/engine.js +1 -3228
  160. package/vendor/desktop/lib/local/entitlement.js +1 -654
  161. package/vendor/desktop/lib/local/git-scope.js +1 -228
  162. package/vendor/desktop/lib/local/local.js +1 -2135
  163. package/vendor/desktop/lib/local/prompt.js +1 -275
  164. package/vendor/desktop/lib/local/queue.js +1 -560
  165. package/vendor/desktop/lib/local/session-rounds.js +1 -208
  166. package/vendor/desktop/lib/local/shell.js +1 -680
  167. package/vendor/desktop/lib/local/telemetry.js +1 -470
  168. package/vendor/desktop/lib/local/tools.js +1 -1238
  169. package/vendor/desktop/lib/local/turn-guard.js +1 -300
  170. package/vendor/desktop/lib/local/worktree-lock.js +1 -235
  171. package/vendor/desktop/lib/provider-key-mirror.js +1 -252
  172. package/vendor/desktop/lib/quick-launcher.js +1 -84
  173. package/vendor/desktop/lib/settings.js +1 -890
  174. package/vendor/desktop/lib/sync/memory-queue.js +1 -60
  175. package/vendor/desktop/lib/sync/persist-gate.js +1 -148
  176. package/vendor/desktop/lib/sync/sessions.js +1 -106
  177. package/vendor/desktop/lib/window-state.js +1 -66
  178. package/vendor/desktop/main.js +1 -4390
  179. package/vendor/desktop/package.json +3 -5
  180. package/vendor/desktop/preload.js +1 -628
  181. package/vendor/desktop/renderer/app.js +1 -6560
  182. package/vendor/desktop/renderer/avatar/assemble.js +1 -335
  183. package/vendor/desktop/renderer/avatar/avatar.js +1 -380
  184. package/vendor/desktop/renderer/avatar/cards.js +1 -141
  185. package/vendor/desktop/renderer/avatar/hud.js +1 -206
  186. package/vendor/desktop/renderer/avatar/machine.js +1 -213
  187. package/vendor/desktop/renderer/avatar/pane.js +1 -439
  188. package/vendor/desktop/renderer/avatar/parts.js +1 -437
  189. package/vendor/desktop/renderer/budget.js +1 -168
  190. package/vendor/desktop/renderer/companion.js +1 -223
  191. package/vendor/desktop/renderer/diff.js +1 -359
  192. package/vendor/desktop/renderer/diffview.js +1 -336
  193. package/vendor/desktop/renderer/fingerprint.js +3 -720
  194. package/vendor/desktop/renderer/markdown.js +1 -168
  195. package/vendor/desktop/renderer/provider-toolbar.js +1 -134
  196. package/vendor/desktop/renderer/providers.js +1 -259
  197. package/vendor/desktop/renderer/quick.js +1 -191
  198. package/vendor/desktop/renderer/stream-policy.js +1 -306
  199. package/vendor/desktop/renderer/transcript-view.js +1 -323
  200. package/vendor/desktop/renderer/usage.js +1 -1239
  201. package/vendor/desktop/vendor/aegis.js +1 -2054
  202. package/vendor/desktop/vendor/attest.js +1 -442
  203. package/vendor/desktop/vendor/authorship-key.js +1 -410
  204. package/vendor/desktop/vendor/auto-provision.js +1 -134
  205. package/vendor/desktop/vendor/brain-catalog.js +1 -268
  206. package/vendor/desktop/vendor/byok-catalog.js +1 -230
  207. package/vendor/desktop/vendor/credentials.js +1 -494
  208. package/vendor/desktop/vendor/device-fingerprint.js +1 -141
  209. package/vendor/desktop/vendor/drive-connect.js +1 -85
  210. package/vendor/desktop/vendor/drive-upload.js +1 -174
  211. package/vendor/desktop/vendor/env-file.js +1 -1273
  212. package/vendor/desktop/vendor/fingerprint.js +1 -1064
  213. package/vendor/desktop/vendor/foreign-memory.js +1 -669
  214. package/vendor/desktop/vendor/google-signin.js +1 -125
  215. package/vendor/desktop/vendor/hooks.js +1 -430
  216. package/vendor/desktop/vendor/model-discovery.js +1 -330
  217. package/vendor/desktop/vendor/platform.js +1 -937
  218. package/vendor/desktop/vendor/prefs.js +1 -351
  219. package/vendor/desktop/vendor/presence-constants.js +1 -107
  220. package/vendor/desktop/vendor/presence.js +1 -438
  221. package/vendor/desktop/vendor/record-vault.js +3 -1055
  222. package/vendor/desktop/vendor/session-store.js +1 -548
  223. package/vendor/desktop/vendor/topup.js +1 -297
  224. package/vendor/desktop/vendor/touch.js +1 -458
  225. package/vendor/desktop/vendor/update.js +1 -704
  226. package/vendor/desktop/vendor/user-models.js +1 -381
@@ -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
+ "use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path"),KEY_ENV="AEGIS_API_KEY",MEMORY_ENV="AEGIS_MEMORY_TOKEN",HOME_ENV="AEGISCODE_HOME",CREDENTIALS_FILE="credentials.json",CONFIG_FILE="config.json",FILE_MODE=384,DIR_MODE=448;function aegisHome(e){const r=e||process.env,n=r&&r[HOME_ENV];return n&&String(n).trim()?path.resolve(String(n).trim()):path.join(os.homedir(),".aegiscode")}function credentialsPath(e){return path.join(e||aegisHome(),CREDENTIALS_FILE)}function configPath(e){return path.join(e||aegisHome(),CONFIG_FILE)}function normalizeApiKey(e){let r=String(null==e?"":e).trim();if(!r)return"";r=r.replace(/^export\s+/i,"").trim();const n=/^[A-Za-z_][A-Za-z0-9_]*\s*=\s*(.+)$/s.exec(r);return n&&(r=n[1].trim()),r=r.replace(/^["']|["']$/g,"").trim(),r=r.replace(/^Bearer\s+/i,"").trim(),r}function validateApiKey(e,r={}){const n=String(r.label||"AEGIS"),t=normalizeApiKey(e);return t?/\s/.test(t)?{ok:!1,key:t,reason:"whitespace",message:"that looks like more than one word — paste just the key"}:t.length<16?{ok:!1,key:t,reason:"too short",message:`that key is ${t.length} characters — ${n} keys are longer than that`}:{ok:!0,key:t,reason:null,message:null}:{ok:!1,key:t,reason:"empty",message:"no key given"}}function readCredentials(e){try{const r=JSON.parse(fs.readFileSync(credentialsPath(e),"utf8"));if(r&&"object"==typeof r)return r}catch{}return{}}function writeCredentials(e,r){const n=credentialsPath(r),t={...readCredentials(r),...e,version:1};try{fs.mkdirSync(path.dirname(n),{recursive:!0,mode:DIR_MODE});const e=n+".tmp";fs.writeFileSync(e,JSON.stringify(t,null,2)+"\n",{mode:FILE_MODE}),fs.renameSync(e,n);try{fs.chmodSync(n,FILE_MODE)}catch{}}catch(e){return process.env.AEGIS_HIST_DEBUG&&console.error("[credentials] write failed:",e),{ok:!1,error:e,credentials:t}}return{ok:!0,credentials:t}}function readLegacyConfig(e){try{const r=JSON.parse(fs.readFileSync(configPath(e),"utf8"));if(!r||"object"!=typeof r)return{};const n=r.aegiscloud&&"object"==typeof r.aegiscloud?r.aegiscloud:{},t=r.memory&&"object"==typeof r.memory?r.memory:{};return{apiKey:normalizeApiKey(n.api_key),memoryToken:String(t.token||"").trim(),syncConversations:!0===n.syncConversations||void 0,lastVerified:n.lastVerified||null,memorySubscribed:!0===t.subscribed||void 0}}catch{return{}}}function legacyKeyOnDisk(e){return!!readLegacyConfig(e).apiKey}function adoptLegacy(e){const r=readLegacyConfig(e),n=readCredentials(e),t={};return r.apiKey&&!n.aegisApiKey&&(t.aegisApiKey=r.apiKey),r.memoryToken&&!n.memoryToken&&(t.memoryToken=r.memoryToken),Object.keys(t).length&&writeCredentials({...t,adoptedFrom:configPath(e)},e).ok?{adopted:Object.keys(t)}:{adopted:[]}}function fromEnvFile(e,r,n){try{const t=require("./env-file.js");return"function"==typeof t.isFromEnvFile&&t.isFromEnvFile(e,r,n?{env:n}:void 0)}catch{return!1}}function resolveApiKey(e={}){const r=e.env||process.env,n=e.dir,t=normalizeApiKey(r&&r[KEY_ENV]);if(t&&!fromEnvFile(KEY_ENV,r&&r[KEY_ENV],r))return{key:t,source:"env",from:KEY_ENV};const o=normalizeApiKey(readCredentials(n).aegisApiKey);if(o)return{key:o,source:"credentials",from:credentialsPath(n)};if(t)return{key:t,source:"envfile",from:envFileLabel(r,n)};const i=readLegacyConfig(n).apiKey;return i?{key:i,source:"config",from:configPath(n)}:{key:"",source:"none",from:""}}function hasApiKey(e={}){return!!resolveApiKey(e).key}function saveApiKey(e,r){const n=validateApiKey(e);if(!n.ok)return{ok:!1,key:n.key,path:credentialsPath(r),message:n.message};const t=writeCredentials({aegisApiKey:n.key,savedAt:(new Date).toISOString()},r);return t.ok?{ok:!0,key:n.key,path:credentialsPath(r)}:{ok:!1,key:n.key,path:credentialsPath(r),error:t.error,message:`could not write ${credentialsPath(r)}`}}function clearApiKey(e){return{cleared:!!normalizeApiKey(readCredentials(e).aegisApiKey),ok:writeCredentials({aegisApiKey:"",adoptedFrom:""},e).ok,path:credentialsPath(e)}}function resolveMemoryToken(e={}){const r=e.env||process.env,n=e.dir,t=String(r&&r[MEMORY_ENV]||"").trim();if(t)return{token:t,source:"env"};const o=readCredentials(n),i=String(o.memoryToken||"").trim();if(i)return{token:i,source:"credentials"};const a=readLegacyConfig(n).memoryToken;return a?{token:a,source:"config"}:{token:"",source:"none"}}function saveMemoryToken(e,r={},n){return writeCredentials({memoryToken:String(e||"").trim(),...r},n)}function clearMemoryToken(e){return writeCredentials({memoryToken:"",memorySubscribed:!1},e)}function keyStatus(e={}){const r=e.dir,{key:n,source:t,from:o}=resolveApiKey(e),i=readCredentials(r);let a=null;try{a=511&fs.statSync(credentialsPath(r)).mode}catch{}return{configured:!!n,key:n,source:t,from:o,path:credentialsPath(r),fileMode:null==a?null:"0"+a.toString(8),stored:!!normalizeApiKey(i.aegisApiKey),legacyPlaintext:legacyKeyOnDisk(r),verifiedAt:i.verifiedAt||null,account:i.account||null,memoryToken:!!resolveMemoryToken(e).token,memorySource:resolveMemoryToken(e).source}}function clientOptions(e={}){const{key:r}=resolveApiKey(e),{token:n}=resolveMemoryToken(e),t={};return t.apiKey=r,t.memoryToken=n,e.channel&&(t.channel=e.channel),t}const SOURCE_LABEL={env:`${KEY_ENV}`,credentials:"saved key file",envfile:`~/.aegiscode/.env (${KEY_ENV})`,config:"config.json (aegis CLI)",none:"not set"};function envFileLabel(e,r){try{const e=require("./env-file.js");if("function"==typeof e.envFileFor)return e.envFileFor(r)}catch{}return envFileForFallback(r)}function envFileForFallback(e){return path.join(e||aegisHome(),".env")}function sourceLabel(e){return SOURCE_LABEL[e]||SOURCE_LABEL.none}function preferNewest(e,r,n={}){const t=normalizeApiKey(e),o=Date.parse(r||"")||0,i=readCredentials(n.dir),a=normalizeApiKey(i.aegisApiKey),s=Date.parse(i.savedAt||"")||0;return a?t?t===a?{key:t,source:"host",sharedAt:s,hostAt:o}:s>o?{key:a,source:"shared",sharedAt:s,hostAt:o}:{key:t,source:"host",sharedAt:s,hostAt:o}:{key:a,source:"shared",sharedAt:s,hostAt:o}:{key:t,source:t?"host":"none",sharedAt:s,hostAt:o}}const HOW_TO_SET="run `aegiscode login` (or /key inside a session) to save one";module.exports={KEY_ENV:KEY_ENV,MEMORY_ENV:MEMORY_ENV,HOME_ENV:HOME_ENV,CREDENTIALS_FILE:CREDENTIALS_FILE,CONFIG_FILE:CONFIG_FILE,aegisHome:aegisHome,credentialsPath:credentialsPath,configPath:configPath,normalizeApiKey:normalizeApiKey,validateApiKey:validateApiKey,readCredentials:readCredentials,writeCredentials:writeCredentials,readLegacyConfig:readLegacyConfig,legacyKeyOnDisk:legacyKeyOnDisk,adoptLegacy:adoptLegacy,resolveApiKey:resolveApiKey,hasApiKey:hasApiKey,fromEnvFile:fromEnvFile,envFileForFallback:envFileForFallback,saveApiKey:saveApiKey,clearApiKey:clearApiKey,resolveMemoryToken:resolveMemoryToken,saveMemoryToken:saveMemoryToken,clearMemoryToken:clearMemoryToken,keyStatus:keyStatus,clientOptions:clientOptions,preferNewest:preferNewest,sourceLabel:sourceLabel,HOW_TO_SET:HOW_TO_SET};
@@ -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};