/**
 * Balance integrity verification using HMAC-SHA256.
 * Prevents direct database modification of balance_cents.
 * If the balance_hmac doesn't match, the balance has been tampered with.
 */
import { createHmac, timingSafeEqual } from 'crypto';
import { getEnv } from './env.js';
/**
 * Compute HMAC-SHA256 of a balance value for a specific license key.
 * Uses LICENSE_SIGNING_KEY as the HMAC key (Ed25519 private seed, high-entropy).
 * Domain-separated with 'balance:' prefix to prevent cross-purpose HMAC confusion.
 */
export function signBalance(keyId, balanceCents) {
    const env = getEnv();
    return createHmac('sha256', env.LICENSE_SIGNING_KEY)
        .update(`balance:${keyId}:${balanceCents}`)
        .digest('hex');
}
/**
 * Verify that a balance record has not been tampered with.
 * Returns true if the HMAC matches, false if tampered.
 *
 * SECURITY: Since v1.2.24, ALL records are signed at startup (verifyBalanceIntegrity in index.ts).
 * A null/missing HMAC means the record was tampered with to remove the HMAC — fail fast.
 */
export function verifyBalance(keyId, balanceCents, storedHmac) {
    if (!storedHmac) {
        // HMAC missing — all records should be signed after startup migration.
        // A null HMAC indicates tampering (the HMAC column was cleared).
        return false;
    }
    const expected = signBalance(keyId, balanceCents);
    if (expected.length !== storedHmac.length)
        return false;
    // Constant-time comparison to prevent timing attacks
    return timingSafeEqual(Buffer.from(expected), Buffer.from(storedHmac));
}
/**
 * Allowed prefixes for stripe_payment_intent_id in payment records.
 * - `pi_` — real Stripe payment intents
 * - `charge_` — internal charge records
 * - `refund_` — internal refund records
 *
 * Reject any payment record with an unknown format to prevent injection.
 */
const ALLOWED_PAYMENT_ID_PREFIXES = ['pi_', 'charge_', 'refund_'];
/**
 * Validate that a stripe_payment_intent_id follows a known format pattern.
 * Returns true if valid, false if the format is unknown.
 */
export function validatePaymentIntentId(paymentIntentId) {
    if (!paymentIntentId || typeof paymentIntentId !== 'string') {
        return false;
    }
    return ALLOWED_PAYMENT_ID_PREFIXES.some(prefix => paymentIntentId.startsWith(prefix));
}
//# sourceMappingURL=balance-integrity.js.map