@astratra/credentials 0.2.0 → 0.3.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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astratra/credentials",
3
- "version": "0.2.0",
3
+ "version": "0.3.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/index.d.ts CHANGED
@@ -302,3 +302,38 @@ export function createCredentialRotation(options: {
302
302
  export function assertAdapter(adapter: unknown, methods: string[], name: string): void;
303
303
  export function maskSecret(value: string | null | undefined): string | null;
304
304
  export function maskEmail(email: string | null | undefined): string;
305
+
306
+ /* ─────────────────── Reading the state, for the screen ─────────────────── */
307
+
308
+ export type CredentialSource = 'interface' | 'serveur' | 'retiree' | 'absente';
309
+
310
+ export interface CredentialEntry {
311
+ key: string;
312
+ label: string;
313
+ /** Doubt favours the secret: an unlabelled key comes back masked. */
314
+ secret: boolean;
315
+ placeholder: string | null;
316
+ configured: boolean;
317
+ source: CredentialSource;
318
+ preview: string | null;
319
+ help: string | null;
320
+ where: string | null;
321
+ readOnly: boolean;
322
+ readOnlyReason: string | null;
323
+ }
324
+
325
+ export interface CredentialSpaceView {
326
+ id: string;
327
+ label: string;
328
+ hint: string;
329
+ keys: CredentialEntry[];
330
+ }
331
+
332
+ /** Reads the server answer without trusting its shape. */
333
+ export function readSpaces(payload: unknown): CredentialSpaceView[];
334
+ export function coverageOf(space: CredentialSpaceView | null | undefined): { done: number; total: number };
335
+ export function missingKeys(spaces: CredentialSpaceView[]): Array<CredentialEntry & { space: string }>;
336
+ export function firstSpaceToOpen(spaces: CredentialSpaceView[]): string | null;
337
+ /** Judged when it is read, never when it arrived. */
338
+ export function unlockState(raw: unknown, now?: number): { unlocked: boolean; minutesLeft: number };
339
+ export function cleanUnlockCode(input: unknown, length?: number): string;
package/src/index.js CHANGED
@@ -7,5 +7,6 @@ module.exports = {
7
7
  ...require('./envHydrator'),
8
8
  ...require('./unlockChallenge'),
9
9
  ...require('./routes'),
10
- ...require('./utils')
10
+ ...require('./utils'),
11
+ ...require('./screenState')
11
12
  };
@@ -0,0 +1,123 @@
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
+
23
+ function text(value, fallback = '') {
24
+ return value === null || value === undefined ? fallback : String(value);
25
+ }
26
+
27
+ function optional(value) {
28
+ return value ? String(value) : null;
29
+ }
30
+
31
+ /** The server answer, turned into something a screen can render safely. */
32
+ function readSpaces(payload) {
33
+ const raw = payload && typeof payload === 'object' ? payload.spaces : null;
34
+ if (!Array.isArray(raw)) return [];
35
+
36
+ return raw.map((item) => {
37
+ const space = item || {};
38
+ const keys = Array.isArray(space.keys) ? space.keys : [];
39
+ return {
40
+ id: text(space.id),
41
+ label: text(space.label),
42
+ hint: text(space.hint),
43
+ keys: keys.map((entry) => {
44
+ const row = entry || {};
45
+ return {
46
+ key: text(row.key),
47
+ label: text(row.label, text(row.key)),
48
+ secret: row.secret !== false,
49
+ placeholder: optional(row.placeholder),
50
+ configured: row.configured === true,
51
+ source: SOURCES.includes(String(row.source)) ? String(row.source) : 'absente',
52
+ preview: optional(row.preview),
53
+ help: optional(row.help),
54
+ where: optional(row.where),
55
+ readOnly: row.readOnly === true,
56
+ readOnlyReason: optional(row.readOnlyReason)
57
+ };
58
+ })
59
+ };
60
+ });
61
+ }
62
+
63
+ /** How many of a space's keys are in place — the badge on its tab. */
64
+ function coverageOf(space) {
65
+ const keys = (space && space.keys) || [];
66
+ return { done: keys.filter((entry) => entry.configured).length, total: keys.length };
67
+ }
68
+
69
+ /**
70
+ * What is left to set, across every space.
71
+ *
72
+ * A key deliberately unplugged counts as missing. It is a choice, but a choice
73
+ * that leaves a service disconnected — the screen must show it, not bury it.
74
+ */
75
+ function missingKeys(spaces) {
76
+ return (Array.isArray(spaces) ? spaces : []).flatMap((space) =>
77
+ space.keys
78
+ .filter((entry) => !entry.configured)
79
+ .map((entry) => ({ space: space.label, ...entry }))
80
+ );
81
+ }
82
+
83
+ /**
84
+ * Which space to open on arrival: the one with the most left to do — that is
85
+ * where there is something to do. On a tie, the first: the catalogue's order
86
+ * means something.
87
+ */
88
+ function firstSpaceToOpen(spaces) {
89
+ const list = Array.isArray(spaces) ? spaces : [];
90
+ if (!list.length) return null;
91
+ let best = list[0];
92
+ let bestGap = -1;
93
+ for (const space of list) {
94
+ const { done, total } = coverageOf(space);
95
+ const gap = total - done;
96
+ if (gap > bestGap) {
97
+ best = space;
98
+ bestGap = gap;
99
+ }
100
+ }
101
+ return best.id;
102
+ }
103
+
104
+ /**
105
+ * Is the editing window open, and for how much longer?
106
+ * @param {*} raw The server payload carrying `unlockedUntil`.
107
+ * @param {number} [now]
108
+ */
109
+ function unlockState(raw, now = Date.now()) {
110
+ const value = raw && typeof raw === 'object' ? raw.unlockedUntil : null;
111
+ if (!value) return { unlocked: false, minutesLeft: 0 };
112
+ const until = new Date(String(value)).getTime();
113
+ if (!Number.isFinite(until) || until <= now) return { unlocked: false, minutesLeft: 0 };
114
+ /* Never zero while it is open: "0 minutes left" reads as closed. */
115
+ return { unlocked: true, minutesLeft: Math.max(1, Math.ceil((until - now) / 60000)) };
116
+ }
117
+
118
+ /** Digits only — what gets pasted out of an e-mail rarely is. */
119
+ function cleanUnlockCode(input, length = 6) {
120
+ return text(input).replace(/\D/g, '').slice(0, length);
121
+ }
122
+
123
+ module.exports = { readSpaces, coverageOf, missingKeys, firstSpaceToOpen, unlockState, cleanUnlockCode };