-- =============================================================================
-- Make workspace API keys revealable.
--
-- Adds `key_encrypted` — base64 of secret-box(VIBN_SECRETS_KEY, plaintext token).
-- Existing rows keep `key_encrypted = NULL` and are therefore NOT revealable;
-- only the hash was stored at mint time and the plaintext is unrecoverable by
-- design. Those keys still work for auth (hash lookup is unchanged); they just
-- can't surface the plaintext again — the UI will flag them as legacy.
--
-- New keys minted after this migration will populate `key_encrypted` and can
-- be revealed on demand by session-authenticated users (never by API-key
-- principals — prevents lateral movement).
--
-- Safe to re-run.
-- =============================================================================

ALTER TABLE vibn_workspace_api_keys
  ADD COLUMN IF NOT EXISTS key_encrypted TEXT;

COMMENT ON COLUMN vibn_workspace_api_keys.key_encrypted IS
  'base64( AES-256-GCM encrypt(VIBN_SECRETS_KEY, plaintext vibn_sk_...) ). '
  'NULL for legacy rows minted before this column existed — those keys '
  'remain valid for auth but cannot be revealed.';

SELECT 'API-key revealability migration complete' AS status;
