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,135 @@
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Agência PSI — Edge Function: sync-email-templates
|
||||
|--------------------------------------------------------------------------
|
||||
| Sincroniza templates globais ativos para email_templates_tenant.
|
||||
|
|
||||
| POST body: { tenant_id: string, owner_id: string }
|
||||
|
|
||||
| Para cada template em email_templates_global (is_active = true):
|
||||
| - Se não existe no tenant → INSERT com subject/body NULL (herda global)
|
||||
| - Se existe mas synced_version < global.version → UPDATE synced_version
|
||||
|
|
||||
| Retorna: { synced: number, updated: number }
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
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, OPTIONS',
|
||||
}
|
||||
|
||||
Deno.serve(async (req: Request) => {
|
||||
// CORS preflight
|
||||
if (req.method === 'OPTIONS') {
|
||||
return new Response('ok', { headers: corsHeaders })
|
||||
}
|
||||
|
||||
if (req.method !== 'POST') {
|
||||
return new Response(
|
||||
JSON.stringify({ error: 'Método não permitido' }),
|
||||
{ status: 405, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
)
|
||||
}
|
||||
|
||||
try {
|
||||
const { tenant_id, owner_id } = await req.json()
|
||||
|
||||
if (!tenant_id || !owner_id) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: 'tenant_id e owner_id são obrigatórios' }),
|
||||
{ status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
)
|
||||
}
|
||||
|
||||
const supabase = createClient(
|
||||
Deno.env.get('SUPABASE_URL')!,
|
||||
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!
|
||||
)
|
||||
|
||||
// 1. Busca todos os templates globais ativos
|
||||
const { data: globals, error: globalsErr } = await supabase
|
||||
.from('email_templates_global')
|
||||
.select('key, version')
|
||||
.eq('is_active', true)
|
||||
|
||||
if (globalsErr) throw globalsErr
|
||||
if (!globals || globals.length === 0) {
|
||||
return new Response(
|
||||
JSON.stringify({ synced: 0, updated: 0, message: 'Nenhum template global ativo' }),
|
||||
{ status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
)
|
||||
}
|
||||
|
||||
// 2. Busca templates existentes do tenant
|
||||
const { data: tenantTemplates, error: tenantErr } = await supabase
|
||||
.from('email_templates_tenant')
|
||||
.select('template_key, synced_version')
|
||||
.eq('tenant_id', tenant_id)
|
||||
.eq('owner_id', owner_id)
|
||||
|
||||
if (tenantErr) throw tenantErr
|
||||
|
||||
const tenantMap = new Map(
|
||||
(tenantTemplates || []).map(t => [t.template_key, t.synced_version])
|
||||
)
|
||||
|
||||
let synced = 0
|
||||
let updated = 0
|
||||
|
||||
for (const global of globals) {
|
||||
const existingVersion = tenantMap.get(global.key)
|
||||
|
||||
if (existingVersion === undefined) {
|
||||
// Não existe → INSERT com campos null (herda do global)
|
||||
const { error: insertErr } = await supabase
|
||||
.from('email_templates_tenant')
|
||||
.insert({
|
||||
tenant_id,
|
||||
owner_id,
|
||||
template_key: global.key,
|
||||
subject: null,
|
||||
body_html: null,
|
||||
body_text: null,
|
||||
enabled: true,
|
||||
synced_version: global.version,
|
||||
})
|
||||
|
||||
if (insertErr) {
|
||||
console.error(`[sync] Erro ao inserir ${global.key}:`, insertErr.message)
|
||||
continue
|
||||
}
|
||||
synced++
|
||||
} else if (existingVersion < global.version) {
|
||||
// Existe mas desatualizado → UPDATE apenas synced_version
|
||||
const { error: updateErr } = await supabase
|
||||
.from('email_templates_tenant')
|
||||
.update({ synced_version: global.version })
|
||||
.eq('tenant_id', tenant_id)
|
||||
.eq('owner_id', owner_id)
|
||||
.eq('template_key', global.key)
|
||||
|
||||
if (updateErr) {
|
||||
console.error(`[sync] Erro ao atualizar ${global.key}:`, updateErr.message)
|
||||
continue
|
||||
}
|
||||
updated++
|
||||
}
|
||||
// Se synced_version >= global.version → já está em dia, skip
|
||||
}
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({ synced, updated }),
|
||||
{ status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
)
|
||||
} catch (err) {
|
||||
console.error('[sync-email-templates] Erro:', err)
|
||||
return new Response(
|
||||
JSON.stringify({ error: err.message || 'Erro interno' }),
|
||||
{ status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
)
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user