aegiscode 6.8.30 → 6.8.31

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.
@@ -0,0 +1,318 @@
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
+ ]);
73
+
74
+ /**
75
+ * The legacy desktop namespace D5 retires: `<userData>/settings.json`'s
76
+ * `__memoryPersist: { enabled }` becomes the shared store's `memoryPersist`
77
+ * boolean — the shell's own spelling (`cli/src/config.js` `MEMORY_PERSIST_KEY`),
78
+ * so one preference has one representation instead of two that could disagree.
79
+ */
80
+ const LEGACY_MEMORY_PERSIST_NAMESPACE = '__memoryPersist';
81
+
82
+ /**
83
+ * Key names that mean "secret" wherever they appear in the tree. Deliberately
84
+ * conservative: `keyMask`-style *previews* never reach this file (they are not
85
+ * preferences), and no legitimate preference is named `token`/`secret`/`auth`.
86
+ */
87
+ const SECRET_KEY_RE =
88
+ /(^|[^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;
89
+
90
+ /**
91
+ * Values that are key material whatever they are called. Every shape here is a
92
+ * real prefix this product's hosts mint or accept: AEGIS Cloud keys
93
+ * (`aegis_…`), OpenAI/BYOK keys (`sk-…`), GitHub/Anthropic strings (`ghp_`,
94
+ * `sk-ant-…`), JWTs (`eyJ…`, which is what an OAuth-ish provider returns), and
95
+ * a bare long base64 blob (which is what Electron's `safeStorage` ciphertext —
96
+ * and a base64-encoded key, the exact fallback `settings.js` uses when
97
+ * `safeStorage` is unavailable — looks like).
98
+ */
99
+ const SECRET_VALUE_RES = [
100
+ /\baegis_[A-Za-z0-9_\-]{12,}/,
101
+ /\bsk-[A-Za-z0-9_\-]{12,}/,
102
+ /\bghp_[A-Za-z0-9_\-]{20,}/,
103
+ /\bxox[baprs]-[A-Za-z0-9\-]{10,}/,
104
+ /\beyJ[A-Za-z0-9_\-]{16,}\.[A-Za-z0-9_\-]{8,}/,
105
+ /^[A-Za-z0-9+/]{48,}={0,2}$/,
106
+ ];
107
+
108
+ /** The shared dir: an explicit `dir`, else `$AEGISCODE_HOME`/`~/.aegiscode`. */
109
+ function prefsDir(opts) {
110
+ const o = opts || {};
111
+ if (o.dir && String(o.dir).trim()) return path.resolve(String(o.dir).trim());
112
+ return aegisHome(o.env);
113
+ }
114
+
115
+ /** The shared file. `prefsFile({ dir, env })`. */
116
+ function prefsFile(opts) {
117
+ const o = opts || {};
118
+ if (o.file && String(o.file).trim()) return path.resolve(String(o.file).trim());
119
+ return path.join(prefsDir(o), PREFS_FILE);
120
+ }
121
+
122
+ /**
123
+ * Every finding in `value` that looks like key material, as dotted paths.
124
+ * An empty array means "nothing key-shaped in here" — the property the exit
125
+ * criteria assert about the shared file, with a negative control that shows the
126
+ * scan can fail.
127
+ */
128
+ function scanForSecrets(value, atPath = '', found = []) {
129
+ if (value == null) return found;
130
+ if (typeof value === 'string') {
131
+ if (SECRET_VALUE_RES.some((re) => re.test(value))) found.push(atPath || '(root)');
132
+ return found;
133
+ }
134
+ if (typeof value !== 'object') return found;
135
+ if (Array.isArray(value)) {
136
+ value.forEach((v, i) => scanForSecrets(v, `${atPath}[${i}]`, found));
137
+ return found;
138
+ }
139
+ for (const [k, v] of Object.entries(value)) {
140
+ const here = atPath ? `${atPath}.${k}` : k;
141
+ // An empty/absent value is not key material — `{ key: null }` is how this
142
+ // repo clears a stored credential, and refusing that would be noise.
143
+ if (SECRET_KEY_RE.test(k) && v != null && v !== '' && v !== false) {
144
+ found.push(here);
145
+ continue;
146
+ }
147
+ scanForSecrets(v, here, found);
148
+ }
149
+ return found;
150
+ }
151
+
152
+ /** Throw when `value` carries key material. The writer's fail-closed gate. */
153
+ function assertNoSecrets(value, what = 'shared preference store') {
154
+ const found = scanForSecrets(value);
155
+ if (found.length) {
156
+ throw new Error(
157
+ `${what} must not carry key material — refusing to write (found: ${found.join(', ')}). ` +
158
+ 'Secrets belong in the host-local credential store, where the OS can protect them.'
159
+ );
160
+ }
161
+ return value;
162
+ }
163
+
164
+ function readJson(file, fallback) {
165
+ try {
166
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
167
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : fallback;
168
+ } catch {
169
+ return fallback;
170
+ }
171
+ }
172
+
173
+ /** Read the shared store. Never throws: a corrupt file reads as empty. */
174
+ function load(opts) {
175
+ return readJson(prefsFile(opts), {});
176
+ }
177
+
178
+ /**
179
+ * Write the shared store atomically and 0600.
180
+ *
181
+ * 0600 rather than 0644 even though nothing secret belongs here: the file
182
+ * decides whether a user's turns are persisted to the cloud (`memoryPersist`)
183
+ * and which provider row the local class dials, so a writable copy is another
184
+ * local account's way to change how this host behaves. The mode is the control;
185
+ * the scan above is the boundary.
186
+ */
187
+ function write(next, opts) {
188
+ assertNoSecrets(next);
189
+ const file = prefsFile(opts);
190
+ fs.mkdirSync(path.dirname(file), { recursive: true });
191
+ const tmp = `${file}.tmp-${process.pid}`;
192
+ fs.writeFileSync(tmp, JSON.stringify(next, null, 2) + '\n', { mode: 0o600 });
193
+ fs.renameSync(tmp, file);
194
+ try {
195
+ fs.chmodSync(file, 0o600);
196
+ } catch {
197
+ /* Windows: POSIX modes are a no-op, ACLs are the OS's business */
198
+ }
199
+ return next;
200
+ }
201
+
202
+ /** Merge a patch into the shared store and return the merged view. */
203
+ function set(patch, opts) {
204
+ const next = { ...load(opts), ...(patch || {}) };
205
+ // `undefined` in a patch is how callers retire a key (JSON.stringify drops
206
+ // it), so drop those before the scan and the write.
207
+ for (const k of Object.keys(next)) if (next[k] === undefined) delete next[k];
208
+ if (next.version === undefined) next.version = PREFS_VERSION;
209
+ return write(next, opts);
210
+ }
211
+
212
+ /** One shared preference value, or `fallback`. */
213
+ function get(key, opts, fallback) {
214
+ const v = load(opts)[key];
215
+ return v === undefined ? fallback : v;
216
+ }
217
+
218
+ /** True when the store holds an explicit value for `key`. */
219
+ function has(key, opts) {
220
+ return load(opts)[key] !== undefined;
221
+ }
222
+
223
+ /**
224
+ * Retire a key. Confined here (read-modify-write) so the two faces never
225
+ * clobber each other's namespaces with a whole-file overwrite.
226
+ */
227
+ function remove(key, opts) {
228
+ const next = load(opts);
229
+ delete next[key];
230
+ return write(next, opts);
231
+ }
232
+
233
+ /**
234
+ * The non-secret half of a legacy `<userData>/settings.json`, in the shared
235
+ * store's spellings. Only namespaces THIS store owns are extracted: the other
236
+ * app-level namespaces (`__confirmMode`, `__avatar`, `__telemetry`,
237
+ * `__autoDrain`, `__autoMint`, `__quickLauncher`) stay host-local until their
238
+ * own phase moves them, and the provider rows are never here at all because a
239
+ * provider row is where a key lives.
240
+ */
241
+ function extractNonSecretHalf(legacy) {
242
+ const out = {};
243
+ const src = (legacy || {})[LEGACY_MEMORY_PERSIST_NAMESPACE];
244
+ if (src && typeof src === 'object' && typeof src.enabled === 'boolean') {
245
+ out.memoryPersist = src.enabled;
246
+ }
247
+ return out;
248
+ }
249
+
250
+ /**
251
+ * One-way, once, idempotent adoption of the legacy desktop store's non-secret
252
+ * half.
253
+ *
254
+ * `adopt({ dir, env, legacyDir })`:
255
+ * - `dir`/`env` locate the SHARED store;
256
+ * - `legacyDir` is the old settings directory (Electron's `<userData>`; main
257
+ * passes the same dir its store was built with).
258
+ *
259
+ * One-way: the legacy file is read, never written — a preference that moved to
260
+ * the shared store is not mirrored back. Once: a key the shared store already
261
+ * carries is never overwritten, so a second run has nothing left to do and
262
+ * returns `adopted:false` without touching the file. That is what makes it
263
+ * idempotent rather than a periodic merge.
264
+ */
265
+ function adopt(opts) {
266
+ const o = opts || {};
267
+ const shared = prefsFile(o);
268
+ const legacyDir = o.legacyDir;
269
+ const legacyFile = legacyDir ? path.join(String(legacyDir), 'settings.json') : null;
270
+ if (legacyFile && path.resolve(legacyFile) === shared) {
271
+ return { adopted: false, keys: [], from: legacyFile, reason: 'shared store is the legacy file' };
272
+ }
273
+ if (!legacyFile || !fs.existsSync(legacyFile)) {
274
+ return { adopted: false, keys: [], from: legacyFile, reason: 'no legacy settings file' };
275
+ }
276
+ const current = load(o);
277
+ const half = extractNonSecretHalf(readJson(legacyFile, {}));
278
+ // One-way means missing-only: an explicit shared value outranks the legacy
279
+ // one and is never clobbered by it.
280
+ const keys = Object.keys(half).filter((k) => current[k] === undefined);
281
+ if (!keys.length) {
282
+ return {
283
+ adopted: false,
284
+ keys: [],
285
+ from: legacyFile,
286
+ reason: Object.keys(half).length
287
+ ? 'shared store already carries these preferences'
288
+ : 'legacy store has no shared preferences',
289
+ };
290
+ }
291
+ const patch = {};
292
+ for (const k of keys) patch[k] = half[k];
293
+ patch.adopted = {
294
+ from: legacyFile,
295
+ at: new Date().toISOString(),
296
+ keys: keys.slice().sort(),
297
+ };
298
+ write({ ...current, ...patch }, o);
299
+ return { adopted: true, keys: keys.slice().sort(), from: legacyFile };
300
+ }
301
+
302
+ module.exports = {
303
+ PREFS_FILE,
304
+ PREFS_VERSION,
305
+ SHARED_PREF_KEYS,
306
+ LEGACY_MEMORY_PERSIST_NAMESPACE,
307
+ prefsDir,
308
+ prefsFile,
309
+ load,
310
+ set,
311
+ get,
312
+ has,
313
+ remove,
314
+ scanForSecrets,
315
+ assertNoSecrets,
316
+ extractNonSecretHalf,
317
+ adopt,
318
+ };
@@ -0,0 +1,294 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * topup.js — the shared token-bank top-up: what to ask for, how to read the
5
+ * answer, and how to know the money arrived.
6
+ *
7
+ * WHY THIS IS SHARED AND NOT HOST CODE. A top-up ends server-side: Stripe's
8
+ * webhook credits the bank (aegis1 `services/billing_service.py`,
9
+ * `add_funds()`), and the browser landing page is pure UI on top of that. But
10
+ * that page (`/topup`) is `@login_required` against a browser SESSION, and
11
+ * `POST /api/v1/auth/register-device` mints the account this product
12
+ * auto-provisions with a password that is never returned and an email at
13
+ * `@device.aegiscloud`. So the very account auto-provision creates cannot sign
14
+ * in to the page it was just sent to: following that link lands on a login
15
+ * wall, and the user concludes the payment failed while the money and the
16
+ * credit are both real.
17
+ *
18
+ * The key that STARTED the checkout is enough to READ the result —
19
+ * `login_required` accepts `X-API-Key`/Bearer, and the same credential
20
+ * authenticates `GET /api/token-bank/balance` — so each host confirms the
21
+ * credit itself. Three hosts need that: the desktop (`desktop/main.js`), the
22
+ * terminal (`aegiscode topup` / `/topup`), and whatever comes next.
23
+ *
24
+ * What must never differ between them, and therefore lives here:
25
+ *
26
+ * 1. the AMOUNT rule — aegis1 rejects anything outside 2..1000 EUR with 400,
27
+ * and a client that accepts 1 EUR is a round trip the user pays for with
28
+ * a rejection message;
29
+ * 2. the PAYLOAD reading (`bankAmount`) — aegis1 has shipped
30
+ * `balance_micros`, `balance_eur`, `balance` and a bare number, and two
31
+ * hosts guessing differently is how one screen shows a credit the other
32
+ * misses;
33
+ * 3. the UNKNOWN-vs-ZERO rule — an unreadable bank stays unknown. Reading it
34
+ * as zero would make the `{}` case look like a real baseline, so the FIRST
35
+ * credit would be silently swallowed as "no change", and elsewhere a zero
36
+ * manufactures a paywall out of a timeout;
37
+ * 4. the RISING-READ rule — announce on the first read strictly above the
38
+ * baseline, once, then stop.
39
+ *
40
+ * What is deliberately NOT here: the timer. The desktop's watch must live in
41
+ * the main process (test/auto.test.mjs asserts "neither renderer starts a timer
42
+ * of its own"), unref'd, because the window stays open and a payment may never
43
+ * complete. The terminal's must block, because the process exits and a
44
+ * detached timer would be killed before the credit lands. Those are two
45
+ * schedulers over one state machine — and the state machine (`createCreditWatch`)
46
+ * is the part that must not drift, so that is what this file owns.
47
+ *
48
+ * No I/O of its own and no host imports: it takes the client it is handed.
49
+ */
50
+
51
+ /** aegis1's own bounds (`app.py` token_bank_topup): outside these is a 400. */
52
+ const TOPUP_MIN_EUR = 2;
53
+ const TOPUP_MAX_EUR = 1000;
54
+ /** The server's default when the body omits the amount. */
55
+ const TOPUP_DEFAULT_EUR = 10;
56
+
57
+ /** Poll period and window for the credit watch: ~2 minutes, then stop asking. */
58
+ const TOPUP_POLL_MS = 4000;
59
+ const TOPUP_POLL_TRIES = 30;
60
+
61
+ /**
62
+ * Read a euro amount out of an aegis1 token-bank payload, across the shapes the
63
+ * server has used (`balance_micros`, `balance_eur`, `balance`, or a bare
64
+ * number). Returns null when nothing numeric is present — an unreadable bank
65
+ * must stay UNKNOWN rather than read as a zero.
66
+ */
67
+ function bankAmount(res) {
68
+ if (res == null) return null;
69
+ if (typeof res === 'number') return isFinite(res) ? res : null;
70
+ if (typeof res === 'string') {
71
+ const n = Number(res.trim());
72
+ return res.trim() !== '' && isFinite(n) ? n : null;
73
+ }
74
+ if (typeof res !== 'object') return null;
75
+ if (res.balance_micros != null) {
76
+ const n = Number(res.balance_micros);
77
+ return isFinite(n) ? n / 1e6 : null;
78
+ }
79
+ for (const key of ['balance_eur', 'balance', 'bank', 'balance_eur_cents']) {
80
+ if (!(key in res)) continue;
81
+ const n = Number(res[key]);
82
+ if (!isFinite(n)) continue;
83
+ return key === 'balance_eur_cents' ? n / 100 : n;
84
+ }
85
+ if (res.data) return bankAmount(res.data);
86
+ return null;
87
+ }
88
+
89
+ /**
90
+ * Parse a user-typed amount against the server's own bounds.
91
+ *
92
+ * Rejecting here rather than letting aegis1 answer 400 is not cosmetic: the
93
+ * whole point of `/topup 1` failing locally is that it says WHY in the same
94
+ * breath, instead of printing the server's "Amount must be between 2 and 1000
95
+ * EUR" after a round trip on a slow connection.
96
+ *
97
+ * @param {string|number} raw the typed argument ('' or undefined ⇒ the default)
98
+ * @param {number} [fallback] default when nothing was typed
99
+ * @returns {{ok:boolean, amount:number|null, message:string|null}}
100
+ */
101
+ function parseTopupAmount(raw, fallback) {
102
+ const str = String(raw == null ? '' : raw).trim();
103
+ if (!str) {
104
+ const d = fallback == null ? TOPUP_DEFAULT_EUR : Number(fallback);
105
+ return { ok: true, amount: d, message: null };
106
+ }
107
+ // A euro figure with the separators a person actually types: `$20`, `20 EUR`,
108
+ // `20eur`. No `\b` before the word — `25eur` has its boundary between the 5
109
+ // and the e, so a boundary-anchored pattern strips nothing and the figure is
110
+ // refused as "not an amount".
111
+ const cleaned = str.replace(/[€$]|eur(o|os)?\b/gi, '').trim();
112
+ const n = Number(cleaned);
113
+ if (!isFinite(n) || cleaned === '') {
114
+ return { ok: false, amount: null, message: `"${str}" is not an amount — give a number of euro, e.g. /topup 20` };
115
+ }
116
+ if (!Number.isInteger(n)) {
117
+ return { ok: false, amount: null, message: `${n} EUR is not whole — Stripe charges whole euro here (e.g. /topup 20)` };
118
+ }
119
+ if (n < TOPUP_MIN_EUR || n > TOPUP_MAX_EUR) {
120
+ return {
121
+ ok: false,
122
+ amount: null,
123
+ message: `${n} EUR is outside the accepted range — top-ups are ${TOPUP_MIN_EUR}..${TOPUP_MAX_EUR} EUR`,
124
+ };
125
+ }
126
+ return { ok: true, amount: n, message: null };
127
+ }
128
+
129
+ /**
130
+ * Classify a failed checkout the way a user needs to hear it. The shared client
131
+ * attaches `err.status` / `err.data` while the failure is still in the host, so
132
+ * the status is read here rather than string-matched out of a message later.
133
+ *
134
+ * `setupRequired` is aegis1's 503 `setup_required` — Stripe is not configured
135
+ * on the deployment, which is NOT the user's problem to fix and must not be
136
+ * reported as one.
137
+ *
138
+ * @returns {{status:number, message:string, hint:string|null, setupRequired:boolean}}
139
+ */
140
+ function classifyTopupError(err) {
141
+ const status = (err && (err.status || (err.response && err.response.status))) || 0;
142
+ const data = (err && err.data) || {};
143
+ const message = err && err.message ? err.message : String(err);
144
+ const setupRequired = Boolean(data.setup_required) || status === 503;
145
+ if (setupRequired) {
146
+ return {
147
+ status: status || 503,
148
+ message,
149
+ hint: 'this deployment has no payment provider configured — top-ups are unavailable here, not on your side',
150
+ setupRequired: true,
151
+ };
152
+ }
153
+ if (status === 400) {
154
+ return { status, message, hint: `pick an amount between ${TOPUP_MIN_EUR} and ${TOPUP_MAX_EUR} EUR`, setupRequired: false };
155
+ }
156
+ if (status === 401 || status === 403) {
157
+ return {
158
+ status,
159
+ message,
160
+ hint: 'the account key was refused — save a fresh one (aegiscode login) and try again',
161
+ setupRequired: false,
162
+ };
163
+ }
164
+ if (status === 402) {
165
+ return { status, message, hint: 'the server refused the checkout for this account — see /billing for the account state', setupRequired: false };
166
+ }
167
+ if (!status) {
168
+ return { status: 0, message, hint: 'the server could not be reached — check the connection and retry', setupRequired: false };
169
+ }
170
+ return { status, message, hint: null, setupRequired: false };
171
+ }
172
+
173
+ /**
174
+ * Create a token-bank checkout and hand back the Stripe-hosted URL.
175
+ *
176
+ * Never throws: a host that has to tell 401 from 400 from 503 must receive the
177
+ * fields, and an exception crossing an IPC boundary loses `status` and `data`.
178
+ *
179
+ * @param {object} aegis the client whose key pays
180
+ * @param {number} amount EUR, already validated by parseTopupAmount
181
+ * @returns {Promise<{ok:boolean, url:string|null, status:number, message:string|null,
182
+ * hint:string|null, setupRequired:boolean, amount:number}>}
183
+ */
184
+ async function startTopup(aegis, amount) {
185
+ const eur = amount == null ? TOPUP_DEFAULT_EUR : Number(amount);
186
+ if (!aegis || typeof aegis.tokenBankTopup !== 'function') {
187
+ return {
188
+ ok: false, url: null, status: 0, amount: eur, setupRequired: false,
189
+ message: 'this host has no billing client', hint: null,
190
+ };
191
+ }
192
+ try {
193
+ const data = await aegis.tokenBankTopup(eur);
194
+ const url = data && data.url ? String(data.url) : null;
195
+ if (!url) {
196
+ // A 2xx with no URL is a success shape we cannot act on. Saying so beats
197
+ // opening "undefined" in a browser and calling it a payment.
198
+ return {
199
+ ok: false, url: null, status: 0, amount: eur, setupRequired: false,
200
+ message: 'the server accepted the request but returned no checkout URL',
201
+ hint: 'check the account in the browser at /billing, then retry',
202
+ };
203
+ }
204
+ return { ok: true, url, status: 0, message: null, hint: null, setupRequired: false, amount: eur };
205
+ } catch (err) {
206
+ const info = classifyTopupError(err);
207
+ return { ok: false, url: null, amount: eur, ...info };
208
+ }
209
+ }
210
+
211
+ /**
212
+ * The credit watch, as a state machine a host drives.
213
+ *
214
+ * `tick()` reads the bank once and returns the next state; the HOST decides
215
+ * when to call it again (an unref'd interval in the desktop's main process, an
216
+ * awaited sleep loop in the terminal). One read per call, so a slow or failing
217
+ * balance call can never overlap itself and double-announce.
218
+ *
219
+ * States:
220
+ * `pending` — nothing conclusive yet; call again
221
+ * `credited` — the bank read strictly above the baseline: announce, then stop
222
+ * `expired` — the window ran out with no rising read
223
+ *
224
+ * A failed or unreadable read is `pending`, never a zero: offline is unknown,
225
+ * and unknown must not become a baseline (see the header).
226
+ *
227
+ * @param {object} aegis the client whose key read the balance
228
+ * @param {object} [opts]
229
+ * @param {number} [opts.maxTries] reads before giving up (default TOPUP_POLL_TRIES)
230
+ * @returns {{tick:function():Promise<{state:string,amount:number|null,baseline:number|null}>,
231
+ * stop:function():void, baseline:number|null, credited:number|null, tries:number}}
232
+ */
233
+ function createCreditWatch(aegis, opts) {
234
+ const options = opts || {};
235
+ const maxTries = options.maxTries || TOPUP_POLL_TRIES;
236
+ const state = { baseline: null, credited: null, tries: 0, stopped: false };
237
+ return {
238
+ get baseline() {
239
+ return state.baseline;
240
+ },
241
+ get credited() {
242
+ return state.credited;
243
+ },
244
+ get tries() {
245
+ return state.tries;
246
+ },
247
+ stop() {
248
+ state.stopped = true;
249
+ },
250
+ async tick() {
251
+ const answer = (s, amount) => ({ state: s, amount: amount == null ? null : amount, baseline: state.baseline });
252
+ if (state.stopped) return answer(state.credited != null ? 'credited' : 'stopped', state.credited);
253
+ state.tries += 1;
254
+ if (state.tries > maxTries) {
255
+ state.stopped = true;
256
+ return answer('expired', null);
257
+ }
258
+ let now = null;
259
+ try {
260
+ now = bankAmount(await aegis.tokenBankBalance());
261
+ } catch {
262
+ return answer('pending', null); // offline or restarting: the next read retries
263
+ }
264
+ if (now === null) return answer('pending', null);
265
+ if (state.baseline === null) {
266
+ // The first successful read is the pre-payment figure. Stripe checkout
267
+ // takes longer than one poll, so this is normally still the old balance
268
+ // — but if it is already higher we still announce on the NEXT read,
269
+ // because the baseline is what "higher" is measured against.
270
+ state.baseline = now;
271
+ return answer('pending', null);
272
+ }
273
+ if (now > state.baseline) {
274
+ state.stopped = true;
275
+ state.credited = now;
276
+ return answer('credited', now);
277
+ }
278
+ return answer('pending', null);
279
+ },
280
+ };
281
+ }
282
+
283
+ module.exports = {
284
+ TOPUP_MIN_EUR,
285
+ TOPUP_MAX_EUR,
286
+ TOPUP_DEFAULT_EUR,
287
+ TOPUP_POLL_MS,
288
+ TOPUP_POLL_TRIES,
289
+ bankAmount,
290
+ parseTopupAmount,
291
+ classifyTopupError,
292
+ startTopup,
293
+ createCreditWatch,
294
+ };