"use strict"; // adpanel:grace-shared-authority - a local cache is never required proof of a // grant; every reuse validates the shared row and its current count. async function readVerifiedActionGrant({ db, withTimeout, candidate, safeCompare, normalizeStepUpProofStrength, clear, logger = console, now = Date.now }) { try { let rows; try { rows = await withTimeout(db.query( "SELECT grant_id, user_id, email, session_hash, secret_hash, ip_hash, ua_hash, verified_at, expires_at, revoked_at, use_count, proof_strength FROM destructive_action_grants WHERE grant_id = ? LIMIT 1", [candidate.grantId] ), 5000, "stepup-grace-validate-timeout"); } catch (error) { if (!((error?.code === "ER_BAD_FIELD_ERROR" || String(error?.message || "").includes("Unknown column")) && String(error?.message || "").includes("proof_strength"))) throw error; rows = await withTimeout(db.query( "SELECT grant_id, user_id, email, session_hash, secret_hash, ip_hash, ua_hash, verified_at, expires_at, revoked_at, use_count FROM destructive_action_grants WHERE grant_id = ? LIMIT 1", [candidate.grantId] ), 5000, "stepup-grace-validate-timeout"); } const row = Array.isArray(rows) ? rows[0] : null; if (!row || row.revoked_at != null || Number(row.user_id) !== candidate.userId || String(row.email || "").trim().toLowerCase() !== candidate.email || Number(row.verified_at) !== candidate.verifiedAt || Number(row.expires_at) !== candidate.expiresAt || Number(row.expires_at) <= now() || !["session", "secret", "ip", "ua"].every((field) => safeCompare(String(row[`${field}_hash`] || ""), candidate[`${field}Hash`]))) { clear(); return null; } return { email: candidate.email, userId: candidate.userId, grantId: candidate.grantId, verifiedAt: candidate.verifiedAt, expiresAt: candidate.expiresAt, useCount: Math.max(0, Number(row.use_count || 0)), proofStrength: normalizeStepUpProofStrength(row.proof_strength) }; } catch (error) { logger.warn("[security] Destructive action grant DB validation failed:", error?.message || error); clear(); return null; } } module.exports = { readVerifiedActionGrant };