-- Audit 2026-06-11 H-D1: AES-GCM envelope versioning + AAD binding.
--
-- Pre-2026-06-11 the per-app secret store, per-app realtime signing
-- key, and email-trigger inbound HMAC secret were all AES-256-GCM
-- sealed with no Associated Authentication Data. Anyone with Postgres
-- write access could ciphertext-swap rows across apps (or rename via
-- row edit) and the decrypt would silently succeed under the wrong
-- identity, returning attacker-chosen plaintext.
--
-- New writes use `crypto::encrypt_with_aad` with a stable identity
-- string ("secret:{app_id}:{name}" / "app_secret:{app_id}:realtime_signing_key")
-- as AAD, so any cross-row swap fails the GCM auth tag.
--
-- This migration introduces a per-row `version` column. v0 = legacy
-- (no AAD); v1 = AAD-bound. Reads dispatch on the column; new writes
-- always emit v1. Existing v0 rows continue to decrypt; the
-- re-encryption sweep is deferred to v1.2's planned key-versioning
-- pass (see SECURITY_AUDIT.md "Notes on remediation methodology").
--
-- email_trigger_details.inbound_secret_encrypted retains a v0-only
-- path for now (audit-classified Medium; deferred).

ALTER TABLE secrets
    ADD COLUMN version SMALLINT NOT NULL DEFAULT 0;

ALTER TABLE app_secrets
    ADD COLUMN realtime_signing_key_version SMALLINT NOT NULL DEFAULT 0;
