teqo-backup/src/collections/Consent.ts
Francisco Solla 9e9864f420 feat(C234): busca por selfie no álbum público — índice A/C consentido, selfie on-device
- /fotos/encontre + POST /api/fotos/selfie: só o vetor 128-d, sem imagem, sem score e
  sem nomes de terceiros; fail-closed pela flag photoAlbum.selfieSearchEnabled (default
  false) e pelos Consents por chave estável (busca-selfie-fotos/busca-selfie-indice, não
  seedados — a superfície nasce fechada até o aval jurídico/DPIA).
- Índice A/C do gate (PR #1370): só quem aderiu é indexado; descriptors do acervo são
  transitórios. Collection faceSubject (admin-only, sem vínculo com Contact), vínculos
  matchedPhotos e marker faces.checkedKey no archivePhoto (modelo + enrolledAt).
- Engine @vladmandic/face-api nos dois lados: browser lazy com modelos same-origin
  (copy-face-vision-assets no prebuild/predev/Docker) e CLI node-wasm sem tfjs-node.
  CLIs ops-only faces:enroll / faces:index --apply|--verify com guardas C231/C232.
- Opt-out self-service por reconhecimento (leave-index) + canal de remoção do C233;
  rate limit próprio (namespace selfie:<hash>) e bounded body extraído do beacon.
- UI portada classe-a-classe do design estendido (paridade certificada, tier primário);
  e2e frontendFotosSelfie (manifest+curado+projeto, engine stubada) e canário do engine
  real; runbook §C234, contrato em AGENTS-public.md e changelog.
- Migration aditiva add_face_subject (SQL revisado); hard-stops aprovados na sessão.
2026-09-27 20:04:41 -03:00

137 lines
4.1 KiB
TypeScript

import { payloadAdminOnly } from '@/utilities/campaignAccess'
import { APIError, type CollectionBeforeDeleteHook, type CollectionConfig } from 'payload'
/**
* Block deleting a Consent that is still referenced by a versioned legal-text
* consumer. The DB uses `ON DELETE SET NULL` FKs, but several consumers store
* the consent as NOT NULL (subscription, signature, pushSubscription) — deleting
* would trip a 23502 — while others (petition, leadership, supporter) null the
* column silently and corrupt the audit link. Either way the text is still in
* use, so we refuse the delete up front with an actionable message instead of a
* raw 500. The counts run with an INTENTIONAL access bypass (`overrideAccess`):
* Consent read is admin-only and the hook must see every reference to decide
* whether to block — mirrors the before-delete guards in CampaignUser /
* personDelete.
*/
const blockConsentDeletionWithReferences: CollectionBeforeDeleteHook = async ({ id, req }) => {
const [
subscriptions,
signatures,
pushSubscriptions,
petitions,
leaderships,
supporters,
voteSupporters,
faceSubjects,
] = await Promise.all([
req.payload.count({
collection: 'subscription',
where: { consent: { equals: id } },
overrideAccess: true,
req,
}),
req.payload.count({
collection: 'signature',
where: { consent: { equals: id } },
overrideAccess: true,
req,
}),
req.payload.count({
collection: 'pushSubscription',
where: { consent: { equals: id } },
overrideAccess: true,
req,
}),
req.payload.count({
collection: 'petition',
where: { 'form.consent': { equals: id } },
overrideAccess: true,
req,
}),
req.payload.count({
collection: 'leadership',
where: { consent: { equals: id } },
overrideAccess: true,
req,
}),
req.payload.count({
collection: 'supporter',
where: { consent: { equals: id } },
overrideAccess: true,
req,
}),
req.payload.count({
collection: 'supporter',
where: { voteIntentionConsent: { equals: id } },
overrideAccess: true,
req,
}),
// C234 — face-subject references: intentional access bypass like every
// count above (the hook must see every reference to decide).
req.payload.count({
collection: 'faceSubject',
where: { consent: { equals: id } },
overrideAccess: true,
req,
}),
])
const references: Array<[number, string]> = [
[subscriptions.totalDocs, 'inscrições'],
[signatures.totalDocs, 'assinaturas'],
[pushSubscriptions.totalDocs, 'inscrições push'],
[petitions.totalDocs, 'petições'],
[leaderships.totalDocs, 'lideranças'],
[supporters.totalDocs, 'apoiadores'],
[voteSupporters.totalDocs, 'apoiadores (intenção de voto)'],
[faceSubjects.totalDocs, 'pessoas no índice de busca por selfie'],
]
const used = references.filter(([count]) => count > 0)
if (used.length === 0) return
const detail = used.map(([count, label]) => `${count} ${label}`).join(', ')
throw new APIError(`Consentimento em uso — não é possível excluir (${detail}).`, 409)
}
export const Consent: CollectionConfig = {
slug: 'consent',
labels: {
singular: 'Consentimento',
plural: 'Consentimentos',
},
admin: {
group: 'Contatos',
useAsTitle: 'text',
},
// Versioned legal texts referenced by signatures/subscriptions/supporters.
// Server flows resolve them via the Local API without a user; only admins
// may create or alter them.
access: {
create: payloadAdminOnly,
read: payloadAdminOnly,
update: payloadAdminOnly,
delete: payloadAdminOnly,
},
hooks: {
beforeDelete: [blockConsentDeletionWithReferences],
},
fields: [
{
name: 'key',
type: 'text',
label: 'Chave estável',
required: false,
unique: true,
index: true,
admin: {
description: 'Identificador estável para referências no código.',
},
},
{
name: 'text',
type: 'richText',
label: 'Texto',
required: true,
},
],
}