@astratra/credentials 0.2.0 → 0.4.0

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 CHANGED
@@ -166,6 +166,38 @@ sinon poser les dix clés d'un fournisseur demanderait dix e-mails, et le
166
166
  garde-fou finirait contourné plutôt qu'utilisé. Demander un nouveau code
167
167
  **referme** la fenêtre en cours.
168
168
 
169
+ ## L'écran qui les gère
170
+
171
+ Tout ce qui précède tourne sur le serveur. Ces fonctions-ci tournent dans
172
+ l'application — site ou mobile — et lisent ce que les routes renvoient.
173
+
174
+ ```js
175
+ const spaces = readSpaces(payload);
176
+
177
+ coverageOf(spaces[0]); // { done: 3, total: 5 } — la pastille de l'onglet
178
+ missingKeys(spaces); // ce qu'il reste à régler, tous espaces confondus
179
+ firstSpaceToOpen(spaces); // celui où il y a le plus à faire
180
+ unlockState(payload); // { unlocked: true, minutesLeft: 4 }
181
+ cleanUnlockCode(' 12 34 56'); // '123456'
182
+ ```
183
+
184
+ **La réponse du serveur est lue sans confiance en sa forme.** Un champ absent,
185
+ une source renommée, un `null` à la place d'un espace : chacun de ces cas
186
+ donnait un écran blanc avec une erreur de type derrière.
187
+
188
+ **Le doute profite au secret.** Une clé dont le drapeau `secret` manque est
189
+ **masquée**. Une clé mal étiquetée affichée en clair est une fuite ; masquée à
190
+ tort, c'est un désagrément mineur.
191
+
192
+ **Une clé volontairement débranchée compte comme manquante.** C'est un choix,
193
+ mais un choix qui laisse un service déconnecté : l'écran doit le montrer, pas
194
+ l'enterrer.
195
+
196
+ **La fenêtre de modification est jugée au moment de la LECTURE**, jamais à la
197
+ réception. Le serveur envoie une date, pas un compte à rebours : décider
198
+ « ouverte » à l'arrivée et s'y fier ensuite laisse un écran de réglages ouvert
199
+ une heure, persuadé qu'il a encore le droit d'écrire.
200
+
169
201
  ## Les routes
170
202
 
