POPIA toolkit part 3: retention, breach register, readiness

- Retention policies (Admin -> Privacy -> Retention) applied by a nightly
  `retention` job: inactive accounts anonymised after 5 years with a
  30-day warning (on by default; never staff roles or people with an
  upcoming registration), form answers, login history, payer details in
  payment notifications, audit/access logs
- User.lastLoginAt (set on login, backfilled) and inactivityWarnedAt
- Breach register (SecurityBreach) with drafts for the people affected
  and the Information Regulator
- Readiness checklist with a score
- Children's/medical flag in the access log; {retention} placeholder in
  the privacy notice
- Unit tests (retention.test.js), e2e (privacy-retention.spec.ts); docs

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012mt6TCv85T9VKRq3cV7rXq
This commit is contained in:
2026-10-23 20:25:58 +02:00
co-authored by Claude Opus 5.5
parent 7f5e31461a
commit 6907bc3bd3
32 changed files with 1441 additions and 35 deletions
+3
View File
@@ -73,6 +73,9 @@ WAITLIST_JOB_ENABLED=true
PAYMENT_STATUS_JOB_ENABLED=true
# Privacy (POPIA): daily 08:00 reminder to admins of data requests due within a week
PRIVACY_JOBS_ENABLED=true
# Privacy (POPIA): nightly 03:30 retention job (Admin → Privacy → Retention). Note: inactive
# accounts are anonymised after 5 years by default (with a warning 30 days before).
RETENTION_JOBS_ENABLED=true
# Nightly database backup at 02:00 (requires the `pg_dump` binary on this host).
# Retention count is set via Admin → Site Settings → Backups (default 14).
BACKUP_ENABLED=true
+9 -1
View File
@@ -582,8 +582,16 @@ Privacy notice, operators and logs (`src/utils/privacyNotice.js`, `src/utils/acc
| PUT / DELETE | `/api/privacy/operators/:id` | admin | Change / remove an operator (audited as `operator_*`) |
| GET | `/api/privacy/consent-log?type=news\|notice\|parental&q=&page=` | admin | News opt-in changes, notice acceptances, or parental consent answers (50 per page) |
| GET | `/api/privacy/access-log?action=&actorId=&from=&to=&page=` | admin | Bulk exports/views of personal information, with `actions` (labels) and `actors` for the filters |
| GET | `/api/privacy/readiness` | admin | `{ score, passed, total, checks: [{ key, label, ok, detail, href, applies }] }` |
| GET | `/api/privacy/retention` | admin | `{ policies, definitions, reviewedAt, reviewedBy, preview, lastRun, related }` — `preview` is what the next run would affect |
| PUT | `/api/privacy/retention` | admin | `{ policies: { inactive_accounts\|form_answers\|login_history\|payment_details\|audit_logs: { enabled, months } } }` — all five required. Audited as `retention_policies_updated` |
| POST | `/api/privacy/retention/run` | admin | Run the retention job now: `{ result, state }` |
| GET / POST | `/api/privacy/breaches` | admin | The breach register / record one `{ title, discoveredAt, description, dataAffected, occurredAt?, peopleAffected?, whoAffected?, consequences?, actionsTaken?, adviceToPeople?, causedBy? }` |
| PUT | `/api/privacy/breaches/:id` | admin | Change any of those, `status` (open\|contained\|closed), `regulatorNotifiedAt`, `peopleNotifiedAt`. Audited as `breach_updated` |
Placeholders in notice sections: `{org}`, `{orgEmail}`, `{website}`, `{ioName}`, `{ioEmail}`, `{medicalRetentionDays}`, and `{operators}` on a line of its own (one bullet per active operator). Login and `GET /api/users/profile` return `noticePromptPending` — true when a version with `requiresAcceptance` is newer than the one the person accepted. Sign-up records an acceptance of the current version (source `signup`).
The `retention` job (03:30, `RETENTION_JOBS_ENABLED=false` to disable) works through each switched-on policy. Inactive accounts: role `user`, not anonymised, whose latest of created / last login (`User.lastLoginAt`) / registration or its event's end / named as attendee / payment is older than the period. Those within 30 days of it are warned (email, else WhatsApp; `User.inactivityWarnedAt`), and those warned at least 30 days ago — after their last activity — are anonymised unless they have a registration for an upcoming event. Logging in clears the warning. At most 300 warnings and 200 anonymisations per run. Payment details: `ProviderTransaction.raw` and `ProviderCheckout.request` older than the period are scrubbed and marked `_scrubbed`. Access log rows carry `sensitive` (medical lists, and anything for an event with `requiresParentalConsent`); `?sensitive=true` filters them.
Placeholders in notice sections: `{org}`, `{orgEmail}`, `{website}`, `{ioName}`, `{ioEmail}`, `{medicalRetentionDays}`, and — each on a line of its own — `{operators}` (one bullet per active operator) and `{retention}` (one bullet per retention period). Login and `GET /api/users/profile` return `noticePromptPending` — true when a version with `requiresAcceptance` is newer than the one the person accepted. Sign-up records an acceptance of the current version (source `signup`).
Access log actions (`DataAccessLog.action`): `report_pdf`, `report_excel`, `report_email`, `report_whatsapp` (`/api/reports/*`, with the row count), `attendance_export`, `certificates_download`, `group_lists` (or `medical_list` with `?medical=true`), `form_responses` (first page of a list), `consent_list`, `medical_list`, `backup_download`, `impersonation`.
@@ -0,0 +1,57 @@
-- CreateEnum
CREATE TYPE "BreachStatus" AS ENUM ('open', 'contained', 'closed');
-- AlterEnum
-- This migration adds more than one value to an enum.
-- With PostgreSQL versions 11 and earlier, this is not possible
-- in a single migration. This can be worked around by creating
-- multiple migrations, each migration adding only one value to
-- the enum.
ALTER TYPE "AdminAuditAction" ADD VALUE 'retention_policies_updated';
ALTER TYPE "AdminAuditAction" ADD VALUE 'retention_run';
ALTER TYPE "AdminAuditAction" ADD VALUE 'breach_recorded';
ALTER TYPE "AdminAuditAction" ADD VALUE 'breach_updated';
-- AlterTable
ALTER TABLE "DataAccessLog" ADD COLUMN "sensitive" BOOLEAN NOT NULL DEFAULT false;
-- AlterTable
ALTER TABLE "User" ADD COLUMN "inactivityWarnedAt" TIMESTAMP(3),
ADD COLUMN "lastLoginAt" TIMESTAMP(3);
-- CreateTable
CREATE TABLE "SecurityBreach" (
"id" TEXT NOT NULL,
"title" TEXT NOT NULL,
"status" "BreachStatus" NOT NULL DEFAULT 'open',
"discoveredAt" TIMESTAMP(3) NOT NULL,
"occurredAt" TIMESTAMP(3),
"description" TEXT NOT NULL,
"dataAffected" TEXT NOT NULL,
"peopleAffected" INTEGER,
"whoAffected" TEXT,
"consequences" TEXT,
"actionsTaken" TEXT,
"adviceToPeople" TEXT,
"causedBy" TEXT,
"regulatorNotifiedAt" TIMESTAMP(3),
"peopleNotifiedAt" TIMESTAMP(3),
"createdById" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "SecurityBreach_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "SecurityBreach_status_discoveredAt_idx" ON "SecurityBreach"("status", "discoveredAt");
-- AddForeignKey
ALTER TABLE "SecurityBreach" ADD CONSTRAINT "SecurityBreach_createdById_fkey" FOREIGN KEY ("createdById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- Last login, from the login history (which the retention job will start expiring).
UPDATE "User" u SET "lastLoginAt" = l.at
FROM (SELECT "userId", MAX("createdAt") AS at FROM "SecurityEvent" WHERE "type" = 'login' AND "userId" IS NOT NULL GROUP BY "userId") l
WHERE u."id" = l."userId";
+45
View File
@@ -84,6 +84,10 @@ model User {
// The privacy notice version they last accepted (0 = the built-in notice). Null = never
// recorded. Asked again when a version that needs re-acceptance is newer.
noticeVersionAccepted Int?
// Retention: when they last logged in (kept here because login history itself expires),
// and when they were warned that their inactive account is about to be deleted.
lastLoginAt DateTime?
inactivityWarnedAt DateTime?
registrations Registration[]
payments Payment[]
paymentsRecorded Payment[] @relation("PaymentRecordedBy")
@@ -136,6 +140,7 @@ model User {
noticesPublished PrivacyNotice[]
noticeAcceptances NoticeAcceptance[]
dataAccessLogs DataAccessLog[]
breachesRecorded SecurityBreach[]
}
model Event {
@@ -593,6 +598,10 @@ enum AdminAuditAction {
operator_created
operator_updated
operator_deleted
retention_policies_updated
retention_run
breach_recorded
breach_updated
}
// Append-only audit trail for admin/supervisor-initiated actions with money or
@@ -1724,6 +1733,8 @@ model DataAccessLog {
what String
eventId String?
records Int?
// Children's or special personal information (youth events, medical details).
sensitive Boolean @default(false)
ip String?
createdAt DateTime @default(now())
@@ -1731,3 +1742,37 @@ model DataAccessLog {
@@index([actorId, createdAt])
@@index([action, createdAt])
}
enum BreachStatus {
open
contained
closed
}
// POPIA s22: a security compromise — what happened, whose information, what was done, and
// when the Information Regulator and the people affected were told.
model SecurityBreach {
id String @id @default(uuid())
title String
status BreachStatus @default(open)
discoveredAt DateTime
occurredAt DateTime?
description String
dataAffected String
peopleAffected Int?
// Free text: who (groups of people, events…), since a breach can involve people without accounts.
whoAffected String?
consequences String?
actionsTaken String?
adviceToPeople String?
// Who caused it, if known (POPIA asks for this when notifying).
causedBy String?
regulatorNotifiedAt DateTime?
peopleNotifiedAt DateTime?
createdById String?
createdBy User? @relation(fields: [createdById], references: [id], onDelete: SetNull)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([status, discoveredAt])
}
@@ -261,6 +261,7 @@ const accessLog = async (req, res) => {
try {
const where = {};
if (req.query.action) where.action = String(req.query.action);
if (req.query.sensitive === 'true') where.sensitive = true;
if (req.query.actorId) where.actorId = String(req.query.actorId);
if (req.query.from || req.query.to) {
where.createdAt = {};
@@ -276,14 +277,161 @@ const accessLog = async (req, res) => {
total, pageSize: PAGE_SIZE,
actions: ACCESS_ACTIONS,
actors: actors.map(a => ({ id: a.actorId, name: a.actor?.name || 'Unknown' })),
rows: rows.map(r => ({ id: r.id, at: r.createdAt, actor: r.actor?.name || 'Deleted user', actorRole: r.actorRole, action: r.action, what: r.what, records: r.records, eventId: r.eventId, ip: r.ip })),
rows: rows.map(r => ({ id: r.id, at: r.createdAt, actor: r.actor?.name || 'Deleted user', actorRole: r.actorRole, action: r.action, what: r.what, records: r.records, eventId: r.eventId, ip: r.ip, sensitive: r.sensitive })),
});
} catch (error) {
fail(res, error);
}
};
// ─── Readiness ────────────────────────────────────────────────────────────────
// @desc POPIA readiness checklist with a score
// @route GET /api/privacy/readiness
// @access Private/Admin
const getReadiness = async (req, res) => {
try {
res.json(await require('../utils/readiness').readiness());
} catch (error) {
fail(res, error);
}
};
// ─── Retention ────────────────────────────────────────────────────────────────
async function retentionState() {
const retention = require('../utils/retention');
const { getSetting } = require('../utils/settingsCache');
const current = await retention.getPolicies();
const [preview, lastRun, medicalDays, backupCount] = await Promise.all([
retention.preview(current.policies),
retention.lastRun(),
getSetting('consent_medical_retention_days', ''),
getSetting('backup_retain_count', ''),
]);
return {
...current,
definitions: Object.fromEntries(Object.entries(retention.POLICIES).map(([k, d]) => [k, { label: d.label, description: d.description, minMonths: d.minMonths, defaults: d.defaults }])),
preview,
lastRun,
related: { medicalDays: parseInt(medicalDays, 10) || 30, backupCount: parseInt(backupCount, 10) || 14, analyticsDays: 90 },
};
}
// @desc Retention policies, what they'd affect now, and the last run
// @route GET /api/privacy/retention
// @access Private/Admin
const getRetention = async (req, res) => {
try {
res.json(await retentionState());
} catch (error) {
fail(res, error);
}
};
// @desc Save retention policies (body.policies: { key: { enabled, months } })
// @route PUT /api/privacy/retention
// @access Private/Admin
const saveRetention = async (req, res) => {
try {
const saved = await require('../utils/retention').savePolicies(req.body?.policies, { reviewedBy: req.user.name });
logAdminAction({ actorId: req.user.id, actorRole: req.user.role, action: 'retention_policies_updated', targetType: 'retention', metadata: saved.policies, ip: getClientIp(req) });
res.json(await retentionState());
} catch (error) {
fail(res, error);
}
};
// @desc Run the retention job now
// @route POST /api/privacy/retention/run
// @access Private/Admin
const runRetentionNow = async (req, res) => {
try {
const result = await require('../utils/retention').runRetention(new Date());
res.json({ result, state: await retentionState() });
} catch (error) {
fail(res, error);
}
};
// ─── Breach register ──────────────────────────────────────────────────────────
const BREACH_TEXT = ['title', 'description', 'dataAffected', 'whoAffected', 'consequences', 'actionsTaken', 'adviceToPeople', 'causedBy'];
const BREACH_DATES = ['discoveredAt', 'occurredAt', 'regulatorNotifiedAt', 'peopleNotifiedAt'];
function breachData(body, { partial = false } = {}) {
const data = {};
for (const f of BREACH_TEXT) {
if (body?.[f] === undefined) continue;
const v = body[f] == null ? '' : String(body[f]).trim().slice(0, f === 'title' ? 200 : 10000);
data[f] = v || (['title', 'description', 'dataAffected'].includes(f) ? '' : null);
}
for (const f of BREACH_DATES) {
if (body?.[f] === undefined) continue;
if (body[f] === null || body[f] === '') { data[f] = null; continue; }
const d = new Date(body[f]);
if (Number.isNaN(d.getTime())) throw new Error(`${f} is not a valid date.`);
data[f] = d;
}
if (body?.peopleAffected !== undefined) {
const n = body.peopleAffected === null || body.peopleAffected === '' ? null : parseInt(body.peopleAffected, 10);
if (n !== null && (!Number.isInteger(n) || n < 0)) throw new Error('People affected must be a whole number.');
data.peopleAffected = n;
}
if (body?.status !== undefined) {
if (!['open', 'contained', 'closed'].includes(body.status)) throw new Error('status must be open, contained or closed');
data.status = body.status;
}
for (const f of ['title', 'description', 'dataAffected']) {
if ((!partial || f in data) && !data[f]) throw new Error({ title: 'Give it a short title.', description: 'Describe what happened.', dataAffected: 'Say what information was affected.' }[f]);
}
if (!partial && !data.discoveredAt) throw new Error('When was it discovered?');
if (partial && 'discoveredAt' in data && !data.discoveredAt) throw new Error('When was it discovered?');
return data;
}
// @route GET /api/privacy/breaches
const listBreaches = async (req, res) => {
try {
res.json(await prisma.securityBreach.findMany({ orderBy: { discoveredAt: 'desc' }, include: { createdBy: { select: { name: true } } } }));
} catch (error) {
fail(res, error);
}
};
// @route POST /api/privacy/breaches
const createBreach = async (req, res) => {
try {
const breach = await prisma.securityBreach.create({ data: { ...breachData(req.body), createdById: req.user.id } });
logAdminAction({ actorId: req.user.id, actorRole: req.user.role, action: 'breach_recorded', targetType: 'security_breach', targetId: breach.id, metadata: { title: breach.title }, ip: getClientIp(req) });
res.status(201).json(breach);
} catch (error) {
fail(res, error);
}
};
// @route PUT /api/privacy/breaches/:id
const updateBreach = async (req, res) => {
try {
const existing = await prisma.securityBreach.findUnique({ where: { id: req.params.id } });
if (!existing) { res.status(404); throw new Error('Not found'); }
const data = breachData(req.body, { partial: true });
const breach = await prisma.securityBreach.update({ where: { id: existing.id }, data });
logAdminAction({ actorId: req.user.id, actorRole: req.user.role, action: 'breach_updated', targetType: 'security_breach', targetId: breach.id, metadata: { title: breach.title, changed: Object.keys(data), status: breach.status }, ip: getClientIp(req) });
res.json(breach);
} catch (error) {
fail(res, error);
}
};
module.exports = {
getReadiness,
getRetention,
saveRetention,
runRetentionNow,
listBreaches,
createBreach,
updateBreach,
getNotice,
acceptMyNotice,
getNoticeDraft,
@@ -153,6 +153,8 @@ function errorStatus(error, res) {
// required): notify, record the activity, and issue the session token.
async function completeLogin(user, req, res, extra = {}) {
const noticePromptPending = await require('../utils/privacyNotice').noticePromptPending(user).catch(() => false);
// Retention: logging in keeps the account (and cancels an inactivity warning).
prisma.user.update({ where: { id: user.id }, data: { lastLoginAt: new Date(), inactivityWarnedAt: null } }).catch(() => {});
// Send login notification in the background
sendLoginNotification(user, req).catch(() => {});
@@ -230,6 +230,11 @@ async function handleIncomingMessage(req) {
return;
}
// Proof for the POPIA readiness page that WAWP's webhook (and so STOP) is set up.
const prisma = require('../config/db');
const now = new Date().toISOString();
prisma.appSetting.upsert({ where: { key: 'wawp_webhook_last_seen' }, update: { value: now }, create: { key: 'wawp_webhook_last_seen', value: now } }).catch(() => {});
const payload = req.body?.payload || {};
if (payload.fromMe || !isStopKeyword(payload.body)) return;
const phone = phoneFromChatId(payload.from);
+12 -1
View File
@@ -932,7 +932,18 @@ app.get('/docs', async (req, res) => {
responses:[{ status:201, desc:'Created' }]},
{ method:'GET', path:'/api/privacy/consent-log', auth:'admin', desc:'Consent records: ?type=news|notice|parental, ?q= name/email, ?page=',
responses:[{ status:200, desc:'Success', body:{ total:1, pageSize:50, rows:[{ at:'2026-10-23T08:00:00.000Z', name:'Jane Doe', email:'jane@example.com', channel:'email', granted:false, source:'unsubscribe_link' }] }}]},
{ method:'GET', path:'/api/privacy/access-log', auth:'admin', desc:'Bulk exports/views of personal information: ?action=, ?actorId=, ?from=, ?to=, ?page=',
{ method:'GET', path:'/api/privacy/readiness', auth:'admin', desc:'POPIA readiness checklist with a score; each open item has a link to fix it',
responses:[{ status:200, desc:'Success', body:{ score:77, passed:10, total:13, checks:[{ key:'notice', label:'Privacy notice published', ok:true, detail:'2 versions published', href:'/dashboard/admin/privacy?tab=notice', applies:true }] }}]},
{ method:'GET', path:'/api/privacy/retention', auth:'admin', desc:'Retention policies, what the next run would affect, and the last run',
responses:[{ status:200, desc:'Success', body:{ policies:{ inactive_accounts:{ enabled:true, months:60 } }, preview:{ inactive_accounts:{ toWarn:3, toAnonymise:0 } }, reviewedAt:null }}]},
{ method:'PUT', path:'/api/privacy/retention', auth:'admin', desc:'Save the retention policies (all five)',
request:{ body:{ policies:{ inactive_accounts:{ enabled:true, months:60 }, form_answers:{ enabled:true, months:12 }, login_history:{ enabled:true, months:24 }, payment_details:{ enabled:true, months:24 }, audit_logs:{ enabled:true, months:60 } } } },
responses:[{ status:200, desc:'Saved' }]},
{ method:'POST', path:'/api/privacy/retention/run', auth:'admin', desc:'Run the retention job now (warn/anonymise inactive accounts, delete expired data)',
responses:[{ status:200, desc:'Done', body:{ result:{ inactive_accounts:{ warned:3, anonymised:0, waiting:0 }, login_history:{ deleted:120 } } }}]},
{ method:'GET', path:'/api/privacy/breaches', auth:'admin', desc:'The breach register (security compromises); POST to record one, PUT /:id to update or mark the Regulator/people told',
responses:[{ status:200, desc:'Success', body:[{ id:'br-uuid-...', title:'Phone with the attendee list lost', status:'open', discoveredAt:'2026-10-23T08:00:00.000Z', regulatorNotifiedAt:null }] }]},
{ method:'GET', path:'/api/privacy/access-log', auth:'admin', desc:'Bulk exports/views of personal information: ?action=, ?actorId=, ?sensitive=true, ?from=, ?to=, ?page=',
responses:[{ status:200, desc:'Success', body:{ total:1, pageSize:50, rows:[{ at:'2026-10-23T08:00:00.000Z', actor:'Sam Supervisor', action:'report_pdf', what:'Camp 2026 attendees', records:48 }] }}]},
]},
+4
View File
@@ -56,6 +56,10 @@ const JOBS = [
name: 'privacy', label: 'Privacy requests: remind admins of requests due soon', cron: '0 8 * * *', env: 'PRIVACY_JOBS_ENABLED',
run: () => require('../utils/privacy').remindDueRequests(new Date()),
},
{
name: 'retention', label: 'Retention: delete or anonymise personal information past its retention period', cron: '30 3 * * *', env: 'RETENTION_JOBS_ENABLED',
run: () => require('../utils/retention').runRetention(new Date()),
},
{
name: 'analytics-rollup', label: 'Funnel analytics: roll up visits older than 90 days', cron: '15 4 * * *', env: 'ANALYTICS_ROLLUP_ENABLED',
run: async () => ({ rolledUp: await require('../utils/analytics').rollupOldEvents() }),
@@ -27,6 +27,13 @@ const {
deleteOperator,
consentLog,
accessLog,
getReadiness,
getRetention,
saveRetention,
runRetentionNow,
listBreaches,
createBreach,
updateBreach,
} = require('../controllers/privacyAdminController');
const { protect, admin } = require('../middleware/authMiddleware');
@@ -66,4 +73,13 @@ router.delete('/operators/:id', protect, admin, deleteOperator);
router.get('/consent-log', protect, admin, consentLog);
router.get('/access-log', protect, admin, accessLog);
// Admin: readiness, retention, breach register
router.get('/readiness', protect, admin, getReadiness);
router.get('/retention', protect, admin, getRetention);
router.put('/retention', protect, admin, saveRetention);
router.post('/retention/run', protect, admin, runRetentionNow);
router.get('/breaches', protect, admin, listBreaches);
router.post('/breaches', protect, admin, createBreach);
router.put('/breaches/:id', protect, admin, updateBreach);
module.exports = router;
+9 -1
View File
@@ -21,8 +21,15 @@ const ACCESS_ACTIONS = {
* POPIA access log: someone exported or viewed personal information in bulk. Fire-and-
* forget like logAdminAction — a logging failure never blocks the export itself.
*/
async function logDataAccess(req, { action, what, eventId = null, records = null }) {
async function logDataAccess(req, { action, what, eventId = null, records = null, sensitive }) {
try {
// Children's or special information: medical lists always; otherwise anything about a
// youth event (one that asks for parental consent).
let isSensitive = sensitive ?? (action === 'medical_list');
if (!isSensitive && eventId) {
const event = await prisma.event.findUnique({ where: { id: eventId }, select: { requiresParentalConsent: true } });
isSensitive = !!event?.requiresParentalConsent;
}
await prisma.dataAccessLog.create({
data: {
actorId: req.user?.id || null,
@@ -31,6 +38,7 @@ async function logDataAccess(req, { action, what, eventId = null, records = null
what: String(what || ACCESS_ACTIONS[action] || action).slice(0, 500),
eventId: eventId || null,
records: Number.isFinite(records) ? records : null,
sensitive: isSensitive,
ip: getClientIp(req),
},
});
+20 -11
View File
@@ -7,11 +7,12 @@
* notice is shown, so it follows Site settings and the operator register:
* {org} {orgEmail} {website} {ioName} {ioEmail} {medicalRetentionDays}
* {operators} — on a line of its own: one bullet per active operator.
* {retention} — on a line of its own: one bullet per retention period (utils/retention.js).
*/
const prisma = require('../config/db');
const PLACEHOLDERS = ['org', 'orgEmail', 'website', 'ioName', 'ioEmail', 'medicalRetentionDays', 'operators'];
const PLACEHOLDERS = ['org', 'orgEmail', 'website', 'ioName', 'ioEmail', 'medicalRetentionDays', 'operators', 'retention'];
const MAX_SECTIONS = 40;
const MAX_TITLE = 200;
const MAX_BODY = 20000;
@@ -120,13 +121,10 @@ const DEFAULT_SECTIONS = [
id: 'retention',
title: '7. Data Retention',
body: [
'We retain your personal data for up to 5 years after your last event registration, or until you ask us to delete your account — whichever comes first.',
'Medical and emergency-contact details from parental consent forms are deleted {medicalRetentionDays} days after the event ends. The record of who gave consent, when, and to which wording is kept.',
'Detailed visit statistics are combined into anonymous daily totals after 90 days.',
"Ticket lists downloaded to a staff member's scanner for offline check-in are deleted from that device when offline mode is ended.",
'Records of support access to accounts (see section 9), of who exported personal information, and other audit records are kept for accountability.',
'You can ask for your account to be deleted from the Privacy page in your account. Your account is closed straight away, and your personal information — your name and contact details, the people you registered, your form answers — is deleted within 30 days (after any upcoming event you registered for). Payment and registration records are kept without your name, because the law requires us to keep financial records.',
'Backups of our database still contain deleted information until they are replaced, which happens automatically within a few weeks.',
'We keep personal information only as long as we need it:',
'{retention}',
"• Ticket lists downloaded to a staff member's scanner for offline check-in are deleted from that device when offline mode is ended.",
'You can ask for your account to be deleted at any time from the Privacy page in your account. Your account is closed straight away, and your personal information — your name and contact details, the people you registered, your form answers — is deleted within 30 days (after any upcoming event you registered for). Payment and registration records are kept without your name, because the law requires us to keep financial records.',
].join('\n'),
},
{
@@ -263,7 +261,7 @@ function cleanSections(input) {
/** Settings and operators the placeholders are filled from. */
async function noticeContext(db = prisma) {
const { getSetting } = require('./settingsCache');
const [org, orgEmail, website, ioName, ioEmail, medicalDays, operators] = await Promise.all([
const [org, orgEmail, website, ioName, ioEmail, medicalDays, operators, retention] = await Promise.all([
getSetting('org_name', process.env.ORG_NAME || 'Cross Code'),
getSetting('org_email', ''),
getSetting('legal_website_url', ''),
@@ -271,6 +269,7 @@ async function noticeContext(db = prisma) {
getSetting('legal_io_email', ''),
getSetting('consent_medical_retention_days', ''),
db.operator.findMany({ where: { active: true }, orderBy: [{ order: 'asc' }, { name: 'asc' }] }),
require('./retention').noticeLines(db),
]);
// Unset legal fields show an obviously-unfinished placeholder, never someone's real details.
return {
@@ -281,9 +280,16 @@ async function noticeContext(db = prisma) {
ioEmail: ioEmail || 'io@example.com',
medicalRetentionDays: String(parseInt(medicalDays, 10) || 30),
operators,
retention,
};
}
// Placeholders that stand on a line of their own and become several bullet lines.
const LIST_PLACEHOLDERS = {
operators: ctx => (ctx.operators.length ? ctx.operators.map(operatorLine) : ['• (No service providers listed.)']),
retention: ctx => ctx.retention || [],
};
function operatorLine(o) {
return `• ${o.name}${o.location ? ` (${o.location})` : ''} — ${o.purpose}. ${o.dataShared ? `Receives: ${o.dataShared}.` : ''}`.trim();
}
@@ -293,8 +299,11 @@ function renderSections(sections, ctx) {
return sections.map(s => {
const body = String(s.body || '')
.split('\n')
.flatMap(line => (line.trim() === '{operators}' ? (ctx.operators.length ? ctx.operators.map(operatorLine) : ['• (No service providers listed.)']) : [line]))
.map(line => line.replace(/\{(\w+)\}/g, (m, key) => (key !== 'operators' && PLACEHOLDERS.includes(key) ? ctx[key] : m)))
.flatMap(line => {
const list = line.trim().match(/^\{(\w+)\}$/)?.[1];
return list && LIST_PLACEHOLDERS[list] ? LIST_PLACEHOLDERS[list](ctx) : [line];
})
.map(line => line.replace(/\{(\w+)\}/g, (m, key) => (!LIST_PLACEHOLDERS[key] && PLACEHOLDERS.includes(key) ? ctx[key] : m)))
.join('\n');
return { id: s.id, title: s.title, body };
});
@@ -0,0 +1,95 @@
/**
* The POPIA readiness checklist for Admin → Privacy: what's set up, what isn't, and where to
* fix it. Checks that don't apply to this install (e.g. WhatsApp STOP without WhatsApp) are
* left out of the score.
*/
const prisma = require('../config/db');
const DAY = 24 * 60 * 60 * 1000;
// Generic names the operator register starts with, which should be replaced with the real provider.
const GENERIC_OPERATORS = ['Email delivery provider', 'Hosting provider'];
async function readiness(now = new Date(), db = prisma) {
const { getSetting } = require('./settingsCache');
const setting = key => getSetting(key, '');
const [ioName, ioEmail, operatorName, website, smtpHost] = await Promise.all([
setting('legal_io_name'), setting('legal_io_email'), setting('legal_operator_name'), setting('legal_website_url'), setting('smtp_host'),
]);
const retention = require('./retention');
const { isEnabled, JOBS } = require('../jobs');
const [notices, operators, policies, lastRun, overdue, openBreaches, webhookSeen, whatsappConfigured, backups] = await Promise.all([
db.privacyNotice.count(),
db.operator.findMany({ where: { active: true }, select: { name: true, location: true } }),
retention.getPolicies(db),
retention.lastRun(db),
db.dataRequest.count({ where: { status: 'open', selfService: false, dueAt: { lt: now } } }),
db.securityBreach.findMany({ where: { status: { not: 'closed' } }, select: { title: true, discoveredAt: true, regulatorNotifiedAt: true } }),
db.appSetting.findUnique({ where: { key: 'wawp_webhook_last_seen' } }),
require('./whatsapp').isConfigured().catch(() => false),
require('./backupUtils').listBackups().catch(() => []),
]);
const checks = [];
const add = (key, label, ok, detail, href, applies = true) => checks.push({ key, label, ok: !!ok, detail, href, applies });
add('io', 'Information Officer named', ioName && ioEmail,
ioName && ioEmail ? `${ioName} (${ioEmail})` : 'Set the Information Officer\'s name and email address — they appear on the privacy notice and contact page.',
'/dashboard/admin/settings?tab=legal');
add('legal', 'Responsible party and website filled in', operatorName && website,
operatorName && website ? `${operatorName} · ${website}` : 'Fill in the operator/responsible party and website for the legal pages.',
'/dashboard/admin/settings?tab=legal');
add('notice', 'Privacy notice published', notices > 0,
notices > 0 ? `${notices} version${notices === 1 ? '' : 's'} published` : 'Review the privacy notice and publish your own version (the built-in text is a starting point).',
'/dashboard/admin/privacy?tab=notice');
const vague = operators.filter(o => !o.location || GENERIC_OPERATORS.includes(o.name)).map(o => o.name);
add('operators', 'Operators listed with their details', operators.length && !vague.length,
!operators.length ? 'List the services that process personal information for you.' : vague.length ? `Check: ${vague.join(', ')} (name the real provider and where it processes data).` : `${operators.length} operator${operators.length === 1 ? '' : 's'} listed`,
'/dashboard/admin/privacy?tab=operators');
add('retention_reviewed', 'Retention periods reviewed', policies.reviewedAt,
policies.reviewedAt ? `Saved ${new Date(policies.reviewedAt).toLocaleDateString('en-ZA')}` : 'Check the retention periods suit your organisation, and save them.',
'/dashboard/admin/privacy?tab=retention');
const retentionJob = JOBS.find(j => j.name === 'retention');
const ranRecently = lastRun?.at && now - new Date(lastRun.at) < 2 * DAY;
add('retention_running', 'Retention job running', isEnabled(retentionJob) && ranRecently,
!isEnabled(retentionJob) ? 'The retention job is switched off (RETENTION_JOBS_ENABLED or JOBS_ENABLED).' : ranRecently ? `Last ran ${new Date(lastRun.at).toLocaleString('en-ZA')}` : 'It hasn\'t run in the last two days — check Background jobs.',
'/dashboard/admin/settings?tab=jobs');
add('requests', 'Privacy requests answered on time', overdue === 0,
overdue ? `${overdue} request${overdue === 1 ? ' is' : 's are'} overdue.` : 'None overdue',
'/dashboard/admin/data-requests');
const unreported = openBreaches.filter(b => !b.regulatorNotifiedAt && now - new Date(b.discoveredAt) > 3 * DAY);
add('breaches', 'Security compromises reported', unreported.length === 0,
unreported.length ? `Not yet reported to the Information Regulator: ${unreported.map(b => b.title).join(', ')}.` : openBreaches.length ? `${openBreaches.length} open, all reported` : 'Nothing open',
'/dashboard/admin/privacy?tab=breaches');
const backendUrl = process.env.BACKEND_URL || '';
// The .env.example value ("https://your-backend-domain.com") doesn't count.
const realHttps = /^https:\/\//i.test(backendUrl) && !/your-|example\./i.test(backendUrl);
add('https', 'Unsubscribe links work in mail apps', realHttps,
realHttps ? backendUrl : 'Set BACKEND_URL on the server to the site\'s public https:// address (used by one-click unsubscribe and the WhatsApp webhook).',
null);
add('smtp', 'Email sending set up', smtpHost || process.env.SMTP_HOST || process.env.EMAIL_HOST,
smtpHost || process.env.SMTP_HOST || process.env.EMAIL_HOST ? 'SMTP configured' : 'Without email, people don\'t get unsubscribe links, request confirmations or inactivity warnings.',
'/dashboard/admin/settings?tab=email');
const seen = webhookSeen?.value ? new Date(webhookSeen.value) : null;
add('whatsapp_stop', 'WhatsApp STOP replies reach the site', seen && now - seen < 30 * DAY,
seen ? `Last message from WAWP ${seen.toLocaleString('en-ZA')}${now - seen >= 30 * DAY ? ' — over a month ago, check the webhook' : ''}` : 'Paste the webhook URL from Site settings → WhatsApp into WAWP (events: message, session.status).',
'/dashboard/admin/settings?tab=whatsapp', whatsappConfigured);
const twoFactorOn = String(process.env.TWO_FACTOR_REQUIRED_ROLES || 'true').toLowerCase() !== 'false';
add('two_factor', 'Two-factor login required for admins and supervisors', twoFactorOn,
twoFactorOn ? 'Required' : 'TWO_FACTOR_REQUIRED_ROLES=false on the server — only for emergencies.', null);
const lastBackup = backups[0]?.createdAt;
add('backups', 'Backups running', lastBackup && now - new Date(lastBackup) < 2 * DAY,
lastBackup ? `Last backup ${new Date(lastBackup).toLocaleString('en-ZA')}` : 'No backups found on this server.',
'/dashboard/admin/settings?tab=backups');
const applicable = checks.filter(c => c.applies);
const passed = applicable.filter(c => c.ok).length;
return { score: applicable.length ? Math.round((passed / applicable.length) * 100) : 0, passed, total: applicable.length, checks };
}
module.exports = { readiness, GENERIC_OPERATORS };
+319
View File
@@ -0,0 +1,319 @@
/**
* POPIA retention: how long each kind of personal information is kept, and the nightly
* `retention` job that deletes or anonymises what's past its time.
*
* Policies live in AppSetting `retention_policies` (JSON) on top of the defaults below.
* Medical details (consent_medical_retention_days), visit statistics (90 days, fixed) and
* backups (backup_retain_count) have their own settings and jobs; they're shown alongside.
*/
const prisma = require('../config/db');
const SETTING_KEY = 'retention_policies';
const LAST_RUN_KEY = 'retention_last_run';
const WARNING_DAYS = 30;
const DAY = 24 * 60 * 60 * 1000;
// Spread a first big run over several nights instead of emailing everyone at once.
const MAX_WARNINGS_PER_RUN = 300;
const MAX_ANONYMISED_PER_RUN = 200;
const BATCH = 500;
const POLICIES = {
inactive_accounts: {
label: 'Inactive accounts',
description: 'Accounts with no login, registration or payment in this time are anonymised, after a warning 30 days before. Staff, supervisor and admin accounts are never touched, nor anyone with a registration for an upcoming event.',
defaults: { enabled: true, months: 60 },
minMonths: 12,
},
form_answers: {
label: 'Attendee form answers',
description: 'Answers to event forms are deleted this long after the event ends.',
defaults: { enabled: true, months: 12 },
minMonths: 1,
},
login_history: {
label: 'Login history',
description: 'Logins, password changes and similar account events (with IP address and device).',
defaults: { enabled: true, months: 24 },
minMonths: 3,
},
payment_details: {
label: 'Payer details in payment notifications',
description: 'Names and email addresses that Yoco and PayFast send with a payment are removed. The payment itself (amount, date, method) is always kept for the accounts.',
defaults: { enabled: true, months: 24 },
minMonths: 3,
},
audit_logs: {
label: 'Audit and access logs',
description: 'The audit log, the access log and "view as" sessions.',
defaults: { enabled: true, months: 60 },
minMonths: 12,
},
};
const MAX_MONTHS = 240;
function monthsAgo(months, now = new Date()) {
const d = new Date(now);
d.setMonth(d.getMonth() - months);
return d;
}
function describeMonths(months) {
return months % 12 === 0 ? `${months / 12} year${months === 12 ? '' : 's'}` : `${months} month${months === 1 ? '' : 's'}`;
}
/** The policies in force (defaults overlaid with what the admin saved), and when they were last reviewed. */
async function getPolicies(db = prisma) {
const row = await db.appSetting.findUnique({ where: { key: SETTING_KEY } });
let saved = {};
try { saved = row?.value ? JSON.parse(row.value) : {}; } catch { saved = {}; }
const policies = {};
for (const [key, def] of Object.entries(POLICIES)) {
const s = saved.policies?.[key] || {};
policies[key] = {
enabled: typeof s.enabled === 'boolean' ? s.enabled : def.defaults.enabled,
months: Number.isInteger(s.months) ? s.months : def.defaults.months,
};
}
return { policies, reviewedAt: saved.reviewedAt || null, reviewedBy: saved.reviewedBy || null };
}
/** Save the admin's policies (validated). Throws a message fit for the admin. */
async function savePolicies(input, { reviewedBy } = {}, db = prisma) {
const policies = {};
for (const [key, def] of Object.entries(POLICIES)) {
const p = input?.[key] || {};
const months = parseInt(p.months, 10);
if (!Number.isInteger(months) || months < def.minMonths || months > MAX_MONTHS) {
throw new Error(`${def.label}: choose between ${def.minMonths} and ${MAX_MONTHS} months.`);
}
policies[key] = { enabled: p.enabled !== false, months };
}
const value = JSON.stringify({ policies, reviewedAt: new Date().toISOString(), reviewedBy: reviewedBy || null });
await db.appSetting.upsert({ where: { key: SETTING_KEY }, update: { value }, create: { key: SETTING_KEY, value } });
return getPolicies(db);
}
// ─── Inactive accounts ────────────────────────────────────────────────────────
/**
* Ordinary accounts (role user, not already anonymised) whose last sign of life — account
* created, last login, a registration (or the end of the event it was for), being named as
* an attendee, a payment — is before `before`.
* warned: false — not warned since that last activity (a warning before it no longer counts);
* otherwise — warned since their last activity, on or before `warnedBefore`.
*/
async function inactiveAccounts(before, { warned, warnedBefore, limit }, db = prisma) {
const rows = await db.$queryRawUnsafe(`
SELECT "id" FROM (
SELECT u."id", u."createdAt", u."inactivityWarnedAt" AS warned_at, GREATEST(
u."createdAt",
COALESCE(u."lastLoginAt", 'epoch'),
COALESCE((SELECT MAX(GREATEST(r."createdAt", e."endDate")) FROM "Registration" r JOIN "Event" e ON e."id" = r."eventId" WHERE r."userId" = u."id"), 'epoch'),
COALESCE((SELECT MAX(a."createdAt") FROM "Attendee" a WHERE a."userId" = u."id"), 'epoch'),
COALESCE((SELECT MAX(p."createdAt") FROM "Payment" p WHERE p."userId" = u."id"), 'epoch')
) AS last_active
FROM "User" u
WHERE u."role" = 'user'
AND u."email" NOT LIKE '%@deleted.invalid' AND u."email" NOT LIKE '%@deleted.local'
) x
WHERE last_active < $1
AND ${warned === false ? '(warned_at IS NULL OR warned_at < last_active)' : 'warned_at >= last_active AND warned_at <= $2'}
ORDER BY "createdAt"
LIMIT ${Math.max(1, Math.min(limit || BATCH, 5000))}`,
before, ...(warned === false ? [] : [warnedBefore]));
return rows.map(r => r.id);
}
async function warnInactive(userId, deleteOn, months, db = prisma) {
const user = await db.user.findUnique({ where: { id: userId }, select: { id: true, name: true, email: true, phoneNumber: true } });
if (!user) return false;
const { getSettingSync } = require('./settingsCache');
const org = getSettingSync('org_name', process.env.ORG_NAME || 'Cross Code');
const url = String(process.env.FRONTEND_URL || process.env.APP_BASE_URL || 'http://localhost:3001').replace(/\/$/, '');
const when = deleteOn.toLocaleDateString('en-ZA', { day: 'numeric', month: 'long', year: 'numeric', timeZone: 'Africa/Johannesburg' });
const text = `Your ${org} account hasn't been used for ${describeMonths(months)}. To protect your personal information, we'll delete it on ${when}. If you'd like to keep your account, just log in before then: ${url}/login`;
const realEmail = user.email && !/@(guest\.local|deleted\.invalid|deleted\.local)$/.test(user.email);
if (realEmail) {
const { sendMail, buildPrivacyEmail } = require('./email');
await sendMail({
to: user.email,
subject: `Your ${org} account will be deleted on ${when}`,
...buildPrivacyEmail({ name: user.name, heading: 'Your account will be deleted', paragraphs: [text, 'If you do nothing, your account is closed and your personal information deleted. Payment records are kept without your name, as the law requires.'] }),
}).catch(() => {});
} else {
const { waTextAny } = require('./notify');
await waTextAny(user, text);
}
await db.user.update({ where: { id: userId }, data: { inactivityWarnedAt: new Date() } });
return true;
}
async function runInactiveAccounts(policy, now, db = prisma) {
const cutoff = monthsAgo(policy.months, now);
const deleteOn = new Date(now.getTime() + WARNING_DAYS * DAY);
const { anonymiseUser, deletionBlockers } = require('./privacy');
// Warn those who'll pass the limit within the warning period.
const toWarn = await inactiveAccounts(new Date(cutoff.getTime() + WARNING_DAYS * DAY), { warned: false, limit: MAX_WARNINGS_PER_RUN }, db);
let warned = 0;
for (const id of toWarn) if (await warnInactive(id, deleteOn, policy.months, db)) warned++;
// Anonymise those past the limit who were warned at least 30 days ago and still haven't come back.
const due = await inactiveAccounts(cutoff, { warnedBefore: new Date(now.getTime() - WARNING_DAYS * DAY), limit: MAX_ANONYMISED_PER_RUN }, db);
let anonymised = 0;
let waiting = 0;
for (const id of due) {
if ((await deletionBlockers(id, db)).length) { waiting++; continue; }
await anonymiseUser(id, db);
await db.dataRequest.updateMany({ where: { userId: id, type: 'deletion', status: 'open' }, data: { status: 'completed', closedAt: now, response: 'Deleted after a long period without use.' } });
anonymised++;
}
return { warned, anonymised, waiting };
}
// ─── The other policies ───────────────────────────────────────────────────────
async function runFormAnswers(policy, now, db = prisma) {
const cutoff = monthsAgo(policy.months, now);
const where = { response: { registration: { event: { endDate: { lt: cutoff } } } } };
const answers = await db.formAnswer.deleteMany({ where });
const drafts = await db.formDraft.deleteMany({ where: { registration: { event: { endDate: { lt: cutoff } } } } });
return { answers: answers.count, drafts: drafts.count };
}
async function runLoginHistory(policy, now, db = prisma) {
const res = await db.securityEvent.deleteMany({ where: { createdAt: { lt: monthsAgo(policy.months, now) } } });
return { deleted: res.count };
}
// Rows not scrubbed yet carry no "_scrubbed" key; scrubbed ones get it so they're skipped next time.
async function scrubJsonColumn(table, column, cutoff, db) {
const { scrubPersonal } = require('./privacy');
let total = 0;
for (;;) {
const rows = await db.$queryRawUnsafe(
`SELECT "id", "${column}" AS data FROM "${table}" WHERE "createdAt" < $1 AND "${column}" IS NOT NULL AND jsonb_typeof("${column}") = 'object' AND NOT ("${column}" ? '_scrubbed') LIMIT ${BATCH}`,
cutoff,
);
if (!rows.length) break;
for (const r of rows) {
const model = table === 'ProviderTransaction' ? db.providerTransaction : db.providerCheckout;
await model.update({ where: { id: r.id }, data: { [column]: { ...scrubPersonal(r.data), _scrubbed: true } } });
}
total += rows.length;
if (rows.length < BATCH) break;
}
return total;
}
async function runPaymentDetails(policy, now, db = prisma) {
const cutoff = monthsAgo(policy.months, now);
return {
notifications: await scrubJsonColumn('ProviderTransaction', 'raw', cutoff, db),
checkouts: await scrubJsonColumn('ProviderCheckout', 'request', cutoff, db),
};
}
async function runAuditLogs(policy, now, db = prisma) {
const cutoff = monthsAgo(policy.months, now);
const [audit, access, sessions] = await Promise.all([
db.adminAuditLog.deleteMany({ where: { createdAt: { lt: cutoff } } }),
db.dataAccessLog.deleteMany({ where: { createdAt: { lt: cutoff } } }),
db.impersonationSession.deleteMany({ where: { startedAt: { lt: cutoff } } }),
]);
return { audit: audit.count, access: access.count, viewAsSessions: sessions.count };
}
const RUNNERS = {
inactive_accounts: runInactiveAccounts,
form_answers: runFormAnswers,
login_history: runLoginHistory,
payment_details: runPaymentDetails,
audit_logs: runAuditLogs,
};
/** The nightly job: apply every switched-on policy. */
async function runRetention(now = new Date(), db = prisma) {
const { policies } = await getPolicies(db);
const result = {};
for (const [key, policy] of Object.entries(policies)) {
if (!policy.enabled) continue;
try {
result[key] = await RUNNERS[key](policy, now, db);
} catch (e) {
result[key] = { error: e?.message || String(e) };
console.warn(`[retention] ${key} failed:`, e?.message || e);
}
}
const value = JSON.stringify({ at: now.toISOString(), result });
await db.appSetting.upsert({ where: { key: LAST_RUN_KEY }, update: { value }, create: { key: LAST_RUN_KEY, value } });
const { isNoop } = require('../jobs');
if (!isNoop(result)) {
require('./adminAudit').logAdminAction({ actorId: null, actorRole: 'system', action: 'retention_run', targetType: 'retention', metadata: result });
}
return result;
}
async function lastRun(db = prisma) {
const row = await db.appSetting.findUnique({ where: { key: LAST_RUN_KEY } });
try { return row?.value ? JSON.parse(row.value) : null; } catch { return null; }
}
/** How much each policy would affect if the job ran now — for the admin page. */
async function preview(policies, now = new Date(), db = prisma) {
const out = {};
const p = policies;
const inactiveCutoff = monthsAgo(p.inactive_accounts.months, now);
const [toWarn, warnedDue, formAnswers, logins, audit] = await Promise.all([
inactiveAccounts(new Date(inactiveCutoff.getTime() + WARNING_DAYS * DAY), { warned: false, limit: 5000 }, db),
inactiveAccounts(inactiveCutoff, { warnedBefore: new Date(now.getTime() - WARNING_DAYS * DAY), limit: 5000 }, db),
db.formAnswer.count({ where: { response: { registration: { event: { endDate: { lt: monthsAgo(p.form_answers.months, now) } } } } } }),
db.securityEvent.count({ where: { createdAt: { lt: monthsAgo(p.login_history.months, now) } } }),
db.adminAuditLog.count({ where: { createdAt: { lt: monthsAgo(p.audit_logs.months, now) } } }),
]);
const payments = await db.$queryRawUnsafe(
`SELECT COUNT(*)::int AS n FROM "ProviderTransaction" WHERE "createdAt" < $1 AND "raw" IS NOT NULL AND jsonb_typeof("raw") = 'object' AND NOT ("raw" ? '_scrubbed')`,
monthsAgo(p.payment_details.months, now),
);
out.inactive_accounts = { toWarn: toWarn.length, toAnonymise: warnedDue.length };
out.form_answers = { count: formAnswers };
out.login_history = { count: logins };
out.payment_details = { count: payments[0]?.n || 0 };
out.audit_logs = { count: audit };
return out;
}
/** One line per policy for the privacy notice's {retention} placeholder. */
async function noticeLines(db = prisma) {
const { policies } = await getPolicies(db);
const { getSetting } = require('./settingsCache');
const [medical, backups] = await Promise.all([getSetting('consent_medical_retention_days', ''), getSetting('backup_retain_count', '')]);
const line = (key, on, off) => (policies[key].enabled ? on(describeMonths(policies[key].months)) : off);
return [
line('inactive_accounts', t => `• Accounts with no login, registration or payment for ${t} are deleted, after a warning 30 days before.`, '• Accounts are kept until you ask us to delete them.'),
line('form_answers', t => `• Answers to event forms are deleted ${t} after the event.`, '• Answers to event forms are kept until you ask us to delete them.'),
`• Medical and emergency-contact details from parental consent forms are deleted ${parseInt(medical, 10) || 30} days after the event. The record of who gave consent, when and to which wording is kept.`,
line('login_history', t => `• Login history (time, IP address, device) is kept for ${t}.`, '• Login history is kept until you ask us to delete it.'),
line('payment_details', t => `• Payer names and email addresses received with payments are removed after ${t}. Payment records themselves (amount, date, method) are kept as tax law requires.`, '• Payment records are kept as tax law requires.'),
line('audit_logs', t => `• Audit and access records (who did what in the system) are kept for ${t}.`, '• Audit and access records are kept for accountability.'),
'• Detailed visit statistics become anonymous daily totals after 90 days.',
`• Database backups are kept for about ${parseInt(backups, 10) || 14} days, so deleted information stays in them until they are replaced.`,
];
}
module.exports = {
POLICIES,
WARNING_DAYS,
getPolicies,
savePolicies,
inactiveAccounts,
runRetention,
lastRun,
preview,
noticeLines,
describeMonths,
monthsAgo,
};
@@ -0,0 +1,85 @@
jest.mock('../src/config/db', () => ({
appSetting: { findUnique: jest.fn(), upsert: jest.fn(), findMany: jest.fn().mockResolvedValue([]) },
$queryRawUnsafe: jest.fn(),
}));
const prisma = require('../src/config/db');
const retention = require('../src/utils/retention');
function saved(value) {
prisma.appSetting.findUnique.mockResolvedValue(value === undefined ? null : { value: JSON.stringify(value) });
}
beforeEach(() => jest.clearAllMocks());
describe('policies', () => {
test('defaults: inactive accounts after 5 years, on', async () => {
saved(undefined);
const { policies, reviewedAt } = await retention.getPolicies();
expect(policies.inactive_accounts).toEqual({ enabled: true, months: 60 });
expect(policies.form_answers).toEqual({ enabled: true, months: 12 });
expect(reviewedAt).toBeNull();
});
test('saved values override the defaults, one policy at a time', async () => {
saved({ policies: { form_answers: { enabled: false, months: 6 } }, reviewedAt: '2026-10-23T00:00:00.000Z' });
const { policies, reviewedAt } = await retention.getPolicies();
expect(policies.form_answers).toEqual({ enabled: false, months: 6 });
expect(policies.login_history).toEqual({ enabled: true, months: 24 });
expect(reviewedAt).toBe('2026-10-23T00:00:00.000Z');
});
test('saving refuses periods below the minimum or silly ones', async () => {
const ok = Object.fromEntries(Object.entries(retention.POLICIES).map(([k, d]) => [k, { ...d.defaults }]));
await expect(retention.savePolicies({ ...ok, inactive_accounts: { enabled: true, months: 6 } })).rejects.toThrow(/Inactive accounts: choose between 12 and 240/);
await expect(retention.savePolicies({ ...ok, form_answers: { enabled: true, months: 'x' } })).rejects.toThrow(/Attendee form answers/);
saved(undefined);
await retention.savePolicies(ok, { reviewedBy: 'Ada' });
const value = JSON.parse(prisma.appSetting.upsert.mock.calls[0][0].create.value);
expect(value.reviewedBy).toBe('Ada');
expect(value.policies.audit_logs).toEqual({ enabled: true, months: 60 });
});
});
describe('describing periods', () => {
test('whole years read as years', () => {
expect(retention.describeMonths(60)).toBe('5 years');
expect(retention.describeMonths(12)).toBe('1 year');
expect(retention.describeMonths(18)).toBe('18 months');
expect(retention.describeMonths(1)).toBe('1 month');
});
test('monthsAgo goes back calendar months', () => {
expect(retention.monthsAgo(24, new Date('2026-10-23T12:00:00Z')).toISOString()).toBe('2024-10-23T12:00:00.000Z');
});
test('the notice lines follow the policies, and say so when one is off', async () => {
saved({ policies: { inactive_accounts: { enabled: false, months: 60 }, form_answers: { enabled: true, months: 24 } } });
const lines = await retention.noticeLines();
expect(lines[0]).toBe('• Accounts are kept until you ask us to delete them.');
expect(lines[1]).toBe('• Answers to event forms are deleted 2 years after the event.');
expect(lines.every(l => l.startsWith('• '))).toBe(true);
});
});
describe('inactive accounts query', () => {
test('not-yet-warned: a warning older than the last activity no longer counts', async () => {
prisma.$queryRawUnsafe.mockResolvedValue([{ id: 'u1' }]);
const before = new Date('2021-10-23');
expect(await retention.inactiveAccounts(before, { warned: false, limit: 10 })).toEqual(['u1']);
const [sql, ...params] = prisma.$queryRawUnsafe.mock.calls[0];
expect(sql).toMatch(/warned_at IS NULL OR warned_at < last_active/);
expect(sql).toMatch(/u\."role" = 'user'/);
expect(params).toEqual([before]);
});
test('due for deletion: warned since the last activity, long enough ago', async () => {
prisma.$queryRawUnsafe.mockResolvedValue([]);
const before = new Date('2021-10-23');
const warnedBefore = new Date('2026-09-23');
await retention.inactiveAccounts(before, { warnedBefore });
const [sql, ...params] = prisma.$queryRawUnsafe.mock.calls[0];
expect(sql).toMatch(/warned_at >= last_active AND warned_at <= \$2/);
expect(params).toEqual([before, warnedBefore]);
});
});