Files
accounted/supabase/migrations/20260803090000_anonymize_whatsapp_channel.sql
Jakob Wennberg 88760ae6f6 fix(whatsapp-inbox): harden against adversarial review findings (#1342)
* fix(whatsapp-inbox): erase the WhatsApp channel on account deletion

whatsapp_phone_links relied on the auth.users ON DELETE CASCADE, but
Accounted never deletes auth.users: account deletion is
anonymize_user_account plus a ~100-year ban that keeps the auth row as a
tombstone, so the cascade never fires and nothing revokes the link. After
erasure the link stayed active with a decryptable phone_enc,
lookupActiveLink kept resolving the number, and every further inbound
message was persisted with body_text and the verbatim raw_payload while
the bot kept replying: GDPR Art 17 plus continued collection with no
lawful basis.

The RPC is re-created verbatim from 20260724150000 with one added block
that revokes and crypto-shreds the link, resets its conversation, nulls
body_text/raw_payload on that link's messages and deletes outstanding
link codes, plus a guarded repair pass for tombstones anonymized before
this migration. Covered by a pg-real test that fails against the previous
definition.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(whatsapp-inbox): pepper the link-code hash and bound code minting

hashLinkCode stored a bare sha256 over CODE_ALPHABET^6 = 30^6 values
behind a fixed 'AC-' prefix. The module cited the invite-token pattern,
but invite tokens are 256-bit random; this space enumerates offline in
about a second, so hashing at rest protected nothing. The sibling
phone-crypto.ts already states the team's own threat model for a LARGER
space ("a plain sha256 would be brute-forceable ... hence the pepper"),
so link codes now hash through the same env-mandated pepper.

/link/start was also an authenticated unbounded INSERT that left every
earlier code valid. Minting now burns the caller's unused codes (the code
the panel shows is the only one that works) and is capped per TTL window,
with the route answering 429 instead of throwing.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(whatsapp-inbox): harden the conversation layer against the review findings

Pre-merge hardening of the unshipped chat layer. Every change below has a
test that fails without it.

Lifecycle and races:
- conversation writes go through updateConversation(), an optimistic
  compare-and-set on updated_at (the trigger makes it a revision counter).
  The ack winner, the answer worker, the pin refresh and the sweep hold
  different claims, so blind whole-jsonb writes resurrected answered
  questions, wiped pending_question and dropped queue entries.
- terminal markStatus writes are guarded on processing_status='processing'
  so a losing worker cannot overwrite the winner's 'done' and null its
  inbox_item_id.
- the message -> inbox item path is idempotent: a pre-check plus a 23505
  fallback adopt the item a concurrent worker created, instead of throwing
  after the WORM document is already committed.
- PROCESSING_STUCK_MS 90s -> 5 min. The enforced step budget of one media
  row already exceeds 90s, so the sweep was re-claiming live workers.
- sweep 2b re-arms only when the conversation itself has been quiet, not
  just the rows: pending_ack=false plus unacked rows is also the state of a
  live finalize, which produced a duplicate combined ack.
- pin expiry re-checks against fresh state instead of writing back a stale
  whole context, which reverted company choices applied mid-pass.
- askNextQueuedQuestion claims the pop before sending, so two answer
  workers cannot ask the same question twice.

Company question:
- the state is rolled back when the M6 send fails, so the next receipt
  re-asks instead of parking receipts behind a question nobody received.
- applyCompanyChoice claims the open question (company_options) rather
  than the state: a double tap confirms once, a transient membership-query
  error is no longer read as "not a member", and a LATE answer still lands.
- at the 48h TTL the parked receipts are kept, not discarded: options and
  staged rows survive so a late digit or tap still files them, and only
  rows past Meta's ~30-day media window get the terminal marker.
- an out-of-range digit or a typed company name now gets the options
  repeated instead of silence or the "I cannot answer questions" reply.

Inline dispositions:
- stop/start/byt/company answers run their side effect BEFORE the terminal
  wamid row, with a SELECT pre-check for dedupe. Writing the row 'done'
  first made them at-most-once: a crash in between lost the action forever.

Copy and answers:
- acks state the extracted currency instead of labelling every total 'kr'.
- M17 stops promising "about 10 minutes" when the daily quota tripped.
- M18 is sent once per message tracked by the outbound row, so a file
  whose first attempt died still reaches the sender, including from the
  max-attempts path.
- M11 no longer claims the number is disconnected: 'stopp' pauses, and
  muted senders now persist no chat content at all.
- 'byt' is recognized in every state but awaiting_company (m6-confirm
  teaches the word, and it was being stored as answer data instead).