171
203
  ```js
@@ -186,6 +218,7 @@ app.use('/api/credentials', createCredentialsRoutes({
186
218
  | `POST /unlock` | vérifie le code, ouvre la fenêtre |
187
219
  | `PUT /:key` | enregistre une valeur |
188
220
  | `DELETE /:key` | débranche une clé |
221
+ | `GET /:key/balance` | relit le solde chez le fournisseur (avec `balances`) |
189
222
 
190
223
  `authorize` est **obligatoire** : ces clés engagent les paiements de toute la
191
224
  plateforme, pas ceux d'un locataire, et Astratra n'a pas d'avis sur qui possède
@@ -293,6 +326,82 @@ un passage interrompu se relance simplement.
293
326
  | `skipped` | marqueur de débranchement ou valeur vide |
294
327
  | `unreadable` | **aucun des deux ciphers ne la lit** — à examiner |
295
328
 
329
+ ## Le solde chez le fournisseur
330
+
331
+ Certains fournisseurs vendent un quota qui s'épuise — et certaines offres
332
+ gratuites ne se renouvellent jamais. Sans le chiffre à l'écran, on découvre la
333
+ panne le jour où le service cesse de répondre, et ce qui en dépendait se
334
+ dégrade sans rien dire.
335
+
336
+ ```js
337
+ const { createBalanceProbe, serperBalanceProbe } = require('@astratra/credentials');
338
+
339
+ const balances = createBalanceProbe({
340
+ vault,
341
+ catalog,
342
+ probes: {
343
+ // Premier exemple fourni : le stock de crédits Serper.
344
+ SERPER_API_KEY: serperBalanceProbe({ fetch }),
345
+ // N'importe quel autre fournisseur : un read() au-dessus d'un fetch injecté.
346
+ AUTRE_API_KEY: {
347
+ read: async (cle, { signal }) => lireQuota(cle, signal), // -> { balance, rateLimit? }
348
+ thresholds: { low: 1000, critical: 100 },
349
+ unit: 'requêtes',
350
+ renewable: true
351
+ }
352
+ }
353
+ });
354
+
355
+ app.use('/api/credentials', createCredentialsRoutes({ vault, challenge, authorize, balances }));
356
+ ```
357
+
358
+ `GET /` ajoute alors `balance` à chaque clé **en place** qui a une sonde :
359
+
360
+ ```js
361
+ { status: 'low', critical: true, balance: 199, rateLimit: 5, unit: 'credits',
362
+ renewable: false, code: null, checkedAt: '2026-09-28T10:00:00.000Z' }
363
+ ```
364
+
365
+ | `status` | Sens |
366
+ |---|---|
367
+ | `ok` | au-dessus des seuils |
368
+ | `low` | sous `low` ; `critical: true` sous `critical` |
369
+ | `empty` | zéro ou moins, quels que soient les seuils |
370
+ | `unknown` | aucune clé à sonder (absente ou débranchée) |
371
+ | `error` | le relevé a échoué — `code` dit pourquoi, `balance` vaut `null` |
372
+
373
+ Les codes d'échec : `unreachable`, `timeout`, `rejected` (avec `httpStatus`,
374
+ pour distinguer une clé révoquée d'une panne), `unreadable`, `no_balance`,
375
+ `failed`. Des codes, jamais du texte : l'écran traduit.
376
+
377
+ Ce que les tests fixent :
378
+
379
+ **Un relevé raté se dit, jamais de chiffre inventé.** Une réponse sans solde
380
+ exploitable est une erreur, pas un zéro.
381
+
382
+ **La clé sondée est celle que sert le coffre** : celle saisie dans
383
+ l'interface l'emporte sur le `.env`, une clé débranchée n'est pas sondée.
384
+
385
+ **La clé ne ressort jamais** : ni dans le résultat, ni dans un journal, ni dans
386
+ une erreur — ni sa valeur, ni une empreinte, ni sa longueur. Une empreinte est
387
+ gardée en mémoire seulement, pour remarquer qu'elle a changé : le relevé mis
388
+ en cache décrivait alors un autre compte.
389
+
390
+ **Un relevé est mis en cache** (`cacheMs`, 5 minutes), un échec moins
391
+ longtemps (`errorCacheMs`, 30 secondes) ; deux écrans qui demandent en même
392
+ temps partagent une seule requête ; un rafraîchissement forcé ne repart pas
393
+ chez le fournisseur à moins de `minRefreshMs` du précédent. Enregistrer ou
394
+ débrancher la clé oublie le relevé.
395
+
396
+ Côté écran, `readBalance(raw)` lit le solde sans croire sa forme — un statut
397
+ qui prétend un chiffre sans en porter un est lu comme illisible — et
398
+ `balanceAlerts(spaces)` liste ce qui demande attention, du plus urgent au
399
+ moins urgent : épuisé, critique, bas, illisible.
400
+
401
+ `readSpaces` lit aussi désormais les sources telles que le coffre les envoie
402
+ (`environment`, `disconnected`, `absent`) : auparavant une clé servie par le
403
+ `.env` s'affichait « absente ».
404
+
296
405
  ## Ce que ce package ne fait pas
297
406
 
298
407
  - Il ne fournit **aucun catalogue** de fournisseurs. Quelles clés existent et ce
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astratra/credentials",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "description": "Encrypted service keys stored in your database, editable from the interface, with no restart.",
5
5
  "engines": {
6
6
  "node": ">=20"
package/src/balance.js ADDED
@@ -0,0 +1,352 @@
1
+ /**
2
+ * What is left on a provider account, read at the provider, shown next to its key.
3
+ *
4
+ * Some providers sell a quota that runs out — worse, some free tiers never
5
+ * renew. Without the number on the settings screen, you learn the service is
6
+ * gone the day it stops answering, and whatever depended on it degrades in
7
+ * silence. So the screen that manages a key also says how much it has left.
8
+ *
9
+ * The package knows no provider's API. Each key that can be probed brings its
10
+ * own `read(value)` — an injected fetch underneath, never a hard-wired client —
11
+ * and this module does the rest the same way for all of them:
12
+ *
13
+ * - the value comes from the vault, so the key typed in the interface is the
14
+ * one probed, never a stale one left in the environment;
15
+ * - a failed reading is SAID, with a code. A number is never invented — an
16
+ * "about 2,400" from memory is exactly the silent failure this exists to
17
+ * prevent;
18
+ * - readings are cached. A balance does not move by the second and a probe
19
+ * can cost a request; a failed one is kept for less time, so a hiccup does
20
+ * not hide the number for long, while a dead provider is not hammered each
21
+ * time someone opens the screen;
22
+ * - two screens asking at once share one request.
23
+ *
24
+ * The key never leaves in a result, a log line or an error: not its value, not
25
+ * a fingerprint, not its length. A digest is kept in memory only, to notice
26
+ * that the key changed and the cached reading no longer describes it.
27
+ */
28
+ const crypto = require('crypto');
29
+
30
+ const OK = 'ok';
31
+ const LOW = 'low';
32
+ const EMPTY = 'empty';
33
+ const UNKNOWN = 'unknown';
34
+ const ERROR = 'error';
35
+
36
+ const BALANCE_STATUSES = Object.freeze([OK, LOW, EMPTY, UNKNOWN, ERROR]);
37
+
38
+ /** Why a reading failed. Codes, never prose: the screen translates them. */
39
+ const BALANCE_ERRORS = Object.freeze({
40
+ UNREACHABLE: 'unreachable',
41
+ TIMEOUT: 'timeout',
42
+ REJECTED: 'rejected',
43
+ UNREADABLE: 'unreadable',
44
+ NO_BALANCE: 'no_balance',
45
+ FAILED: 'failed'
46
+ });
47
+
48
+ const DEFAULT_CACHE_MS = 5 * 60 * 1000;
49
+ const DEFAULT_ERROR_CACHE_MS = 30 * 1000;
50
+ const DEFAULT_MIN_REFRESH_MS = 10 * 1000;
51
+ const DEFAULT_TIMEOUT_MS = 6000;
52
+
53
+ const NOOP_LOGGER = { warn() {} };
54
+
55
+ /** A failed reading, carrying a code and — for a refusal — the HTTP status. */
56
+ class BalanceProbeError extends Error {
57
+ constructor(code, detail = {}) {
58
+ super(`balance probe failed: ${code}`);
59
+ this.name = 'BalanceProbeError';
60
+ this.code = code;
61
+ if (Number.isInteger(detail.httpStatus)) this.httpStatus = detail.httpStatus;
62
+ }
63
+ }
64
+
65
+ /**
66
+ * The status of a balance against its thresholds.
67
+ *
68
+ * `critical` is a second, stricter line under `low`: "keep an eye on it" and
69
+ * "act now" are not the same message. At or under zero is empty, whatever the
70
+ * thresholds say.
71
+ */
72
+ function classifyBalance(balance, thresholds = {}) {
73
+ if (typeof balance !== 'number' || !Number.isFinite(balance)) return { status: ERROR, critical: false };
74
+ if (balance <= 0) return { status: EMPTY, critical: true };
75
+ const low = Number.isFinite(thresholds.low) ? thresholds.low : null;
76
+ const critical = Number.isFinite(thresholds.critical) ? thresholds.critical : null;
77
+ if (critical !== null && balance < critical) return { status: LOW, critical: true };
78
+ if (low !== null && balance < low) return { status: LOW, critical: false };
79
+ return { status: OK, critical: false };
80
+ }
81
+
82
+ function validateThresholds(key, thresholds) {
83
+ if (!thresholds) return {};
84
+ const { low, critical } = thresholds;
85
+ for (const [name, value] of [['low', low], ['critical', critical]]) {
86
+ if (value !== undefined && (typeof value !== 'number' || !Number.isFinite(value) || value < 0)) {
87
+ throw new Error(`createBalanceProbe: thresholds.${name} for "${key}" must be a non-negative number.`);
88
+ }
89
+ }
90
+ if (low !== undefined && critical !== undefined && critical > low) {
91
+ throw new Error(`createBalanceProbe: thresholds.critical for "${key}" cannot exceed thresholds.low.`);
92
+ }
93
+ return { ...(low !== undefined ? { low } : {}), ...(critical !== undefined ? { critical } : {}) };
94
+ }
95
+
96
+ /** Anything a probe throws, reduced to a code. The message is never kept: it may quote the request. */
97
+ function codeOf(error) {
98
+ if (error && Object.values(BALANCE_ERRORS).includes(error.code)) return error.code;
99
+ if (error && (error.name === 'TimeoutError' || error.name === 'AbortError')) return BALANCE_ERRORS.TIMEOUT;
100
+ return BALANCE_ERRORS.FAILED;
101
+ }
102
+
103
+ const digest = (value) => crypto.createHash('sha256').update(String(value)).digest('hex');
104
+
105
+ /**
106
+ * @param {object} options
107
+ * @param {Record<string, object>} options.probes key name -> {
108
+ * read(value, { signal }) -> { balance, rateLimit?, limit? },
109
+ * thresholds?: { low?, critical? }, unit?: string, renewable?: boolean,
110
+ * timeoutMs?: number }
111
+ * @param {object} [options.vault] anything with get(key) — the credential vault.
112
+ * @param {Function} [options.getValue] (key) => value, instead of a vault.
113
+ * @param {object} [options.catalog] when given, every probed key must be in it.
114
+ * @param {number} [options.cacheMs] how long a reading holds. Default 5 min.
115
+ * @param {number} [options.errorCacheMs] how long a failed reading holds. Default 30 s.
116
+ * @param {number} [options.minRefreshMs] a forced refresh closer than this to the
117
+ * last reading is served from the cache. Default 10 s.
118
+ * @param {Function} [options.now]
119
+ * @param {object} [options.logger] { warn } — key name and code only.
120
+ */
121
+ function createBalanceProbe(options = {}) {
122
+ const probes = options.probes && typeof options.probes === 'object' ? options.probes : null;
123
+ if (!probes || !Object.keys(probes).length) {
124
+ throw new Error('createBalanceProbe requires at least one probe in options.probes.');
125
+ }
126
+
127
+ let readValue;
128
+ if (typeof options.getValue === 'function') readValue = options.getValue;
129
+ else if (options.vault && typeof options.vault.get === 'function') readValue = (key) => options.vault.get(key);
130
+ else throw new Error('createBalanceProbe requires options.vault (with get) or options.getValue.');
131
+
132
+ const catalog = options.catalog || null;
133
+ const definitions = new Map();
134
+ for (const [key, probe] of Object.entries(probes)) {
135
+ if (!probe || typeof probe.read !== 'function') {
136
+ throw new Error(`createBalanceProbe: the probe for "${key}" needs a read(value) function.`);
137
+ }
138
+ if (catalog && typeof catalog.has === 'function' && !catalog.has(key)) {
139
+ throw new Error(`createBalanceProbe: "${key}" is not in the credential catalog.`);
140
+ }
141
+ definitions.set(key, {
142
+ read: probe.read,
143
+ thresholds: validateThresholds(key, probe.thresholds),
144
+ unit: probe.unit || null,
145
+ renewable: probe.renewable === undefined ? null : Boolean(probe.renewable),
146
+ timeoutMs: probe.timeoutMs || DEFAULT_TIMEOUT_MS
147
+ });
148
+ }
149
+
150
+ const cacheMs = options.cacheMs === undefined ? DEFAULT_CACHE_MS : options.cacheMs;
151
+ const errorCacheMs = options.errorCacheMs === undefined ? DEFAULT_ERROR_CACHE_MS : options.errorCacheMs;
152
+ const minRefreshMs = options.minRefreshMs === undefined ? DEFAULT_MIN_REFRESH_MS : options.minRefreshMs;
153
+ const now = options.now || (() => Date.now());
154
+ const logger = options.logger || NOOP_LOGGER;
155
+
156
+ /* key -> { fingerprint, report, at } */
157
+ const cache = new Map();
158
+ /* key -> { fingerprint, promise } */
159
+ const inFlight = new Map();
160
+
161
+ function report(key, fields) {
162
+ const definition = definitions.get(key);
163
+ return {
164
+ key,
165
+ status: fields.status,
166
+ critical: Boolean(fields.critical),
167
+ balance: fields.balance === undefined ? null : fields.balance,
168
+ rateLimit: fields.rateLimit === undefined ? null : fields.rateLimit,
169
+ limit: fields.limit === undefined ? null : fields.limit,
170
+ unit: definition.unit,
171
+ renewable: definition.renewable,
172
+ code: fields.code || null,
173
+ checkedAt: fields.checkedAt || null
174
+ };
175
+ }
176
+
177
+ async function probe(key, value) {
178
+ const definition = definitions.get(key);
179
+ const checkedAt = new Date(now()).toISOString();
180
+ let reading;
181
+ try {
182
+ reading = await definition.read(value, { signal: globalThis.AbortSignal.timeout(definition.timeoutMs) });
183
+ } catch (error) {
184
+ const code = codeOf(error);
185
+ logger.warn(`[credentials] balance of ${key} unreadable: ${code}`);
186
+ return report(key, { status: ERROR, code, checkedAt });
187
+ }
188
+ const balance = reading && reading.balance;
189
+ if (typeof balance !== 'number' || !Number.isFinite(balance)) {
190
+ logger.warn(`[credentials] balance of ${key} unreadable: ${BALANCE_ERRORS.NO_BALANCE}`);
191
+ return report(key, { status: ERROR, code: BALANCE_ERRORS.NO_BALANCE, checkedAt });
192
+ }
193
+ const { status, critical } = classifyBalance(balance, definition.thresholds);
194
+ const number = (field) => (typeof reading[field] === 'number' && Number.isFinite(reading[field]) ? reading[field] : null);
195
+ return report(key, { status, critical, balance, rateLimit: number('rateLimit'), limit: number('limit'), checkedAt });
196
+ }
197
+
198
+ /**
199
+ * The balance behind one key. Never rejects.
200
+ * @param {string} key
201
+ * @param {{ refresh?: boolean }} [opts] bypass the cache (bounded by minRefreshMs).
202
+ */
203
+ async function check(key, opts = {}) {
204
+ if (!definitions.has(key)) return null;
205
+
206
+ let value = null;
207
+ try {
208
+ value = await readValue(key);
209
+ } catch (_error) {
210
+ /* The vault does not throw on a read; a custom getValue might. */
211
+ logger.warn(`[credentials] balance of ${key}: key unreadable`);
212
+ return report(key, { status: ERROR, code: BALANCE_ERRORS.FAILED });
213
+ }
214
+ /* No key, or one deliberately unplugged: nothing to probe. That is a fact
215
+ about the key, not a failed reading — and it is never cached, so a key
216
+ typed a second later is probed at once. */
217
+ if (!value) {
218
+ cache.delete(key);
219
+ return report(key, { status: UNKNOWN });
220
+ }
221
+
222
+ const fingerprint = digest(value);
223
+ const cached = cache.get(key);
224
+ if (cached && cached.fingerprint === fingerprint) {
225
+ const age = now() - cached.at;
226
+ const ttl = cached.report.status === ERROR ? errorCacheMs : cacheMs;
227
+ const fresh = age < ttl;
228
+ if (fresh && !opts.refresh) return { ...cached.report };
229
+ if (opts.refresh && age < minRefreshMs) return { ...cached.report };
230
+ }
231
+
232
+ const running = inFlight.get(key);
233
+ if (running && running.fingerprint === fingerprint) return { ...(await running.promise) };
234
+
235
+ const promise = probe(key, value).then((result) => {
236
+ cache.set(key, { fingerprint, report: result, at: now() });
237
+ return result;
238
+ }).finally(() => {
239
+ if (inFlight.get(key) && inFlight.get(key).promise === promise) inFlight.delete(key);
240
+ });
241
+ inFlight.set(key, { fingerprint, promise });
242
+ return { ...(await promise) };
243
+ }
244
+
245
+ /** Several keys at once — every probed key by default. */
246
+ async function checkAll(keys, opts = {}) {
247
+ const names = (Array.isArray(keys) ? keys : [...definitions.keys()]).filter((key) => definitions.has(key));
248
+ const results = await Promise.all(names.map((key) => check(key, opts)));
249
+ return Object.fromEntries(names.map((key, index) => [key, results[index]]));
250
+ }
251
+
252
+ /** Drop the cached reading — after the key changed, for instance. */
253
+ function forget(key) {
254
+ if (key === undefined) cache.clear();
255
+ else cache.delete(key);
256
+ }
257
+
258
+ return {
259
+ check,
260
+ checkAll,
261
+ forget,
262
+ has: (key) => definitions.has(key),
263
+ keys: () => [...definitions.keys()]
264
+ };
265
+ }
266
+
267
+ /* ─────────────────────────── Serper, the first built-in probe ─────────────────────────── */
268
+
269
+ const SERPER_ACCOUNT_URL = 'https://google.serper.dev/account';
270
+
271
+ /**
272
+ * Serper's free tier is a one-off stock of credits that never renews: the
273
+ * provider this module was written for. Thresholds are the ones chosen when
274
+ * the stock was 2,500 credits; pass your own for a paid plan.
275
+ */
276
+ const SERPER_THRESHOLDS = Object.freeze({ low: 600, critical: 200 });
277
+
278
+ /**
279
+ * Reads the credits left on a Serper account. The account endpoint consumes
280
+ * no credit. Throws a BalanceProbeError with a code; never puts the key in it.
281
+ *
282
+ * @param {object} options
283
+ * @param {Function} options.fetch a WHATWG fetch — injected, never global by surprise.
284
+ * @param {string} [options.url]
285
+ */
286
+ function createSerperBalanceReader(options = {}) {
287
+ const fetchImpl = options.fetch;
288
+ if (typeof fetchImpl !== 'function') {
289
+ throw new Error('createSerperBalanceReader requires options.fetch.');
290
+ }
291
+ const url = options.url || SERPER_ACCOUNT_URL;
292
+
293
+ return async function readSerperBalance(apiKey, { signal } = {}) {
294
+ let response;
295
+ try {
296
+ response = await fetchImpl(url, {
297
+ method: 'GET',
298
+ headers: { 'X-API-KEY': String(apiKey), 'Content-Type': 'application/json' },
299
+ ...(signal ? { signal } : {})
300
+ });
301
+ } catch (error) {
302
+ if (error && (error.name === 'TimeoutError' || error.name === 'AbortError')) {
303
+ throw new BalanceProbeError(BALANCE_ERRORS.TIMEOUT);
304
+ }
305
+ throw new BalanceProbeError(BALANCE_ERRORS.UNREACHABLE);
306
+ }
307
+ if (!response || response.status !== 200) {
308
+ throw new BalanceProbeError(BALANCE_ERRORS.REJECTED, { httpStatus: response && response.status });
309
+ }
310
+ let data;
311
+ try {
312
+ data = await response.json();
313
+ } catch (_error) {
314
+ throw new BalanceProbeError(BALANCE_ERRORS.UNREADABLE);
315
+ }
316
+ if (!data || typeof data.balance !== 'number' || !Number.isFinite(data.balance)) {
317
+ throw new BalanceProbeError(BALANCE_ERRORS.NO_BALANCE);
318
+ }
319
+ return {
320
+ balance: data.balance,
321
+ rateLimit: typeof data.rateLimit === 'number' && Number.isFinite(data.rateLimit) ? data.rateLimit : null
322
+ };
323
+ };
324
+ }
325
+
326
+ /** A ready probe definition for createBalanceProbe({ probes: { SERPER_API_KEY: serperBalanceProbe({ fetch }) } }). */
327
+ function serperBalanceProbe(options = {}) {
328
+ return {
329
+ read: createSerperBalanceReader(options),
330
+ thresholds: options.thresholds || SERPER_THRESHOLDS,
331
+ unit: 'credits',
332
+ renewable: options.renewable === undefined ? false : Boolean(options.renewable),
333
+ timeoutMs: options.timeoutMs || DEFAULT_TIMEOUT_MS
334
+ };
335
+ }
336
+
337
+ module.exports = {
338
+ createBalanceProbe,
339
+ classifyBalance,
340
+ BalanceProbeError,
341
+ BALANCE_STATUSES,
342
+ BALANCE_ERRORS,
343
+ BALANCE_OK: OK,
344
+ BALANCE_LOW: LOW,
345
+ BALANCE_EMPTY: EMPTY,
346
+ BALANCE_UNKNOWN: UNKNOWN,
347
+ BALANCE_ERROR: ERROR,
348
+ createSerperBalanceReader,
349
+ serperBalanceProbe,
350
+ SERPER_ACCOUNT_URL,
351
+ SERPER_THRESHOLDS
352
+ };
package/src/index.d.ts CHANGED
@@ -256,8 +256,112 @@ export function createCredentialsRoutes(options: {
256
256
  challenge?: UnlockChallenge | null;
257
257
  subjectOf?: (req: unknown) => string | number;
258
258
  logger?: { info?(message: string): void };
259
+ /** Adds `balance` next to each configured key that has a probe, and GET /:key/balance. */
260
+ balances?: BalanceProbe | null;
259
261
  }): Router;
260
262
 
263
+ /* ─────────────────── Provider balances ─────────────────── */
264
+
265
+ export type BalanceStatus = 'ok' | 'low' | 'empty' | 'unknown' | 'error';
266
+ export type BalanceErrorCode = 'unreachable' | 'timeout' | 'rejected' | 'unreadable' | 'no_balance' | 'failed';
267
+
268
+ export const BALANCE_STATUSES: readonly BalanceStatus[];
269
+ export const BALANCE_ERRORS: {
270
+ readonly UNREACHABLE: 'unreachable';
271
+ readonly TIMEOUT: 'timeout';
272
+ readonly REJECTED: 'rejected';
273
+ readonly UNREADABLE: 'unreadable';
274
+ readonly NO_BALANCE: 'no_balance';
275
+ readonly FAILED: 'failed';
276
+ };
277
+ export const BALANCE_OK: 'ok';
278
+ export const BALANCE_LOW: 'low';
279
+ export const BALANCE_EMPTY: 'empty';
280
+ export const BALANCE_UNKNOWN: 'unknown';
281
+ export const BALANCE_ERROR: 'error';
282
+
283
+ export class BalanceProbeError extends Error {
284
+ constructor(code: BalanceErrorCode | string, detail?: { httpStatus?: number });
285
+ code: BalanceErrorCode | string;
286
+ httpStatus?: number;
287
+ }
288
+
289
+ export interface BalanceThresholds {
290
+ /** Under this: "low". */
291
+ low?: number;
292
+ /** Under this: "low" and critical. Cannot exceed `low`. */
293
+ critical?: number;
294
+ }
295
+
296
+ export interface BalanceReading {
297
+ balance: number;
298
+ rateLimit?: number | null;
299
+ limit?: number | null;
300
+ }
301
+
302
+ export interface BalanceProbeDefinition {
303
+ /** Reads the provider. Throw a BalanceProbeError to say why it failed. */
304
+ read(value: string, context: { signal: AbortSignal }): Promise<BalanceReading> | BalanceReading;
305
+ thresholds?: BalanceThresholds;
306
+ unit?: string;
307
+ renewable?: boolean;
308
+ timeoutMs?: number;
309
+ }
310
+
311
+ /** Never carries the key: not its value, not a fingerprint, not its length. */
312
+ export interface BalanceReport {
313
+ key: string;
314
+ status: BalanceStatus;
315
+ critical: boolean;
316
+ balance: number | null;
317
+ rateLimit: number | null;
318
+ limit: number | null;
319
+ unit: string | null;
320
+ renewable: boolean | null;
321
+ code: BalanceErrorCode | string | null;
322
+ checkedAt: string | null;
323
+ }
324
+
325
+ export interface BalanceProbe {
326
+ /** Never rejects. Null for a key without a probe. */
327
+ check(key: string, options?: { refresh?: boolean }): Promise<BalanceReport | null>;
328
+ checkAll(keys?: string[], options?: { refresh?: boolean }): Promise<Record<string, BalanceReport>>;
329
+ forget(key?: string): void;
330
+ has(key: string): boolean;
331
+ keys(): string[];
332
+ }
333
+
334
+ export function createBalanceProbe(options: {
335
+ probes: Record<string, BalanceProbeDefinition>;
336
+ vault?: Pick<CredentialVault, 'get'>;
337
+ getValue?: (key: string) => Promise<string | null | undefined> | string | null | undefined;
338
+ catalog?: Pick<CredentialCatalog, 'has'>;
339
+ cacheMs?: number;
340
+ errorCacheMs?: number;
341
+ minRefreshMs?: number;
342
+ now?: () => number;
343
+ logger?: { warn?(message: string): void };
344
+ }): BalanceProbe;
345
+
346
+ export function classifyBalance(balance: unknown, thresholds?: BalanceThresholds): { status: BalanceStatus; critical: boolean };
347
+
348
+ export type FetchLike = (url: string, init?: {
349
+ method?: string;
350
+ headers?: Record<string, string>;
351
+ signal?: AbortSignal;
352
+ }) => Promise<{ status: number; json(): Promise<unknown> }>;
353
+
354
+ export const SERPER_ACCOUNT_URL: string;
355
+ export const SERPER_THRESHOLDS: Readonly<{ low: number; critical: number }>;
356
+ export function createSerperBalanceReader(options: { fetch: FetchLike; url?: string }): (apiKey: string, context?: { signal?: AbortSignal }) => Promise<{ balance: number; rateLimit: number | null }>;
357
+ export function serperBalanceProbe(options: {
358
+ fetch: FetchLike;
359
+ url?: string;
360
+ thresholds?: BalanceThresholds;
361
+ renewable?: boolean;
362
+ timeoutMs?: number;
363
+ }): BalanceProbeDefinition;
364
+
261
365
  export interface RotationReport {
262
366
  apply: boolean;
263
367
  scanned: number;
@@ -302,3 +406,55 @@ export function createCredentialRotation(options: {
302
406
  export function assertAdapter(adapter: unknown, methods: string[], name: string): void;
303
407
  export function maskSecret(value: string | null | undefined): string | null;
304
408
  export function maskEmail(email: string | null | undefined): string;
409
+
410
+ /* ─────────────────── Reading the state, for the screen ─────────────────── */
411
+
412
+ export type CredentialSource = 'interface' | 'serveur' | 'retiree' | 'absente';
413
+
414
+ export interface CredentialEntry {
415
+ key: string;
416
+ label: string;
417
+ /** Doubt favours the secret: an unlabelled key comes back masked. */
418
+ secret: boolean;
419
+ placeholder: string | null;
420
+ configured: boolean;
421
+ source: CredentialSource;
422
+ preview: string | null;
423
+ help: string | null;
424
+ where: string | null;
425
+ readOnly: boolean;
426
+ readOnlyReason: string | null;
427
+ /** Present only when the server read a balance for this key. */
428
+ balance?: BalanceView;
429
+ }
430
+
431
+ /** A balance the screen may show; a status claiming a number without one reads as 'error'. */
432
+ export interface BalanceView {
433
+ status: BalanceStatus;
434
+ critical: boolean;
435
+ balance: number | null;
436
+ rateLimit: number | null;
437
+ unit: string | null;
438
+ renewable: boolean | null;
439
+ code: string | null;
440
+ checkedAt: string | null;
441
+ }
442
+
443
+ export interface CredentialSpaceView {
444
+ id: string;
445
+ label: string;
446
+ hint: string;
447
+ keys: CredentialEntry[];
448
+ }
449
+
450
+ /** Reads the server answer without trusting its shape. */
451
+ export function readSpaces(payload: unknown): CredentialSpaceView[];
452
+ export function coverageOf(space: CredentialSpaceView | null | undefined): { done: number; total: number };
453
+ export function missingKeys(spaces: CredentialSpaceView[]): Array<CredentialEntry & { space: string }>;
454
+ export function firstSpaceToOpen(spaces: CredentialSpaceView[]): string | null;
455
+ /** Judged when it is read, never when it arrived. */
456
+ export function unlockState(raw: unknown, now?: number): { unlocked: boolean; minutesLeft: number };
457
+ export function cleanUnlockCode(input: unknown, length?: number): string;
458
+ export function readBalance(raw: unknown): BalanceView | undefined;
459
+ /** Most urgent first: empty, critical, low, unreadable. */
460
+ export function balanceAlerts(spaces: CredentialSpaceView[]): Array<{ space: string; key: string; label: string; balance: BalanceView }>;
package/src/index.js CHANGED
@@ -7,5 +7,7 @@ module.exports = {
7
7
  ...require('./envHydrator'),
8
8
  ...require('./unlockChallenge'),
9
9
  ...require('./routes'),
10
- ...require('./utils')
10
+ ...require('./utils'),
11
+ ...require('./screenState'),
12
+ ...require('./balance')
11
13
  };
package/src/routes.js CHANGED
@@ -31,6 +31,9 @@ const unlockValidation = [
31
31
  * no second factor stands between an admin session and a payment key.
32
32
  * @param {Function} [options.subjectOf] (req) => id. Defaults to req.user.id.
33
33
  * @param {object} [options.logger] { info } — records who changed what, never the value.
34
+ * @param {object} [options.balances] from createBalanceProbe(). The status then
35
+ * carries, next to each configured key that has a probe, what is left on the
36
+ * provider account — the number, never the key.
34
37
  */
35
38
  function createCredentialsRoutes(options = {}) {
36
39
  const vault = options.vault;
@@ -46,6 +49,24 @@ function createCredentialsRoutes(options = {}) {
46
49
  const challenge = options.challenge || null;
47
50
  const subjectOf = options.subjectOf || ((req) => req.user && req.user.id);
48
51
  const logger = options.logger || NOOP_LOGGER;
52
+ const balances = options.balances || null;
53
+ if (balances && (typeof balances.check !== 'function' || typeof balances.has !== 'function')) {
54
+ throw new Error('createCredentialsRoutes requires options.balances from createBalanceProbe().');
55
+ }
56
+
57
+ /* Only a key that is in place has a balance to read. A probe that fails says
58
+ so in the entry; it never fails the whole screen. */
59
+ async function withBalances(state) {
60
+ if (!balances) return state;
61
+ const spaces = await Promise.all(state.spaces.map(async (space) => ({
62
+ ...space,
63
+ keys: await Promise.all(space.keys.map(async (entry) => {
64
+ if (!entry.configured || !balances.has(entry.key)) return entry;
65
+ return { ...entry, balance: await balances.check(entry.key) };
66
+ }))
67
+ })));
68
+ return { ...state, spaces };
69
+ }
49
70
 
50
71
  const requireUnlocked = async (req) => {
51
72
  if (challenge) await challenge.assertUnlocked(subjectOf(req));
@@ -56,7 +77,7 @@ function createCredentialsRoutes(options = {}) {
56
77
 
57
78
  /** The state of every managed key. */
58
79
  router.get('/', asyncHandler(async (req, res) => {
59
- const state = await vault.status();
80
+ const state = await withBalances(await vault.status());
60
81
  /* The screen needs to know whether the window is open: otherwise it offers
61
82
  "Edit" only to hit a refusal once the key has been typed. */
62
83
  const unlockedUntil = challenge ? await challenge.unlockedUntil(subjectOf(req)) : null;
@@ -77,12 +98,21 @@ function createCredentialsRoutes(options = {}) {
77
98
  return apiResponse(res, 200, 'Keys can be changed for the next few minutes.', result);
78
99
  }));
79
100
 
101
+ /** Read one balance again, now — "refresh" on the screen. Bounded by the probe's minRefreshMs. */
102
+ router.get('/:key/balance', asyncHandler(async (req, res) => {
103
+ if (!balances || !balances.has(req.params.key)) return apiResponse(res, 404, 'No balance is read for this key.');
104
+ const balance = await balances.check(req.params.key, { refresh: true });
105
+ return apiResponse(res, 200, 'Balance', balance);
106
+ }));
107
+
80
108
  /** Store a key. */
81
109
  router.put('/:key', validateMiddleware(setValidation), asyncHandler(async (req, res) => {
82
110
  /* Knowing the account password is not enough: replacing a payment key with
83
111
  your own breaks nothing visible, the money simply goes elsewhere. */
84
112
  await requireUnlocked(req);
85
113
  await vault.set(req.params.key, req.body.value, { updatedBy: subjectOf(req) });
114
+ /* The reading described the previous key. */
115
+ if (balances && typeof balances.forget === 'function') balances.forget(req.params.key);
86
116
  logger.info(`[credentials] ${req.params.key} stored by ${subjectOf(req)}`);
87
117
  return apiResponse(res, 200, 'Key stored.', { key: req.params.key });
88
118
  }));
@@ -92,6 +122,7 @@ function createCredentialsRoutes(options = {}) {
92
122
  /* Unplugging a service is as consequential as plugging one in. */
93
123
  await requireUnlocked(req);
94
124
  await vault.disconnect(req.params.key, { updatedBy: subjectOf(req) });
125
+ if (balances && typeof balances.forget === 'function') balances.forget(req.params.key);
95
126
  logger.info(`[credentials] ${req.params.key} disconnected by ${subjectOf(req)}`);
96
127
  return apiResponse(res, 200, 'Key disconnected.', { key: req.params.key });
97
128
  }));
@@ -0,0 +1,191 @@
1
+ /**
2
+ * Reading the state of the keys, for the screen that manages them.
3
+ *
4
+ * The server side of this package decides what may be stored and hands back a
5
+ * catalogue. THIS side reads that answer — and reads it the way any client
6
+ * should read a payload: without believing a word of its shape. A missing
7
+ * field, a renamed source, a null in place of a space: each one used to be a
8
+ * blank screen with a type error behind it.
9
+ *
10
+ * Two judgements are worth stating.
11
+ *
12
+ * DOUBT FAVOURS THE SECRET. A key whose `secret` flag is missing is masked. A
13
+ * mislabelled key shown in clear is a leak; a mislabelled key shown masked is
14
+ * a minor annoyance.
15
+ *
16
+ * THE UNLOCK WINDOW IS JUDGED WHEN IT IS READ. The server sends a date, not a
17
+ * countdown. Deciding "open" on arrival and trusting it afterwards leaves a
18
+ * settings screen sitting open for an hour, still believing it may write.
19
+ */
20
+
21
+ const SOURCES = ['interface', 'serveur', 'retiree', 'absente'];
22
+ /* The vault's status() speaks English ('environment', 'disconnected',
23
+ 'absent'); the screen reads the French names. Without this map a key served
24
+ by the environment read as ABSENT and an unplugged one lost its "unplugged"
25
+ badge — the two cases the screen exists to show. */
26
+ const SOURCE_ALIASES = { environment: 'serveur', disconnected: 'retiree', absent: 'absente' };
27
+
28
+ function readSource(value) {
29
+ const name = String(value);
30
+ if (SOURCES.includes(name)) return name;
31
+ return Object.prototype.hasOwnProperty.call(SOURCE_ALIASES, name) ? SOURCE_ALIASES[name] : 'absente';
32
+ }
33
+
34
+ const BALANCE_STATUSES = ['ok', 'low', 'empty', 'unknown', 'error'];
35
+
36
+ function finiteOrNull(value) {
37
+ return typeof value === 'number' && Number.isFinite(value) ? value : null;
38
+ }
39
+
40
+ /**
41
+ * A balance as the screen may show it — or an honest "unreadable".
42
+ *
43
+ * A status that claims a number (ok, low, empty) without carrying one is not
44
+ * believed: the screen says the reading failed rather than draw a figure it
45
+ * would have to guess. Absent stays absent: no probe, nothing to draw.
46
+ */
47
+ function readBalance(raw) {
48
+ if (raw === undefined || raw === null) return undefined;
49
+ if (typeof raw !== 'object') return { status: 'error', critical: false, balance: null, rateLimit: null, unit: null, renewable: null, code: null, checkedAt: null };
50
+ const status = BALANCE_STATUSES.includes(String(raw.status)) ? String(raw.status) : 'error';
51
+ const balance = finiteOrNull(raw.balance);
52
+ const needsNumber = status === 'ok' || status === 'low' || status === 'empty';
53
+ const unreadable = needsNumber && balance === null;
54
+ return {
55
+ status: unreadable ? 'error' : status,
56
+ critical: !unreadable && (raw.critical === true || status === 'empty'),
57
+ balance: unreadable || !needsNumber ? null : balance,
58
+ rateLimit: finiteOrNull(raw.rateLimit),
59
+ unit: optional(raw.unit),
60
+ renewable: typeof raw.renewable === 'boolean' ? raw.renewable : null,
61
+ code: optional(raw.code),
62
+ checkedAt: optional(raw.checkedAt)
63
+ };
64
+ }
65
+
66
+ function text(value, fallback = '') {
67
+ return value === null || value === undefined ? fallback : String(value);
68
+ }
69
+
70
+ function optional(value) {
71
+ return value ? String(value) : null;
72
+ }
73
+
74
+ /** The server answer, turned into something a screen can render safely. */
75
+ function readSpaces(payload) {
76
+ const raw = payload && typeof payload === 'object' ? payload.spaces : null;
77
+ if (!Array.isArray(raw)) return [];
78
+
79
+ return raw.map((item) => {
80
+ const space = item || {};
81
+ const keys = Array.isArray(space.keys) ? space.keys : [];
82
+ return {
83
+ id: text(space.id),
84
+ label: text(space.label),
85
+ hint: text(space.hint),
86
+ keys: keys.map((entry) => {
87
+ const row = entry || {};
88
+ return {
89
+ key: text(row.key),
90
+ label: text(row.label, text(row.key)),
91
+ secret: row.secret !== false,
92
+ placeholder: optional(row.placeholder),
93
+ configured: row.configured === true,
94
+ source: readSource(row.source),
95
+ preview: optional(row.preview),
96
+ help: optional(row.help),
97
+ where: optional(row.where),
98
+ readOnly: row.readOnly === true,
99
+ readOnlyReason: optional(row.readOnlyReason),
100
+ ...(row.balance === undefined ? {} : { balance: readBalance(row.balance) })
101
+ };
102
+ })
103
+ };
104
+ });
105
+ }
106
+
107
+ /** How many of a space's keys are in place — the badge on its tab. */
108
+ function coverageOf(space) {
109
+ const keys = (space && space.keys) || [];
110
+ return { done: keys.filter((entry) => entry.configured).length, total: keys.length };
111
+ }
112
+
113
+ /**
114
+ * What is left to set, across every space.
115
+ *
116
+ * A key deliberately unplugged counts as missing. It is a choice, but a choice
117
+ * that leaves a service disconnected — the screen must show it, not bury it.
118
+ */
119
+ function missingKeys(spaces) {
120
+ return (Array.isArray(spaces) ? spaces : []).flatMap((space) =>
121
+ space.keys
122
+ .filter((entry) => !entry.configured)
123
+ .map((entry) => ({ space: space.label, ...entry }))
124
+ );
125
+ }
126
+
127
+ /**
128
+ * Which space to open on arrival: the one with the most left to do — that is
129
+ * where there is something to do. On a tie, the first: the catalogue's order
130
+ * means something.
131
+ */
132
+ function firstSpaceToOpen(spaces) {
133
+ const list = Array.isArray(spaces) ? spaces : [];
134
+ if (!list.length) return null;
135
+ let best = list[0];
136
+ let bestGap = -1;
137
+ for (const space of list) {
138
+ const { done, total } = coverageOf(space);
139
+ const gap = total - done;
140
+ if (gap > bestGap) {
141
+ best = space;
142
+ bestGap = gap;
143
+ }
144
+ }
145
+ return best.id;
146
+ }
147
+
148
+ /**
149
+ * Is the editing window open, and for how much longer?
150
+ * @param {*} raw The server payload carrying `unlockedUntil`.
151
+ * @param {number} [now]
152
+ */
153
+ function unlockState(raw, now = Date.now()) {
154
+ const value = raw && typeof raw === 'object' ? raw.unlockedUntil : null;
155
+ if (!value) return { unlocked: false, minutesLeft: 0 };
156
+ const until = new Date(String(value)).getTime();
157
+ if (!Number.isFinite(until) || until <= now) return { unlocked: false, minutesLeft: 0 };
158
+ /* Never zero while it is open: "0 minutes left" reads as closed. */
159
+ return { unlocked: true, minutesLeft: Math.max(1, Math.ceil((until - now) / 60000)) };
160
+ }
161
+
162
+ /**
163
+ * The balances that need attention, most urgent first: empty, then critical,
164
+ * then low, then unreadable. A reading that failed is listed — a balance you
165
+ * cannot see is one you cannot watch.
166
+ */
167
+ function balanceAlerts(spaces) {
168
+ const rank = (balance) => {
169
+ if (balance.status === 'empty') return 0;
170
+ if (balance.status === 'low' && balance.critical) return 1;
171
+ if (balance.status === 'low') return 2;
172
+ if (balance.status === 'error') return 3;
173
+ return -1;
174
+ };
175
+ return (Array.isArray(spaces) ? spaces : [])
176
+ .flatMap((space) => (space.keys || [])
177
+ .filter((entry) => entry.balance && rank(entry.balance) >= 0)
178
+ .map((entry) => ({ space: space.label, key: entry.key, label: entry.label, balance: entry.balance, rank: rank(entry.balance) })))
179
+ .sort((a, b) => a.rank - b.rank)
180
+ .map(({ rank: _rank, ...alert }) => alert);
181
+ }
182
+
183
+ /** Digits only — what gets pasted out of an e-mail rarely is. */
184
+ function cleanUnlockCode(input, length = 6) {
185
+ return text(input).replace(/\D/g, '').slice(0, length);
186
+ }
187
+
188
+ module.exports = {
189
+ readSpaces, coverageOf, missingKeys, firstSpaceToOpen, unlockState, cleanUnlockCode,
190
+ readBalance, balanceAlerts
191
+ };