@astratra/credentials 1.0.0 → 1.1.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
@@ -406,8 +406,8 @@ moins urgent : épuisé, critique, bas, illisible.
406
406
 
407
407
  - Il ne fournit **aucun catalogue** de fournisseurs. Quelles clés existent et ce
408
408
  qui cesse de marcher sans chacune, c'est ton produit qui le sait.
409
- - Il ne **chiffre** rien lui-même : passe-lui un cipher, par exemple
410
- `createFieldCipher` de `@astratra/security`.
409
+ - Il accepte ton cipher existant ; `createContextCipher` fournit aussi AES-256-GCM
410
+ avec contexte authentifié (depuis 1.1.0).
411
411
  - Il ne décide pas **qui** a le droit d'y toucher.
412
412
  - Il n'envoie **aucun e-mail**.
413
413
 
@@ -416,3 +416,206 @@ moins urgent : épuisé, critique, bas, illisible.
416
416
  ```bash
417
417
  npm test --workspace @astratra/credentials
418
418
  ```
419
+
420
+ ## Ajouts de la version 1.1.0
421
+
422
+ Les options existantes gardent leurs valeurs par défaut : espace plat, repli
423
+ sur l'environnement, cache de 60 secondes, aucune version conservée. Les
424
+ ciphers à un argument continuent de fonctionner.
425
+
426
+ ### Lecture stricte et espaces isolés
427
+
428
+ ```js
429
+ const {
430
+ createCredentialVault, createContextCipher,
431
+ createMemoryVersionedCredentialStore
432
+ } = require('@astratra/credentials');
433
+
434
+ const scope = { tenant: 'organisation-123', environment: 'production' };
435
+ const cipher = createContextCipher({ key: cleDe32Octets }); // Buffer, conservé par le serveur
436
+ const store = createMemoryVersionedCredentialStore(); // tests/développement
437
+ const vault = createCredentialVault({
438
+ catalog, store, cipher, scope,
439
+ strict: true,
440
+ fallback: 'none',
441
+ history: true,
442
+ retentionMs: 30 * 86400_000,
443
+ cacheMs: 0,
444
+ onWrite: async (event) => invaliderOuProgrammerLivraison(event)
445
+ });
446
+ ```
447
+
448
+ `strict: true` lève une erreur constante en cas de lecture du store ou de
449
+ chiffrement illisible, y compris via `getMany`, `stored` et `status`. Son
450
+ `code` est `CREDENTIAL_STORE_UNREADABLE` ou `CREDENTIAL_VALUE_UNREADABLE`.
451
+ L'événement de journal est constant : aucune valeur ni message brut de
452
+ l'adapter. Une clé absente reste une absence : `strict` ne supprime pas à lui
453
+ seul le repli ; `fallback: 'none'` le désactive, même pour une clé absente.
454
+ Un cache encore valide peut servir sa valeur sans lire la base ; avec
455
+ `cacheMs: 0`, chaque lecture contrôle le store. Une erreur de lecture après
456
+ expiration ne sert jamais le cache périmé en mode strict.
457
+
458
+ `scope: { tenant, environment }` lie toutes les opérations d'un coffre au même
459
+ locataire et au même environnement. Les deux champs sont obligatoires et non
460
+ vides ; leurs valeurs restent celles fournies par l'app (`production`,
461
+ `preproduction`, `development`, ou ses propres noms). Crée un coffre par
462
+ couple, sans partager `process.env` pour hydrater les secrets des locataires.
463
+ L'app choisit le locataire depuis son autorisation serveur.
464
+
465
+ Les stores mémoire et Mongo fournis isolent aussi l'espace plat (champs
466
+ `tenant`/`environment` absents ou nuls). Pour un store personnalisé, annonce
467
+ `supportsScopes: true` et implémente `findAll(scope?, { strict }?)` et
468
+ `upsert(row)` avec les champs `tenant` et `environment`. Un store sans support
469
+ explicite est refusé pour un coffre scoped. `isReady: false` du store Mongo
470
+ lève en mode strict et garde le retour vide historique autrement.
471
+ Sur une collection Mongo classique existante, remplace un éventuel index
472
+ unique `{ key: 1 }` par `{ tenant: 1, environment: 1, key: 1 }` avant d'utiliser
473
+ plusieurs espaces ; cette migration reste à la charge de l'app.
474
+
475
+ ### Chiffrement authentifié
476
+
477
+ ```js
478
+ const contexte = {
479
+ tenant: 'organisation-123', environment: 'production', name: 'SERVICE_KEY', version: 1
480
+ };
481
+ const chiffre = cipher.encrypt('valeur', contexte);
482
+ const clair = cipher.decrypt(chiffre, contexte);
483
+ ```
484
+
485
+ Le contexte est fourni séparément, jamais récupéré d'un contexte embarqué
486
+ auquel on ferait confiance. AES-256-GCM authentifie chaque champ en AAD dans
487
+ un ordre canonique. Un autre locataire, environnement, nom ou numéro de version
488
+ refuse le déchiffrement. Les nonces sont aléatoires ; le format JSON transporte
489
+ seulement `v`, `iv`, `tag`, `data`. La clé doit être un Buffer de 32 octets.
490
+ Le coffre transmet automatiquement le contexte : `tenant`/`environment` sont
491
+ `null` dans l'espace plat, `version` vaut `0` sans historique. Le contexte est
492
+ obligatoire pour ce cipher, même si les anciens ciphers l'ignorent.
493
+
494
+ Changer le format d'anciens chiffrés exige une migration explicite.
495
+ `previousCipher` reste disponible pour lire une ancienne génération ; une
496
+ fois retiré, les anciens chiffrés ne doivent plus dépendre de lui. La rotation
497
+ classique accepte `scope` et transmet l'AAD, mais refuse les stores versionnés :
498
+ avec l'historique, écris une nouvelle version via un coffre utilisant le cipher
499
+ courant et garde l'ancien cipher tant que des versions conservées en ont besoin.
500
+
501
+ ### Versions et conservation
502
+
503
+ ```js
504
+ await vault.set('SERVICE_KEY', 'nouvelle-valeur', { updatedBy: 'acteur-123' });
505
+ await vault.get('SERVICE_KEY'); // courante
506
+ await vault.get('SERVICE_KEY', { version: 1 }); // ancienne, ou null si absente/expirée/purgée
507
+ await vault.listVersions('SERVICE_KEY'); // métadonnées seulement, récente d'abord
508
+ await vault.purgeVersions(); // nombre de chiffrés effacés dans CET espace
509
+ ```
510
+
511
+ `history: true` exige un store versionné. Chaque `set` et `disconnect` crée
512
+ une version ; les écritures concurrentes ne réutilisent pas les numéros.
513
+ La conservation démarre au retrait de la version courante : une version
514
+ courante n'expire jamais. `retentionMs: 0` retire immédiatement l'accès aux
515
+ anciennes valeurs. La purge efface leur chiffré, conserve leurs métadonnées
516
+ et marque `purged: true`. Programme `purgeVersions()` périodiquement pour
517
+ l'effacement physique ; une lecture refuse déjà une ancienne valeur expirée.
518
+ Une version absente ne reprend jamais la valeur de l'environnement.
519
+
520
+ Les métadonnées sont `{ key, tenant?, environment?, version?, updatedAt,
521
+ updatedBy, retiredAt, expiresAt, purged }` ; jamais `value`.
522
+ Les gardes de lecture restent appliqués aux valeurs historiques.
523
+
524
+ Stores fournis : `createMemoryVersionedCredentialStore()` et
525
+ `createMongoVersionedCredentialStore({ collection, isReady?, maxTimeMS? })`.
526
+ Le second exige une collection dédiée et stocke un document par clé isolée ;
527
+ son `_id` unique et sa révision compare-and-swap rendent l'ajout atomique sans
528
+ transaction multi-document. L'historique de métadonnées grossit : archive-le
529
+ avant la limite de taille des documents Mongo si une clé reçoit beaucoup
530
+ d'écritures. Il ne réutilise pas automatiquement la collection du store plat.
531
+ Pour PostgreSQL ou le schéma existant de la Centrale, fournis cet adapter :
532
+
533
+ ```text
534
+ supportsScopes: true
535
+ findAll(scope?, { strict }?) -> lignes courantes chiffrées
536
+ upsert(row) -> refusé (utiliser appendVersion)
537
+ appendVersion(key, scope, build(version), retentionMs) -> ligne écrite
538
+ findVersion(key, version, scope?) -> ligne ou null
539
+ listVersions(key, scope?) -> métadonnées
540
+ purgeVersions(date, scope?) -> nombre effacé
541
+ ```
542
+
543
+ `appendVersion` doit attribuer une version et appeler `build(version)` dans
544
+ une opération atomique par clé ; `build` chiffre avec ce numéro en AAD.
545
+ Le store retire la version précédente avec `retiredAt`/`expiresAt` et ne
546
+ retourne la nouvelle ligne qu'après validation de l'écriture.
547
+
548
+ ### Crochet et rechargement à chaud
549
+
550
+ `onWrite(event)` reçoit les métadonnées ci-dessus et `action: 'set' |
551
+ 'disconnect'`, après validation de l'écriture et invalidation du cache local.
552
+ `onChange({ key, action })` reste disponible et est appelé ensuite.
553
+ Si `onWrite` échoue, l'erreur constante porte
554
+ `code: 'CREDENTIAL_AFTER_WRITE_FAILED', committed: true` : la clé a été écrite,
555
+ la livraison ou l'invalidation doit être reprise sans réécrire une version.
556
+ Le crochet n'est pas une file durable ni une transaction avec ta livraison.
557
+
558
+ Dans un processus, les écritures oublient automatiquement le cache ; une
559
+ lecture déjà en cours ne peut pas remettre une ancienne image après cela.
560
+ Entre processus, utilise le crochet pour publier une invalidation vers
561
+ `vault.forget()` dans chaque lecteur, ou `cacheMs: 0` pour relire à chaque
562
+ appel. Un `cacheMs` positif borne le délai d'une modification externe.
563
+
564
+ ### Défi injectable pour UNE lecture
565
+
566
+ Le déverrouillage par courrier existant (`createUnlockChallenge`) reste
567
+ inchangé. La nouvelle primitive ne crée pas de fenêtre générale :
568
+
569
+ ```js
570
+ const { createReadChallenge, createMemoryReadChallengeStore } = require('@astratra/credentials');
571
+ const lecture = createReadChallenge({
572
+ store: createMemoryReadChallengeStore(),
573
+ ttlMs: 60_000, // maximum 5 minutes
574
+ verify: async ({ challenge, proof }) => verifierPasskeyDeLApp(challenge, proof)
575
+ });
576
+ const defi = await lecture.request('acteur-123', {
577
+ key: 'SERVICE_KEY', scope, version: 1 // version facultative : courante à la lecture
578
+ });
579
+ const valeur = await lecture.read('acteur-123', defi.id, assertion, vault);
580
+ ```
581
+
582
+ Le vérificateur doit renvoyer exactement `true` et vérifier le nonce,
583
+ l'identité et le contexte signé (ainsi que l'origine/RP pour une passkey).
584
+ Le défi est lié au sujet, à la clé, à la version demandée et à l'espace ; il
585
+ est consommé atomiquement **avant** la vérification, même en cas de refus.
586
+ Il ne peut être rejoué, y compris simultanément ; son expiration est contrôlée
587
+ avant et après la vérification. La lecture ne sert qu'au code serveur autorisé.
588
+ `vault.get()` reste l'API serveur pour les services ; elle n'exige pas ce défi.
589
+
590
+ `createMongoReadChallengeStore({ collection })` fournit le store durable
591
+ avec `findOneAndDelete` (driver Mongo supportant `includeResultMetadata: false`).
592
+ Les adapters personnalisés implémentent `save(record)` et
593
+ `consume(id, subjectId)` atomiquement. Un index TTL sur `expiresAt` peut nettoyer
594
+ les défis expirés non consommés ; la primitive vérifie toujours la date.
595
+
596
+ ### Sonde d'essai générique
597
+
598
+ ```js
599
+ const { createKeyProbe } = require('@astratra/credentials');
600
+ const essais = createKeyProbe({
601
+ vault, transport: monTransportInjecte, timeoutMs: 10_000,
602
+ probes: {
603
+ SERVICE_KEY: async (valeur, { transport, signal }) => {
604
+ const reponse = await transport(urlFixeDuService, {
605
+ headers: { Authorization: `Bearer ${valeur}` }, signal
606
+ });
607
+ return reponse.ok ? 'ok' : reponse.status === 429 ? 'quota'
608
+ : [401, 403].includes(reponse.status) ? 'rejected' : 'unavailable';
609
+ }
610
+ }
611
+ });
612
+ await essais.check('SERVICE_KEY'); // { status: 'ok' | 'rejected' | 'quota' | 'unavailable' }
613
+ ```
614
+
615
+ La sonde utilise la valeur servie par le coffre, un transport obligatoirement
616
+ injecté et un signal d'annulation. Clé absente/débranchée, service inconnu,
617
+ échec du coffre, erreur de transport, délai dépassé ou réponse mal formée :
618
+ `unavailable`. Seul le statut sort ; aucune réponse brute, valeur ou erreur
619
+ fournisseur n'est journalisée. Les callbacks injectés reçoivent le secret pour
620
+ l'utiliser et doivent eux aussi éviter de le journaliser. La sonde de solde
621
+ Serper et `createBalanceProbe` gardent leur API actuelle.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astratra/credentials",
3
- "version": "1.0.0",
3
+ "version": "1.1.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/context.js ADDED
@@ -0,0 +1,35 @@
1
+ /** Scope and authenticated context are canonical, independent of property order. */
2
+ function normalizeScope(scope) {
3
+ if (scope === undefined || scope === null) return null;
4
+ if (typeof scope.tenant !== 'string' || !scope.tenant.trim() ||
5
+ typeof scope.environment !== 'string' || !scope.environment.trim()) {
6
+ throw new Error('A scope requires nonempty tenant and environment.');
7
+ }
8
+ return Object.freeze({ tenant: scope.tenant, environment: scope.environment });
9
+ }
10
+ function sameScope(row, scope) {
11
+ return scope ? row.tenant === scope.tenant && row.environment === scope.environment
12
+ : row.tenant == null && row.environment == null;
13
+ }
14
+ function rowId(key, scope) {
15
+ return JSON.stringify([scope?.tenant ?? null, scope?.environment ?? null, key]);
16
+ }
17
+ function rowContext(row, scope) {
18
+ return { tenant: scope?.tenant ?? null, environment: scope?.environment ?? null,
19
+ name: row.key, version: row.version ?? 0 };
20
+ }
21
+ function contextBytes(context) {
22
+ if (!context || typeof context.name !== 'string' || !context.name ||
23
+ !Number.isSafeInteger(context.version) || context.version < 0 ||
24
+ ![context.tenant, context.environment].every(v => v === null || (typeof v === 'string' && v.length > 0)) ||
25
+ (context.tenant === null) !== (context.environment === null)) throw new Error('Invalid authenticated context.');
26
+ return Buffer.from(JSON.stringify(['astratra.credentials.v1', context.tenant,
27
+ context.environment, context.name, context.version]), 'utf8');
28
+ }
29
+ function versionMetadata(row) {
30
+ return { key: row.key, ...(row.tenant == null ? {} : { tenant: row.tenant, environment: row.environment }),
31
+ ...(row.version === undefined ? {} : { version: row.version }),
32
+ updatedAt: row.updatedAt || null, updatedBy: row.updatedBy || null,
33
+ retiredAt: row.retiredAt || null, expiresAt: row.expiresAt || null, purged: row.purged === true };
34
+ }
35
+ module.exports = { normalizeScope, sameScope, rowId, rowContext, contextBytes, versionMetadata };
@@ -0,0 +1,36 @@
1
+ const crypto = require('crypto');
2
+ const { contextBytes } = require('./context');
3
+
4
+ /** AES-256-GCM with a mandatory, externally supplied authenticated context. */
5
+ function createContextCipher({ key } = {}) {
6
+ if (!Buffer.isBuffer(key) || key.length !== 32) throw new Error('A 32-byte Buffer key is required.');
7
+ const material = Buffer.from(key);
8
+ return {
9
+ encrypt(plaintext, context) {
10
+ const aad = contextBytes(context);
11
+ const iv = crypto.randomBytes(12);
12
+ const cipher = crypto.createCipheriv('aes-256-gcm', material, iv);
13
+ cipher.setAAD(aad);
14
+ const data = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
15
+ return JSON.stringify({ v: 1, iv: iv.toString('base64'), tag: cipher.getAuthTag().toString('base64'), data: data.toString('base64') });
16
+ },
17
+ decrypt(payload, context) {
18
+ try {
19
+ const aad = contextBytes(context);
20
+ const parsed = JSON.parse(payload);
21
+ function decode(value, length) {
22
+ if (typeof value !== 'string') throw new Error();
23
+ const bytes = Buffer.from(value, 'base64');
24
+ if (bytes.toString('base64') !== value || (length && bytes.length !== length)) throw new Error();
25
+ return bytes;
26
+ }
27
+ if (parsed.v !== 1) throw new Error();
28
+ const cipher = crypto.createDecipheriv('aes-256-gcm', material, decode(parsed.iv, 12));
29
+ cipher.setAAD(aad);
30
+ cipher.setAuthTag(decode(parsed.tag, 16));
31
+ return Buffer.concat([cipher.update(decode(parsed.data)), cipher.final()]).toString('utf8');
32
+ } catch { throw new Error('Credential decryption refused.'); }
33
+ }
34
+ };
35
+ }
36
+ module.exports = { createContextCipher };
package/src/index.d.ts CHANGED
@@ -103,7 +103,21 @@ export function createValueGuard(options?: {
103
103
 
104
104
  export function createPermissiveGuard(): ValueGuard;
105
105
 
106
+ export interface CredentialScope { tenant: string; environment: string }
107
+ export interface CredentialContext { tenant: string | null; environment: string | null; name: string; version: number }
108
+ export interface VersionMetadata {
109
+ key: string; tenant?: string; environment?: string; version?: number;
110
+ updatedAt: Date | string | null; updatedBy: string | null;
111
+ retiredAt: Date | string | null; expiresAt: Date | string | null; purged: boolean;
112
+ }
113
+ export interface WriteEvent extends VersionMetadata { action: 'set' | 'disconnect' }
106
114
  export interface CredentialRow {
115
+ tenant?: string;
116
+ environment?: string;
117
+ version?: number;
118
+ retiredAt?: Date | string | null;
119
+ expiresAt?: Date | string | null;
120
+ purged?: boolean;
107
121
  key: string;
108
122
  value: string;
109
123
  secret?: boolean;
@@ -112,7 +126,8 @@ export interface CredentialRow {
112
126
  }
113
127
 
114
128
  export interface CredentialStore {
115
- findAll(): Promise<CredentialRow[]>;
129
+ supportsScopes?: boolean;
130
+ findAll(scope?: CredentialScope, options?: { strict?: boolean }): Promise<CredentialRow[]>;
116
131
  upsert(row: CredentialRow): Promise<void>;
117
132
  }
118
133
 
@@ -141,8 +156,8 @@ export function createMongoCredentialStore(options: {
141
156
  export function createMongoChallengeStore(options: { collection: unknown }): ChallengeStore;
142
157
 
143
158
  export interface FieldCipher {
144
- encrypt(plaintext: string): string;
145
- decrypt(payload: string): string;
159
+ encrypt(plaintext: string, context?: CredentialContext): string;
160
+ decrypt(payload: string, context?: CredentialContext): string;
146
161
  }
147
162
 
148
163
  export interface CredentialStatusEntry {
@@ -170,7 +185,10 @@ export interface CredentialStatus {
170
185
  }
171
186
 
172
187
  export interface CredentialVault {
173
- get(key: string): Promise<string | null>;
188
+ readonly scope: Readonly<CredentialScope> | null;
189
+ listVersions(key: string): Promise<VersionMetadata[]>;
190
+ purgeVersions(): Promise<number>;
191
+ get(key: string, options?: { version?: number }): Promise<string | null>;
174
192
  getMany(keys: string[]): Promise<Record<string, string | null>>;
175
193
  stored(): Promise<Map<string, string | null>>;
176
194
  set(key: string, value: unknown, meta?: { updatedBy?: string | null }): Promise<void>;
@@ -191,6 +209,12 @@ export function createCredentialVault(options: {
191
209
  guard?: ValueGuard;
192
210
  env?: NodeJS.ProcessEnv;
193
211
  cacheMs?: number;
212
+ strict?: boolean;
213
+ fallback?: 'env' | 'none';
214
+ scope?: CredentialScope;
215
+ history?: boolean;
216
+ retentionMs?: number;
217
+ onWrite?: (event: WriteEvent) => void | Promise<void>;
194
218
  now?: () => number;
195
219
  logger?: { warn?(message: string): void; error?(message: string): void };
196
220
  onChange?: (event: { key: string; action: 'set' | 'disconnect' }) => void | Promise<void>;
@@ -396,6 +420,7 @@ export interface CredentialRotation {
396
420
  }
397
421
 
398
422
  export function createCredentialRotation(options: {
423
+ scope?: CredentialScope;
399
424
  store: CredentialStore;
400
425
  catalog: CredentialCatalog;
401
426
  to: FieldCipher;
@@ -458,3 +483,43 @@ export function cleanUnlockCode(input: unknown, length?: number): string;
458
483
  export function readBalance(raw: unknown): BalanceView | undefined;
459
484
  /** Most urgent first: empty, critical, low, unreadable. */
460
485
  export function balanceAlerts(spaces: CredentialSpaceView[]): Array<{ space: string; key: string; label: string; balance: BalanceView }>;
486
+
487
+ /** Context is mandatory at runtime; this factory supplies a vault-compatible cipher. */
488
+ export function createContextCipher(options: { key: Buffer }): FieldCipher;
489
+ export interface VersionedCredentialStore extends CredentialStore {
490
+ appendVersion(key: string, scope: CredentialScope | undefined,
491
+ build: (version: number) => CredentialRow, retentionMs: number): Promise<CredentialRow>;
492
+ findVersion(key: string, version: number, scope?: CredentialScope): Promise<CredentialRow | null>;
493
+ listVersions(key: string, scope?: CredentialScope): Promise<VersionMetadata[]>;
494
+ purgeVersions(at: Date, scope?: CredentialScope): Promise<number>;
495
+ }
496
+ export function createMemoryVersionedCredentialStore(): VersionedCredentialStore;
497
+ export function createMongoVersionedCredentialStore(options: {
498
+ collection: unknown; isReady?: () => boolean; maxTimeMS?: number;
499
+ }): VersionedCredentialStore;
500
+ export interface ReadChallengeRecord {
501
+ id: string; nonce: string; subjectId: string; key: string; version?: number;
502
+ scope: CredentialScope | null; expiresAt: Date | string;
503
+ }
504
+ export interface ReadChallengeStore {
505
+ save(record: ReadChallengeRecord): Promise<void>;
506
+ consume(id: string, subjectId: string | number): Promise<ReadChallengeRecord | null>;
507
+ }
508
+ export function createMemoryReadChallengeStore(): ReadChallengeStore;
509
+ export function createMongoReadChallengeStore(options: { collection: unknown }): ReadChallengeStore;
510
+ export interface ReadChallenge {
511
+ request(subjectId: string | number, target: { key: string; version?: number; scope?: CredentialScope }): Promise<ReadChallengeRecord>;
512
+ read(subjectId: string | number, id: string, proof: unknown, vault: CredentialVault): Promise<string | null>;
513
+ }
514
+ export function createReadChallenge(options: {
515
+ store: ReadChallengeStore;
516
+ verify: (input: { challenge: ReadChallengeRecord; proof: unknown }) => boolean | Promise<boolean>;
517
+ ttlMs?: number; now?: () => number;
518
+ }): ReadChallenge;
519
+ export type KeyProbeStatus = 'ok' | 'rejected' | 'quota' | 'unavailable';
520
+ export interface KeyProbe { check(key: string): Promise<{ status: KeyProbeStatus }> }
521
+ export function createKeyProbe<TTransport extends (...args: any[]) => any>(options: {
522
+ vault: Pick<CredentialVault, 'get'>;
523
+ probes: Record<string, (value: string, context: { transport: TTransport; signal: AbortSignal }) => KeyProbeStatus | Promise<KeyProbeStatus>>;
524
+ transport: TTransport; timeoutMs?: number;
525
+ }): KeyProbe;
package/src/index.js CHANGED
@@ -9,5 +9,9 @@ module.exports = {
9
9
  ...require('./routes'),
10
10
  ...require('./utils'),
11
11
  ...require('./screenState'),
12
- ...require('./balance')
12
+ ...require('./balance'),
13
+ ...require('./contextCipher'),
14
+ ...require('./versionedStores'),
15
+ ...require('./readChallenge'),
16
+ ...require('./keyProbe')
13
17
  };
@@ -0,0 +1,29 @@
1
+ /* global AbortController */
2
+ const STATUSES = new Set(['ok', 'rejected', 'quota', 'unavailable']);
3
+ /** Only a fixed status leaves the injected probe. No provider body or error text. */
4
+ function createKeyProbe({ vault, probes, transport, timeoutMs = 10_000 } = {}) {
5
+ if (!vault || typeof vault.get !== 'function' || !probes || typeof transport !== 'function') {
6
+ throw new Error('A key probe requires vault, probes and an injected transport.');
7
+ }
8
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new Error('Invalid timeoutMs.');
9
+ return {
10
+ async check(key) {
11
+ if (!Object.prototype.hasOwnProperty.call(probes, key) || typeof probes[key] !== 'function') return { status: 'unavailable' };
12
+ const controller = new AbortController();
13
+ let timer;
14
+ try {
15
+ const result = await Promise.race([
16
+ (async () => {
17
+ const value = await vault.get(key);
18
+ if (!value) return 'unavailable';
19
+ return probes[key](value, { transport, signal: controller.signal });
20
+ })(),
21
+ new Promise(resolve => { timer = setTimeout(() => { controller.abort(); resolve('unavailable'); }, timeoutMs); })
22
+ ]);
23
+ return { status: typeof result === 'string' && STATUSES.has(result) ? result : 'unavailable' };
24
+ } catch { return { status: 'unavailable' }; }
25
+ finally { clearTimeout(timer); }
26
+ }
27
+ };
28
+ }
29
+ module.exports = { createKeyProbe };
@@ -0,0 +1,60 @@
1
+ /* global structuredClone */
2
+ const crypto = require('crypto');
3
+ const { normalizeScope } = require('./context');
4
+
5
+ /** Stores must consume atomically BEFORE the verifier runs, including on failure. */
6
+ function createMemoryReadChallengeStore() {
7
+ const records = new Map();
8
+ return {
9
+ async save(record) { records.set(record.id, structuredClone(record)); },
10
+ async consume(id, subjectId) {
11
+ const record = records.get(id);
12
+ if (!record || record.subjectId !== String(subjectId)) return null;
13
+ records.delete(id);
14
+ return structuredClone(record);
15
+ }
16
+ };
17
+ }
18
+ function createMongoReadChallengeStore({ collection } = {}) {
19
+ if (!collection || typeof collection.insertOne !== 'function' || typeof collection.findOneAndDelete !== 'function') {
20
+ throw new Error('A Mongo collection with insertOne/findOneAndDelete is required.');
21
+ }
22
+ return {
23
+ async save(record) { await collection.insertOne({ ...record, _id: record.id }); },
24
+ async consume(id, subjectId) {
25
+ return collection.findOneAndDelete({ _id: id, subjectId: String(subjectId) }, { includeResultMetadata: false });
26
+ }
27
+ };
28
+ }
29
+
30
+ /** A verifier (e.g. an application's passkey verifier) authorises ONE bound read. */
31
+ function createReadChallenge({ store, verify, ttlMs = 60_000, now = Date.now } = {}) {
32
+ if (!store || !['save', 'consume'].every(method => typeof store[method] === 'function') || typeof verify !== 'function') {
33
+ throw new Error('A read challenge requires an atomic store and a verifier.');
34
+ }
35
+ if (!Number.isFinite(ttlMs) || ttlMs <= 0 || ttlMs > 300_000) throw new Error('ttlMs must be within five minutes.');
36
+ const refused = () => new Error('Credential read challenge refused.');
37
+ return {
38
+ async request(subjectId, { key, version, scope } = {}) {
39
+ if (typeof key !== 'string' || !key || (version !== undefined && (!Number.isSafeInteger(version) || version < 1))) throw refused();
40
+ const record = { id: crypto.randomUUID(), nonce: crypto.randomBytes(32).toString('base64url'),
41
+ subjectId: String(subjectId), key, ...(version === undefined ? {} : { version }),
42
+ scope: normalizeScope(scope), expiresAt: new Date(now() + ttlMs) };
43
+ await store.save(record);
44
+ return structuredClone(record);
45
+ },
46
+ async read(subjectId, id, proof, vault) {
47
+ let record;
48
+ try { record = await store.consume(id, subjectId); } catch { throw refused(); }
49
+ const expiresAt = new Date(record?.expiresAt).getTime();
50
+ if (!record || record.id !== id || record.subjectId !== String(subjectId) ||
51
+ !Number.isFinite(expiresAt) || expiresAt <= now()) throw refused();
52
+ if (!vault || JSON.stringify(vault.scope || null) !== JSON.stringify(record.scope)) throw refused();
53
+ let valid;
54
+ try { valid = await verify({ challenge: structuredClone(record), proof }); } catch { throw refused(); }
55
+ if (valid !== true || new Date(record.expiresAt).getTime() <= now()) throw refused();
56
+ return vault.get(record.key, record.version === undefined ? {} : { version: record.version });
57
+ }
58
+ };
59
+ }
60
+ module.exports = { createReadChallenge, createMemoryReadChallengeStore, createMongoReadChallengeStore };
package/src/rotation.js CHANGED
@@ -23,6 +23,7 @@
23
23
  * recognised and left alone, so an interrupted run is simply re-run.
24
24
  */
25
25
  const { assertAdapter } = require('./utils');
26
+ const { normalizeScope, rowContext } = require('./context');
26
27
 
27
28
  const DISCONNECTED = '__disconnected__';
28
29
  const MAX_SAMPLES = 10;
@@ -36,7 +37,10 @@ const MAX_SAMPLES = 10;
36
37
  * @param {object} [options.logger] { warn, error }.
37
38
  */
38
39
  function createCredentialRotation(options = {}) {
40
+ const scope = normalizeScope(options.scope);
39
41
  const store = options.store;
42
+ if (scope && !store?.supportsScopes) throw new Error('The store must support credential scopes.');
43
+ if (typeof store?.appendVersion === 'function') throw new Error('Rotate versioned stores by writing a new version through the vault.');
40
44
  assertAdapter(store, ['findAll', 'upsert'], 'options.store');
41
45
 
42
46
  const catalog = options.catalog;
@@ -75,14 +79,14 @@ function createCredentialRotation(options = {}) {
75
79
  if (!catalog.isSecret(row.key)) return { status: 'plain' };
76
80
 
77
81
  try {
78
- to.decrypt(row.value);
82
+ to.decrypt(row.value, rowContext(row, scope));
79
83
  return { status: 'already' };
80
84
  } catch {
81
85
  /* Not migrated yet — the normal case. */
82
86
  }
83
87
 
84
88
  try {
85
- return { status: 'rotated', value: to.encrypt(from.decrypt(row.value)) };
89
+ return { status: 'rotated', value: to.encrypt(from.decrypt(row.value, rowContext(row, scope)), rowContext(row, scope)) };
86
90
  } catch {
87
91
  /* Neither generation reads it. We do not guess, and we do not overwrite. */
88
92
  }
@@ -105,10 +109,10 @@ function createCredentialRotation(options = {}) {
105
109
 
106
110
  let rows;
107
111
  try {
108
- rows = (await store.findAll()) || [];
109
- } catch (error) {
110
- logger.warn(`[credentials] rotation could not read the store: ${error.message}`);
111
- throw error;
112
+ rows = (await store.findAll(scope || undefined, { strict: true })) || [];
113
+ } catch {
114
+ logger.warn?.('[credentials] rotation could not read the store');
115
+ throw new Error('Credential rotation store read failed.');
112
116
  }
113
117
 
114
118
  for (const row of rows) {
@@ -122,6 +126,7 @@ function createCredentialRotation(options = {}) {
122
126
 
123
127
  if (decision.status === 'rotated' && apply) {
124
128
  await store.upsert({
129
+ ...row,
125
130
  key: row.key,
126
131
  value: decision.value,
127
132
  secret: true,
package/src/stores.js CHANGED
@@ -1,3 +1,4 @@
1
+ const { normalizeScope, sameScope, rowId } = require('./context');
1
2
  /**
2
3
  * Persistence adapters.
3
4
  *
@@ -18,14 +19,17 @@ function clone(value) {
18
19
 
19
20
  /** In-process adapter for tests and local development. Not persistent. */
20
21
  function createMemoryCredentialStore(initialRows = []) {
21
- const rows = new Map(initialRows.map((row) => [row.key, { ...row }]));
22
+ const rows = new Map(initialRows.map((row) => [rowId(row.key, normalizeScope(row.tenant == null && row.environment == null ? undefined : row)), { ...row }]));
22
23
 
23
24
  return {
24
- async findAll() {
25
- return [...rows.values()].map((row) => ({ ...row }));
25
+ supportsScopes: true,
26
+ async findAll(scope) {
27
+ scope = normalizeScope(scope);
28
+ return [...rows.values()].filter(row => sameScope(row, scope)).map((row) => ({ ...row }));
26
29
  },
27
30
  async upsert(row) {
28
- rows.set(row.key, { ...rows.get(row.key), ...row, updatedAt: row.updatedAt || new Date() });
31
+ const id = rowId(row.key, normalizeScope(row.tenant == null && row.environment == null ? undefined : row));
32
+ rows.set(id, { ...rows.get(id), ...row, updatedAt: row.updatedAt || new Date() });
29
33
  }
30
34
  };
31
35
  }
@@ -67,18 +71,23 @@ function createMongoCredentialStore(options = {}) {
67
71
  const maxTimeMS = options.maxTimeMS || 3000;
68
72
 
69
73
  return {
70
- async findAll() {
71
- if (!isReady()) return [];
74
+ supportsScopes: true,
75
+ async findAll(scope, { strict = false } = {}) {
76
+ scope = normalizeScope(scope);
77
+ if (!isReady()) {
78
+ if (strict) throw new Error('Credential store unavailable.');
79
+ return [];
80
+ }
72
81
  const cursor = collection.find(
73
- {},
74
- { projection: { key: 1, value: 1, secret: 1, updatedAt: 1, updatedBy: 1 } }
82
+ scope || { tenant: null, environment: null },
83
+ { projection: { key: 1, value: 1, secret: 1, updatedAt: 1, updatedBy: 1, tenant: 1, environment: 1, version: 1 } }
75
84
  );
76
85
  const capped = typeof cursor.maxTimeMS === 'function' ? cursor.maxTimeMS(maxTimeMS) : cursor;
77
86
  return capped.toArray();
78
87
  },
79
88
  async upsert(row) {
80
89
  await collection.updateOne(
81
- { key: row.key },
90
+ { key: row.key, ...(normalizeScope(row.tenant == null && row.environment == null ? undefined : row) || { tenant: null, environment: null }) },
82
91
  { $set: { ...row, updatedAt: row.updatedAt || new Date() } },
83
92
  { upsert: true }
84
93
  );
package/src/vault.js CHANGED
@@ -19,13 +19,14 @@
19
19
  * the fallback environment variable bring it straight back — and you would
20
20
  * never know whether a service is really unplugged.
21
21
  *
22
- * Nothing here throws on a read. No store, no cipher, a corrupted value: it
22
+ * By default nothing here throws on a read. No store, no cipher, a corrupted value: it
23
23
  * falls back to the environment. A payment must not fail because the database
24
24
  * hiccuped.
25
25
  */
26
26
  const AppError = require('@astratra/core').AppError;
27
27
  const { assertAdapter, maskSecret } = require('./utils');
28
28
  const { createPermissiveGuard } = require('./valueGuard');
29
+ const { normalizeScope, sameScope, rowContext, versionMetadata } = require('./context');
29
30
 
30
31
  /** Written in place of a value to mean "deliberately unplugged". */
31
32
  const DISCONNECTED = '__disconnected__';
@@ -47,7 +48,15 @@ const NOOP_LOGGER = { warn() {}, error() {} };
47
48
  * @param {Function} [options.onChange] called after a successful set/disconnect.
48
49
  */
49
50
  function createCredentialVault(options = {}) {
51
+ const scope = normalizeScope(options.scope);
52
+ const strict = options.strict === true;
53
+ const fallback = options.fallback === undefined ? 'env' : options.fallback;
54
+ if (!['env', 'none'].includes(fallback)) throw new Error('Invalid credential fallback.');
50
55
  const store = options.store;
56
+ if (scope && !store?.supportsScopes) throw new Error('The store must support credential scopes.');
57
+ if (options.history && !['appendVersion', 'findVersion', 'listVersions', 'purgeVersions'].every(method => typeof store?.[method] === 'function')) throw new Error('History requires a versioned store.');
58
+ const retentionMs = options.retentionMs === undefined ? 30 * 86400_000 : options.retentionMs;
59
+ if (!Number.isFinite(retentionMs) || retentionMs < 0) throw new Error('Invalid retentionMs.');
51
60
  assertAdapter(store, ['findAll', 'upsert'], 'options.store');
52
61
 
53
62
  const catalog = options.catalog;
@@ -78,12 +87,12 @@ function createCredentialVault(options = {}) {
78
87
  }
79
88
 
80
89
  /** Decrypt with the current generation, falling back to the retiring one. */
81
- function decryptStored(value) {
90
+ function decryptStored(value, row) {
82
91
  try {
83
- return cipher.decrypt(value);
84
- } catch (error) {
85
- if (!previousCipher) throw error;
86
- return previousCipher.decrypt(value);
92
+ return cipher.decrypt(value, rowContext(row, scope));
93
+ } catch {
94
+ if (!previousCipher) throw new Error('Credential decryption refused.');
95
+ return previousCipher.decrypt(value, rowContext(row, scope));
87
96
  }
88
97
  }
89
98
 
@@ -94,6 +103,18 @@ function createCredentialVault(options = {}) {
94
103
  const logger = options.logger || NOOP_LOGGER;
95
104
  const onChange = typeof options.onChange === 'function' ? options.onChange : null;
96
105
 
106
+ const onWrite = options.onWrite;
107
+ if (onWrite !== undefined && typeof onWrite !== 'function') throw new Error('Invalid onWrite.');
108
+ if (!Number.isFinite(cacheMs) || cacheMs < 0) throw new Error('Invalid cacheMs.');
109
+ function readFailure(kind) {
110
+ logger[kind === 'store' ? 'warn' : 'error']?.(`[credentials] ${kind} unreadable`);
111
+ if (strict) {
112
+ const error = new Error(`Credential ${kind} read failed.`);
113
+ error.code = kind === 'store' ? 'CREDENTIAL_STORE_UNREADABLE' : 'CREDENTIAL_VALUE_UNREADABLE';
114
+ throw error;
115
+ }
116
+ }
117
+ let generation = 0;
97
118
  let cache = null;
98
119
  let cachedAt = 0;
99
120
 
@@ -101,11 +122,13 @@ function createCredentialVault(options = {}) {
101
122
  async function load() {
102
123
  if (cache && now() - cachedAt < cacheMs) return cache;
103
124
 
125
+ const started = generation;
104
126
  let rows;
105
127
  try {
106
- rows = await store.findAll();
107
- } catch (error) {
108
- logger.warn(`[credentials] store unreadable: ${error.message}`);
128
+ rows = await store.findAll(scope || undefined, { strict });
129
+ if (!Array.isArray(rows) || rows.some(row => !row || typeof row.key !== 'string' || typeof row.value !== 'string' || (scope && !sameScope(row, scope)))) throw new Error();
130
+ } catch {
131
+ readFailure('store');
109
132
  return cache || new Map();
110
133
  }
111
134
 
@@ -116,14 +139,15 @@ function createCredentialVault(options = {}) {
116
139
  continue;
117
140
  }
118
141
  try {
119
- next.set(row.key, catalog.isSecret(row.key) ? decryptStored(row.value) : row.value);
120
- } catch (error) {
142
+ next.set(row.key, catalog.isSecret(row.key) ? decryptStored(row.value, row) : row.value);
143
+ } catch {
121
144
  /* One unreadable key — rotated cipher, corrupted value — must not take
122
145
  the other nineteen down with it. It simply falls back to the env. */
123
- logger.error(`[credentials] ${row.key} unreadable: ${error.message}`);
146
+ readFailure('value');
124
147
  }
125
148
  }
126
149
 
150
+ if (started !== generation) return load();
127
151
  cache = next;
128
152
  cachedAt = now();
129
153
  return cache;
@@ -137,11 +161,24 @@ function createCredentialVault(options = {}) {
137
161
  }
138
162
 
139
163
  function fromEnv(name) {
140
- return env[name] || null;
164
+ return fallback === 'none' ? null : env[name] || null;
141
165
  }
142
166
 
143
167
  /** The value of one key — store first, environment next, null if unplugged. */
144
- async function get(name) {
168
+ async function get(name, readOptions = {}) {
169
+ if (readOptions.version !== undefined) {
170
+ if (!options.history) throw new Error('History is not enabled.');
171
+ if (!Number.isSafeInteger(readOptions.version) || readOptions.version < 1) throw new Error('Invalid version.');
172
+ let row;
173
+ try { row = await store.findVersion(name, readOptions.version, scope || undefined); }
174
+ catch { readFailure('store'); return null; }
175
+ if (!row || row.purged || (row.expiresAt && new Date(row.expiresAt).getTime() <= now())) return null;
176
+ const stored = await load();
177
+ let value;
178
+ try { value = row.value === DISCONNECTED ? null : catalog.isSecret(name) ? decryptStored(row.value, row) : row.value; }
179
+ catch { readFailure('value'); return null; }
180
+ return guard.mayRead(name, { value, decidingValue: stored.get(guard.decidingKey) }) ? value : null;
181
+ }
145
182
  const stored = await load();
146
183
  if (stored.has(name) && readable(name, stored)) return stored.get(name);
147
184
  return fromEnv(name);
@@ -170,6 +207,7 @@ function createCredentialVault(options = {}) {
170
207
 
171
208
  /** Forget the cache: after a write, the new value must serve immediately. */
172
209
  function forget() {
210
+ generation += 1;
173
211
  cache = null;
174
212
  cachedAt = 0;
175
213
  }
@@ -197,33 +235,60 @@ function createCredentialVault(options = {}) {
197
235
  assertWritable(name, clean);
198
236
  if (!clean) throw new AppError('Provide a value.', 400);
199
237
 
238
+ await write(name, clean, meta, 'set');
239
+ }
240
+
241
+ async function write(name, value, meta, action) {
200
242
  const secret = catalog.isSecret(name);
201
- await store.upsert({
202
- key: name,
203
- value: secret ? cipher.encrypt(clean) : clean,
204
- secret,
205
- updatedBy: meta.updatedBy || null,
206
- updatedAt: new Date()
243
+ const build = (version) => ({
244
+ key: name, ...(scope || {}), ...(version === undefined ? {} : { version }),
245
+ value: action === 'disconnect' ? DISCONNECTED : secret
246
+ ? cipher.encrypt(value, rowContext({ key: name, version }, scope)) : value,
247
+ secret, updatedBy: meta.updatedBy || null, updatedAt: new Date(now())
207
248
  });
249
+ let row;
250
+ try {
251
+ if (options.history) row = await store.appendVersion(name, scope || undefined, build, retentionMs);
252
+ else { row = build(); await store.upsert(row); }
253
+ } catch {
254
+ throw new Error('Credential write failed.');
255
+ }
208
256
  forget();
209
- if (onChange) await onChange({ key: name, action: 'set' });
257
+ const event = { ...versionMetadata(row), action };
258
+ if (onWrite) {
259
+ try { await onWrite(event); }
260
+ catch {
261
+ const error = new Error('Credential written, but onWrite failed.');
262
+ error.code = 'CREDENTIAL_AFTER_WRITE_FAILED';
263
+ error.committed = true;
264
+ throw error;
265
+ }
266
+ }
267
+ if (onChange) await onChange({ key: name, action });
210
268
  }
211
269
 
212
270
  /** Unplug a key — the environment does NOT take over. */
213
271
  async function disconnect(name, meta = {}) {
214
- /* Unplugging carries no value to judge, but it is as consequential as
215
- plugging in: unplugging a live payment key from a laptop would take
216
- production down just as effectively. */
217
272
  assertWritable(name, await get(name));
218
- await store.upsert({
219
- key: name,
220
- value: DISCONNECTED,
221
- secret: catalog.isSecret(name),
222
- updatedBy: meta.updatedBy || null,
223
- updatedAt: new Date()
224
- });
273
+ await write(name, null, meta, 'disconnect');
274
+ }
275
+
276
+ async function listVersions(name) {
277
+ if (!options.history) throw new Error('History is not enabled.');
278
+ try {
279
+ const rows = await store.listVersions(name, scope || undefined);
280
+ return rows.map(versionMetadata);
281
+ } catch {
282
+ readFailure('store');
283
+ return [];
284
+ }
285
+ }
286
+
287
+ async function purgeVersions() {
288
+ if (!options.history) throw new Error('History is not enabled.');
289
+ const count = await store.purgeVersions(new Date(now()), scope || undefined);
225
290
  forget();
226
- if (onChange) await onChange({ key: name, action: 'disconnect' });
291
+ return count;
227
292
  }
228
293
 
229
294
  /**
@@ -237,9 +302,11 @@ function createCredentialVault(options = {}) {
237
302
  async function status() {
238
303
  let rows = [];
239
304
  try {
240
- rows = (await store.findAll()) || [];
241
- } catch (error) {
242
- logger.warn(`[credentials] status read failed: ${error.message}`);
305
+ rows = await store.findAll(scope || undefined, { strict });
306
+ if (!Array.isArray(rows) || rows.some(row => !row || typeof row.key !== 'string' || typeof row.value !== 'string' || (scope && !sameScope(row, scope)))) throw new Error();
307
+ } catch {
308
+ readFailure('store');
309
+ rows = [];
243
310
  }
244
311
  const byKey = new Map(rows.map((row) => [row.key, row]));
245
312
 
@@ -251,15 +318,15 @@ function createCredentialVault(options = {}) {
251
318
  const row = byKey.get(entry.key);
252
319
  const disconnected = row?.value === DISCONNECTED;
253
320
  const inStore = Boolean(row) && !disconnected;
254
- const inEnv = Boolean(env[entry.key]);
321
+ const inEnv = fallback === 'env' && Boolean(env[entry.key]);
255
322
 
256
323
  let preview = null;
257
324
  if (inStore) {
258
325
  try {
259
- const value = entry.secret ? decryptStored(row.value) : row.value;
326
+ const value = entry.secret ? decryptStored(row.value, row) : row.value;
260
327
  preview = entry.secret ? maskSecret(value) : value;
261
- } catch (error) {
262
- logger.error(`[credentials] ${entry.key} unreadable: ${error.message}`);
328
+ } catch {
329
+ readFailure('value');
263
330
  }
264
331
  } else if (inEnv) {
265
332
  preview = entry.secret ? maskSecret(env[entry.key]) : env[entry.key];
@@ -295,7 +362,8 @@ function createCredentialVault(options = {}) {
295
362
  const isRotating = () => Boolean(previousCipher);
296
363
 
297
364
  return {
298
- get, getMany, stored, set, disconnect, forget, status,
365
+ scope, get, getMany, stored, set, disconnect, forget, status,
366
+ listVersions, purgeVersions,
299
367
  isRotating, mask: maskSecret, DISCONNECTED,
300
368
  };
301
369
  }
@@ -0,0 +1,129 @@
1
+ /* global structuredClone */
2
+ const { normalizeScope, sameScope, rowId, versionMetadata } = require('./context');
3
+ const copy = value => structuredClone(value);
4
+
5
+ /** Retire the previous current version; never expire the current one. */
6
+ function append(rows, build, retentionMs) {
7
+ const version = (rows.at(-1)?.version || 0) + 1;
8
+ const row = build(version);
9
+ if (row.version !== version || !Number.isFinite(new Date(row.updatedAt).getTime())) throw new Error('Invalid version row.');
10
+ const result = copy(rows);
11
+ if (result.length) {
12
+ result.at(-1).retiredAt = row.updatedAt;
13
+ result.at(-1).expiresAt = new Date(new Date(row.updatedAt).getTime() + retentionMs);
14
+ }
15
+ result.push(copy(row));
16
+ return result;
17
+ }
18
+ function purge(rows, at) {
19
+ let count = 0;
20
+ for (const row of rows.slice(0, -1)) {
21
+ if (!row.purged && row.expiresAt && new Date(row.expiresAt).getTime() <= at.getTime()) {
22
+ delete row.value;
23
+ row.purged = true;
24
+ count++;
25
+ }
26
+ }
27
+ return count;
28
+ }
29
+
30
+ /** Each append is synchronous until its atomic in-memory commit. */
31
+ function createMemoryVersionedCredentialStore() {
32
+ const histories = new Map();
33
+ return {
34
+ supportsScopes: true,
35
+ async findAll(scope) {
36
+ scope = normalizeScope(scope);
37
+ return [...histories.values()].map(rows => rows.at(-1)).filter(row => sameScope(row, scope)).map(copy);
38
+ },
39
+ async upsert() { throw new Error('Use appendVersion for a versioned store.'); },
40
+ async appendVersion(key, scope, build, retentionMs) {
41
+ scope = normalizeScope(scope);
42
+ const id = rowId(key, scope);
43
+ const rows = append(histories.get(id) || [], build, retentionMs);
44
+ if (rows.at(-1).key !== key || !sameScope(rows.at(-1), scope)) throw new Error('Invalid version scope.');
45
+ histories.set(id, rows);
46
+ return copy(rows.at(-1));
47
+ },
48
+ async findVersion(key, version, scope) {
49
+ return copy((histories.get(rowId(key, normalizeScope(scope))) || []).find(row => row.version === version) || null);
50
+ },
51
+ async listVersions(key, scope) {
52
+ return (histories.get(rowId(key, normalizeScope(scope))) || []).slice().reverse().map(versionMetadata);
53
+ },
54
+ async purgeVersions(at, scope) {
55
+ scope = normalizeScope(scope);
56
+ let count = 0;
57
+ for (const rows of histories.values()) if (sameScope(rows.at(-1), scope)) count += purge(rows, at);
58
+ return count;
59
+ }
60
+ };
61
+ }
62
+
63
+ /** One document per scoped key; Mongo's unique _id plus revision CAS avoids lost writes.
64
+ * Use a dedicated collection. History grows with writes; applications must archive
65
+ * metadata before Mongo's document-size limit when using long-lived high-volume keys.
66
+ */
67
+ function createMongoVersionedCredentialStore({ collection, isReady = () => true, maxTimeMS = 3000 } = {}) {
68
+ if (!collection || !['find', 'findOne', 'updateOne', 'insertOne'].every(method => typeof collection[method] === 'function')) {
69
+ throw new Error('A Mongo collection with find/findOne/updateOne/insertOne is required.');
70
+ }
71
+ const ready = () => { if (!isReady()) throw new Error('Credential store unavailable.'); };
72
+ const filterScope = scope => normalizeScope(scope) || { tenant: null, environment: null };
73
+ async function documents(scope) {
74
+ ready();
75
+ return collection.find(filterScope(scope), { maxTimeMS }).toArray();
76
+ }
77
+ async function mutate(id, change) {
78
+ for (let attempt = 0; attempt < 32; attempt++) {
79
+ ready();
80
+ const old = await collection.findOne({ _id: id }, { maxTimeMS });
81
+ const next = change(copy(old));
82
+ if (!old) {
83
+ try { await collection.insertOne({ _id: id, revision: 1, ...next }); return next; }
84
+ catch (error) { if (error.code === 11000) continue; throw new Error('Credential store write failed.'); }
85
+ }
86
+ const result = await collection.updateOne({ _id: id, revision: old.revision },
87
+ { $set: { ...next, revision: old.revision + 1 } });
88
+ if (result.matchedCount === 1) return next;
89
+ }
90
+ throw new Error('Credential store write contention.');
91
+ }
92
+ return {
93
+ supportsScopes: true,
94
+ async findAll(scope) { return (await documents(scope)).map(doc => copy(doc.versions.at(-1))); },
95
+ async upsert() { throw new Error('Use appendVersion for a versioned store.'); },
96
+ async appendVersion(key, scope, build, retentionMs) {
97
+ scope = normalizeScope(scope);
98
+ const doc = await mutate(rowId(key, scope), old => {
99
+ const versions = append(old?.versions || [], build, retentionMs);
100
+ if (versions.at(-1).key !== key || !sameScope(versions.at(-1), scope)) throw new Error('Invalid version scope.');
101
+ return { key, ...(scope || { tenant: null, environment: null }), versions };
102
+ });
103
+ return copy(doc.versions.at(-1));
104
+ },
105
+ async findVersion(key, version, scope) {
106
+ ready();
107
+ const doc = await collection.findOne({ _id: rowId(key, normalizeScope(scope)) }, { maxTimeMS });
108
+ return copy(doc?.versions.find(row => row.version === version) || null);
109
+ },
110
+ async listVersions(key, scope) {
111
+ ready();
112
+ const doc = await collection.findOne({ _id: rowId(key, normalizeScope(scope)) }, { maxTimeMS });
113
+ return (doc?.versions || []).slice().reverse().map(versionMetadata);
114
+ },
115
+ async purgeVersions(at, scope) {
116
+ let count = 0;
117
+ for (const doc of await documents(scope)) {
118
+ let changed = 0;
119
+ await mutate(doc._id, old => {
120
+ changed = purge(old.versions, at);
121
+ return { key: old.key, tenant: old.tenant, environment: old.environment, versions: old.versions };
122
+ });
123
+ count += changed;
124
+ }
125
+ return count;
126
+ }
127
+ };
128
+ }
129
+ module.exports = { createMemoryVersionedCredentialStore, createMongoVersionedCredentialStore };