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:
@@ -31,6 +31,8 @@
|
||||
|
||||
import { ref } from 'vue';
|
||||
import { supabase } from '@/lib/supabase/client';
|
||||
import { useTenantStore } from '@/stores/tenantStore';
|
||||
import { assertTenantId } from '@/features/agenda/services/_tenantGuards';
|
||||
import { logRecurrence, logError, logPerf } from '@/support/supportLogger';
|
||||
|
||||
// ─── helpers de data ────────────────────────────────────────────────────────
|
||||
@@ -197,6 +199,11 @@ export function generateDates(rule, rangeStart, rangeEnd) {
|
||||
|
||||
// ─── expansão principal ──────────────────────────────────────────────────────
|
||||
|
||||
// Cap defensivo: a agenda real sempre passa ranges mensais/semanais (≤42d).
|
||||
// Range muito grande com muitas regras = milhares de ocorrências no browser.
|
||||
// Não bloqueamos (relatórios legítimos podem precisar), só avisamos.
|
||||
const MAX_RANGE_DAYS = 730; // 2 anos
|
||||
|
||||
/**
|
||||
* Expande regras em ocorrências, aplica exceções.
|
||||
*
|
||||
@@ -207,6 +214,15 @@ export function generateDates(rule, rangeStart, rangeEnd) {
|
||||
* @returns {Array} occurrences — objetos com shape compatível com FullCalendar
|
||||
*/
|
||||
export function expandRules(rules, exceptions, rangeStart, rangeEnd) {
|
||||
const rangeDays = Math.round((rangeEnd.getTime() - rangeStart.getTime()) / 86_400_000);
|
||||
if (rangeDays > MAX_RANGE_DAYS) {
|
||||
logError('useRecurrence', 'expandRules: range grande pode degradar UI', {
|
||||
rangeDays,
|
||||
maxRecommended: MAX_RANGE_DAYS,
|
||||
ruleCount: (rules || []).length
|
||||
});
|
||||
}
|
||||
|
||||
// índice de exceções por regra+data
|
||||
const exMap = new Map();
|
||||
for (const ex of exceptions || []) {
|
||||
@@ -399,6 +415,13 @@ export function useRecurrence() {
|
||||
const exceptions = ref([]);
|
||||
const loading = ref(false);
|
||||
const error = ref(null);
|
||||
const tenantStore = useTenantStore();
|
||||
|
||||
function currentTenantId() {
|
||||
const tid = tenantStore.activeTenantId;
|
||||
assertTenantId(tid);
|
||||
return tid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Carrega regras ativas para um owner no range dado.
|
||||
@@ -493,6 +516,7 @@ export function useRecurrence() {
|
||||
return true;
|
||||
});
|
||||
} catch (e) {
|
||||
logError('useRecurrence', 'loadExceptions ERRO', e);
|
||||
error.value = e?.message || 'Erro ao carregar exceções';
|
||||
exceptions.value = [];
|
||||
}
|
||||
@@ -546,13 +570,16 @@ export function useRecurrence() {
|
||||
// ── CRUD de regras ──────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Cria uma nova regra de recorrência
|
||||
* Cria uma nova regra de recorrência.
|
||||
* tenant_id é injetado do tenantStore se não vier no payload (defesa em profundidade).
|
||||
* @param {Object} rule - campos da tabela recurrence_rules
|
||||
* @returns {Object} regra criada
|
||||
*/
|
||||
async function createRule(rule) {
|
||||
const tenantId = currentTenantId();
|
||||
logRecurrence('createRule →', { patient_id: rule?.patient_id, type: rule?.type });
|
||||
const { data, error: err } = await supabase.from('recurrence_rules').insert([rule]).select('*').single();
|
||||
const safeRule = { ...rule, tenant_id: rule?.tenant_id || tenantId };
|
||||
const { data, error: err } = await supabase.from('recurrence_rules').insert([safeRule]).select('*').single();
|
||||
if (err) {
|
||||
logError('useRecurrence', 'createRule ERRO', err);
|
||||
throw err;
|
||||
@@ -562,13 +589,16 @@ export function useRecurrence() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Atualiza a regra toda (editar todos)
|
||||
* Atualiza a regra toda (editar todos).
|
||||
* Filtro adicional por tenant_id — defesa em profundidade (RLS cobre, mas reforçamos).
|
||||
*/
|
||||
async function updateRule(id, patch) {
|
||||
const tenantId = currentTenantId();
|
||||
const { data, error: err } = await supabase
|
||||
.from('recurrence_rules')
|
||||
.update({ ...patch, updated_at: new Date().toISOString() })
|
||||
.eq('id', id)
|
||||
.eq('tenant_id', tenantId)
|
||||
.select('*')
|
||||
.single();
|
||||
if (err) throw err;
|
||||
@@ -576,10 +606,15 @@ export function useRecurrence() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancela a série inteira
|
||||
* Cancela a série inteira (filtro por tenant_id — defesa em profundidade).
|
||||
*/
|
||||
async function cancelRule(id) {
|
||||
const { error: err } = await supabase.from('recurrence_rules').update({ status: 'cancelado', updated_at: new Date().toISOString() }).eq('id', id);
|
||||
const tenantId = currentTenantId();
|
||||
const { error: err } = await supabase
|
||||
.from('recurrence_rules')
|
||||
.update({ status: 'cancelado', updated_at: new Date().toISOString() })
|
||||
.eq('id', id)
|
||||
.eq('tenant_id', tenantId);
|
||||
if (err) throw err;
|
||||
}
|
||||
|
||||
@@ -610,19 +645,33 @@ export function useRecurrence() {
|
||||
// ── CRUD de exceções ────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Cria ou atualiza uma exceção para uma ocorrência específica
|
||||
* Cria ou atualiza uma exceção para uma ocorrência específica.
|
||||
* tenant_id é injetado do tenantStore se não vier no payload.
|
||||
*/
|
||||
async function upsertException(ex) {
|
||||
const { data, error: err } = await supabase.from('recurrence_exceptions').upsert([ex], { onConflict: 'recurrence_id,original_date' }).select('*').single();
|
||||
const tenantId = currentTenantId();
|
||||
const safeEx = { ...ex, tenant_id: ex?.tenant_id || tenantId };
|
||||
const { data, error: err } = await supabase
|
||||
.from('recurrence_exceptions')
|
||||
.upsert([safeEx], { onConflict: 'recurrence_id,original_date' })
|
||||
.select('*')
|
||||
.single();
|
||||
if (err) throw err;
|
||||
return data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove uma exceção (restaura a ocorrência ao normal)
|
||||
* Remove uma exceção (restaura a ocorrência ao normal).
|
||||
* Filtro por tenant_id — defesa em profundidade.
|
||||
*/
|
||||
async function deleteException(recurrenceId, originalDate) {
|
||||
const { error: err } = await supabase.from('recurrence_exceptions').delete().eq('recurrence_id', recurrenceId).eq('original_date', originalDate);
|
||||
const tenantId = currentTenantId();
|
||||
const { error: err } = await supabase
|
||||
.from('recurrence_exceptions')
|
||||
.delete()
|
||||
.eq('recurrence_id', recurrenceId)
|
||||
.eq('original_date', originalDate)
|
||||
.eq('tenant_id', tenantId);
|
||||
if (err) throw err;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user