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:
@@ -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),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -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 };
|
||||
@@ -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,
|
||||
};
|
||||
Reference in New Issue
Block a user