fix(2fa): gate two-factor auth when the encryption key is missing
TWO_FACTOR_ENCRYPTION_KEY has no default, so instances upgrading to 3.3 without setting it hit an unhandled throw from encryptSecret: the setup dialog only reported "Something went wrong", and where 2FA was required the blocking dialog made the whole app unusable. The status endpoint now reports 2FA as not required while the key is missing or invalid, and setup initiation returns 503 with a two-factor-error-not-configured code that the setup dialog renders as a readable message. Also documents the variable in the README and the example compose file. Closes #4443
This commit is contained in:
1 parent
de474a1da9
commit
a40b418038
12 files changed
+182
-8
No files matched your search
@@ -51,3 +51,31 @@ describe('encryptSecret/decryptSecret', () => {
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
});
|
||||
|
||||
describe('isTwoFactorConfigured', () => {
|
||||
test('returns true with a valid key', async () => {
|
||||
vi.stubEnv('TWO_FACTOR_ENCRYPTION_KEY', KEY);
|
||||
vi.resetModules();
|
||||
const { isTwoFactorConfigured } = await import('./crypto');
|
||||
|
||||
expect(isTwoFactorConfigured()).toBe(true);
|
||||
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
test('returns false when the key is missing or invalid', async () => {
|
||||
vi.stubEnv('TWO_FACTOR_ENCRYPTION_KEY', '');
|
||||
vi.resetModules();
|
||||
const { isTwoFactorConfigured } = await import('./crypto');
|
||||
|
||||
expect(isTwoFactorConfigured()).toBe(false);
|
||||
|
||||
vi.stubEnv('TWO_FACTOR_ENCRYPTION_KEY', 'too-short');
|
||||
expect(isTwoFactorConfigured()).toBe(false);
|
||||
|
||||
vi.stubEnv('TWO_FACTOR_ENCRYPTION_KEY', 'z'.repeat(64));
|
||||
expect(isTwoFactorConfigured()).toBe(false);
|
||||
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
});
|
||||
@@ -1,14 +1,20 @@
|
||||
import { createCipheriv, createDecipheriv, randomBytes } from 'crypto';
|
||||
|
||||
const ALGORITHM = 'aes-256-gcm';
|
||||
const KEY_REGEX = /^[0-9a-fA-F]{64}$/;
|
||||
|
||||
/** Checks that TWO_FACTOR_ENCRYPTION_KEY holds a valid 256-bit key, without throwing. */
|
||||
export function isTwoFactorConfigured(): boolean {
|
||||
const hex = process.env.TWO_FACTOR_ENCRYPTION_KEY;
|
||||
return !!hex && KEY_REGEX.test(hex);
|
||||
}
|
||||
|
||||
/** Loads and validates the 256-bit encryption key from TWO_FACTOR_ENCRYPTION_KEY. */
|
||||
function getKey(): Buffer {
|
||||
const hex = process.env.TWO_FACTOR_ENCRYPTION_KEY;
|
||||
if (!hex || hex.length !== 64 || !/^[0-9a-fA-F]{64}$/.test(hex)) {
|
||||
if (!isTwoFactorConfigured()) {
|
||||
throw new Error('TWO_FACTOR_ENCRYPTION_KEY is missing or invalid');
|
||||
}
|
||||
return Buffer.from(hex, 'hex');
|
||||
return Buffer.from(process.env.TWO_FACTOR_ENCRYPTION_KEY, 'hex');
|
||||
}
|
||||
|
||||
/** Encrypts a TOTP secret using AES-256-GCM. Returns `ciphertext:iv:authTag` as hex. */
|
||||
|
||||
Reference in new issue
Block a user