/** * The keychain and the retired MQTT codec, as the OLD build wrote them and as * the NEW build reads them. Self-contained on purpose (the server's own module * is not importable from the CLI). Nothing here ever logs or returns a * plaintext: callers get ciphertext, counts and booleans. * * Formats (read from `keychain-crypto.ts` and `retired-ciphertext.ts`): * value `ck1....` AES-256-GCM under the DEK, AAD = the ref * DEK `kw1...` AES-256-GCM under the KEK, AAD = `` * KEK id HMAC-SHA256(KEK, label) hex * mqtt `enc:v1:::` key = the 32 raw bytes of `.secret-key`, else scrypt(passphrase, salt) */ import { createCipheriv, createDecipheriv, createHmac, randomBytes, scryptSync, } from 'node:crypto' import { NEW_DEK_AAD_PREFIX, NEW_FINGERPRINT_LABEL, NEW_MQTT_SALT, OLD_DEK_AAD_PREFIX, OLD_FINGERPRINT_LABEL, OLD_MQTT_SALT, } from './names.js' const KEY_BYTES = 32 const IV_BYTES = 12 const TAG_BYTES = 16 const VALUE_PREFIX = 'ck1' const WRAP_PREFIX = 'kw1' /** Key material from a key file: 64 hex chars or base64 of 32 bytes; anything else is `null`. */ export function decodeKeyMaterial(textContent: string): Buffer | null { const trimmed = textContent.trim() if (/^[0-9a-fA-F]{64}$/.test(trimmed)) return Buffer.from(trimmed, 'hex') if (!/^[A-Za-z0-9+/=_-]+$/.test(trimmed)) return null const buf = Buffer.from(trimmed, 'base64') return buf.length === KEY_BYTES ? buf : null } export type Era = 'old' | 'new' export function fingerprint(kek: Buffer, era: Era): string { const label = era === 'old' ? OLD_FINGERPRINT_LABEL : NEW_FINGERPRINT_LABEL return createHmac('sha256', kek).update(label).digest('hex') } function dekAad(era: Era, keyId: string): string { return `${era === 'old' ? OLD_DEK_AAD_PREFIX : NEW_DEK_AAD_PREFIX}${keyId}` } function seal(key: Buffer, plaintext: Buffer, aad: string): readonly [string, string, string] { const iv = randomBytes(IV_BYTES) const cipher = createCipheriv('aes-256-gcm', key, iv) cipher.setAAD(Buffer.from(aad, 'utf8')) const ct = Buffer.concat([cipher.update(plaintext), cipher.final()]) return [iv.toString('base64'), cipher.getAuthTag().toString('base64'), ct.toString('base64')] } function open( key: Buffer, parts: readonly [string, string, string], aad: string, ): Buffer | null { try { const iv = Buffer.from(parts[0], 'base64') const tag = Buffer.from(parts[1], 'base64') if (iv.length !== IV_BYTES || tag.length !== TAG_BYTES) return null const decipher = createDecipheriv('aes-256-gcm', key, iv) decipher.setAAD(Buffer.from(aad, 'utf8')) decipher.setAuthTag(tag) return Buffer.concat([decipher.update(Buffer.from(parts[2], 'base64')), decipher.final()]) } catch { return null } } export function wrapDek(kek: Buffer, dek: Buffer, keyId: string, era: Era): string { const [iv, tag, ct] = seal(kek, dek, dekAad(era, keyId)) return `${WRAP_PREFIX}.${iv}.${tag}.${ct}` } export function unwrapDek(kek: Buffer, wrapped: string, keyId: string, era: Era): Buffer | null { const parts = wrapped.split('.') const [prefix, iv, tag, ct] = parts if (parts.length !== 4 || prefix !== WRAP_PREFIX) return null if (iv === undefined || tag === undefined || ct === undefined) return null const dek = open(kek, [iv, tag, ct], dekAad(era, keyId)) return dek !== null && dek.length === KEY_BYTES ? dek : null } /** The key id inside a `ck1` envelope, or `null`. */ export function envelopeKeyId(envelope: string): string | null { const parts = envelope.split('.') return parts.length === 5 && parts[0] === VALUE_PREFIX ? (parts[1] ?? null) : null } export function encryptValue(dek: Buffer, keyId: string, ref: string, value: Buffer): string { const [iv, tag, ct] = seal(dek, value, ref) return `${VALUE_PREFIX}.${keyId}.${iv}.${tag}.${ct}` } /** The plaintext as BYTES (never a string a caller could log), or `null` when it does not authenticate. */ export function decryptValue(dek: Buffer, ref: string, envelope: string): Buffer | null { const parts = envelope.split('.') const [prefix, , iv, tag, ct] = parts if (parts.length !== 5 || prefix !== VALUE_PREFIX) return null if (iv === undefined || tag === undefined || ct === undefined) return null return open(dek, [iv, tag, ct], ref) } // ── the retired MQTT codec ───────────────────────────────────────────────── /** Every ciphertext the retired codec wrote. base64 never contains `:` or a quote. */ export const MQTT_CIPHERTEXT = /enc:v1:[A-Za-z0-9+/=]+:[A-Za-z0-9+/=]+:[A-Za-z0-9+/=]+/g export interface MqttKeys { readonly oldKey: Buffer readonly newKey: Buffer /** A raw 32-byte key file never touched the salt: nothing to re-encrypt. */ readonly saltDerived: boolean } /** Both keys for one `.secret-key` file's bytes (exactly as the retired codec read it). */ export function mqttKeysFor(fileBytes: Buffer): MqttKeys { if (fileBytes.length === KEY_BYTES) { return { oldKey: fileBytes, newKey: fileBytes, saltDerived: false } } const passphrase = fileBytes.toString('utf-8') return { oldKey: scryptSync(passphrase, Buffer.from(OLD_MQTT_SALT, 'utf-8'), KEY_BYTES), newKey: scryptSync(passphrase, Buffer.from(NEW_MQTT_SALT, 'utf-8'), KEY_BYTES), saltDerived: true, } } function mqttParts(ciphertext: string): readonly [string, string, string] | null { const parts = ciphertext.slice('enc:v1:'.length).split(':') const [iv, tag, ct] = parts if (parts.length !== 3 || iv === undefined || tag === undefined || ct === undefined) return null return [iv, tag, ct] } /** One ciphertext moved from the old key to the new one, or `null` when the old key does not open it. */ export function reencryptMqtt(ciphertext: string, keys: MqttKeys): string | null { const parts = mqttParts(ciphertext) if (parts === null) return null const iv = Buffer.from(parts[0], 'base64') const tag = Buffer.from(parts[1], 'base64') if (iv.length !== IV_BYTES || tag.length !== TAG_BYTES) return null let plain: Buffer try { const decipher = createDecipheriv('aes-256-gcm', keys.oldKey, iv) decipher.setAuthTag(tag) plain = Buffer.concat([decipher.update(Buffer.from(parts[2], 'base64')), decipher.final()]) } catch { return null } const nextIv = randomBytes(IV_BYTES) const cipher = createCipheriv('aes-256-gcm', keys.newKey, nextIv) const ct = Buffer.concat([cipher.update(plain), cipher.final()]) plain.fill(0) return `enc:v1:${nextIv.toString('base64')}:${cipher.getAuthTag().toString('base64')}:${ct.toString('base64')}` }