* 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>
321 lines
11 KiB
TypeScript
321 lines
11 KiB
TypeScript
/**
|
|
* The company question (M6): asked when a multi-company sender has no live
|
|
* pin and no default, answered with a reply button, a list row, or a typed
|
|
* digit. The answer pins the conversation's company for 8 sliding hours.
|
|
*
|
|
* While the question is open, the receipt rows are PARKED as
|
|
* whatsapp_messages with processing_status='skipped' and
|
|
* error_message='staged_awaiting_company' (no upload happens: a document
|
|
* cannot enter the company-scoped WORM archive before a company exists).
|
|
* The rows themselves are the staged refs; media stays re-downloadable from
|
|
* Meta for days, so no bytes are stored anywhere else.
|
|
*/
|
|
|
|
import type { SupabaseClient } from '@supabase/supabase-js'
|
|
import { createLogger } from '@/lib/logger'
|
|
import type { WhatsAppConversation, WhatsAppPhoneLink } from '@/types'
|
|
import {
|
|
sendReplyButtons,
|
|
sendList,
|
|
sendText,
|
|
MAX_REPLY_BUTTONS,
|
|
MAX_LIST_ROWS,
|
|
type SendMessageBase,
|
|
} from './graph-api'
|
|
import { botCopy, TEMPLATE } from './messages'
|
|
import {
|
|
COMPANY_PIN_TTL_MS,
|
|
STAGED_AWAITING_COMPANY,
|
|
getContext,
|
|
updateConversation,
|
|
type ConversationContext,
|
|
} from './conversation'
|
|
|
|
const log = createLogger('whatsapp-inbox/company-question')
|
|
|
|
/** Defensive ceiling on the numbered text list (>10 companies). */
|
|
const MAX_NUMBERED_OPTIONS = 30
|
|
|
|
export type CompanyChoiceVia = 'button' | 'list' | 'numbered'
|
|
|
|
export interface CompanyOption {
|
|
id: string
|
|
name: string
|
|
}
|
|
|
|
type ReplyBase = Omit<SendMessageBase, 'to' | 'template'>
|
|
|
|
/** All companies the linked user belongs to, alphabetical (stable digits). */
|
|
export async function loadCompanyOptions(
|
|
supabase: SupabaseClient,
|
|
userId: string,
|
|
): Promise<CompanyOption[]> {
|
|
const { data: memberships } = await supabase
|
|
.from('company_members')
|
|
.select('company_id')
|
|
.eq('user_id', userId)
|
|
const companyIds = [...new Set((memberships ?? []).map((m) => m.company_id as string))]
|
|
if (companyIds.length === 0) return []
|
|
|
|
const { data: companies } = await supabase
|
|
.from('companies')
|
|
.select('id, name')
|
|
.in('id', companyIds)
|
|
const options = ((companies ?? []) as { id: string; name: string | null }[]).map((c) => ({
|
|
id: c.id,
|
|
name: c.name ?? 'Företag',
|
|
}))
|
|
options.sort((a, b) => a.name.localeCompare(b.name, 'sv'))
|
|
return options.slice(0, MAX_NUMBERED_OPTIONS)
|
|
}
|
|
|
|
/**
|
|
* Ask the company question ONCE per open episode. The guarded state
|
|
* transition (WHERE state <> 'awaiting_company') makes concurrent workers of
|
|
* one burst produce exactly one M6; losers stage silently.
|
|
*
|
|
* The state is committed BEFORE the send (a fast tap must find it) but rolled
|
|
* back when the send fails: sends are best-effort and never throw, so without
|
|
* the rollback an expired token or a Graph 5xx left the conversation parked on
|
|
* a question the user never received, with the guard suppressing every later
|
|
* ask and the 48h TTL eventually discarding the staged receipts.
|
|
*
|
|
* Returns true when this caller sent the question.
|
|
*/
|
|
export async function askCompanyQuestion(
|
|
supabase: SupabaseClient,
|
|
args: {
|
|
conversation: WhatsAppConversation
|
|
link: WhatsAppPhoneLink
|
|
to: string
|
|
replyBase: ReplyBase
|
|
/** How many receipts wait on the answer (question body wording). */
|
|
stagedCount: number
|
|
},
|
|
): Promise<boolean> {
|
|
const options = await loadCompanyOptions(supabase, args.link.user_id)
|
|
if (options.length < 2) {
|
|
// Degenerate: resolution should have succeeded. Leave the rows staged;
|
|
// the sweep TTL cleans up if this persists.
|
|
log.warn('company question requested with fewer than 2 options', {
|
|
conversationId: args.conversation.id,
|
|
})
|
|
return false
|
|
}
|
|
|
|
const now = new Date()
|
|
const askedAt = now.toISOString()
|
|
const previousState = args.conversation.state
|
|
const context = getContext(args.conversation)
|
|
const nextContext: ConversationContext = {
|
|
...context,
|
|
company_options: options,
|
|
pending_question: { type: 'company', inbox_item_id: null, asked_at: askedAt },
|
|
}
|
|
|
|
const { data: won } = await supabase
|
|
.from('whatsapp_conversations')
|
|
.update({ state: 'awaiting_company', context: nextContext as Record<string, unknown> })
|
|
.eq('id', args.conversation.id)
|
|
.neq('state', 'awaiting_company')
|
|
.select('*')
|
|
if (!Array.isArray(won) || won.length === 0) return false
|
|
// Take updated_at (the revision guard) from the echoed row, but state and
|
|
// context from what we just wrote: that is what a rollback must match.
|
|
const committed: WhatsAppConversation = {
|
|
...args.conversation,
|
|
...((won[0] as WhatsAppConversation | undefined) ?? {}),
|
|
state: 'awaiting_company',
|
|
context: nextContext as Record<string, unknown>,
|
|
}
|
|
|
|
const copy = botCopy('sv')
|
|
const body = copy.m6CompanyQuestion({ count: args.stagedCount })
|
|
const base = { to: args.to, template: TEMPLATE.m6CompanyQuestion, ...args.replyBase }
|
|
|
|
let sent: { ok: boolean }
|
|
if (options.length <= MAX_REPLY_BUTTONS) {
|
|
sent = await sendReplyButtons(supabase, {
|
|
...base,
|
|
body,
|
|
buttons: options.map((o) => ({ id: o.id, title: o.name })),
|
|
})
|
|
} else if (options.length <= MAX_LIST_ROWS) {
|
|
sent = await sendList(supabase, {
|
|
...base,
|
|
body,
|
|
buttonLabel: 'Välj företag',
|
|
rows: options.map((o) => ({ id: o.id, title: o.name })),
|
|
})
|
|
} else {
|
|
sent = await sendText(supabase, {
|
|
...base,
|
|
body: copy.m6CompanyQuestionNumbered({
|
|
count: args.stagedCount,
|
|
options: options.map((o) => o.name),
|
|
}),
|
|
})
|
|
}
|
|
|
|
if (!sent.ok) {
|
|
// Undo the ask so the next receipt re-triggers it. Only our own question
|
|
// is rolled back: a newer one (different asked_at) is left alone.
|
|
await updateConversation(supabase, committed, (current, currentContext) => {
|
|
if (
|
|
current.state !== 'awaiting_company' ||
|
|
currentContext.pending_question?.asked_at !== askedAt
|
|
) {
|
|
return null
|
|
}
|
|
const rolledBack: ConversationContext = { ...currentContext }
|
|
delete rolledBack.company_options
|
|
delete rolledBack.pending_question
|
|
return { state: previousState === 'awaiting_company' ? 'idle' : previousState, context: rolledBack }
|
|
})
|
|
log.warn('company question send failed; question rolled back', {
|
|
conversationId: args.conversation.id,
|
|
})
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
export interface AppliedCompanyChoice {
|
|
ok: true
|
|
companyId: string
|
|
companyName: string
|
|
/** Parked message rows re-opened for processing (run through the kick). */
|
|
stagedMessageIds: string[]
|
|
}
|
|
|
|
export interface RejectedCompanyChoice {
|
|
ok: false
|
|
/**
|
|
* - invalid_option: a typed digit outside the numbered range. Ordinary
|
|
* user input (a typo), so the caller re-prompts instead of going silent.
|
|
* - not_member / lookup_failed / already_applied: stale or forged payloads
|
|
* and races. Silence.
|
|
*/
|
|
reason: 'invalid_option' | 'not_member' | 'lookup_failed' | 'already_applied'
|
|
}
|
|
|
|
export type CompanyChoiceResult = AppliedCompanyChoice | RejectedCompanyChoice
|
|
|
|
/**
|
|
* Apply a company answer (button/list id or typed digit). Validates
|
|
* membership, pins the company for 8h, confirms with M6-confirm, re-opens
|
|
* the parked rows and arms the combined ack.
|
|
*
|
|
* The open question, not the conversation state, is the thing being claimed:
|
|
* company_options are deleted by the winning write, so a double tap delivered
|
|
* into parallel invocations confirms exactly once, and a LATE answer (the 48h
|
|
* TTL reset the state to idle but kept the options) still lands.
|
|
*/
|
|
export async function applyCompanyChoice(
|
|
supabase: SupabaseClient,
|
|
args: {
|
|
conversation: WhatsAppConversation
|
|
link: WhatsAppPhoneLink
|
|
choice: { companyId: string } | { digit: number }
|
|
via: CompanyChoiceVia
|
|
to: string
|
|
replyBase: ReplyBase
|
|
},
|
|
): Promise<CompanyChoiceResult> {
|
|
const context = getContext(args.conversation)
|
|
const options = context.company_options ?? []
|
|
if (options.length === 0) return { ok: false, reason: 'already_applied' }
|
|
|
|
let companyId: string | null = null
|
|
if ('companyId' in args.choice) {
|
|
companyId = args.choice.companyId
|
|
} else {
|
|
const option = options[args.choice.digit - 1]
|
|
companyId = option?.id ?? null
|
|
if (!companyId) return { ok: false, reason: 'invalid_option' }
|
|
}
|
|
if (!companyId) return { ok: false, reason: 'invalid_option' }
|
|
|
|
// Defense in depth: the chosen company must be one the sender belongs to,
|
|
// whatever the payload claimed. A query ERROR is not a missing membership:
|
|
// treating a transient failure as "not a member" silently drops the answer.
|
|
const { data: membership, error: membershipError } = await supabase
|
|
.from('company_members')
|
|
.select('company_id')
|
|
.eq('user_id', args.link.user_id)
|
|
.eq('company_id', companyId)
|
|
.limit(1)
|
|
.maybeSingle()
|
|
if (membershipError) {
|
|
log.error('company choice membership lookup failed', membershipError, {
|
|
conversationId: args.conversation.id,
|
|
})
|
|
return { ok: false, reason: 'lookup_failed' }
|
|
}
|
|
if (!membership) {
|
|
log.warn('company choice rejected: sender is not a member', {
|
|
conversationId: args.conversation.id,
|
|
})
|
|
return { ok: false, reason: 'not_member' }
|
|
}
|
|
|
|
const known = options.find((o) => o.id === companyId)
|
|
let companyName = known?.name ?? null
|
|
if (!companyName) {
|
|
const { data: company } = await supabase
|
|
.from('companies')
|
|
.select('name')
|
|
.eq('id', companyId)
|
|
.maybeSingle()
|
|
companyName = (company as { name?: string } | null)?.name ?? 'Företag'
|
|
}
|
|
|
|
const now = new Date()
|
|
// Pin + arm the combined ack: the staged receipts process right after,
|
|
// and the finalize step claims `pending_ack AND debounce_until <= now()`.
|
|
// Guarded: whoever deletes company_options first owns the answer.
|
|
const applied = await updateConversation(supabase, args.conversation, (_current, currentContext) => {
|
|
if ((currentContext.company_options?.length ?? 0) === 0) return null
|
|
const nextContext: ConversationContext = { ...currentContext }
|
|
delete nextContext.company_options
|
|
delete nextContext.pending_question
|
|
nextContext.pin_expires_at = new Date(now.getTime() + COMPANY_PIN_TTL_MS).toISOString()
|
|
nextContext.pin_source = args.via
|
|
return {
|
|
state: 'idle',
|
|
company_id: companyId,
|
|
context: nextContext,
|
|
pending_ack: true,
|
|
debounce_until: now.toISOString(),
|
|
}
|
|
})
|
|
if (!applied) return { ok: false, reason: 'already_applied' }
|
|
|
|
await supabase
|
|
.from('whatsapp_phone_links')
|
|
.update({ last_company_id: companyId })
|
|
.eq('id', args.link.id)
|
|
|
|
await sendText(supabase, {
|
|
to: args.to,
|
|
body: botCopy('sv').m6CompanyConfirm({ companyName }),
|
|
template: TEMPLATE.m6CompanyConfirm,
|
|
...args.replyBase,
|
|
})
|
|
|
|
const { data: reopened } = await supabase
|
|
.from('whatsapp_messages')
|
|
.update({ processing_status: 'received', error_message: null })
|
|
.eq('conversation_id', args.conversation.id)
|
|
.eq('processing_status', 'skipped')
|
|
.eq('error_message', STAGED_AWAITING_COMPANY)
|
|
.select('id')
|
|
|
|
return {
|
|
ok: true,
|
|
companyId,
|
|
companyName,
|
|
stagedMessageIds: ((reopened ?? []) as { id: string }[]).map((r) => r.id),
|
|
}
|
|
}
|