@astratra/credentials 0.3.0 → 1.0.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 +77 -0
- package/package.json +1 -1
- package/src/balance.js +352 -0
- package/src/index.d.ts +121 -0
- package/src/index.js +2 -1
- package/src/routes.js +32 -1
- package/src/screenState.js +71 -3
package/README.md
CHANGED
|
@@ -218,6 +218,7 @@ app.use('/api/credentials', createCredentialsRoutes({
|
|
|
218
218
|
| `POST /unlock` | vérifie le code, ouvre la fenêtre |
|
|
219
219
|
| `PUT /:key` | enregistre une valeur |
|
|
220
220
|
| `DELETE /:key` | débranche une clé |
|
|
221
|
+
| `GET /:key/balance` | relit le solde chez le fournisseur (avec `balances`) |
|
|
221
222
|
|
|
222
223
|
`authorize` est **obligatoire** : ces clés engagent les paiements de toute la
|
|
223
224
|
plateforme, pas ceux d'un locataire, et Astratra n'a pas d'avis sur qui possède
|
|
@@ -325,6 +326,82 @@ un passage interrompu se relance simplement.
|
|
|
325
326
|
| `skipped` | marqueur de débranchement ou valeur vide |
|
|
326
327
|
| `unreadable` | **aucun des deux ciphers ne la lit** — à examiner |
|
|
327
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
|
+
|
|
328
405
|
## Ce que ce package ne fait pas
|
|
329
406
|
|
|
330
407
|
- Il ne fournit **aucun catalogue** de fournisseurs. Quelles clés existent et ce
|
package/package.json
CHANGED
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;
|
|
@@ -320,6 +424,20 @@ export interface CredentialEntry {
|
|
|
320
424
|
where: string | null;
|
|
321
425
|
readOnly: boolean;
|
|
322
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;
|
|
323
441
|
}
|
|
324
442
|
|
|
325
443
|
export interface CredentialSpaceView {
|
|
@@ -337,3 +455,6 @@ export function firstSpaceToOpen(spaces: CredentialSpaceView[]): string | null;
|
|
|
337
455
|
/** Judged when it is read, never when it arrived. */
|
|
338
456
|
export function unlockState(raw: unknown, now?: number): { unlocked: boolean; minutesLeft: number };
|
|
339
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
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
|
}));
|
package/src/screenState.js
CHANGED
|
@@ -19,6 +19,49 @@
|
|
|
19
19
|
*/
|
|
20
20
|
|
|
21
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
|
+
}
|
|
22
65
|
|
|
23
66
|
function text(value, fallback = '') {
|
|
24
67
|
return value === null || value === undefined ? fallback : String(value);
|
|
@@ -48,12 +91,13 @@ function readSpaces(payload) {
|
|
|
48
91
|
secret: row.secret !== false,
|
|
49
92
|
placeholder: optional(row.placeholder),
|
|
50
93
|
configured: row.configured === true,
|
|
51
|
-
source:
|
|
94
|
+
source: readSource(row.source),
|
|
52
95
|
preview: optional(row.preview),
|
|
53
96
|
help: optional(row.help),
|
|
54
97
|
where: optional(row.where),
|
|
55
98
|
readOnly: row.readOnly === true,
|
|
56
|
-
readOnlyReason: optional(row.readOnlyReason)
|
|
99
|
+
readOnlyReason: optional(row.readOnlyReason),
|
|
100
|
+
...(row.balance === undefined ? {} : { balance: readBalance(row.balance) })
|
|
57
101
|
};
|
|
58
102
|
})
|
|
59
103
|
};
|
|
@@ -115,9 +159,33 @@ function unlockState(raw, now = Date.now()) {
|
|
|
115
159
|
return { unlocked: true, minutesLeft: Math.max(1, Math.ceil((until - now) / 60000)) };
|
|
116
160
|
}
|
|
117
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
|
+
|
|
118
183
|
/** Digits only — what gets pasted out of an e-mail rarely is. */
|
|
119
184
|
function cleanUnlockCode(input, length = 6) {
|
|
120
185
|
return text(input).replace(/\D/g, '').slice(0, length);
|
|
121
186
|
}
|
|
122
187
|
|
|
123
|
-
module.exports = {
|
|
188
|
+
module.exports = {
|
|
189
|
+
readSpaces, coverageOf, missingKeys, firstSpaceToOpen, unlockState, cleanUnlockCode,
|
|
190
|
+
readBalance, balanceAlerts
|
|
191
|
+
};
|