@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/LICENSE +21 -0
- package/README.md +309 -0
- package/package.json +42 -0
- package/src/catalog.js +83 -0
- package/src/envHydrator.js +130 -0
- package/src/index.d.ts +304 -0
- package/src/index.js +11 -0
- package/src/rotation.js +165 -0
- package/src/routes.js +102 -0
- package/src/stores.js +115 -0
- package/src/unlockChallenge.js +153 -0
- package/src/utils.js +40 -0
- package/src/valueGuard.js +115 -0
- package/src/vault.js +303 -0
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The one-time code that authorises a key change.
|
|
3
|
+
*
|
|
4
|
+
* The principle: knowing the account password is not enough — you must also be
|
|
5
|
+
* able to read the account's inbox. Replacing a payment key with your own
|
|
6
|
+
* breaks nothing visible; the money simply goes somewhere else. That is the
|
|
7
|
+
* kind of theft you only notice on a statement.
|
|
8
|
+
*
|
|
9
|
+
* This module knows nothing about email. It generates, stores and checks the
|
|
10
|
+
* code; `deliverCode` is yours, and it is where you decide whether the code
|
|
11
|
+
* travels by mail, SMS or anything else. Deliver it to the address ALREADY on
|
|
12
|
+
* the account, never to one supplied in the request — that would hand a thief
|
|
13
|
+
* the means to send it to themselves.
|
|
14
|
+
*/
|
|
15
|
+
const crypto = require('crypto');
|
|
16
|
+
const AppError = require('@astratra/core').AppError;
|
|
17
|
+
const { assertAdapter } = require('./utils');
|
|
18
|
+
|
|
19
|
+
const DEFAULT_CODE_TTL_MS = 10 * 60 * 1000; // the code expires in ten minutes
|
|
20
|
+
const DEFAULT_WINDOW_MS = 10 * 60 * 1000; // and then opens ten minutes of editing
|
|
21
|
+
const DEFAULT_MAX_ATTEMPTS = 5;
|
|
22
|
+
const DEFAULT_RESEND_DELAY_MS = 60 * 1000; // at most one send per minute
|
|
23
|
+
|
|
24
|
+
/* Math.random() is fine for a display code. Not here: these six digits protect
|
|
25
|
+
what collects your payments, and a predictable generator is guessable. */
|
|
26
|
+
function newCode() {
|
|
27
|
+
return String(crypto.randomInt(0, 1_000_000)).padStart(6, '0');
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const hash = (code) => crypto.createHash('sha256').update(String(code)).digest('hex');
|
|
31
|
+
|
|
32
|
+
/** Constant-time comparison: the response time must reveal nothing. */
|
|
33
|
+
function sameHash(a, b) {
|
|
34
|
+
const left = Buffer.from(String(a || ''), 'utf8');
|
|
35
|
+
const right = Buffer.from(String(b || ''), 'utf8');
|
|
36
|
+
if (left.length !== right.length) return false;
|
|
37
|
+
return crypto.timingSafeEqual(left, right);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* @param {object} options
|
|
42
|
+
* @param {object} options.store challenge store adapter (find, save).
|
|
43
|
+
* @param {Function} options.deliverCode async ({ subjectId, code, expiresInMs }) => any.
|
|
44
|
+
* @param {number} [options.codeTtlMs]
|
|
45
|
+
* @param {number} [options.windowMs]
|
|
46
|
+
* @param {number} [options.maxAttempts]
|
|
47
|
+
* @param {number} [options.resendDelayMs]
|
|
48
|
+
* @param {Function} [options.now] () => epoch ms, for tests.
|
|
49
|
+
*/
|
|
50
|
+
function createUnlockChallenge(options = {}) {
|
|
51
|
+
const store = options.store;
|
|
52
|
+
assertAdapter(store, ['find', 'save'], 'options.store');
|
|
53
|
+
|
|
54
|
+
const deliverCode = options.deliverCode;
|
|
55
|
+
if (typeof deliverCode !== 'function') {
|
|
56
|
+
throw new Error('createUnlockChallenge requires options.deliverCode.');
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const codeTtlMs = options.codeTtlMs || DEFAULT_CODE_TTL_MS;
|
|
60
|
+
const windowMs = options.windowMs || DEFAULT_WINDOW_MS;
|
|
61
|
+
const maxAttempts = options.maxAttempts || DEFAULT_MAX_ATTEMPTS;
|
|
62
|
+
const resendDelayMs = options.resendDelayMs === undefined ? DEFAULT_RESEND_DELAY_MS : options.resendDelayMs;
|
|
63
|
+
const now = options.now || (() => Date.now());
|
|
64
|
+
|
|
65
|
+
const asTime = (value) => (value ? new Date(value).getTime() : 0);
|
|
66
|
+
|
|
67
|
+
/** Generate a code and hand it to your delivery function. */
|
|
68
|
+
async function requestCode(subjectId) {
|
|
69
|
+
const at = now();
|
|
70
|
+
const existing = await store.find(subjectId);
|
|
71
|
+
|
|
72
|
+
if (existing?.lastRequestedAt && at - asTime(existing.lastRequestedAt) < resendDelayMs) {
|
|
73
|
+
throw new AppError('A code was just sent. Wait a minute before asking for another.', 429);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const code = newCode();
|
|
77
|
+
await store.save(subjectId, {
|
|
78
|
+
codeHash: hash(code),
|
|
79
|
+
codeExpiresAt: new Date(at + codeTtlMs),
|
|
80
|
+
attempts: 0,
|
|
81
|
+
lastRequestedAt: new Date(at),
|
|
82
|
+
/* Asking for a new code CLOSES the window currently open: otherwise a
|
|
83
|
+
stolen session would ride the window you just opened yourself. */
|
|
84
|
+
unlockedUntil: null
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
const delivery = await deliverCode({ subjectId, code, expiresInMs: codeTtlMs });
|
|
88
|
+
return { ...(delivery || {}), expiresInMs: codeTtlMs };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Check the code and open the editing window. */
|
|
92
|
+
async function verifyCode(subjectId, code) {
|
|
93
|
+
const record = await store.find(subjectId);
|
|
94
|
+
const invalid = () => new AppError('That code is wrong or has expired. Ask for a new one.', 400);
|
|
95
|
+
|
|
96
|
+
if (!record?.codeHash || asTime(record.codeExpiresAt) < now()) throw invalid();
|
|
97
|
+
|
|
98
|
+
if ((record.attempts || 0) >= maxAttempts) {
|
|
99
|
+
/* The code is dead: erase it so no later attempt can succeed. */
|
|
100
|
+
await store.save(subjectId, { ...record, codeHash: null, codeExpiresAt: null });
|
|
101
|
+
throw new AppError('Too many attempts. Ask for a new code.', 429);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
if (!sameHash(hash(code), record.codeHash)) {
|
|
105
|
+
await store.save(subjectId, { ...record, attempts: (record.attempts || 0) + 1 });
|
|
106
|
+
throw invalid();
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/* The code has served; it will not serve again. */
|
|
110
|
+
const unlockedUntil = new Date(now() + windowMs);
|
|
111
|
+
await store.save(subjectId, {
|
|
112
|
+
...record,
|
|
113
|
+
codeHash: null,
|
|
114
|
+
codeExpiresAt: null,
|
|
115
|
+
attempts: 0,
|
|
116
|
+
unlockedUntil
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
return { unlockedUntil };
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Is the window open? Returns the deadline, or null. */
|
|
123
|
+
async function unlockedUntil(subjectId) {
|
|
124
|
+
const record = await store.find(subjectId);
|
|
125
|
+
const until = record?.unlockedUntil ? new Date(record.unlockedUntil) : null;
|
|
126
|
+
return until && until.getTime() > now() ? until : null;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Refuse the change while the window is closed. */
|
|
130
|
+
async function assertUnlocked(subjectId) {
|
|
131
|
+
if (await unlockedUntil(subjectId)) return;
|
|
132
|
+
throw new AppError('Request the emailed code before changing a key.', 403);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
return {
|
|
136
|
+
requestCode,
|
|
137
|
+
verifyCode,
|
|
138
|
+
unlockedUntil,
|
|
139
|
+
assertUnlocked,
|
|
140
|
+
codeTtlMs,
|
|
141
|
+
windowMs,
|
|
142
|
+
maxAttempts,
|
|
143
|
+
resendDelayMs
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
module.exports = {
|
|
148
|
+
createUnlockChallenge,
|
|
149
|
+
DEFAULT_CODE_TTL_MS,
|
|
150
|
+
DEFAULT_WINDOW_MS,
|
|
151
|
+
DEFAULT_MAX_ATTEMPTS,
|
|
152
|
+
DEFAULT_RESEND_DELAY_MS
|
|
153
|
+
};
|
package/src/utils.js
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Small helpers shared across the package. Nothing here is Astratra-specific;
|
|
3
|
+
* they exist so the modules below read the same way.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Fail at wiring time rather than at the first request. An adapter missing a
|
|
8
|
+
* method is a mistake in the caller's setup, and the earlier it is named the
|
|
9
|
+
* cheaper it is to fix.
|
|
10
|
+
*/
|
|
11
|
+
function assertAdapter(adapter, methods, name) {
|
|
12
|
+
for (const method of methods) {
|
|
13
|
+
if (!adapter || typeof adapter[method] !== 'function') {
|
|
14
|
+
throw new Error(`Astratra credentials requires ${name}.${method}().`);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Never show a secret in full: the last four characters are enough to
|
|
21
|
+
* recognise a key, never enough to use it. A screenshot of the settings
|
|
22
|
+
* screen must not compromise anything.
|
|
23
|
+
*/
|
|
24
|
+
function maskSecret(value) {
|
|
25
|
+
if (!value) return null;
|
|
26
|
+
const text = String(value);
|
|
27
|
+
return text.length <= 4 ? '••••' : `••••${text.slice(-4)}`;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Same idea for the address a one-time code was sent to: enough to confirm it
|
|
32
|
+
* is the right inbox, not enough to learn an address you did not already know.
|
|
33
|
+
*/
|
|
34
|
+
function maskEmail(email) {
|
|
35
|
+
const [name, domain] = String(email || '').split('@');
|
|
36
|
+
if (!domain) return '•••';
|
|
37
|
+
return `${name.slice(0, 2)}${'•'.repeat(Math.max(3, name.length - 2))}@${domain}`;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
module.exports = { assertAdapter, maskSecret, maskEmail };
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The rule that keeps a real key where it belongs.
|
|
3
|
+
*
|
|
4
|
+
* A development machine and production often share one credential store — that
|
|
5
|
+
* is the whole point of storing keys centrally. It is harmless while the values
|
|
6
|
+
* are test values; it is a disaster the day a laptop picks up a live payment
|
|
7
|
+
* key and starts charging real cards.
|
|
8
|
+
*
|
|
9
|
+
* So the judgement is made on the VALUE, not on the environment alone:
|
|
10
|
+
*
|
|
11
|
+
* a test value → usable anywhere;
|
|
12
|
+
* a live value → production only, no exception.
|
|
13
|
+
*
|
|
14
|
+
* Some keys cannot classify themselves. A webhook signing secret says nothing
|
|
15
|
+
* about which account it belongs to — but it belongs to the SAME account as the
|
|
16
|
+
* secret key, and must follow its fate. That is what `decidingKey` expresses:
|
|
17
|
+
* without it you would block the live key and let the matching signature
|
|
18
|
+
* through.
|
|
19
|
+
*
|
|
20
|
+
* Astratra guards nothing by default. Which keys move money, and how a live
|
|
21
|
+
* value is recognised, is the product's business.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
const LIVE = 'live';
|
|
25
|
+
const TEST = 'test';
|
|
26
|
+
const UNKNOWN = 'unknown';
|
|
27
|
+
|
|
28
|
+
const DEFAULT_RESTRICTED_MESSAGE =
|
|
29
|
+
'A live value for this key can only be saved from production. From anywhere else it would act on real data.';
|
|
30
|
+
|
|
31
|
+
function buildClassifier(options) {
|
|
32
|
+
if (typeof options.classify === 'function') return options.classify;
|
|
33
|
+
|
|
34
|
+
const livePattern = options.livePattern || null;
|
|
35
|
+
const testPattern = options.testPattern || null;
|
|
36
|
+
if (!livePattern && !testPattern) {
|
|
37
|
+
/* Nothing to recognise: every value is unclassified, and unclassified is
|
|
38
|
+
never treated as live. A guard that cannot tell must not block. */
|
|
39
|
+
return () => UNKNOWN;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
return (value) => {
|
|
43
|
+
const text = String(value == null ? '' : value);
|
|
44
|
+
if (livePattern && livePattern.test(text)) return LIVE;
|
|
45
|
+
if (testPattern && testPattern.test(text)) return TEST;
|
|
46
|
+
return UNKNOWN;
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* @param {object} [options]
|
|
52
|
+
* @param {string[]} [options.keys] key names this guard applies to.
|
|
53
|
+
* @param {string} [options.decidingKey] the key whose value classifies the group.
|
|
54
|
+
* @param {Function} [options.classify] (value) => 'live'|'test'|'unknown'.
|
|
55
|
+
* @param {RegExp} [options.livePattern] used when `classify` is not given.
|
|
56
|
+
* @param {RegExp} [options.testPattern] used when `classify` is not given.
|
|
57
|
+
* @param {Function} [options.isProduction] () => boolean.
|
|
58
|
+
* @param {string} [options.restrictedMessage] shown when a write is refused.
|
|
59
|
+
*/
|
|
60
|
+
function createValueGuard(options = {}) {
|
|
61
|
+
const guarded = new Set(options.keys || []);
|
|
62
|
+
const decidingKey = options.decidingKey || null;
|
|
63
|
+
const classify = buildClassifier(options);
|
|
64
|
+
const isProduction = options.isProduction
|
|
65
|
+
|| (() => (options.env || process.env).NODE_ENV === 'production');
|
|
66
|
+
const restrictedMessage = options.restrictedMessage || DEFAULT_RESTRICTED_MESSAGE;
|
|
67
|
+
|
|
68
|
+
const isGuarded = (name) => guarded.has(name);
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* May this key be read from the store, here and now?
|
|
72
|
+
* @param {string} name
|
|
73
|
+
* @param {object} [context]
|
|
74
|
+
* @param {*} [context.value] the value stored for this key.
|
|
75
|
+
* @param {*} [context.decidingValue] the value stored for the deciding key.
|
|
76
|
+
*/
|
|
77
|
+
function mayRead(name, context = {}) {
|
|
78
|
+
if (!isGuarded(name) || isProduction()) return true;
|
|
79
|
+
/* Its own value first — a live secret key recognises itself. */
|
|
80
|
+
if (classify(context.value) === LIVE) return false;
|
|
81
|
+
/* Then the group's, for the keys that cannot speak for themselves. */
|
|
82
|
+
return classify(context.decidingValue) !== LIVE;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* May this value be written from here?
|
|
87
|
+
* @returns {{ok: true} | {ok: false, reason: string}}
|
|
88
|
+
*/
|
|
89
|
+
function mayWrite(name, value) {
|
|
90
|
+
if (!isGuarded(name) || isProduction()) return { ok: true };
|
|
91
|
+
if (classify(value) === LIVE) return { ok: false, reason: restrictedMessage };
|
|
92
|
+
return { ok: true };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Would a live value be refused here, whatever it is?
|
|
97
|
+
*
|
|
98
|
+
* The settings screen asks this before showing an input: letting someone
|
|
99
|
+
* type a key only to have it refused on save is a worse experience than
|
|
100
|
+
* saying up front that this machine cannot hold one.
|
|
101
|
+
*/
|
|
102
|
+
function restrictsHere(name) {
|
|
103
|
+
if (!isGuarded(name) || isProduction()) return { ok: true };
|
|
104
|
+
return { ok: false, reason: restrictedMessage };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
return { isGuarded, classify, mayRead, mayWrite, restrictsHere, decidingKey, isProduction };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** A guard that allows everything — the default when a product declares none. */
|
|
111
|
+
function createPermissiveGuard() {
|
|
112
|
+
return createValueGuard();
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
module.exports = { createValueGuard, createPermissiveGuard, LIVE, TEST, UNKNOWN };
|
package/src/vault.js
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Service keys, encrypted in a store instead of a .env file.
|
|
3
|
+
*
|
|
4
|
+
* Changing a payment or mail provider key used to mean opening an SSH session,
|
|
5
|
+
* editing a file and restarting the service. Three chances to get it wrong, and
|
|
6
|
+
* a secret sitting in plaintext on the server's disk.
|
|
7
|
+
*
|
|
8
|
+
* Here a value arrives encrypted and never leaves towards a browser: the
|
|
9
|
+
* interface only ever sees the last four characters. The environment keeps its
|
|
10
|
+
* role as the fallback, so nothing breaks before a key has been entered.
|
|
11
|
+
*
|
|
12
|
+
* The order never changes:
|
|
13
|
+
*
|
|
14
|
+
* 1. a value entered through the interface → decrypted and used;
|
|
15
|
+
* 2. a key explicitly disconnected → nothing, even if the env has one;
|
|
16
|
+
* 3. nothing stored → the environment, as before.
|
|
17
|
+
*
|
|
18
|
+
* Point two is the trap. Without a disconnect marker, deleting a key would let
|
|
19
|
+
* the fallback environment variable bring it straight back — and you would
|
|
20
|
+
* never know whether a service is really unplugged.
|
|
21
|
+
*
|
|
22
|
+
* Nothing here throws on a read. No store, no cipher, a corrupted value: it
|
|
23
|
+
* falls back to the environment. A payment must not fail because the database
|
|
24
|
+
* hiccuped.
|
|
25
|
+
*/
|
|
26
|
+
const AppError = require('@astratra/core').AppError;
|
|
27
|
+
const { assertAdapter, maskSecret } = require('./utils');
|
|
28
|
+
const { createPermissiveGuard } = require('./valueGuard');
|
|
29
|
+
|
|
30
|
+
/** Written in place of a value to mean "deliberately unplugged". */
|
|
31
|
+
const DISCONNECTED = '__disconnected__';
|
|
32
|
+
|
|
33
|
+
const NOOP_LOGGER = { warn() {}, error() {} };
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* @param {object} options
|
|
37
|
+
* @param {object} options.store credential store adapter (findAll, upsert).
|
|
38
|
+
* @param {object} options.catalog from createCredentialCatalog().
|
|
39
|
+
* @param {object} options.cipher { encrypt, decrypt } — e.g. createFieldCipher().
|
|
40
|
+
* @param {object} [options.previousCipher] the generation being retired, for
|
|
41
|
+
* the duration of a rotation. See createCredentialRotation().
|
|
42
|
+
* @param {object} [options.guard] from createValueGuard(). Permissive by default.
|
|
43
|
+
* @param {object} [options.env] defaults to process.env.
|
|
44
|
+
* @param {number} [options.cacheMs] how long a read stays cached. Default 60000.
|
|
45
|
+
* @param {Function} [options.now] () => epoch ms, for tests.
|
|
46
|
+
* @param {object} [options.logger] { warn, error }.
|
|
47
|
+
* @param {Function} [options.onChange] called after a successful set/disconnect.
|
|
48
|
+
*/
|
|
49
|
+
function createCredentialVault(options = {}) {
|
|
50
|
+
const store = options.store;
|
|
51
|
+
assertAdapter(store, ['findAll', 'upsert'], 'options.store');
|
|
52
|
+
|
|
53
|
+
const catalog = options.catalog;
|
|
54
|
+
if (!catalog || typeof catalog.has !== 'function') {
|
|
55
|
+
throw new Error('createCredentialVault requires options.catalog from createCredentialCatalog().');
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const cipher = options.cipher;
|
|
59
|
+
if (!cipher || typeof cipher.encrypt !== 'function' || typeof cipher.decrypt !== 'function') {
|
|
60
|
+
throw new Error('createCredentialVault requires options.cipher with encrypt() and decrypt().');
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/*
|
|
64
|
+
* The generation being retired, present only while a rotation runs.
|
|
65
|
+
*
|
|
66
|
+
* Swapping the cipher in one go would make every stored key unreadable at
|
|
67
|
+
* once — and silently, since a failed decrypt here is caught per row and the
|
|
68
|
+
* environment quietly takes over. Reading both generations is what lets a
|
|
69
|
+
* rotation happen without an outage: values migrate one by one, and the old
|
|
70
|
+
* cipher is dropped once nothing needs it.
|
|
71
|
+
*
|
|
72
|
+
* WRITES always use the current cipher. That is what makes the rotation
|
|
73
|
+
* converge instead of ping-ponging between generations.
|
|
74
|
+
*/
|
|
75
|
+
const previousCipher = options.previousCipher || null;
|
|
76
|
+
if (previousCipher && typeof previousCipher.decrypt !== 'function') {
|
|
77
|
+
throw new Error('createCredentialVault requires options.previousCipher to expose decrypt().');
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Decrypt with the current generation, falling back to the retiring one. */
|
|
81
|
+
function decryptStored(value) {
|
|
82
|
+
try {
|
|
83
|
+
return cipher.decrypt(value);
|
|
84
|
+
} catch (error) {
|
|
85
|
+
if (!previousCipher) throw error;
|
|
86
|
+
return previousCipher.decrypt(value);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const guard = options.guard || createPermissiveGuard();
|
|
91
|
+
const env = options.env || process.env;
|
|
92
|
+
const cacheMs = options.cacheMs === undefined ? 60_000 : options.cacheMs;
|
|
93
|
+
const now = options.now || (() => Date.now());
|
|
94
|
+
const logger = options.logger || NOOP_LOGGER;
|
|
95
|
+
const onChange = typeof options.onChange === 'function' ? options.onChange : null;
|
|
96
|
+
|
|
97
|
+
let cache = null;
|
|
98
|
+
let cachedAt = 0;
|
|
99
|
+
|
|
100
|
+
/** Everything in the store, decrypted, held in memory for `cacheMs`. */
|
|
101
|
+
async function load() {
|
|
102
|
+
if (cache && now() - cachedAt < cacheMs) return cache;
|
|
103
|
+
|
|
104
|
+
let rows;
|
|
105
|
+
try {
|
|
106
|
+
rows = await store.findAll();
|
|
107
|
+
} catch (error) {
|
|
108
|
+
logger.warn(`[credentials] store unreadable: ${error.message}`);
|
|
109
|
+
return cache || new Map();
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const next = new Map();
|
|
113
|
+
for (const row of rows || []) {
|
|
114
|
+
if (row.value === DISCONNECTED) {
|
|
115
|
+
next.set(row.key, null);
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
try {
|
|
119
|
+
next.set(row.key, catalog.isSecret(row.key) ? decryptStored(row.value) : row.value);
|
|
120
|
+
} catch (error) {
|
|
121
|
+
/* One unreadable key — rotated cipher, corrupted value — must not take
|
|
122
|
+
the other nineteen down with it. It simply falls back to the env. */
|
|
123
|
+
logger.error(`[credentials] ${row.key} unreadable: ${error.message}`);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
cache = next;
|
|
128
|
+
cachedAt = now();
|
|
129
|
+
return cache;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function readable(name, stored) {
|
|
133
|
+
return guard.mayRead(name, {
|
|
134
|
+
value: stored.get(name),
|
|
135
|
+
decidingValue: guard.decidingKey ? stored.get(guard.decidingKey) : undefined
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function fromEnv(name) {
|
|
140
|
+
return env[name] || null;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** The value of one key — store first, environment next, null if unplugged. */
|
|
144
|
+
async function get(name) {
|
|
145
|
+
const stored = await load();
|
|
146
|
+
if (stored.has(name) && readable(name, stored)) return stored.get(name);
|
|
147
|
+
return fromEnv(name);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Several keys at once, without re-reading the store for each. */
|
|
151
|
+
async function getMany(names) {
|
|
152
|
+
const stored = await load();
|
|
153
|
+
const out = {};
|
|
154
|
+
for (const name of names || []) {
|
|
155
|
+
out[name] = stored.has(name) && readable(name, stored) ? stored.get(name) : fromEnv(name);
|
|
156
|
+
}
|
|
157
|
+
return out;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* What the STORE says, with no environment fallback.
|
|
162
|
+
*
|
|
163
|
+
* A key absent from the store is absent from this map; a disconnected key is
|
|
164
|
+
* present with `null`. `get()` erases that distinction — the env hydrator
|
|
165
|
+
* cannot work without it.
|
|
166
|
+
*/
|
|
167
|
+
async function stored() {
|
|
168
|
+
return new Map(await load());
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Forget the cache: after a write, the new value must serve immediately. */
|
|
172
|
+
function forget() {
|
|
173
|
+
cache = null;
|
|
174
|
+
cachedAt = 0;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function assertWritable(name, value) {
|
|
178
|
+
if (catalog.isReserved(name)) {
|
|
179
|
+
throw new AppError(
|
|
180
|
+
'This key cannot be stored here: it protects the others and stays on the server.',
|
|
181
|
+
400
|
|
182
|
+
);
|
|
183
|
+
}
|
|
184
|
+
if (!catalog.has(name)) {
|
|
185
|
+
throw new AppError('This key is not recognised.', 400);
|
|
186
|
+
}
|
|
187
|
+
/* A development machine and production share one store: without this guard
|
|
188
|
+
a value pasted from a laptop would be live in production within a
|
|
189
|
+
minute. The judgement is on the value, not on the environment alone. */
|
|
190
|
+
const permission = guard.mayWrite(name, value);
|
|
191
|
+
if (!permission.ok) throw new AppError(permission.reason, 403);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** Store a value entered through the interface. */
|
|
195
|
+
async function set(name, value, meta = {}) {
|
|
196
|
+
const clean = String(value === undefined || value === null ? '' : value).trim();
|
|
197
|
+
assertWritable(name, clean);
|
|
198
|
+
if (!clean) throw new AppError('Provide a value.', 400);
|
|
199
|
+
|
|
200
|
+
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()
|
|
207
|
+
});
|
|
208
|
+
forget();
|
|
209
|
+
if (onChange) await onChange({ key: name, action: 'set' });
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** Unplug a key — the environment does NOT take over. */
|
|
213
|
+
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
|
+
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
|
+
});
|
|
225
|
+
forget();
|
|
226
|
+
if (onChange) await onChange({ key: name, action: 'disconnect' });
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* The state of every managed key, safe to send to a browser.
|
|
231
|
+
*
|
|
232
|
+
* One rule holds the whole thing together: a secret value goes in and never
|
|
233
|
+
* comes back out. What is returned says whether a key is in place, where it
|
|
234
|
+
* comes from and how it ends — enough to recognise it, never enough to use
|
|
235
|
+
* it. A screenshot of this screen must compromise nothing.
|
|
236
|
+
*/
|
|
237
|
+
async function status() {
|
|
238
|
+
let rows = [];
|
|
239
|
+
try {
|
|
240
|
+
rows = (await store.findAll()) || [];
|
|
241
|
+
} catch (error) {
|
|
242
|
+
logger.warn(`[credentials] status read failed: ${error.message}`);
|
|
243
|
+
}
|
|
244
|
+
const byKey = new Map(rows.map((row) => [row.key, row]));
|
|
245
|
+
|
|
246
|
+
const spaces = catalog.spaces.map((space) => ({
|
|
247
|
+
id: space.id,
|
|
248
|
+
label: space.label,
|
|
249
|
+
hint: space.hint,
|
|
250
|
+
keys: space.keys.map((entry) => {
|
|
251
|
+
const row = byKey.get(entry.key);
|
|
252
|
+
const disconnected = row?.value === DISCONNECTED;
|
|
253
|
+
const inStore = Boolean(row) && !disconnected;
|
|
254
|
+
const inEnv = Boolean(env[entry.key]);
|
|
255
|
+
|
|
256
|
+
let preview = null;
|
|
257
|
+
if (inStore) {
|
|
258
|
+
try {
|
|
259
|
+
const value = entry.secret ? decryptStored(row.value) : row.value;
|
|
260
|
+
preview = entry.secret ? maskSecret(value) : value;
|
|
261
|
+
} catch (error) {
|
|
262
|
+
logger.error(`[credentials] ${entry.key} unreadable: ${error.message}`);
|
|
263
|
+
}
|
|
264
|
+
} else if (inEnv) {
|
|
265
|
+
preview = entry.secret ? maskSecret(env[entry.key]) : env[entry.key];
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/* Locked by the environment: saying so up front beats letting someone
|
|
269
|
+
type a value only to have it refused on save. */
|
|
270
|
+
const permission = typeof guard.restrictsHere === 'function'
|
|
271
|
+
? guard.restrictsHere(entry.key)
|
|
272
|
+
: { ok: true };
|
|
273
|
+
|
|
274
|
+
return {
|
|
275
|
+
key: entry.key,
|
|
276
|
+
label: entry.label,
|
|
277
|
+
help: entry.help,
|
|
278
|
+
where: entry.where,
|
|
279
|
+
placeholder: entry.placeholder,
|
|
280
|
+
secret: entry.secret,
|
|
281
|
+
readOnly: !permission.ok,
|
|
282
|
+
readOnlyReason: permission.ok ? null : permission.reason,
|
|
283
|
+
configured: inStore || (inEnv && !disconnected),
|
|
284
|
+
source: disconnected ? 'disconnected' : inStore ? 'interface' : inEnv ? 'environment' : 'absent',
|
|
285
|
+
preview,
|
|
286
|
+
updatedAt: inStore ? row.updatedAt || null : null
|
|
287
|
+
};
|
|
288
|
+
})
|
|
289
|
+
}));
|
|
290
|
+
|
|
291
|
+
return { spaces };
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** Is a rotation in progress? */
|
|
295
|
+
const isRotating = () => Boolean(previousCipher);
|
|
296
|
+
|
|
297
|
+
return {
|
|
298
|
+
get, getMany, stored, set, disconnect, forget, status,
|
|
299
|
+
isRotating, mask: maskSecret, DISCONNECTED,
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
module.exports = { createCredentialVault, DISCONNECTED };
|