Sessoes 1-6 acumuladas: hardening B2, defesa em camadas, +192 testes
Repositorio estava ha ~5 sessoes sem commit. Consolida tudo desde d088a89.
Ver commit.md na raiz para descricao completa por sessao.
# Numeros
- A# auditoria abertos: 0/30
- V# verificacoes abertos: 5/52 (todos adiados com plano)
- T# testes escritos: 10/10
- Vitest: 192/192
- SQL integration: 33/33
- E2E (Playwright, novo): 5/5
- Migrations: 17 (10 novas Sessao 6)
- Areas auditadas: 7 (+documentos com 10 V#)
# Highlights Sessao 6 (hoje)
- V#34/V#41 Opcao B2: tenant_features com plano + override (RPC SECURITY DEFINER, tela /saas/tenant-features)
- A#20 rev2 self-hosted: defesa em 5 camadas (honeypot + rate limit + math captcha condicional + paranoid mode + dashboard /saas/security)
- Documentos hardening (V#43-V#49): tenant scoping em storage policies (vazamento entre clinicas eliminado), RPC validate_share_token, signatures policy granular
- SaaS Twilio Config (/saas/twilio-config): UI editavel para SID/webhook/cotacao; AUTH_TOKEN permanece em env var
- T#9 + T#10: useAgendaEvents.spec.js + Playwright E2E (descobriu bug no front que foi corrigido)
# Sessoes anteriores (1-5) consolidadas
- Sessao 1: auth/router/session, normalizeRole extraido
- Sessao 2: agenda - composables/services consolidados
- Sessao 3: pacientes - tenant_id em todas queries
- Sessao 4: security review pagina publica - 14/15 vulnerabilidades corrigidas
- Sessao 5: SaaS - P0 (A#30: 7 tabelas com RLS off corrigidas)
# .gitignore ajustado
- supabase/* + !supabase/functions/ (mantem 10 edge functions, ignora .temp/migrations gerados pelo CLI)
- database-novo/backups/ (regeneravel via db.cjs backup)
- test-results/ + playwright-report/
- .claude/settings.local.json (config local com senha de dev removida do tracking)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,112 @@
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Agência PSI — Edge Function: twilio-whatsapp-webhook
|
||||
|--------------------------------------------------------------------------
|
||||
| Recebe callbacks de status do Twilio para mensagens WhatsApp enviadas
|
||||
| pelas subcontas de cada tenant.
|
||||
|
|
||||
| URL configurada no número de cada subconta:
|
||||
| https://<project>.supabase.co/functions/v1/twilio-whatsapp-webhook?tenant_id=<uuid>
|
||||
|
|
||||
| Eventos recebidos (MessageStatus):
|
||||
| queued, failed, sent, delivered, undelivered, read
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'
|
||||
|
||||
const corsHeaders = {
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
||||
'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',
|
||||
}
|
||||
|
||||
// Mapeia status Twilio → status interno
|
||||
function mapStatus(twilioStatus: string): string | null {
|
||||
switch (twilioStatus) {
|
||||
case 'delivered': return 'delivered'
|
||||
case 'read': return 'read'
|
||||
case 'failed':
|
||||
case 'undelivered': return 'failed'
|
||||
case 'sent': return 'sent'
|
||||
default: return null
|
||||
}
|
||||
}
|
||||
|
||||
Deno.serve(async (req: Request) => {
|
||||
if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders })
|
||||
|
||||
// Twilio envia POST com form-encoded
|
||||
if (req.method !== 'POST') {
|
||||
return new Response('ok', { status: 200, headers: corsHeaders })
|
||||
}
|
||||
|
||||
try {
|
||||
const supabase = createClient(
|
||||
Deno.env.get('SUPABASE_URL')!,
|
||||
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!
|
||||
)
|
||||
|
||||
const url = new URL(req.url)
|
||||
const tenantId = url.searchParams.get('tenant_id')
|
||||
|
||||
const formData = await req.formData()
|
||||
const messageSid = formData.get('MessageSid') as string
|
||||
const messageStatus = formData.get('MessageStatus') as string
|
||||
const to = formData.get('To') as string
|
||||
const errorCode = formData.get('ErrorCode') as string | null
|
||||
const errorMessage = formData.get('ErrorMessage') as string | null
|
||||
|
||||
if (!messageSid || !messageStatus) {
|
||||
return new Response('ok', { status: 200, headers: corsHeaders })
|
||||
}
|
||||
|
||||
const internalStatus = mapStatus(messageStatus)
|
||||
if (!internalStatus) {
|
||||
// Status intermediário (queued, accepted, etc.) — ignora
|
||||
return new Response('ok', { status: 200, headers: corsHeaders })
|
||||
}
|
||||
|
||||
// Atualiza notification_logs pelo provider_message_id
|
||||
const updateData: Record<string, unknown> = {
|
||||
provider_status: messageStatus,
|
||||
status: internalStatus,
|
||||
}
|
||||
|
||||
if (internalStatus === 'delivered') {
|
||||
updateData.delivered_at = new Date().toISOString()
|
||||
} else if (internalStatus === 'read') {
|
||||
updateData.read_at = new Date().toISOString()
|
||||
updateData.delivered_at = new Date().toISOString()
|
||||
} else if (internalStatus === 'failed') {
|
||||
updateData.failed_at = new Date().toISOString()
|
||||
updateData.failure_reason = errorMessage
|
||||
? `${errorCode}: ${errorMessage}`
|
||||
: `Twilio status: ${messageStatus}`
|
||||
}
|
||||
|
||||
const query = supabase
|
||||
.from('notification_logs')
|
||||
.update(updateData)
|
||||
.eq('provider_message_id', messageSid)
|
||||
|
||||
if (tenantId) query.eq('tenant_id', tenantId)
|
||||
|
||||
const { error } = await query
|
||||
|
||||
if (error) {
|
||||
console.error('[webhook] Erro ao atualizar log:', error.message)
|
||||
} else {
|
||||
console.log(`[webhook] ${messageSid} → ${messageStatus} (tenant: ${tenantId ?? 'unknown'})`)
|
||||
}
|
||||
|
||||
// Twilio espera 200 TwiML vazio ou texto simples
|
||||
return new Response('<?xml version="1.0" encoding="UTF-8"?><Response></Response>', {
|
||||
status: 200,
|
||||
headers: { ...corsHeaders, 'Content-Type': 'text/xml' },
|
||||
})
|
||||
} catch (e) {
|
||||
console.error('[webhook] Erro:', e)
|
||||
return new Response('ok', { status: 200, headers: corsHeaders })
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user