@nodefony/redis 10.0.0-alpha.1

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.
Files changed (36) hide show
  1. package/LICENSE +544 -0
  2. package/README.md +110 -0
  3. package/dist/_virtual/_@oxc-project_runtime@0.148.0/helpers/esm/decorate.js +9 -0
  4. package/dist/_virtual/_@oxc-project_runtime@0.148.0/helpers/esm/decorateMetadata.js +6 -0
  5. package/dist/index.js +58 -0
  6. package/dist/nodefony/config/config.js +98 -0
  7. package/dist/nodefony/config/defineModuleConfig.js +90 -0
  8. package/dist/nodefony/interfaces/IRedisConfig.js +1 -0
  9. package/dist/nodefony/interfaces/index.js +1 -0
  10. package/dist/nodefony/registerStores.js +38 -0
  11. package/dist/nodefony/service/redis.js +177 -0
  12. package/dist/nodefony/src/Connection.js +111 -0
  13. package/dist/nodefony/src/RedisTokenStore.js +390 -0
  14. package/dist/nodefony/src/RedisWebAuthnCredentialStore.js +247 -0
  15. package/dist/nodefony/src/SessionStorage.js +249 -0
  16. package/dist/nodefony/src/buildClientOptions.js +63 -0
  17. package/dist/nodefony/src/keyNamespace.js +80 -0
  18. package/dist/nodefony/src/scanCursor.js +69 -0
  19. package/dist/types/index.d.ts +53 -0
  20. package/dist/types/nodefony/config/config.d.ts +41 -0
  21. package/dist/types/nodefony/config/defineModuleConfig.d.ts +26 -0
  22. package/dist/types/nodefony/interfaces/IRedisConfig.d.ts +17 -0
  23. package/dist/types/nodefony/interfaces/index.d.ts +5 -0
  24. package/dist/types/nodefony/registerStores.d.ts +5 -0
  25. package/dist/types/nodefony/service/redis.d.ts +82 -0
  26. package/dist/types/nodefony/src/Connection.d.ts +39 -0
  27. package/dist/types/nodefony/src/RedisTokenStore.d.ts +121 -0
  28. package/dist/types/nodefony/src/RedisWebAuthnCredentialStore.d.ts +108 -0
  29. package/dist/types/nodefony/src/SessionStorage.d.ts +87 -0
  30. package/dist/types/nodefony/src/buildClientOptions.d.ts +21 -0
  31. package/dist/types/nodefony/src/keyNamespace.d.ts +12 -0
  32. package/dist/types/nodefony/src/scanCursor.d.ts +50 -0
  33. package/docs/architecture.md +718 -0
  34. package/docs/configuration.md +773 -0
  35. package/docs/index.md +295 -0
  36. package/package.json +95 -0
