"use strict"; const totpSecretCrypto = require("../utils/totp-secret-crypto"); async function migratePlaintextTotpSecrets({ db, secretCrypto = totpSecretCrypto, logger = console } = {}) { if (typeof db?.pool?.query !== "function" || typeof db?.query !== "function") { throw new TypeError("TOTP migration requires the database query dependencies"); } let sealedCount = 0; try { const [plainRows] = await db.pool.query( "SELECT id, secret FROM users WHERE secret IS NOT NULL AND secret != ''" ); for (const row of plainRows || []) { const stored = String(row.secret || "").trim(); if (!stored || secretCrypto.isTotpSecretEnvelope(stored)) continue; const sealed = secretCrypto.encryptTotpSecret(stored); if (!sealed) { logger.warn("[db] Skipped sealing a users.secret row: SESSION_SECRET is not set or sealing failed"); break; } // adpanel:totp-migration-cas - sealing must not reinstate a seed // revoked or rotated since the read, including during rolling startup. const result = await db.query( "UPDATE users SET secret = ? WHERE id = ? AND BINARY secret = BINARY ?", [sealed, row.id, row.secret] ); if (result?.affectedRows === 1) sealedCount += 1; } if (sealedCount > 0) logger.log(`[db] Sealed ${sealedCount} plaintext TOTP seed row(s) (AES-256-GCM)`); } catch (err) { logger.debug("[db] TOTP seed sealing migration note:", err?.message || err); } return sealedCount; } module.exports = { migratePlaintextTotpSecrets };