- text sent while a re-send question is open is kept as a note on THAT
  receipt with the question left open, instead of binding to another
  receipt's question.
- a quoted reply wins over the pending question and is appended when the
  quoted question is already answered, so corrections stop landing on the
  wrong receipt.
- context answers keep raw_answer + answered_at like representation does.
- finalizeBurst checks the send result: on failure it rolls the question
  back and leaves the rows unacked for the sweep.

PII:
- the sender's plaintext number is stripped from raw_payload before it is
  persisted; replies decrypt the link's phone_enc instead.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs(whatsapp-inbox): record the erasure path and the hardening decisions

RoPA gains the account-deletion row (immediate, not via the cron: the
auth.users cascade never fires because the row is tombstoned) plus the
two new security measures, and its "never in the clear" phone claim is
now true of the stored payload. DECISIONS.md records the non-obvious
calls: revoke-not-delete on erasure, commit-then-roll-back for the
company question, keeping expired company choices answerable, the
compare-and-set conversation write, effect-before-terminal-row for inline
dispositions, honest M11 copy, and the raw_payload redaction.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(whatsapp-inbox): stop the answer re-claim from following a confirm with M16

A worker that died after applying an answer and sending its confirmation
leaves the row 'processing'. The sweep re-runs it, resolveAnswerTarget
finds the question already answered, and the user got "I did not
understand" immediately after the confirmation they had just received.
The fallback is now first-attempt only.

The catch comment claiming the sweep retries these rows is corrected
too: 'error' is terminal for the sweep, and nothing on the answer path
throws anyway (interpretChatAnswer degrades, sends never throw,
supabase-js returns errors), so the catch is a programming-error net.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(whatsapp-inbox): drop the amount floor on the representation question

The Swedish compliance review on #1340 caught a real error in the trigger
rules: the representation question only fired above 150 kr, but the duty to
document deltagare and syfte is what makes the expense deductible at all
(BFL 5 kap 6-7 §) and it is not conditioned on any amount. The 300 kr per
person figure I had in mind is the VAT-deduction base cap, a different rule.
A 120 kr business lunch would have been booked with no participant trail,
which is exactly the deduction Skatteverket denies later.

Noise stays bounded by the triggers that were already there: the question
fires only for receipt-shaped documents from restaurant, cafe or hotel
merchants, at most once per receipt, twice per burst and six times per
sender per day, and a single "nej" dismisses it.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Jakob Wennberg <jakob.wennberg@gmail.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
2026-08-05 15:47:23 +02:00

158 lines
6.4 KiB
PL/PgSQL

