BEGIN; CREATE TABLE device_credential ( device_id uuid PRIMARY KEY, tenant_id uuid NOT NULL, credential_ref varchar(500) NOT NULL UNIQUE, key_version bigint NOT NULL DEFAULT 1 CHECK (key_version > 0), algorithm varchar(32) NOT NULL DEFAULT 'HMAC-SHA256' CHECK (algorithm = 'HMAC-SHA256'), encryption varchar(32) NOT NULL DEFAULT 'AES-256-GCM' CHECK (encryption = 'AES-256-GCM'), encrypted_secret bytea NOT NULL, nonce bytea NOT NULL CHECK (octet_length(nonce) = 12), status varchar(24) NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'revoked')), created_at timestamptz NOT NULL DEFAULT now(), rotated_at timestamptz, revoked_at timestamptz, CONSTRAINT device_credential_device_tenant_fk FOREIGN KEY (device_id, tenant_id) REFERENCES device(id, tenant_id) ); CREATE INDEX device_credential_tenant_status_idx ON device_credential (tenant_id, status); COMMENT ON TABLE device_credential IS 'Recoverable device HMAC credentials encrypted with the API credential master key; plaintext is never stored.'; COMMIT;