/** * 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, }, kids_profiles: { label: 'Children at kids check-in', description: 'A child\'s profile (name, date of birth, allergies, medical and custody notes) is deleted when they haven\'t been checked in for this long, then families left without children. Who collected a child is cleared from check-ins this old; the attendance itself stays.', defaults: { enabled: true, months: 6 }, minMonths: 1, }, 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' -- 3.0.0: people who sign in through the church's Accounts are kept or removed there -- (EVENTS-3.0-PLAN §7); Events still cleans up guests and anyone not linked. AND u."accountId" IS NULL ) 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 }; } async function runKidsProfiles(policy, now, db = prisma) { return require('./kids').runKidsRetention(monthsAgo(policy.months, now), db); } const RUNNERS = { kids_profiles: runKidsProfiles, 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, kidsProfiles] = 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) } } }), require('./kids').previewKidsRetention(monthsAgo(p.kids_profiles.months, now), db), ]); 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 }; out.kids_profiles = kidsProfiles; 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('kids_profiles', t => `• Children's details for kids check-in (including allergies, medical and custody notes) are deleted when a child hasn't been checked in for ${t}.`, '• Children\'s details for kids check-in are kept until a parent removes them.'), 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, };