@@ -0,0 +1,390 @@
1
+ import { MAX_SCAN, decodeCursor, encodeCursor } from "./scanCursor.js";
2
+ import { assertPageQuery } from "nodefony";
3
+ //#region nodefony/src/RedisTokenStore.ts
4
+ /** Préfixe namespacé des clés de jetons dans Redis. */
5
+ /**
6
+ * Préfixe HISTORIQUE des clés (jetons). Utilisé tel quel par une application sans
7
+ * cloison ; sinon le service y insère le nom de l'application (cf
8
+ * {@link RedisService.keyPrefix}) — deux applications sur un même Redis ne
9
+ * doivent ni écrire ni BALAYER le même espace de clés.
10
+ */
11
+ const KEY_BASE = "nf:tok";
12
+ /** Fenêtre par défaut de conservation d'un PAT révoqué sans expiration (30 j). */
13
+ const DEFAULT_RETENTION_REVOKED_MS = 2592e6;
14
+ /**
15
+ * Store de jetons **Redis** (node-redis v6) — implémentation d'{@link ITokenStore}
16
+ * pour le cluster (source unique cross-pod, denylist hot).
17
+ *
18
+ * **Approche B** : `@nodefony/security` n'est connu qu'en `import type` (0 dép
19
+ * runtime). L'application câble la fabrique (`registerTokenStore("redis", …)`).
20
+ *
21
+ * **Modèle de clés** (préfixe `nf:tok`) :
22
+ * - `rec:<jti>` = **HASH** du record (1 champ par colonne ; tableaux/objets en
23
+ * JSON dans le champ ; `null` = champ absent). HASH (≠ blob JSON) car `markUsed`
24
+ * écrit 1-3 champs via `HSET` **sans réécrire le record ni toucher le TTL** ;
25
+ * - `hash:<secretHash>` = `jti` (index de lookup au login) ;
26
+ * - `subj:<subjectId>` / `fam:<family>` = **SET** d'ids (index secondaires —
27
+ * les membres orphelins sont nettoyés paresseusement à la lecture) ;
28
+ * - `deny:<jti>` = `"1"` avec **`EX`** (révocation ciblée, TTL natif) ;
29
+ * - `revsub:<subjectId>` = seuil `invalidBefore` (révocation en masse).
30
+ *
31
+ * **TTL natif → `gc()` est un no-op** : un refresh expire par son `exp`
32
+ * (`EXPIRE`), un PAT **révoqué sans exp** reçoit un `EXPIRE = rétention` au moment
33
+ * du `revoke`, la denylist expire par `EX`. Redis purge seul (zéro balayage).
34
+ *
35
+ * Dégradation gracieuse : si la connexion `main` n'est pas (ou plus) ouverte, les
36
+ * lectures renvoient vide et les écritures sont des no-op (comme le session store).
37
+ */
38
+ var RedisTokenStore = class RedisTokenStore {
39
+ #resolveClient;
40
+ /** Fournit le préfixe cloisonné (lazy : le service peut n'exister qu'au boot). */
41
+ #resolvePrefix;
42
+ /** Préfixe mémoïsé — il est lu à chaque clé. */
43
+ #prefixCache = null;
44
+ #now;
45
+ #retentionRevokedMs;
46
+ /** Canal d'alerte du store (balayage plafonné) — muet par défaut. */
47
+ #notify;
48
+ /**
49
+ * @param resolveClient - résolveur **lazy** du client Redis (l'ordre de boot
50
+ * n'est pas garanti à la construction ; `null` = connexion indisponible).
51
+ * @param now - horloge (epoch ms) injectable pour les tests.
52
+ * @param retentionRevokedMs - rétention d'un PAT révoqué sans `exp` avant purge.
53
+ */
54
+ constructor(resolveClient, now = Date.now, retentionRevokedMs = DEFAULT_RETENTION_REVOKED_MS, resolvePrefix = () => KEY_BASE, notify = () => {}) {
55
+ this.#resolveClient = resolveClient;
56
+ this.#resolvePrefix = resolvePrefix;
57
+ this.#now = now;
58
+ this.#retentionRevokedMs = retentionRevokedMs;
59
+ this.#notify = notify;
60
+ }
61
+ /**
62
+ * Construit le store depuis un {@link RedisService} (connexion `main`).
63
+ * Résolution **lazy** du client (boot order).
64
+ *
65
+ * @param service - service Redis fournissant `getClient("main")`.
66
+ * @param now - horloge injectable (tests).
67
+ * @param retentionRevokedMs - rétention des PAT révoqués sans `exp`.
68
+ */
69
+ static from(service, now, retentionRevokedMs) {
70
+ return new RedisTokenStore(() => service.getClient("main"), now, retentionRevokedMs, () => service.keyPrefix(KEY_BASE), (message) => service.log(message, "WARNING"));
71
+ }
72
+ /** Préfixe effectif des clés, cloisonné par application (mémoïsé). */
73
+ #prefix() {
74
+ if (this.#prefixCache === null) this.#prefixCache = this.#resolvePrefix();
75
+ return this.#prefixCache;
76
+ }
77
+ #client() {
78
+ return this.#resolveClient();
79
+ }
80
+ #recKey(id) {
81
+ return `${this.#prefix()}:rec:${id}`;
82
+ }
83
+ #hashKey(secretHash) {
84
+ return `${this.#prefix()}:hash:${secretHash}`;
85
+ }
86
+ #subjKey(subjectId) {
87
+ return `${this.#prefix()}:subj:${subjectId}`;
88
+ }
89
+ #famKey(family) {
90
+ return `${this.#prefix()}:fam:${family}`;
91
+ }
92
+ #denyKey(jti) {
93
+ return `${this.#prefix()}:deny:${jti}`;
94
+ }
95
+ #revsubKey(subjectId) {
96
+ return `${this.#prefix()}:revsub:${subjectId}`;
97
+ }
98
+ /** TTL en secondes pour un `expiresAt` absolu (epoch ms), au moins 1 ; `undefined` si aucun. */
99
+ #ttlSeconds(expiresAt) {
100
+ if (expiresAt === null) return;
101
+ return Math.max(1, Math.ceil((expiresAt - this.#now()) / 1e3));
102
+ }
103
+ /** Sérialise un record en champs de HASH (omet les `null`, JSON pour les composites). */
104
+ #encode(record) {
105
+ const h = {};
106
+ const put = (k, v) => {
107
+ if (v !== null && v !== void 0) h[k] = String(v);
108
+ };
109
+ put("id", record.id);
110
+ put("kind", record.kind);
111
+ put("name", record.name);
112
+ put("prefix", record.prefix);
113
+ put("subjectId", record.subjectId);
114
+ put("subjectType", record.subjectType);
115
+ put("tenantId", record.tenantId);
116
+ h.scopes = JSON.stringify(record.scopes);
117
+ h.audience = JSON.stringify(record.audience);
118
+ if (record.resources !== null) h.resources = JSON.stringify(record.resources);
119
+ put("secretHash", record.secretHash);
120
+ put("hashAlg", record.hashAlg);
121
+ put("clientId", record.clientId);
122
+ put("cnf", record.cnf);
123
+ put("family", record.family);
124
+ put("replacedBy", record.replacedBy);
125
+ put("createdAt", record.createdAt);
126
+ put("expiresAt", record.expiresAt);
127
+ put("lastUsedAt", record.lastUsedAt);
128
+ put("lastUsedIp", record.lastUsedIp);
129
+ put("lastUsedUserAgent", record.lastUsedUserAgent);
130
+ put("revokedAt", record.revokedAt);
131
+ put("revokedReason", record.revokedReason);
132
+ h.metadata = JSON.stringify(record.metadata);
133
+ return h;
134
+ }
135
+ /** Désérialise un HASH en record (`null` pour les champs absents). */
136
+ #decode(h) {
137
+ const str = (k) => k in h ? h[k] : null;
138
+ const num = (k) => k in h ? Number(h[k]) : null;
139
+ return {
140
+ id: h.id,
141
+ kind: h.kind,
142
+ name: h.name,
143
+ prefix: str("prefix"),
144
+ subjectId: h.subjectId,
145
+ subjectType: h.subjectType,
146
+ tenantId: str("tenantId"),
147
+ scopes: h.scopes ? JSON.parse(h.scopes) : [],
148
+ audience: h.audience ? JSON.parse(h.audience) : [],
149
+ resources: h.resources ? JSON.parse(h.resources) : null,
150
+ secretHash: h.secretHash,
151
+ hashAlg: h.hashAlg,
152
+ clientId: str("clientId"),
153
+ cnf: str("cnf"),
154
+ family: str("family"),
155
+ replacedBy: str("replacedBy"),
156
+ createdAt: Number(h.createdAt),
157
+ expiresAt: num("expiresAt"),
158
+ lastUsedAt: num("lastUsedAt"),
159
+ lastUsedIp: str("lastUsedIp"),
160
+ lastUsedUserAgent: str("lastUsedUserAgent"),
161
+ revokedAt: num("revokedAt"),
162
+ revokedReason: str("revokedReason"),
163
+ metadata: h.metadata ? JSON.parse(h.metadata) : {}
164
+ };
165
+ }
166
+ async put(record) {
167
+ const client = this.#client();
168
+ if (!client) return;
169
+ const recKey = this.#recKey(record.id);
170
+ await client.del(recKey);
171
+ await client.hSet(recKey, this.#encode(record));
172
+ const ttl = this.#ttlSeconds(record.expiresAt);
173
+ if (ttl !== void 0) {
174
+ await client.expire(recKey, ttl);
175
+ await client.set(this.#hashKey(record.secretHash), record.id, { EX: ttl });
176
+ } else await client.set(this.#hashKey(record.secretHash), record.id);
177
+ await client.sAdd(this.#subjKey(record.subjectId), record.id);
178
+ if (record.family) await client.sAdd(this.#famKey(record.family), record.id);
179
+ }
180
+ async findById(id) {
181
+ const client = this.#client();
182
+ if (!client) return null;
183
+ const h = await client.hGetAll(this.#recKey(id));
184
+ return Object.keys(h).length > 0 ? this.#decode(h) : null;
185
+ }
186
+ async findByHash(secretHash) {
187
+ const client = this.#client();
188
+ if (!client) return null;
189
+ const id = await client.get(this.#hashKey(secretHash));
190
+ if (id === null) return null;
191
+ const h = await client.hGetAll(this.#recKey(id));
192
+ if (Object.keys(h).length === 0) {
193
+ await client.del(this.#hashKey(secretHash));
194
+ return null;
195
+ }
196
+ return this.#decode(h);
197
+ }
198
+ async findBySubject(subjectId) {
199
+ const client = this.#client();
200
+ if (!client) return [];
201
+ const subjKey = this.#subjKey(subjectId);
202
+ const ids = await client.sMembers(subjKey);
203
+ const out = [];
204
+ for (const id of ids) {
205
+ const h = await client.hGetAll(this.#recKey(id));
206
+ if (Object.keys(h).length > 0) out.push(this.#decode(h));
207
+ else await client.sRem(subjKey, id);
208
+ }
209
+ return out;
210
+ }
211
+ /**
212
+ * Tous les jetons (PAT + refresh) — vue d'administration cross-porteur.
213
+ * Énumère les records par **SCAN** (curseur non-bloquant, `MATCH nf:tok:rec:*`).
214
+ * Opération admin RARE (cold-path, jamais sur le hot-path d'auth) ; à très
215
+ * grande échelle, préférer le système de référence SQL pour la gouvernance.
216
+ *
217
+ * Le balayage est **plafonné** à {@link MAX_SCAN} clés, comme celui des
218
+ * sessions : sans plafond, une vue d'administration lancée sur un très grand
219
+ * parc balaie tout le keyspace. Au-delà on s'arrête et on **journalise** — un
220
+ * listing partiel se dit, il ne se tronque pas en silence.
221
+ */
222
+ async listAll() {
223
+ const client = this.#client();
224
+ if (!client) return [];
225
+ const match = `${this.#prefix()}:rec:*`;
226
+ const out = [];
227
+ let cursor = "0";
228
+ let scanned = 0;
229
+ do {
230
+ const res = await client.scan(cursor, {
231
+ MATCH: match,
232
+ COUNT: 200
233
+ });
234
+ cursor = String(res.cursor);
235
+ for (const key of res.keys) {
236
+ const h = await client.hGetAll(key);
237
+ if (Object.keys(h).length > 0) out.push(this.#decode(h));
238
+ }
239
+ scanned += res.keys.length;
240
+ if (scanned >= 1e4) {
241
+ this.#notify(`REDIS TOKENS listAll: balayage plafonné à ${MAX_SCAN} clés (${out.length} jetons rendus) — listing PARTIEL`);
242
+ break;
243
+ }
244
+ } while (cursor !== "0");
245
+ return out;
246
+ }
247
+ /**
248
+ * {@inheritDoc ITokenStore.listPage}
249
+ *
250
+ * **Curseur SCAN pur** : UN passage `SCAN` par appel (cold-path admin). Capacité
251
+ * réduite ASSUMÉE et annoncée — pas de `total`, pas d'ordre global sur `createdAt`
252
+ * (Redis n'a pas d'index secondaire ici), la page peut compter moins d'éléments
253
+ * que `limit` (le filtre s'applique au batch). Le client boucle tant que
254
+ * `hasNext` en repassant `nextCursor`. Renvoie les records BRUTS.
255
+ */
256
+ async listPage(query) {
257
+ assertPageQuery(query, "cursor");
258
+ const limit = Math.max(1, Math.floor(query.limit));
259
+ const client = this.#client();
260
+ if (!client) return {
261
+ items: [],
262
+ limit,
263
+ hasNext: false,
264
+ nextCursor: null
265
+ };
266
+ const { scanCursor, skip } = decodeCursor(query.cursor);
267
+ const res = await client.scan(scanCursor, {
268
+ MATCH: `${this.#prefix()}:rec:*`,
269
+ COUNT: limit
270
+ });
271
+ const next = String(res.cursor);
272
+ const now = this.#now();
273
+ const items = [];
274
+ let consumed = 0;
275
+ for (const key of res.keys.slice(skip)) {
276
+ if (items.length >= limit) break;
277
+ consumed += 1;
278
+ const h = await client.hGetAll(key);
279
+ if (Object.keys(h).length === 0) continue;
280
+ const rec = this.#decode(h);
281
+ if (query.subjectId !== void 0 && rec.subjectId !== query.subjectId) continue;
282
+ if (query.kind !== void 0 && rec.kind !== query.kind) continue;
283
+ if (query.status !== void 0) {
284
+ if ((rec.revokedAt !== null ? "revoked" : rec.expiresAt !== null && rec.expiresAt <= now ? "expired" : "active") !== query.status) continue;
285
+ }
286
+ items.push(rec);
287
+ }
288
+ const nextCursor = skip + consumed < res.keys.length ? encodeCursor(scanCursor, skip + consumed) : next === "0" ? null : encodeCursor(next, 0);
289
+ return {
290
+ items,
291
+ limit,
292
+ hasNext: nextCursor !== null,
293
+ nextCursor
294
+ };
295
+ }
296
+ /**
297
+ * {@inheritDoc ITokenStore.countTokens}
298
+ *
299
+ * Un comptage exact exigerait un `SCAN` complet O(N) → refusé sur le cold-path
300
+ * admin : renvoie `-1` (« inconnu », capacité réduite Redis assumée).
301
+ */
302
+ countTokens(_query) {
303
+ return Promise.resolve(-1);
304
+ }
305
+ async markUsed(id, usage) {
306
+ const client = this.#client();
307
+ if (!client) return;
308
+ const recKey = this.#recKey(id);
309
+ if (await client.exists(recKey) === 0) return;
310
+ const fields = { lastUsedAt: String(usage.at) };
311
+ if (usage.ip != null) fields.lastUsedIp = usage.ip;
312
+ if (usage.userAgent != null) fields.lastUsedUserAgent = usage.userAgent;
313
+ await client.hSet(recKey, fields);
314
+ if (usage.ip == null) await client.hDel(recKey, "lastUsedIp");
315
+ if (usage.userAgent == null) await client.hDel(recKey, "lastUsedUserAgent");
316
+ }
317
+ async revoke(id, reason) {
318
+ const client = this.#client();
319
+ if (!client) return;
320
+ const h = await client.hGetAll(this.#recKey(id));
321
+ if (Object.keys(h).length === 0) return;
322
+ const record = this.#decode(h);
323
+ if (record.revokedAt !== null) return;
324
+ await this.#applyRevoke(client, record, reason);
325
+ }
326
+ async revokeFamily(family, reason) {
327
+ const client = this.#client();
328
+ if (!client) return;
329
+ const famKey = this.#famKey(family);
330
+ const ids = await client.sMembers(famKey);
331
+ for (const id of ids) {
332
+ const h = await client.hGetAll(this.#recKey(id));
333
+ if (Object.keys(h).length === 0) {
334
+ await client.sRem(famKey, id);
335
+ continue;
336
+ }
337
+ const record = this.#decode(h);
338
+ if (record.revokedAt === null) await this.#applyRevoke(client, record, reason);
339
+ }
340
+ }
341
+ /** Pose `revokedAt`/`revokedReason` ; un PAT sans `exp` reçoit un TTL = rétention. */
342
+ async #applyRevoke(client, record, reason) {
343
+ const recKey = this.#recKey(record.id);
344
+ await client.hSet(recKey, {
345
+ revokedAt: String(this.#now()),
346
+ revokedReason: reason
347
+ });
348
+ if (record.expiresAt === null) {
349
+ const ttl = Math.max(1, Math.ceil(this.#retentionRevokedMs / 1e3));
350
+ await client.expire(recKey, ttl);
351
+ await client.expire(this.#hashKey(record.secretHash), ttl);
352
+ }
353
+ }
354
+ async denyJti(jti, expiresAt) {
355
+ const client = this.#client();
356
+ if (!client) return;
357
+ const ttl = Math.ceil((expiresAt - this.#now()) / 1e3);
358
+ if (ttl > 0) await client.set(this.#denyKey(jti), "1", { EX: ttl });
359
+ }
360
+ async isJtiDenied(jti) {
361
+ const client = this.#client();
362
+ if (!client) return false;
363
+ return await client.exists(this.#denyKey(jti)) > 0;
364
+ }
365
+ async revokeAllForSubject(subjectId, invalidBefore) {
366
+ const client = this.#client();
367
+ if (!client) return;
368
+ const key = this.#revsubKey(subjectId);
369
+ const current = await client.get(key);
370
+ if (current === null || invalidBefore > Number(current)) await client.set(key, String(invalidBefore));
371
+ }
372
+ async getInvalidBefore(subjectId) {
373
+ const client = this.#client();
374
+ if (!client) return null;
375
+ const value = await client.get(this.#revsubKey(subjectId));
376
+ return value !== null ? Number(value) : null;
377
+ }
378
+ /**
379
+ * **No-op** : Redis gère toute l'expiration par TTL natif (refresh par leur
380
+ * `exp`, PAT révoqués par la rétention posée au `revoke`, denylist par `EX`).
381
+ * Aucun balayage applicatif n'est nécessaire (≠ Drizzle/Mongoose).
382
+ *
383
+ * @returns toujours `0` (rien à purger côté application).
384
+ */
385
+ gc() {
386
+ return Promise.resolve(0);
387
+ }
388
+ };
389
+ //#endregion
390
+ export { RedisTokenStore };
@@ -0,0 +1,247 @@
1
+ import { decodeCursor, encodeCursor } from "./scanCursor.js";
2
+ import { assertPageQuery } from "nodefony";
3
+ //#region nodefony/src/RedisWebAuthnCredentialStore.ts
4
+ /** Préfixe namespacé des clés de credentials WebAuthn dans Redis. */
5
+ /**
6
+ * Préfixe HISTORIQUE des clés (identifiants WebAuthn). Utilisé tel quel par une application sans
7
+ * cloison ; sinon le service y insère le nom de l'application (cf
8
+ * {@link RedisService.keyPrefix}) — deux applications sur un même Redis ne
9
+ * doivent ni écrire ni BALAYER le même espace de clés.
10
+ */
11
+ const KEY_BASE = "nf:wac";
12
+ /**
13
+ * Store de credentials WebAuthn **Redis** (node-redis v6) — implémentation
14
+ * d'{@link IWebAuthnCredentialStore} pour le cluster (source unique cross-pod,
15
+ * les passkeys survivent au redémarrage et sont partagées entre process).
16
+ *
17
+ * **Approche B** : `@nodefony/security` n'est connu qu'en `import type` (0 dép
18
+ * runtime). L'application câble la fabrique (`registerWebAuthnStore("redis", …)`).
19
+ *
20
+ * **Modèle de clés** (préfixe `nf:wac`) :
21
+ * - `cred:<credentialId>` = **HASH** du credential (1 champ par colonne ;
22
+ * `transports` en JSON ; booléens en `"1"`/`"0"` ; `lastUsedAt`/`nickname`
23
+ * absents = `null`/non défini). HASH (≠ blob JSON) car `update` réécrit 1-4
24
+ * champs via `HSET` sans relire le record ;
25
+ * - `user:<userId>` = **SET** des credentialIds de l'utilisateur (`findByUser`,
26
+ * `allowCredentials`, « mes appareils ») — les membres orphelins (credential
27
+ * supprimé hors `delete`) sont nettoyés paresseusement à la lecture.
28
+ *
29
+ * **Aucun TTL → aucun `gc`** : le contrat {@link IWebAuthnCredentialStore} n'a pas
30
+ * de maintenance (≠ `ITokenStore`) — un credential ne disparaît que sur `delete`.
31
+ *
32
+ * Dégradation gracieuse : si la connexion `main` n'est pas (ou plus) ouverte, les
33
+ * lectures renvoient vide et les écritures sont des no-op (comme le session store).
34
+ */
35
+ var RedisWebAuthnCredentialStore = class RedisWebAuthnCredentialStore {
36
+ #resolveClient;
37
+ /** Fournit le préfixe cloisonné (lazy : le service peut n'exister qu'au boot). */
38
+ #resolvePrefix;
39
+ /** Préfixe mémoïsé — il est lu à chaque clé. */
40
+ #prefixCache = null;
41
+ /**
42
+ * @param resolveClient - résolveur **lazy** du client Redis (l'ordre de boot
43
+ * n'est pas garanti à la construction ; `null` = connexion indisponible).
44
+ * @param resolvePrefix - résolveur **lazy** du préfixe cloisonné par application.
45
+ */
46
+ constructor(resolveClient, resolvePrefix = () => KEY_BASE) {
47
+ this.#resolveClient = resolveClient;
48
+ this.#resolvePrefix = resolvePrefix;
49
+ }
50
+ /**
51
+ * Construit le store depuis un {@link RedisService} (connexion `main`).
52
+ * Résolution **lazy** du client (boot order).
53
+ *
54
+ * @param service - service Redis fournissant `getClient("main")`.
55
+ */
56
+ static from(service) {
57
+ return new RedisWebAuthnCredentialStore(() => service.getClient("main"), () => service.keyPrefix(KEY_BASE));
58
+ }
59
+ /** Préfixe effectif des clés, cloisonné par application (mémoïsé). */
60
+ #prefix() {
61
+ if (this.#prefixCache === null) this.#prefixCache = this.#resolvePrefix();
62
+ return this.#prefixCache;
63
+ }
64
+ #client() {
65
+ return this.#resolveClient();
66
+ }
67
+ #credKey(id) {
68
+ return `${this.#prefix()}:cred:${id}`;
69
+ }
70
+ #userKey(userId) {
71
+ return `${this.#prefix()}:user:${userId}`;
72
+ }
73
+ /** Sérialise un credential en champs de HASH (omet `lastUsedAt`/`nickname` absents). */
74
+ #encode(c) {
75
+ const h = {
76
+ id: c.id,
77
+ userId: c.userId,
78
+ publicKey: c.publicKey,
79
+ signCount: String(c.signCount),
80
+ transports: JSON.stringify(c.transports),
81
+ backupEligible: c.backupEligible ? "1" : "0",
82
+ backupState: c.backupState ? "1" : "0",
83
+ uvInitialized: c.uvInitialized ? "1" : "0",
84
+ createdAt: String(c.createdAt)
85
+ };
86
+ if (c.lastUsedAt !== null) h.lastUsedAt = String(c.lastUsedAt);
87
+ if (c.nickname !== void 0) h.nickname = c.nickname;
88
+ return h;
89
+ }
90
+ /** Désérialise un HASH en credential (`lastUsedAt`/`nickname` absents → `null`/omis). */
91
+ #decode(h) {
92
+ return {
93
+ id: h.id,
94
+ userId: h.userId,
95
+ publicKey: h.publicKey,
96
+ signCount: Number(h.signCount),
97
+ transports: h.transports ? JSON.parse(h.transports) : [],
98
+ backupEligible: h.backupEligible === "1",
99
+ backupState: h.backupState === "1",
100
+ uvInitialized: h.uvInitialized === "1",
101
+ createdAt: Number(h.createdAt),
102
+ lastUsedAt: "lastUsedAt" in h ? Number(h.lastUsedAt) : null,
103
+ ..."nickname" in h ? { nickname: h.nickname } : {}
104
+ };
105
+ }
106
+ async findById(credentialId) {
107
+ const client = this.#client();
108
+ if (!client) return null;
109
+ const h = await client.hGetAll(this.#credKey(credentialId));
110
+ return Object.keys(h).length > 0 ? this.#decode(h) : null;
111
+ }
112
+ async findByUser(userId) {
113
+ const client = this.#client();
114
+ if (!client) return [];
115
+ const userKey = this.#userKey(userId);
116
+ const ids = await client.sMembers(userKey);
117
+ const out = [];
118
+ for (const id of ids) {
119
+ const h = await client.hGetAll(this.#credKey(id));
120
+ if (Object.keys(h).length > 0) out.push(this.#decode(h));
121
+ else await client.sRem(userKey, id);
122
+ }
123
+ return out;
124
+ }
125
+ /**
126
+ * `SCARD` natif — O(1), aucune lecture de HASH (le plafond ne charge rien).
127
+ *
128
+ * Peut **sur-compter** les membres orphelins que {@link findByUser} nettoie
129
+ * paresseusement (credential supprimé hors `delete` — sans TTL sur les
130
+ * credentials, cas dégénéré). Écart assumé **fail-closed** : au pire un
131
+ * enrôlement de plus est refusé, jamais un de trop accepté. Client
132
+ * indisponible → `0` (cohérent avec les lectures qui renvoient vide).
133
+ */
134
+ async countByUser(userId) {
135
+ const client = this.#client();
136
+ if (!client) return 0;
137
+ return client.sCard(this.#userKey(userId));
138
+ }
139
+ async save(credential) {
140
+ const client = this.#client();
141
+ if (!client) return;
142
+ const credKey = this.#credKey(credential.id);
143
+ await client.del(credKey);
144
+ await client.hSet(credKey, this.#encode(credential));
145
+ await client.sAdd(this.#userKey(credential.userId), credential.id);
146
+ }
147
+ async update(credentialId, patch) {
148
+ const client = this.#client();
149
+ if (!client) return;
150
+ const credKey = this.#credKey(credentialId);
151
+ if (await client.exists(credKey) === 0) return;
152
+ await client.hSet(credKey, {
153
+ signCount: String(patch.signCount),
154
+ backupState: patch.backupState ? "1" : "0",
155
+ uvInitialized: patch.uvInitialized ? "1" : "0",
156
+ lastUsedAt: String(patch.lastUsedAt)
157
+ });
158
+ }
159
+ async delete(credentialId) {
160
+ const client = this.#client();
161
+ if (!client) return;
162
+ const credKey = this.#credKey(credentialId);
163
+ const h = await client.hGetAll(credKey);
164
+ if (Object.keys(h).length === 0) return;
165
+ await client.del(credKey);
166
+ if (h.userId) await client.sRem(this.#userKey(h.userId), credentialId);
167
+ }
168
+ /**
169
+ * {@inheritDoc IWebAuthnCredentialStore.listPage}
170
+ *
171
+ * **Curseur SCAN pur** : UN passage `SCAN` par appel (cold-path admin). Capacité
172
+ * réduite ASSUMÉE et annoncée — pas de `total`, pas d'ordre global sur
173
+ * `createdAt` (Redis n'a pas d'index secondaire ici), la page peut compter moins
174
+ * d'éléments que `limit` (le filtre s'applique au batch). Le client boucle tant
175
+ * que `hasNext` en repassant `nextCursor`.
176
+ *
177
+ * ⚠️ On SCANne les HASH de credentials, pas les Set par utilisateur : le filtre
178
+ * `userId` reste un filtre de page. Passer par `sMembers` serait plus direct
179
+ * mais donnerait deux stratégies de pagination pour un même contrat — la
180
+ * seconde sans curseur, donc incohérente dès qu'on mélange les filtres.
181
+ */
182
+ async listPage(query) {
183
+ assertPageQuery(query, "cursor");
184
+ const limit = Math.max(1, Math.floor(query.limit));
185
+ const client = this.#client();
186
+ if (!client) return {
187
+ items: [],
188
+ limit,
189
+ hasNext: false,
190
+ nextCursor: null
191
+ };
192
+ const { scanCursor, skip } = decodeCursor(query.cursor);
193
+ const res = await client.scan(scanCursor, {
194
+ MATCH: `${this.#prefix()}:cred:*`,
195
+ COUNT: limit
196
+ });
197
+ const next = String(res.cursor);
198
+ const items = [];
199
+ let consumed = 0;
200
+ for (const key of res.keys.slice(skip)) {
201
+ if (items.length >= limit) break;
202
+ consumed += 1;
203
+ const h = await client.hGetAll(key);
204
+ if (Object.keys(h).length === 0) continue;
205
+ const cred = this.#decode(h);
206
+ if (query.userId !== void 0 && cred.userId !== query.userId) continue;
207
+ if (query.userId === void 0 && query.q !== void 0 && query.q.length > 0 && !cred.userId.startsWith(query.q)) continue;
208
+ if (query.backedUp !== void 0 && cred.backupState !== query.backedUp) continue;
209
+ items.push(this.#toSummary(cred));
210
+ }
211
+ const nextCursor = skip + consumed < res.keys.length ? encodeCursor(scanCursor, skip + consumed) : next === "0" ? null : encodeCursor(next, 0);
212
+ return {
213
+ items,
214
+ limit,
215
+ hasNext: nextCursor !== null,
216
+ nextCursor
217
+ };
218
+ }
219
+ /**
220
+ * {@inheritDoc IWebAuthnCredentialStore.countCredentials}
221
+ *
222
+ * Un comptage exact exigerait un `SCAN` complet O(N) → refusé sur le cold-path
223
+ * admin : renvoie `-1` (« inconnu », capacité réduite Redis assumée).
224
+ * ⚠️ Ne pas confondre avec {@link countByUser}, qui est O(1) (`SCARD`) parce
225
+ * qu'il porte sur un index existant.
226
+ */
227
+ countCredentials(_query) {
228
+ return Promise.resolve(-1);
229
+ }
230
+ /** Credential complet → vue admin (sans `publicKey`, cf le contrat). */
231
+ #toSummary(c) {
232
+ return {
233
+ id: c.id,
234
+ userId: c.userId,
235
+ transports: c.transports,
236
+ backupEligible: c.backupEligible,
237
+ backupState: c.backupState,
238
+ uvInitialized: c.uvInitialized,
239
+ signCount: c.signCount,
240
+ createdAt: c.createdAt,
241
+ lastUsedAt: c.lastUsedAt,
242
+ ...c.nickname !== void 0 ? { nickname: c.nickname } : {}
243
+ };
244
+ }
245
+ };
246
+ //#endregion
247
+ export { RedisWebAuthnCredentialStore };