@astratra/credentials 0.2.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/src/index.d.ts ADDED
@@ -0,0 +1,304 @@
1
+ /*
2
+ * Structural express types, declared here rather than pulled from @types/express:
3
+ * a package that only hands back a router should not force a type dependency on
4
+ * its consumers.
5
+ */
6
+ export interface RequestLike {
7
+ params?: Record<string, string>;
8
+ body?: Record<string, unknown>;
9
+ user?: Record<string, unknown>;
10
+ [key: string]: unknown;
11
+ }
12
+
13
+ export interface ResponseLike {
14
+ status(statusCode: number): { json(payload: unknown): unknown };
15
+ [key: string]: unknown;
16
+ }
17
+
18
+ export type NextFunction = (error?: unknown) => unknown;
19
+ export type RequestHandler = (req: RequestLike, res: ResponseLike, next: NextFunction) => unknown;
20
+
21
+ /** An express Router — opaque here, mount it with `app.use(path, router)`. */
22
+ export type Router = unknown;
23
+
24
+ export interface CredentialEntryInput {
25
+ key: string;
26
+ label?: string;
27
+ /** Defaults to true. A public client id or sender address should be false. */
28
+ secret?: boolean;
29
+ help?: string;
30
+ where?: string;
31
+ placeholder?: string;
32
+ }
33
+
34
+ export interface CredentialSpaceInput {
35
+ id: string;
36
+ label?: string;
37
+ hint?: string;
38
+ keys: CredentialEntryInput[];
39
+ }
40
+
41
+ export interface CredentialEntry {
42
+ key: string;
43
+ label: string;
44
+ secret: boolean;
45
+ help: string | null;
46
+ where: string | null;
47
+ placeholder: string | null;
48
+ space: string;
49
+ }
50
+
51
+ export interface CredentialSpace {
52
+ id: string;
53
+ label: string;
54
+ hint: string | null;
55
+ keys: CredentialEntry[];
56
+ }
57
+
58
+ export interface CredentialCatalog {
59
+ spaces: CredentialSpace[];
60
+ has(key: string): boolean;
61
+ describe(key: string): CredentialEntry | null;
62
+ isReserved(key: string): boolean;
63
+ isSecret(key: string): boolean;
64
+ keys(): string[];
65
+ }
66
+
67
+ export function createCredentialCatalog(options: {
68
+ spaces: CredentialSpaceInput[];
69
+ reservedKeys?: string[];
70
+ }): CredentialCatalog;
71
+
72
+ export type ValueClass = 'live' | 'test' | 'unknown';
73
+
74
+ export const LIVE: 'live';
75
+ export const TEST: 'test';
76
+ export const UNKNOWN: 'unknown';
77
+
78
+ export interface WritePermission {
79
+ ok: boolean;
80
+ reason?: string;
81
+ }
82
+
83
+ export interface ValueGuard {
84
+ isGuarded(key: string): boolean;
85
+ classify(value: unknown): ValueClass;
86
+ mayRead(key: string, context?: { value?: unknown; decidingValue?: unknown }): boolean;
87
+ mayWrite(key: string, value: unknown): WritePermission;
88
+ restrictsHere(key: string): WritePermission;
89
+ decidingKey: string | null;
90
+ isProduction(): boolean;
91
+ }
92
+
93
+ export function createValueGuard(options?: {
94
+ keys?: string[];
95
+ decidingKey?: string;
96
+ classify?: (value: unknown) => ValueClass;
97
+ livePattern?: RegExp;
98
+ testPattern?: RegExp;
99
+ isProduction?: () => boolean;
100
+ restrictedMessage?: string;
101
+ env?: NodeJS.ProcessEnv;
102
+ }): ValueGuard;
103
+
104
+ export function createPermissiveGuard(): ValueGuard;
105
+
106
+ export interface CredentialRow {
107
+ key: string;
108
+ value: string;
109
+ secret?: boolean;
110
+ updatedAt?: Date | string | null;
111
+ updatedBy?: string | null;
112
+ }
113
+
114
+ export interface CredentialStore {
115
+ findAll(): Promise<CredentialRow[]>;
116
+ upsert(row: CredentialRow): Promise<void>;
117
+ }
118
+
119
+ export interface ChallengeRecord {
120
+ codeHash?: string | null;
121
+ codeExpiresAt?: Date | string | null;
122
+ attempts?: number;
123
+ unlockedUntil?: Date | string | null;
124
+ lastRequestedAt?: Date | string | null;
125
+ }
126
+
127
+ export interface ChallengeStore {
128
+ find(subjectId: string | number): Promise<ChallengeRecord | null>;
129
+ save(subjectId: string | number, record: ChallengeRecord): Promise<void>;
130
+ }
131
+
132
+ export function createMemoryCredentialStore(initialRows?: CredentialRow[]): CredentialStore;
133
+ export function createMemoryChallengeStore(): ChallengeStore;
134
+
135
+ export function createMongoCredentialStore(options: {
136
+ collection: unknown;
137
+ isReady?: () => boolean;
138
+ maxTimeMS?: number;
139
+ }): CredentialStore;
140
+
141
+ export function createMongoChallengeStore(options: { collection: unknown }): ChallengeStore;
142
+
143
+ export interface FieldCipher {
144
+ encrypt(plaintext: string): string;
145
+ decrypt(payload: string): string;
146
+ }
147
+
148
+ export interface CredentialStatusEntry {
149
+ key: string;
150
+ label: string;
151
+ help: string | null;
152
+ where: string | null;
153
+ placeholder: string | null;
154
+ secret: boolean;
155
+ readOnly: boolean;
156
+ readOnlyReason: string | null;
157
+ configured: boolean;
158
+ source: 'interface' | 'environment' | 'disconnected' | 'absent';
159
+ preview: string | null;
160
+ updatedAt: Date | string | null;
161
+ }
162
+
163
+ export interface CredentialStatus {
164
+ spaces: Array<{
165
+ id: string;
166
+ label: string;
167
+ hint: string | null;
168
+ keys: CredentialStatusEntry[];
169
+ }>;
170
+ }
171
+
172
+ export interface CredentialVault {
173
+ get(key: string): Promise<string | null>;
174
+ getMany(keys: string[]): Promise<Record<string, string | null>>;
175
+ stored(): Promise<Map<string, string | null>>;
176
+ set(key: string, value: unknown, meta?: { updatedBy?: string | null }): Promise<void>;
177
+ disconnect(key: string, meta?: { updatedBy?: string | null }): Promise<void>;
178
+ forget(): void;
179
+ status(): Promise<CredentialStatus>;
180
+ isRotating(): boolean;
181
+ mask(value: string | null | undefined): string | null;
182
+ DISCONNECTED: string;
183
+ }
184
+
185
+ export function createCredentialVault(options: {
186
+ store: CredentialStore;
187
+ catalog: CredentialCatalog;
188
+ cipher: FieldCipher;
189
+ /** The generation being retired, for the duration of a rotation. */
190
+ previousCipher?: Pick<FieldCipher, 'decrypt'>;
191
+ guard?: ValueGuard;
192
+ env?: NodeJS.ProcessEnv;
193
+ cacheMs?: number;
194
+ now?: () => number;
195
+ logger?: { warn?(message: string): void; error?(message: string): void };
196
+ onChange?: (event: { key: string; action: 'set' | 'disconnect' }) => void | Promise<void>;
197
+ }): CredentialVault;
198
+
199
+ export const DISCONNECTED: string;
200
+
201
+ export interface HydrationResult {
202
+ applied: number;
203
+ removed: number;
204
+ restored: number;
205
+ }
206
+
207
+ export interface EnvHydrator {
208
+ hydrate(keys: string[]): Promise<HydrationResult>;
209
+ startRefresh(
210
+ keys: string[],
211
+ options?: { intervalMs?: number; onChange?: (result: HydrationResult) => void }
212
+ ): () => void;
213
+ reset(): void;
214
+ }
215
+
216
+ export function createEnvHydrator(options: {
217
+ vault: Pick<CredentialVault, 'stored'>;
218
+ guard?: ValueGuard;
219
+ env?: NodeJS.ProcessEnv;
220
+ logger?: { warn?(message: string): void };
221
+ }): EnvHydrator;
222
+
223
+ export interface UnlockChallenge {
224
+ requestCode(subjectId: string | number): Promise<Record<string, unknown> & { expiresInMs: number }>;
225
+ verifyCode(subjectId: string | number, code: string): Promise<{ unlockedUntil: Date }>;
226
+ unlockedUntil(subjectId: string | number): Promise<Date | null>;
227
+ assertUnlocked(subjectId: string | number): Promise<void>;
228
+ codeTtlMs: number;
229
+ windowMs: number;
230
+ maxAttempts: number;
231
+ resendDelayMs: number;
232
+ }
233
+
234
+ export function createUnlockChallenge(options: {
235
+ store: ChallengeStore;
236
+ deliverCode: (payload: {
237
+ subjectId: string | number;
238
+ code: string;
239
+ expiresInMs: number;
240
+ }) => Promise<Record<string, unknown> | void> | Record<string, unknown> | void;
241
+ codeTtlMs?: number;
242
+ windowMs?: number;
243
+ maxAttempts?: number;
244
+ resendDelayMs?: number;
245
+ now?: () => number;
246
+ }): UnlockChallenge;
247
+
248
+ export const DEFAULT_CODE_TTL_MS: number;
249
+ export const DEFAULT_WINDOW_MS: number;
250
+ export const DEFAULT_MAX_ATTEMPTS: number;
251
+ export const DEFAULT_RESEND_DELAY_MS: number;
252
+
253
+ export function createCredentialsRoutes(options: {
254
+ vault: CredentialVault;
255
+ authorize: RequestHandler;
256
+ challenge?: UnlockChallenge | null;
257
+ subjectOf?: (req: unknown) => string | number;
258
+ logger?: { info?(message: string): void };
259
+ }): Router;
260
+
261
+ export interface RotationReport {
262
+ apply: boolean;
263
+ scanned: number;
264
+ rotated: number;
265
+ already: number;
266
+ plain: number;
267
+ skipped: number;
268
+ unreadable: number;
269
+ written: number;
270
+ unreadableKeys: string[];
271
+ }
272
+
273
+ export interface RotationCompletion {
274
+ complete: boolean;
275
+ pending: number;
276
+ unreadable: number;
277
+ unreadableKeys: string[];
278
+ }
279
+
280
+ export type RotationDecision =
281
+ | { status: 'rotated'; value: string }
282
+ | { status: 'already' | 'plain' | 'skipped' | 'unreadable' };
283
+
284
+ export interface CredentialRotation {
285
+ /** Read-only: what a rotation would do. Writes nothing. */
286
+ plan(): Promise<RotationReport>;
287
+ /** Rewrite every value the retiring cipher can still read. */
288
+ apply(): Promise<RotationReport>;
289
+ /** May the retiring cipher be dropped yet? */
290
+ isComplete(): Promise<RotationCompletion>;
291
+ decide(row: CredentialRow): RotationDecision;
292
+ }
293
+
294
+ export function createCredentialRotation(options: {
295
+ store: CredentialStore;
296
+ catalog: CredentialCatalog;
297
+ to: FieldCipher;
298
+ from: Pick<FieldCipher, 'decrypt'>;
299
+ logger?: { warn?(message: string): void; error?(message: string): void };
300
+ }): CredentialRotation;
301
+
302
+ export function assertAdapter(adapter: unknown, methods: string[], name: string): void;
303
+ export function maskSecret(value: string | null | undefined): string | null;
304
+ export function maskEmail(email: string | null | undefined): string;
package/src/index.js ADDED
@@ -0,0 +1,11 @@
1
+ module.exports = {
2
+ ...require('./catalog'),
3
+ ...require('./valueGuard'),
4
+ ...require('./stores'),
5
+ ...require('./vault'),
6
+ ...require('./rotation'),
7
+ ...require('./envHydrator'),
8
+ ...require('./unlockChallenge'),
9
+ ...require('./routes'),
10
+ ...require('./utils')
11
+ };
@@ -0,0 +1,165 @@
1
+ /**
2
+ * Changing the cipher without losing what it protects.
3
+ *
4
+ * The failure this exists to prevent is quiet. Swap the encryption key and
5
+ * nothing throws: the vault catches a failed decrypt per row, falls back to the
6
+ * environment, and every stored key simply stops being used. Payments go
7
+ * through the old .env value, or stop going through at all. You find out from
8
+ * a customer, not from a log.
9
+ *
10
+ * So a rotation is three moves, and the middle one is the whole point:
11
+ *
12
+ * 1. hand the vault BOTH ciphers — new as `cipher`, old as `previousCipher`.
13
+ * Nothing has moved yet, and nothing is broken;
14
+ * 2. run this: every value readable with the old cipher is rewritten with
15
+ * the new one, in place, one at a time;
16
+ * 3. once `plan()` reports nothing left and nothing unreadable, drop
17
+ * `previousCipher`.
18
+ *
19
+ * Never skip step 3's check. A value neither cipher can read is already lost,
20
+ * and dropping the old cipher is what makes that permanent.
21
+ *
22
+ * Every operation is idempotent: a value already carrying the new generation is
23
+ * recognised and left alone, so an interrupted run is simply re-run.
24
+ */
25
+ const { assertAdapter } = require('./utils');
26
+
27
+ const DISCONNECTED = '__disconnected__';
28
+ const MAX_SAMPLES = 10;
29
+
30
+ /**
31
+ * @param {object} options
32
+ * @param {object} options.store credential store adapter (findAll, upsert).
33
+ * @param {object} options.catalog from createCredentialCatalog().
34
+ * @param {object} options.to the cipher to migrate TO. Needs encrypt+decrypt.
35
+ * @param {object} options.from the cipher being retired. Needs decrypt.
36
+ * @param {object} [options.logger] { warn, error }.
37
+ */
38
+ function createCredentialRotation(options = {}) {
39
+ const store = options.store;
40
+ assertAdapter(store, ['findAll', 'upsert'], 'options.store');
41
+
42
+ const catalog = options.catalog;
43
+ if (!catalog || typeof catalog.isSecret !== 'function') {
44
+ throw new Error('createCredentialRotation requires options.catalog from createCredentialCatalog().');
45
+ }
46
+
47
+ const to = options.to;
48
+ if (!to || typeof to.encrypt !== 'function' || typeof to.decrypt !== 'function') {
49
+ throw new Error('createCredentialRotation requires options.to with encrypt() and decrypt().');
50
+ }
51
+
52
+ const from = options.from;
53
+ if (!from || typeof from.decrypt !== 'function') {
54
+ throw new Error('createCredentialRotation requires options.from with decrypt().');
55
+ }
56
+
57
+ const logger = options.logger || { warn() {}, error() {} };
58
+
59
+ /**
60
+ * What should happen to one stored row.
61
+ *
62
+ * The new cipher is tried FIRST. A value already migrated is then recognised
63
+ * as such instead of being reported unreadable — which is what makes the run
64
+ * safe to repeat.
65
+ *
66
+ * @returns {{status: "rotated"|"already"|"plain"|"skipped"|"unreadable", value?: string}}
67
+ */
68
+ function decide(row) {
69
+ if (!row || row.value === null || row.value === undefined || row.value === '') return { status: 'skipped' };
70
+ /* A disconnect marker is not ciphertext. Rewriting it would turn a key
71
+ that is deliberately unplugged into one that is merely unreadable. */
72
+ if (row.value === DISCONNECTED) return { status: 'skipped' };
73
+ /* A value declared not-secret is stored in the clear on purpose — a public
74
+ client id has to stay readable in the interface. */
75
+ if (!catalog.isSecret(row.key)) return { status: 'plain' };
76
+
77
+ try {
78
+ to.decrypt(row.value);
79
+ return { status: 'already' };
80
+ } catch {
81
+ /* Not migrated yet — the normal case. */
82
+ }
83
+
84
+ try {
85
+ return { status: 'rotated', value: to.encrypt(from.decrypt(row.value)) };
86
+ } catch {
87
+ /* Neither generation reads it. We do not guess, and we do not overwrite. */
88
+ }
89
+
90
+ return { status: 'unreadable' };
91
+ }
92
+
93
+ async function walk(apply) {
94
+ const report = {
95
+ apply,
96
+ scanned: 0,
97
+ rotated: 0,
98
+ already: 0,
99
+ plain: 0,
100
+ skipped: 0,
101
+ unreadable: 0,
102
+ written: 0,
103
+ unreadableKeys: []
104
+ };
105
+
106
+ let rows;
107
+ 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
+ }
113
+
114
+ for (const row of rows) {
115
+ report.scanned += 1;
116
+ const decision = decide(row);
117
+ report[decision.status] += 1;
118
+
119
+ if (decision.status === 'unreadable' && report.unreadableKeys.length < MAX_SAMPLES) {
120
+ report.unreadableKeys.push(row.key);
121
+ }
122
+
123
+ if (decision.status === 'rotated' && apply) {
124
+ await store.upsert({
125
+ key: row.key,
126
+ value: decision.value,
127
+ secret: true,
128
+ updatedBy: row.updatedBy || null,
129
+ updatedAt: new Date()
130
+ });
131
+ report.written += 1;
132
+ }
133
+ }
134
+
135
+ return report;
136
+ }
137
+
138
+ return {
139
+ /** Read-only: what a rotation WOULD do. Writes nothing. */
140
+ plan: () => walk(false),
141
+
142
+ /** Rewrite every value the retiring cipher can still read. */
143
+ apply: () => walk(true),
144
+
145
+ /**
146
+ * May the retiring cipher be dropped?
147
+ *
148
+ * The only question that matters at the end, and the one worth answering
149
+ * out loud: nothing left to migrate, and nothing that neither cipher reads.
150
+ */
151
+ async isComplete() {
152
+ const report = await walk(false);
153
+ return {
154
+ complete: report.rotated === 0 && report.unreadable === 0,
155
+ pending: report.rotated,
156
+ unreadable: report.unreadable,
157
+ unreadableKeys: report.unreadableKeys
158
+ };
159
+ },
160
+
161
+ decide
162
+ };
163
+ }
164
+
165
+ module.exports = { createCredentialRotation };
package/src/routes.js ADDED
@@ -0,0 +1,102 @@
1
+ /**
2
+ * The service-keys screen, server side.
3
+ *
4
+ * These keys commit the whole platform's payments and mail, not one tenant's.
5
+ * Which accounts may reach them is your decision, so `authorize` is required —
6
+ * there is no sensible default for "who owns the money".
7
+ *
8
+ * One rule holds the whole file: a secret value goes in and never comes back
9
+ * out. Every response describes a key; none carries one.
10
+ */
11
+ const express = require('express');
12
+ const { body, param } = require('express-validator');
13
+ const { apiResponse, asyncHandler, validateMiddleware } = require('@astratra/core');
14
+
15
+ const NOOP_LOGGER = { info() {} };
16
+
17
+ const setValidation = [
18
+ param('key').trim().notEmpty().isLength({ max: 200 }).withMessage('key must be between 1 and 200 characters'),
19
+ body('value').isString().trim().notEmpty().withMessage('value is required')
20
+ ];
21
+
22
+ const unlockValidation = [
23
+ body('code').isString().trim().notEmpty().withMessage('code is required')
24
+ ];
25
+
26
+ /**
27
+ * @param {object} options
28
+ * @param {object} options.vault from createCredentialVault().
29
+ * @param {Function} options.authorize express middleware guarding every route.
30
+ * @param {object} [options.challenge] from createUnlockChallenge(). Without it,
31
+ * no second factor stands between an admin session and a payment key.
32
+ * @param {Function} [options.subjectOf] (req) => id. Defaults to req.user.id.
33
+ * @param {object} [options.logger] { info } — records who changed what, never the value.
34
+ */
35
+ function createCredentialsRoutes(options = {}) {
36
+ const vault = options.vault;
37
+ if (!vault || typeof vault.status !== 'function') {
38
+ throw new Error('createCredentialsRoutes requires options.vault from createCredentialVault().');
39
+ }
40
+
41
+ const authorize = options.authorize;
42
+ if (typeof authorize !== 'function') {
43
+ throw new Error('createCredentialsRoutes requires options.authorize.');
44
+ }
45
+
46
+ const challenge = options.challenge || null;
47
+ const subjectOf = options.subjectOf || ((req) => req.user && req.user.id);
48
+ const logger = options.logger || NOOP_LOGGER;
49
+
50
+ const requireUnlocked = async (req) => {
51
+ if (challenge) await challenge.assertUnlocked(subjectOf(req));
52
+ };
53
+
54
+ const router = express.Router();
55
+ router.use(authorize);
56
+
57
+ /** The state of every managed key. */
58
+ router.get('/', asyncHandler(async (req, res) => {
59
+ const state = await vault.status();
60
+ /* The screen needs to know whether the window is open: otherwise it offers
61
+ "Edit" only to hit a refusal once the key has been typed. */
62
+ const unlockedUntil = challenge ? await challenge.unlockedUntil(subjectOf(req)) : null;
63
+ return apiResponse(res, 200, 'Credential status', { ...state, unlockedUntil });
64
+ }));
65
+
66
+ /** Send the change code to the address already on the account. */
67
+ router.post('/challenge', asyncHandler(async (req, res) => {
68
+ if (!challenge) return apiResponse(res, 404, 'No unlock challenge is configured.');
69
+ const result = await challenge.requestCode(subjectOf(req));
70
+ return apiResponse(res, 200, 'A code has been sent.', result);
71
+ }));
72
+
73
+ /** Check the code and open the editing window. */
74
+ router.post('/unlock', validateMiddleware(unlockValidation), asyncHandler(async (req, res) => {
75
+ if (!challenge) return apiResponse(res, 404, 'No unlock challenge is configured.');
76
+ const result = await challenge.verifyCode(subjectOf(req), req.body.code);
77
+ return apiResponse(res, 200, 'Keys can be changed for the next few minutes.', result);
78
+ }));
79
+
80
+ /** Store a key. */
81
+ router.put('/:key', validateMiddleware(setValidation), asyncHandler(async (req, res) => {
82
+ /* Knowing the account password is not enough: replacing a payment key with
83
+ your own breaks nothing visible, the money simply goes elsewhere. */
84
+ await requireUnlocked(req);
85
+ await vault.set(req.params.key, req.body.value, { updatedBy: subjectOf(req) });
86
+ logger.info(`[credentials] ${req.params.key} stored by ${subjectOf(req)}`);
87
+ return apiResponse(res, 200, 'Key stored.', { key: req.params.key });
88
+ }));
89
+
90
+ /** Unplug a key — the environment does not take over. */
91
+ router.delete('/:key', asyncHandler(async (req, res) => {
92
+ /* Unplugging a service is as consequential as plugging one in. */
93
+ await requireUnlocked(req);
94
+ await vault.disconnect(req.params.key, { updatedBy: subjectOf(req) });
95
+ logger.info(`[credentials] ${req.params.key} disconnected by ${subjectOf(req)}`);
96
+ return apiResponse(res, 200, 'Key disconnected.', { key: req.params.key });
97
+ }));
98
+
99
+ return router;
100
+ }
101
+
102
+ module.exports = { createCredentialsRoutes };
package/src/stores.js ADDED
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Persistence adapters.
3
+ *
4
+ * The vault never talks to a database itself — it talks to one of these, or to
5
+ * whatever you write instead. Two contracts, both tiny:
6
+ *
7
+ * credential store : findAll() -> rows, upsert(row)
8
+ * challenge store : find(subjectId) -> record|null, save(subjectId, record)
9
+ *
10
+ * A credential row is { key, value, secret, updatedAt, updatedBy }. `value` is
11
+ * already encrypted when `secret` is true — encryption happens in the vault, so
12
+ * an adapter never sees a plaintext secret it might log by accident.
13
+ */
14
+
15
+ function clone(value) {
16
+ return value == null ? value : JSON.parse(JSON.stringify(value));
17
+ }
18
+
19
+ /** In-process adapter for tests and local development. Not persistent. */
20
+ function createMemoryCredentialStore(initialRows = []) {
21
+ const rows = new Map(initialRows.map((row) => [row.key, { ...row }]));
22
+
23
+ return {
24
+ async findAll() {
25
+ return [...rows.values()].map((row) => ({ ...row }));
26
+ },
27
+ async upsert(row) {
28
+ rows.set(row.key, { ...rows.get(row.key), ...row, updatedAt: row.updatedAt || new Date() });
29
+ }
30
+ };
31
+ }
32
+
33
+ /** In-process adapter for unlock challenges. Not persistent. */
34
+ function createMemoryChallengeStore() {
35
+ const records = new Map();
36
+
37
+ return {
38
+ async find(subjectId) {
39
+ return clone(records.get(String(subjectId))) || null;
40
+ },
41
+ async save(subjectId, record) {
42
+ records.set(String(subjectId), clone(record));
43
+ }
44
+ };
45
+ }
46
+
47
+ /**
48
+ * MongoDB adapter over a driver collection — `db.collection('credentials')`,
49
+ * or `mongooseConnection.collection('credentials')`. No mongoose import, no
50
+ * schema, no model registration.
51
+ *
52
+ * `isReady` matters more than it looks. Mongoose queues queries while it is
53
+ * disconnected: without this guard a read would hang instead of falling back
54
+ * to the environment — a frozen payment rather than a working one.
55
+ *
56
+ * @param {object} options
57
+ * @param {object} options.collection a MongoDB driver collection.
58
+ * @param {Function} [options.isReady] () => boolean, checked before each read.
59
+ * @param {number} [options.maxTimeMS] server-side cap on the read. Default 3000.
60
+ */
61
+ function createMongoCredentialStore(options = {}) {
62
+ const collection = options.collection;
63
+ if (!collection || typeof collection.find !== 'function') {
64
+ throw new Error('createMongoCredentialStore requires options.collection.');
65
+ }
66
+ const isReady = options.isReady || (() => true);
67
+ const maxTimeMS = options.maxTimeMS || 3000;
68
+
69
+ return {
70
+ async findAll() {
71
+ if (!isReady()) return [];
72
+ const cursor = collection.find(
73
+ {},
74
+ { projection: { key: 1, value: 1, secret: 1, updatedAt: 1, updatedBy: 1 } }
75
+ );
76
+ const capped = typeof cursor.maxTimeMS === 'function' ? cursor.maxTimeMS(maxTimeMS) : cursor;
77
+ return capped.toArray();
78
+ },
79
+ async upsert(row) {
80
+ await collection.updateOne(
81
+ { key: row.key },
82
+ { $set: { ...row, updatedAt: row.updatedAt || new Date() } },
83
+ { upsert: true }
84
+ );
85
+ }
86
+ };
87
+ }
88
+
89
+ /** MongoDB adapter for unlock challenges, over a driver collection. */
90
+ function createMongoChallengeStore(options = {}) {
91
+ const collection = options.collection;
92
+ if (!collection || typeof collection.findOne !== 'function') {
93
+ throw new Error('createMongoChallengeStore requires options.collection.');
94
+ }
95
+
96
+ return {
97
+ async find(subjectId) {
98
+ return collection.findOne({ subject: String(subjectId) });
99
+ },
100
+ async save(subjectId, record) {
101
+ await collection.updateOne(
102
+ { subject: String(subjectId) },
103
+ { $set: { ...record, subject: String(subjectId), updatedAt: new Date() } },
104
+ { upsert: true }
105
+ );
106
+ }
107
+ };
108
+ }
109
+
110
+ module.exports = {
111
+ createMemoryCredentialStore,
112
+ createMemoryChallengeStore,
113
+ createMongoCredentialStore,
114
+ createMongoChallengeStore
115
+ };