-- Extend anonymize_user_account with the WhatsApp channel.
--
-- WHY
-- ---
-- whatsapp_phone_links.user_id is declared REFERENCES auth.users(id) ON DELETE
-- CASCADE (migration 20260802090000), and the channel relied on that cascade
-- for erasure. Accounted never deletes auth.users: account deletion is
-- app/api/account/delete/route.ts -> anonymize_user_account plus a ~100-year
-- ban, which deliberately KEEPS the auth row as a tombstone. The cascade
-- therefore never fires, and nothing else revokes the link: no extension
-- subscribes to account.deleted either.
--
-- Consequence before this migration: after erasure the phone link stayed
-- ACTIVE (revoked_at NULL) with a decryptable phone_enc and the WhatsApp
-- profile name, lookupActiveLink kept resolving the number, and every further
-- inbound message from the erased data subject was persisted with body_text
-- and the verbatim raw_payload while the bot kept replying. That is continued
-- collection with no lawful basis and a GDPR Art 17 gap.
--
-- WHAT
-- ----
-- The RPC is re-created verbatim from 20260724150000 with one added block.
-- The link is REVOKED and crypto-shredded rather than deleted, matching the
-- channel's own revocation-not-deletion discipline and the retention cron's
-- shredding shape (phone_enc = '' is the cleared marker on a NOT NULL column):
-- * revoked_at set -> lookupActiveLink stops resolving the number, so any
-- further message falls to the unknown-sender path,
-- which persists no content at all.
-- * phone_enc = '' -> the number is no longer recoverable from the row.
-- * wa_profile_name, phone_masked, default/last company -> cleared.
-- * phone_hash STAYS: it is an HMAC under a server-side pepper (not
-- reversible), and it is what keeps "this phone was once linked" honest
-- for the uniqueness history the same way auth.users.email is kept.
-- * conversation state/context reset (pinned company, pending questions).
-- * body_text + raw_payload nulled on every message of that link: same
-- shape as the 90-day retention purge, only immediate.
-- * unused link codes deleted (they mint a NEW link for the erased user).
--
-- Idempotent: every predicate only matches rows still carrying the data, and
-- the RPC already refuses a second run against an anonymized profile.
CREATE OR REPLACE FUNCTION public.anonymize_user_account(target_user_id uuid)
RETURNS void
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path TO 'public'
AS $function$
DECLARE
blocker_count int;
BEGIN
IF auth.uid() IS DISTINCT FROM target_user_id THEN
RAISE EXCEPTION 'Can only delete your own account';
END IF;
-- Reject repeat invocations against an already-anonymized tombstone: the
-- account is gone, re-running would only churn the scrubbed row.
IF EXISTS (
SELECT 1 FROM public.profiles
WHERE id = target_user_id AND anonymized_at IS NOT NULL
) THEN
RAISE EXCEPTION 'Account is already deleted' USING ERRCODE = 'P0002';
END IF;
SELECT count(*) INTO blocker_count
FROM public.company_members cm
JOIN public.companies c ON c.id = cm.company_id
WHERE cm.user_id = target_user_id
AND cm.role = 'owner'
AND c.archived_at IS NULL;
IF blocker_count > 0 THEN
RAISE EXCEPTION 'Cannot delete account: user still owns % active compan(y/ies)', blocker_count
USING ERRCODE = 'P0001';
END IF;
DELETE FROM public.company_members WHERE user_id = target_user_id;
DELETE FROM public.team_members WHERE user_id = target_user_id;
DELETE FROM public.bankid_identities WHERE user_id = target_user_id;
DELETE FROM public.user_preferences WHERE user_id = target_user_id;
DELETE FROM public.api_keys WHERE user_id = target_user_id;
-- WhatsApp channel (see header): the auth.users cascade never fires here.
DELETE FROM public.whatsapp_link_codes WHERE user_id = target_user_id;
UPDATE public.whatsapp_messages m
SET body_text = NULL,
raw_payload = NULL
FROM public.whatsapp_phone_links l
WHERE l.user_id = target_user_id
AND m.phone_link_id = l.id
AND (m.body_text IS NOT NULL OR m.raw_payload IS NOT NULL);
UPDATE public.whatsapp_conversations c
SET state = 'idle',
context = '{}'::jsonb,
company_id = NULL
FROM public.whatsapp_phone_links l
WHERE l.user_id = target_user_id
AND c.phone_link_id = l.id;
UPDATE public.whatsapp_phone_links
SET revoked_at = coalesce(revoked_at, now()),
phone_enc = '',
phone_masked = '+** *** ** **',
wa_profile_name = NULL,
default_company_id = NULL,
last_company_id = NULL
WHERE user_id = target_user_id;
UPDATE public.profiles
SET email = NULL,
full_name = NULL,
avatar_url = NULL,
deleted_at = now(),
anonymized_at = now(),
updated_at = now()
WHERE id = target_user_id;
-- Scrub PII from the auth tombstone. auth.users.email is intentionally
-- kept (blocks re-signup + lets support verify identity for BFL-retained
-- data recovery; documented legitimate interest, see
-- app/api/account/delete/route.ts).
UPDATE auth.users
SET raw_user_meta_data = '{}'::jsonb,
raw_app_meta_data = coalesce(raw_app_meta_data, '{}'::jsonb) - 'bankid_linked' - 'has_password'
WHERE id = target_user_id;
END;
$function$;
REVOKE ALL ON FUNCTION public.anonymize_user_account(uuid) FROM PUBLIC, anon;
GRANT EXECUTE ON FUNCTION public.anonymize_user_account(uuid) TO authenticated;
-- Repair pass: tombstones anonymized before this migration whose WhatsApp
-- link is still live. Guarded by anonymized_at, so live users are untouched.
UPDATE public.whatsapp_messages m
SET body_text = NULL,
raw_payload = NULL
FROM public.whatsapp_phone_links l
JOIN public.profiles p ON p.id = l.user_id
WHERE p.anonymized_at IS NOT NULL
AND m.phone_link_id = l.id
AND (m.body_text IS NOT NULL OR m.raw_payload IS NOT NULL);
UPDATE public.whatsapp_phone_links l
SET revoked_at = coalesce(l.revoked_at, now()),
phone_enc = '',
phone_masked = '+** *** ** **',
wa_profile_name = NULL,
default_company_id = NULL,
last_company_id = NULL
FROM public.profiles p
WHERE p.id = l.user_id
AND p.anonymized_at IS NOT NULL
AND (l.revoked_at IS NULL OR l.phone_enc <> '' OR l.wa_profile_name IS NOT NULL);
NOTIFY pgrst, 'reload schema';