aegiscode 6.8.30 → 6.8.33
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/README.md +55 -10
- package/bin/aegiscode.js +31 -0
- package/package.json +1 -1
- package/scripts/predist.mjs +32 -328
- package/src/app.js +46 -3
- package/src/autonomous.js +2 -2
- package/src/chatflow.js +28 -1
- package/src/commands.js +298 -5
- package/src/config.js +260 -11
- package/src/entitlement.js +9 -3
- package/src/panels.js +1 -1
- package/src/permissions.js +92 -0
- package/src/ping.js +223 -0
- package/src/settings.js +152 -0
- package/src/shared.js +5 -1
- package/src/todos.js +109 -0
- package/src/topup.js +207 -0
- package/vendor/client/platform.js +7 -0
- package/vendor/client/prefs.js +348 -0
- package/vendor/client/topup.js +294 -0
- package/vendor/client/update.js +141 -3
- package/vendor/desktop/lib/local/autonomous.js +105 -38
- package/vendor/desktop/lib/local/context.js +92 -0
- package/vendor/desktop/lib/local/engine.js +26 -0
- package/vendor/desktop/lib/local/local.js +1410 -46
- package/vendor/desktop/lib/local/queue.js +20 -16
- package/vendor/desktop/lib/settings.js +189 -28
package/src/topup.js
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* topup.js — `aegiscode topup [EUR]`: the terminal's own top-up.
|
|
5
|
+
*
|
|
6
|
+
* WHY THE TERMINAL NEEDS THIS AT ALL. `/billing` prints a link (`/go/topup`) and
|
|
7
|
+
* that was the whole funding affordance: the CLI could not start a checkout.
|
|
8
|
+
* The link is real but it lands on `/topup`, which is `@login_required` against
|
|
9
|
+
* a browser SESSION — and the account this product auto-provisions is created by
|
|
10
|
+
* `POST /api/v1/auth/register-device`, with a password that is never returned
|
|
11
|
+
* and an email at `@device.aegiscloud`. So the user who most needs to fund a
|
|
12
|
+
* free account is the one who cannot sign in to the page that funds it: they pay
|
|
13
|
+
* the link a visit, hit a login wall, and conclude it failed while the money is
|
|
14
|
+
* real.
|
|
15
|
+
*
|
|
16
|
+
* What makes this work is that the credential which CREATES the checkout can
|
|
17
|
+
* also READ the result: `POST /api/token-bank/topup` and `GET
|
|
18
|
+
* /api/token-bank/balance` are both `login_required`, which accepts
|
|
19
|
+
* `X-API-Key`/Bearer. So this command starts the session, opens the hosted page
|
|
20
|
+
* for the actual card entry, and then confirms the credit itself from the
|
|
21
|
+
* balance endpoint — the same confirmation the desktop does, over the same state
|
|
22
|
+
* machine (`client/topup.js`, `createCreditWatch`), so the terminal and the GUI
|
|
23
|
+
* cannot disagree about whether the money arrived.
|
|
24
|
+
*
|
|
25
|
+
* It BLOCKS on purpose. The desktop's watch is an unref'd interval because the
|
|
26
|
+
* window stays open for hours; here the process exits, so a detached timer would
|
|
27
|
+
* be killed before the webhook fires. A loop is the honest scheduler for a
|
|
28
|
+
* one-shot command, and it is why the shared module owns the state machine and
|
|
29
|
+
* not the timer.
|
|
30
|
+
*
|
|
31
|
+
* Exit codes (a script can gate on them): 0 credited, 1 checkout opened but no
|
|
32
|
+
* credit observed in the window, 2 usage / no usable credential / the server
|
|
33
|
+
* refused the checkout.
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
const { resolveShared } = require('./sharedpaths.js');
|
|
37
|
+
const { openUrl: defaultOpenUrl } = require('./system.js');
|
|
38
|
+
const credentials = require('./credentials.js');
|
|
39
|
+
|
|
40
|
+
/** Resolve a shared module by existence (repo checkout or the staged tree). */
|
|
41
|
+
function loadShared(rel) {
|
|
42
|
+
return require(resolveShared(rel));
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** The same thin client the session and the entitlement gate use. */
|
|
46
|
+
function createCliClient() {
|
|
47
|
+
const { createClient } = loadShared('client/aegis.js');
|
|
48
|
+
return createClient(credentials.clientOptions({ channel: 'cli' }));
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* A key is needed to create a checkout at all, so a fresh machine gets the same
|
|
53
|
+
* free device key the session path asks for — one implementation, the shared
|
|
54
|
+
* auto-provision helper (client/auto-provision.js), and one attempt.
|
|
55
|
+
*
|
|
56
|
+
* Best-effort by design: if the helper is unreachable or the server declines,
|
|
57
|
+
* this returns false and the caller says so, rather than throwing a module error
|
|
58
|
+
* at a user who is trying to give us money.
|
|
59
|
+
*/
|
|
60
|
+
async function ensureKey(client, store) {
|
|
61
|
+
if (client.apiKey) return true;
|
|
62
|
+
try {
|
|
63
|
+
const mod = loadShared('client/auto-provision.js');
|
|
64
|
+
const provision = mod.autoProvisionApiKey || mod.default;
|
|
65
|
+
if (typeof provision === 'function') {
|
|
66
|
+
const res = await provision(client, store);
|
|
67
|
+
if (res && res.key && typeof client.setApiKey === 'function') client.setApiKey(res.key);
|
|
68
|
+
}
|
|
69
|
+
} catch {
|
|
70
|
+
/* fall through: the caller reports the missing credential plainly */
|
|
71
|
+
}
|
|
72
|
+
return Boolean(client.apiKey);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Run the command and return a process exit code.
|
|
77
|
+
*
|
|
78
|
+
* @param {string|null} arg the typed amount (null ⇒ the server default, 10 EUR)
|
|
79
|
+
* @param {object} [io] injectable for tests: `stdout`, `stderr`, `client`,
|
|
80
|
+
* `openUrl`, `sleep`, `intervalMs`, `maxTries`, `json`, `onStep`.
|
|
81
|
+
*/
|
|
82
|
+
async function runTopupCommand(arg, io) {
|
|
83
|
+
const options = io || {};
|
|
84
|
+
const stdout = options.stdout || process.stdout;
|
|
85
|
+
const stderr = options.stderr || process.stderr;
|
|
86
|
+
// JSON mode is a script's stdout: one object (written by finish()) and no
|
|
87
|
+
// human chatter, so a parser never has to skip progress lines. Errors still
|
|
88
|
+
// go to stderr, which is not the stream being parsed.
|
|
89
|
+
const out = options.json ? () => {} : (s) => stdout.write(s);
|
|
90
|
+
let payload = null;
|
|
91
|
+
|
|
92
|
+
// JSON mode prints ONE object and nothing else, so a script parsing stdout
|
|
93
|
+
// does not have to skip progress chatter.
|
|
94
|
+
const finish = (code, result) => {
|
|
95
|
+
if (options.json) stdout.write(JSON.stringify(result) + '\n');
|
|
96
|
+
return code;
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
let shared;
|
|
100
|
+
try {
|
|
101
|
+
shared = loadShared('client/topup.js');
|
|
102
|
+
} catch (error) {
|
|
103
|
+
stderr.write(`aegiscode: the shared top-up module is missing — ${(error && error.message) || error}\n`);
|
|
104
|
+
return 2;
|
|
105
|
+
}
|
|
106
|
+
const {
|
|
107
|
+
parseTopupAmount,
|
|
108
|
+
startTopup,
|
|
109
|
+
createCreditWatch,
|
|
110
|
+
TOPUP_POLL_MS,
|
|
111
|
+
TOPUP_POLL_TRIES,
|
|
112
|
+
TOPUP_MIN_EUR,
|
|
113
|
+
TOPUP_MAX_EUR,
|
|
114
|
+
} = shared;
|
|
115
|
+
|
|
116
|
+
const parsed = parseTopupAmount(arg);
|
|
117
|
+
if (!parsed.ok) {
|
|
118
|
+
stderr.write(
|
|
119
|
+
`aegiscode: ${parsed.message}\n` +
|
|
120
|
+
` usage: aegiscode topup [${TOPUP_MIN_EUR}..${TOPUP_MAX_EUR}] (default 10)\n`
|
|
121
|
+
);
|
|
122
|
+
// JSON mode still emits its ONE object here: a script that checks the exit
|
|
123
|
+
// code must not be the only way to learn why — "no stdout at all" reads as
|
|
124
|
+
// a crash, not as a rejected amount.
|
|
125
|
+
return finish(2, { ok: false, credited: false, amount_eur: null, url: null, balance_eur: null, error: parsed.message });
|
|
126
|
+
}
|
|
127
|
+
payload = { ok: false, credited: false, amount_eur: parsed.amount, url: null, balance_eur: null };
|
|
128
|
+
|
|
129
|
+
// Say something BEFORE the first network call. The transport's ceiling is 60s
|
|
130
|
+
// per request and this path can make two (auto-provision, then the checkout),
|
|
131
|
+
// so an unreachable server used to mean two silent minutes and then a line —
|
|
132
|
+
// which a user reads as a hung command, not as a network problem. stderr, not
|
|
133
|
+
// stdout: in --json mode stdout is a script's parse target.
|
|
134
|
+
stderr.write(`aegiscode: requesting a ${parsed.amount} EUR top-up from the account service…\n`);
|
|
135
|
+
|
|
136
|
+
const client = options.client || createCliClient();
|
|
137
|
+
if (!client.apiKey && !(await ensureKey(client, credentials))) {
|
|
138
|
+
stderr.write(
|
|
139
|
+
'aegiscode: no AEGIS key on this machine and none could be provisioned —\n' +
|
|
140
|
+
' `aegiscode login <api_key>` (from https://aegiscloud.org/dashboard) first\n'
|
|
141
|
+
);
|
|
142
|
+
payload.error = 'no usable AEGIS key';
|
|
143
|
+
return finish(2, payload);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const started = await startTopup(client, parsed.amount);
|
|
147
|
+
if (!started.ok) {
|
|
148
|
+
stderr.write(`aegiscode: the top-up could not be started — ${started.message}\n`);
|
|
149
|
+
if (started.hint) stderr.write(`aegiscode: ${started.hint}\n`);
|
|
150
|
+
payload.error = started.message;
|
|
151
|
+
payload.status = started.status;
|
|
152
|
+
return finish(2, payload);
|
|
153
|
+
}
|
|
154
|
+
payload.url = started.url;
|
|
155
|
+
|
|
156
|
+
const open = options.openUrl || defaultOpenUrl;
|
|
157
|
+
const sleep = options.sleep || ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
158
|
+
const intervalMs = options.intervalMs == null ? TOPUP_POLL_MS : options.intervalMs;
|
|
159
|
+
const maxTries = options.maxTries == null ? TOPUP_POLL_TRIES : options.maxTries;
|
|
160
|
+
const windowSeconds = Math.max(1, Math.round((intervalMs * maxTries) / 1000));
|
|
161
|
+
|
|
162
|
+
// `openUrl` returns false when the platform opener is missing (a container, a
|
|
163
|
+
// server over ssh); the URL is then the ONLY way to pay, so it is printed
|
|
164
|
+
// rather than swallowed — a command that silently does nothing is worse than
|
|
165
|
+
// one that says "paste this".
|
|
166
|
+
if (open(started.url)) {
|
|
167
|
+
out(`aegiscode: opening the payment page in your browser — ${started.amount} EUR\n`);
|
|
168
|
+
} else {
|
|
169
|
+
out(`aegiscode: open this to pay ${started.amount} EUR:\n ${started.url}\n`);
|
|
170
|
+
}
|
|
171
|
+
out(`aegiscode: watching this account's bank for up to ${windowSeconds}s to confirm the credit\n`);
|
|
172
|
+
|
|
173
|
+
const watch = createCreditWatch(client, { maxTries });
|
|
174
|
+
let announcedBaseline = false;
|
|
175
|
+
for (;;) {
|
|
176
|
+
const step = await watch.tick();
|
|
177
|
+
if (typeof options.onStep === 'function') options.onStep(step);
|
|
178
|
+
if (step.state === 'credited') {
|
|
179
|
+
payload.ok = true;
|
|
180
|
+
payload.credited = true;
|
|
181
|
+
payload.balance_eur = step.amount;
|
|
182
|
+
out(
|
|
183
|
+
`aegiscode: credit confirmed — the bank is now ${step.amount.toFixed(2)} EUR\n` +
|
|
184
|
+
'aegiscode: (this account was created by this machine, so the browser there has no\n' +
|
|
185
|
+
' session for it — the confirmation comes from the API, not the page)\n'
|
|
186
|
+
);
|
|
187
|
+
return finish(0, payload);
|
|
188
|
+
}
|
|
189
|
+
if (step.state === 'expired') {
|
|
190
|
+
// Honest about what is and is not known: the window closed on OUR watch,
|
|
191
|
+
// which is not the same claim as "you were not charged".
|
|
192
|
+
out(
|
|
193
|
+
`aegiscode: no credit observed within ${windowSeconds}s — if you completed the payment it\n` +
|
|
194
|
+
'aegiscode: may still land; re-run `aegiscode topup` or check `/billing` in a session\n'
|
|
195
|
+
);
|
|
196
|
+
payload.error = 'no credit observed within the watch window';
|
|
197
|
+
return finish(1, payload);
|
|
198
|
+
}
|
|
199
|
+
if (step.baseline != null && !announcedBaseline && !options.json) {
|
|
200
|
+
announcedBaseline = true;
|
|
201
|
+
out(`aegiscode: bank before the payment: ${step.baseline.toFixed(2)} EUR\n`);
|
|
202
|
+
}
|
|
203
|
+
await sleep(intervalMs);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
module.exports = { runTopupCommand, ensureKey, createCliClient };
|
|
@@ -909,6 +909,13 @@ function baseName(input) {
|
|
|
909
909
|
|
|
910
910
|
const api = {
|
|
911
911
|
IS_WIN32,
|
|
912
|
+
// The seam bag itself (`seams(options)` above), exported since ON6/ON7 of the
|
|
913
|
+
// AEGISONE plan: `one/src/host.js` is the product's single OS answer and it
|
|
914
|
+
// has to *ask* here rather than keep a second `process.platform` read. The
|
|
915
|
+
// bag is what makes the answer injectable (`seams({ platform: 'win32' })`),
|
|
916
|
+
// and the function itself was always the point of this module — it simply
|
|
917
|
+
// was not reachable from outside it.
|
|
918
|
+
seams,
|
|
912
919
|
resolveExecutable,
|
|
913
920
|
shellSpec,
|
|
914
921
|
killTree,
|
|
@@ -0,0 +1,348 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* prefs.js — the ONE shared, non-secret preference store (AEGISONE, decision
|
|
5
|
+
* D5: "one store for preferences; secrets stay where the OS can decrypt them").
|
|
6
|
+
*
|
|
7
|
+
* Both faces read and write this file:
|
|
8
|
+
*
|
|
9
|
+
* the window desktop/lib/settings.js (the memory-persist preference, and the
|
|
10
|
+
* CLI-key accessors `getSharedPref`/
|
|
11
|
+
* `setSharedPref` the store exposes)
|
|
12
|
+
* the shell cli/src/config.js (theme, model/class pin, effort, vim,
|
|
13
|
+
* memoryPersist)
|
|
14
|
+
*
|
|
15
|
+
* and `desktop/lib/sync/persist-gate.js` reads it directly, in the main process,
|
|
16
|
+
* before it opens a socket.
|
|
17
|
+
*
|
|
18
|
+
* WHY A THIRD FILE, when the repo already has credentials.json and sessions.json
|
|
19
|
+
* in the same directory: those two are a *secret* store and a *content* store.
|
|
20
|
+
* This one is neither. Splitting the desktop's single `<userData>/settings.json`
|
|
21
|
+
* along the line D5 already drew for sessions and credentials is what makes the
|
|
22
|
+
* split honest:
|
|
23
|
+
*
|
|
24
|
+
* $AEGISCODE_HOME/preferences.json non-secret preferences (this file)
|
|
25
|
+
* <userData>/settings.json host-local: `safeStorage` blobs (a plain
|
|
26
|
+
* Node process, i.e. the CLI, cannot decrypt
|
|
27
|
+
* those on Linux) + machine/UI state
|
|
28
|
+
*
|
|
29
|
+
* The boundary is enforced, not documented: `set()` refuses to write anything
|
|
30
|
+
* that looks like key material (`scanForSecrets`/`assertNoSecrets` below), so a
|
|
31
|
+
* caller that tries to park an API key in the shared store gets a thrown error
|
|
32
|
+
* rather than a plaintext secret in a file the other host reads. A preference
|
|
33
|
+
* store that *can* carry a key is a second place to leak one; this one cannot.
|
|
34
|
+
*
|
|
35
|
+
* Adoption of a pre-unification `<userData>/settings.json` is one-way, once and
|
|
36
|
+
* idempotent — the pattern `client/session-store.js` already proves and
|
|
37
|
+
* `test/shared-store.test.mjs` property D already asserts. There is no merge
|
|
38
|
+
* loop and no last-writer-wins ping-pong: shared values are never copied back
|
|
39
|
+
* into the legacy file, and a second adoption attempt is refused.
|
|
40
|
+
*/
|
|
41
|
+
|
|
42
|
+
const fs = require('node:fs');
|
|
43
|
+
const path = require('node:path');
|
|
44
|
+
|
|
45
|
+
// The data dir is defined once, in the shared credential module — the same rule
|
|
46
|
+
// cli/src/config.js and desktop/lib/sync/sessions.js follow, so the two faces
|
|
47
|
+
// cannot drift about where the store lives (`$AEGISCODE_HOME`, else
|
|
48
|
+
// `~/.aegiscode`).
|
|
49
|
+
const { aegisHome } = require('./credentials.js');
|
|
50
|
+
|
|
51
|
+
const PREFS_FILE = 'preferences.json';
|
|
52
|
+
const PREFS_VERSION = 1;
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* The non-secret preference keys the shell's `config.js` keeps in the shared
|
|
56
|
+
* store (everything else in its config — `updateCheck`, `lastCwd`, a legacy
|
|
57
|
+
* `provider`/`baseURL` row — stays in `config.json`, which is host-local).
|
|
58
|
+
*
|
|
59
|
+
* This list is also the access-control list for the desktop's generic
|
|
60
|
+
* `getSharedPref`/`setSharedPref`, so the window can read exactly the
|
|
61
|
+
* preferences the shell owns and not reach into anyone else's state.
|
|
62
|
+
*/
|
|
63
|
+
const SHARED_PREF_KEYS = Object.freeze([
|
|
64
|
+
'themeIndex',
|
|
65
|
+
'model',
|
|
66
|
+
'modelClass',
|
|
67
|
+
'currentModelId',
|
|
68
|
+
'models',
|
|
69
|
+
'effort',
|
|
70
|
+
'vim',
|
|
71
|
+
'memoryPersist',
|
|
72
|
+
// ON8 / D8 rule 1: the confirmation gate is a POSTURE, not a surface. The
|
|
73
|
+
// window's "confirm before running tools" switch and the shell's rule set
|
|
74
|
+
// answer the same question ("may this call run unattended?"), so the switch
|
|
75
|
+
// lives beside the rules that gate answers, in the one store both hosts read.
|
|
76
|
+
'confirmMode',
|
|
77
|
+
]);
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* The legacy desktop namespace D5 retires: `<userData>/settings.json`'s
|
|
81
|
+
* `__memoryPersist: { enabled }` becomes the shared store's `memoryPersist`
|
|
82
|
+
* boolean — the shell's own spelling (`cli/src/config.js` `MEMORY_PERSIST_KEY`),
|
|
83
|
+
* so one preference has one representation instead of two that could disagree.
|
|
84
|
+
*/
|
|
85
|
+
const LEGACY_MEMORY_PERSIST_NAMESPACE = '__memoryPersist';
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* The second legacy namespace this store retires (ON8): the window's
|
|
89
|
+
* `__confirmMode: { enabled }` becomes the shared `confirmMode` boolean. Same
|
|
90
|
+
* rule, same reason as memory-persist above — and it is the one that closes
|
|
91
|
+
* D8's rule 1 in the direction that used to be impossible: a posture set in
|
|
92
|
+
* the window is now the posture the shell reads.
|
|
93
|
+
*/
|
|
94
|
+
const LEGACY_CONFIRM_MODE_NAMESPACE = '__confirmMode';
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Key names that mean "secret" wherever they appear in the tree. Deliberately
|
|
98
|
+
* conservative: `keyMask`-style *previews* never reach this file (they are not
|
|
99
|
+
* preferences), and no legitimate preference is named `token`/`secret`/`auth`.
|
|
100
|
+
*/
|
|
101
|
+
const SECRET_KEY_RE =
|
|
102
|
+
/(^|[^a-z0-9])(api[_-]?key|apikey|key|keys|token|secret|password|passwd|credential|credentials|authorization|bearer|private[_-]?key|access[_-]?key|session[_-]?key)([^a-z0-9]|$)/i;
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Values that are key material whatever they are called. Every shape here is a
|
|
106
|
+
* real prefix this product's hosts mint or accept: AEGIS Cloud keys
|
|
107
|
+
* (`aegis_…`), OpenAI/BYOK keys (`sk-…`), GitHub/Anthropic strings (`ghp_`,
|
|
108
|
+
* `sk-ant-…`), JWTs (`eyJ…`, which is what an OAuth-ish provider returns), and
|
|
109
|
+
* a bare long base64 blob (which is what Electron's `safeStorage` ciphertext —
|
|
110
|
+
* and a base64-encoded key, the exact fallback `settings.js` uses when
|
|
111
|
+
* `safeStorage` is unavailable — looks like).
|
|
112
|
+
*/
|
|
113
|
+
const SECRET_VALUE_RES = [
|
|
114
|
+
/\baegis_[A-Za-z0-9_\-]{12,}/,
|
|
115
|
+
/\bsk-[A-Za-z0-9_\-]{12,}/,
|
|
116
|
+
/\bghp_[A-Za-z0-9_\-]{20,}/,
|
|
117
|
+
/\bxox[baprs]-[A-Za-z0-9\-]{10,}/,
|
|
118
|
+
/\beyJ[A-Za-z0-9_\-]{16,}\.[A-Za-z0-9_\-]{8,}/,
|
|
119
|
+
/^[A-Za-z0-9+/]{48,}={0,2}$/,
|
|
120
|
+
];
|
|
121
|
+
|
|
122
|
+
/** The shared dir: an explicit `dir`, else `$AEGISCODE_HOME`/`~/.aegiscode`. */
|
|
123
|
+
function prefsDir(opts) {
|
|
124
|
+
const o = opts || {};
|
|
125
|
+
if (o.dir && String(o.dir).trim()) return path.resolve(String(o.dir).trim());
|
|
126
|
+
return aegisHome(o.env);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** The shared file. `prefsFile({ dir, env })`. */
|
|
130
|
+
function prefsFile(opts) {
|
|
131
|
+
const o = opts || {};
|
|
132
|
+
if (o.file && String(o.file).trim()) return path.resolve(String(o.file).trim());
|
|
133
|
+
return path.join(prefsDir(o), PREFS_FILE);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Every finding in `value` that looks like key material, as dotted paths.
|
|
138
|
+
* An empty array means "nothing key-shaped in here" — the property the exit
|
|
139
|
+
* criteria assert about the shared file, with a negative control that shows the
|
|
140
|
+
* scan can fail.
|
|
141
|
+
*/
|
|
142
|
+
function scanForSecrets(value, atPath = '', found = []) {
|
|
143
|
+
if (value == null) return found;
|
|
144
|
+
if (typeof value === 'string') {
|
|
145
|
+
if (SECRET_VALUE_RES.some((re) => re.test(value))) found.push(atPath || '(root)');
|
|
146
|
+
return found;
|
|
147
|
+
}
|
|
148
|
+
if (typeof value !== 'object') return found;
|
|
149
|
+
if (Array.isArray(value)) {
|
|
150
|
+
value.forEach((v, i) => scanForSecrets(v, `${atPath}[${i}]`, found));
|
|
151
|
+
return found;
|
|
152
|
+
}
|
|
153
|
+
for (const [k, v] of Object.entries(value)) {
|
|
154
|
+
const here = atPath ? `${atPath}.${k}` : k;
|
|
155
|
+
// An empty/absent value is not key material — `{ key: null }` is how this
|
|
156
|
+
// repo clears a stored credential, and refusing that would be noise.
|
|
157
|
+
if (SECRET_KEY_RE.test(k) && v != null && v !== '' && v !== false) {
|
|
158
|
+
found.push(here);
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
scanForSecrets(v, here, found);
|
|
162
|
+
}
|
|
163
|
+
return found;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Throw when `value` carries key material. The writer's fail-closed gate. */
|
|
167
|
+
function assertNoSecrets(value, what = 'shared preference store') {
|
|
168
|
+
const found = scanForSecrets(value);
|
|
169
|
+
if (found.length) {
|
|
170
|
+
throw new Error(
|
|
171
|
+
`${what} must not carry key material — refusing to write (found: ${found.join(', ')}). ` +
|
|
172
|
+
'Secrets belong in the host-local credential store, where the OS can protect them.'
|
|
173
|
+
);
|
|
174
|
+
}
|
|
175
|
+
return value;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function readJson(file, fallback) {
|
|
179
|
+
try {
|
|
180
|
+
const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
181
|
+
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : fallback;
|
|
182
|
+
} catch {
|
|
183
|
+
return fallback;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Read the shared store. Never throws: a corrupt file reads as empty. */
|
|
188
|
+
function load(opts) {
|
|
189
|
+
return readJson(prefsFile(opts), {});
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Write the shared store atomically and 0600.
|
|
194
|
+
*
|
|
195
|
+
* 0600 rather than 0644 even though nothing secret belongs here: the file
|
|
196
|
+
* decides whether a user's turns are persisted to the cloud (`memoryPersist`)
|
|
197
|
+
* and which provider row the local class dials, so a writable copy is another
|
|
198
|
+
* local account's way to change how this host behaves. The mode is the control;
|
|
199
|
+
* the scan above is the boundary.
|
|
200
|
+
*/
|
|
201
|
+
function write(next, opts) {
|
|
202
|
+
assertNoSecrets(next);
|
|
203
|
+
const file = prefsFile(opts);
|
|
204
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
205
|
+
const tmp = `${file}.tmp-${process.pid}`;
|
|
206
|
+
fs.writeFileSync(tmp, JSON.stringify(next, null, 2) + '\n', { mode: 0o600 });
|
|
207
|
+
fs.renameSync(tmp, file);
|
|
208
|
+
try {
|
|
209
|
+
fs.chmodSync(file, 0o600);
|
|
210
|
+
} catch {
|
|
211
|
+
/* Windows: POSIX modes are a no-op, ACLs are the OS's business */
|
|
212
|
+
}
|
|
213
|
+
return next;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** Merge a patch into the shared store and return the merged view. */
|
|
217
|
+
function set(patch, opts) {
|
|
218
|
+
const next = { ...load(opts), ...(patch || {}) };
|
|
219
|
+
// `undefined` in a patch is how callers retire a key (JSON.stringify drops
|
|
220
|
+
// it), so drop those before the scan and the write.
|
|
221
|
+
for (const k of Object.keys(next)) if (next[k] === undefined) delete next[k];
|
|
222
|
+
if (next.version === undefined) next.version = PREFS_VERSION;
|
|
223
|
+
return write(next, opts);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** One shared preference value, or `fallback`. */
|
|
227
|
+
function get(key, opts, fallback) {
|
|
228
|
+
const v = load(opts)[key];
|
|
229
|
+
return v === undefined ? fallback : v;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** True when the store holds an explicit value for `key`. */
|
|
233
|
+
function has(key, opts) {
|
|
234
|
+
return load(opts)[key] !== undefined;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* Retire a key. Confined here (read-modify-write) so the two faces never
|
|
239
|
+
* clobber each other's namespaces with a whole-file overwrite.
|
|
240
|
+
*/
|
|
241
|
+
function remove(key, opts) {
|
|
242
|
+
const next = load(opts);
|
|
243
|
+
delete next[key];
|
|
244
|
+
return write(next, opts);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* The non-secret half of a legacy `<userData>/settings.json`, in the shared
|
|
249
|
+
* store's spellings. Only namespaces THIS store owns are extracted: the other
|
|
250
|
+
* app-level namespaces (`__avatar`, `__telemetry`,
|
|
251
|
+
* `__autoDrain`, `__autoMint`, `__quickLauncher`) stay host-local until their
|
|
252
|
+
* own phase moves them, and the provider rows are never here at all because a
|
|
253
|
+
* provider row is where a key lives.
|
|
254
|
+
*/
|
|
255
|
+
function extractNonSecretHalf(legacy) {
|
|
256
|
+
const out = {};
|
|
257
|
+
const src = (legacy || {})[LEGACY_MEMORY_PERSIST_NAMESPACE];
|
|
258
|
+
if (src && typeof src === 'object' && typeof src.enabled === 'boolean') {
|
|
259
|
+
out.memoryPersist = src.enabled;
|
|
260
|
+
}
|
|
261
|
+
// ON8: the confirmation gate adopts the same way. `enabled: true` means the
|
|
262
|
+
// gate is UP, which is the shared `confirmMode: true`; the shared key keeps
|
|
263
|
+
// the window's own polarity so an adopting install cannot flip its gate.
|
|
264
|
+
const gate = (legacy || {})[LEGACY_CONFIRM_MODE_NAMESPACE];
|
|
265
|
+
if (gate && typeof gate === 'object' && typeof gate.enabled === 'boolean') {
|
|
266
|
+
out.confirmMode = gate.enabled;
|
|
267
|
+
}
|
|
268
|
+
return out;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* One-way, once, idempotent adoption of the legacy desktop store's non-secret
|
|
273
|
+
* half.
|
|
274
|
+
*
|
|
275
|
+
* `adopt({ dir, env, legacyDir })`:
|
|
276
|
+
* - `dir`/`env` locate the SHARED store;
|
|
277
|
+
* - `legacyDir` is the old settings directory (Electron's `<userData>`; main
|
|
278
|
+
* passes the same dir its store was built with).
|
|
279
|
+
*
|
|
280
|
+
* One-way: the legacy file is read, never written — a preference that moved to
|
|
281
|
+
* the shared store is not mirrored back. Once: a key the shared store already
|
|
282
|
+
* carries is never overwritten, so a second run has nothing left to do and
|
|
283
|
+
* returns `adopted:false` without touching the file. That is what makes it
|
|
284
|
+
* idempotent rather than a periodic merge.
|
|
285
|
+
*/
|
|
286
|
+
function adopt(opts) {
|
|
287
|
+
const o = opts || {};
|
|
288
|
+
const shared = prefsFile(o);
|
|
289
|
+
const legacyDir = o.legacyDir;
|
|
290
|
+
const legacyFile = legacyDir ? path.join(String(legacyDir), 'settings.json') : null;
|
|
291
|
+
if (legacyFile && path.resolve(legacyFile) === shared) {
|
|
292
|
+
return { adopted: false, keys: [], from: legacyFile, reason: 'shared store is the legacy file' };
|
|
293
|
+
}
|
|
294
|
+
if (!legacyFile || !fs.existsSync(legacyFile)) {
|
|
295
|
+
return { adopted: false, keys: [], from: legacyFile, reason: 'no legacy settings file' };
|
|
296
|
+
}
|
|
297
|
+
const current = load(o);
|
|
298
|
+
const half = extractNonSecretHalf(readJson(legacyFile, {}));
|
|
299
|
+
// One-way means missing-only: an explicit shared value outranks the legacy
|
|
300
|
+
// one and is never clobbered by it.
|
|
301
|
+
const keys = Object.keys(half).filter((k) => current[k] === undefined);
|
|
302
|
+
if (!keys.length) {
|
|
303
|
+
return {
|
|
304
|
+
adopted: false,
|
|
305
|
+
keys: [],
|
|
306
|
+
from: legacyFile,
|
|
307
|
+
reason: Object.keys(half).length
|
|
308
|
+
? 'shared store already carries these preferences'
|
|
309
|
+
: 'legacy store has no shared preferences',
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
const patch = {};
|
|
313
|
+
for (const k of keys) patch[k] = half[k];
|
|
314
|
+
// `names`, NOT `keys` (AEGISONE ON8): this ledger is written through `write()`
|
|
315
|
+
// below, so it is scanned like everything else — and `SECRET_KEY_RE` matches
|
|
316
|
+
// `key`/`keys` by design, because a preference named `keys` IS how key material
|
|
317
|
+
// would smuggle itself into a file the desktop and the shell both read. Spelled
|
|
318
|
+
// `keys`, this field made `assertNoSecrets` refuse the store's own write, so
|
|
319
|
+
// EVERY adoption with something to adopt threw — the whole pre-D5 migration was
|
|
320
|
+
// dead, silently (settings.js's best-effort catch turned the throw into "no
|
|
321
|
+
// adoption" and no one was told). The scanner is the control here, not the bug;
|
|
322
|
+
// a field name is free to change.
|
|
323
|
+
patch.adopted = {
|
|
324
|
+
from: legacyFile,
|
|
325
|
+
at: new Date().toISOString(),
|
|
326
|
+
names: keys.slice().sort(),
|
|
327
|
+
};
|
|
328
|
+
write({ ...current, ...patch }, o);
|
|
329
|
+
return { adopted: true, keys: keys.slice().sort(), from: legacyFile };
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
module.exports = {
|
|
333
|
+
PREFS_FILE,
|
|
334
|
+
PREFS_VERSION,
|
|
335
|
+
SHARED_PREF_KEYS,
|
|
336
|
+
LEGACY_MEMORY_PERSIST_NAMESPACE,
|
|
337
|
+
prefsDir,
|
|
338
|
+
prefsFile,
|
|
339
|
+
load,
|
|
340
|
+
set,
|
|
341
|
+
get,
|
|
342
|
+
has,
|
|
343
|
+
remove,
|
|
344
|
+
scanForSecrets,
|
|
345
|
+
assertNoSecrets,
|
|
346
|
+
extractNonSecretHalf,
|
|
347
|
+
adopt,
|
|
348
|
+
};
|