fix(andreknie.de): harden personal data lifecycle
This commit is contained in:
@@ -9,7 +9,6 @@ const DATA_DIR = join(__dirname, '..', 'data')
|
||||
const TOKENS_FILE = join(DATA_DIR, 'pending-tokens.json')
|
||||
const tokenMutex = new Mutex()
|
||||
|
||||
// Ensure data directory exists
|
||||
mkdirSync(DATA_DIR, { recursive: true })
|
||||
|
||||
function loadTokens() {
|
||||
@@ -22,13 +21,6 @@ function saveTokens(tokens) {
|
||||
writeFileSync(TOKENS_FILE, JSON.stringify(tokens, null, 2), 'utf-8')
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a confirmation token.
|
||||
* @param {string} type - 'contact' | 'talk-request' | 'newsletter'
|
||||
* @param {object} data - The form data to store
|
||||
* @param {number} expiresInHours - Token expiration (default: 48h)
|
||||
* @returns {string} The generated token
|
||||
*/
|
||||
export async function createToken(type, data, expiresInHours = 48) {
|
||||
const token = crypto.randomUUID()
|
||||
await tokenMutex.runExclusive(async () => {
|
||||
@@ -39,51 +31,64 @@ export async function createToken(type, data, expiresInHours = 48) {
|
||||
data,
|
||||
createdAt: new Date().toISOString(),
|
||||
expiresAt: new Date(Date.now() + expiresInHours * 60 * 60 * 1000).toISOString(),
|
||||
confirmed: false,
|
||||
status: 'pending',
|
||||
})
|
||||
saveTokens(tokens)
|
||||
})
|
||||
return token
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify and consume a token.
|
||||
* @returns {object|null} The stored data if valid, null if expired/invalid
|
||||
*/
|
||||
export async function verifyToken(token) {
|
||||
/** Reserve a valid token for exactly one confirmation flow. */
|
||||
export async function reserveToken(token) {
|
||||
return await tokenMutex.runExclusive(async () => {
|
||||
const tokens = loadTokens()
|
||||
const idx = tokens.findIndex(t => t.token === token && !t.confirmed)
|
||||
const idx = tokens.findIndex(t => t.token === token && (t.status || (t.confirmed ? 'completed' : 'pending')) === 'pending')
|
||||
if (idx === -1) return null
|
||||
|
||||
const entry = tokens[idx]
|
||||
if (new Date(entry.expiresAt) < new Date()) {
|
||||
// Expired — remove it
|
||||
if (new Date(entry.expiresAt) <= new Date()) {
|
||||
tokens.splice(idx, 1)
|
||||
saveTokens(tokens)
|
||||
return null
|
||||
}
|
||||
|
||||
// Mark as confirmed
|
||||
tokens[idx].confirmed = true
|
||||
tokens[idx].status = 'processing'
|
||||
saveTokens(tokens)
|
||||
return entry
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean up expired tokens (run periodically).
|
||||
*/
|
||||
/** Remove a successfully processed token and its personal payload. */
|
||||
export async function completeToken(token) {
|
||||
await tokenMutex.runExclusive(async () => {
|
||||
const tokens = loadTokens()
|
||||
const remaining = tokens.filter(t => t.token !== token)
|
||||
if (remaining.length !== tokens.length) saveTokens(remaining)
|
||||
})
|
||||
}
|
||||
|
||||
/** Return a failed confirmation to pending so it can be retried. */
|
||||
export async function releaseToken(token) {
|
||||
await tokenMutex.runExclusive(async () => {
|
||||
const tokens = loadTokens()
|
||||
const entry = tokens.find(t => t.token === token)
|
||||
if (!entry) return
|
||||
entry.status = 'pending'
|
||||
saveTokens(tokens)
|
||||
})
|
||||
}
|
||||
|
||||
// Compatibility for code that only needs the reservation behavior.
|
||||
export const verifyToken = reserveToken
|
||||
|
||||
export async function cleanupExpiredTokens() {
|
||||
await tokenMutex.runExclusive(async () => {
|
||||
const tokens = loadTokens()
|
||||
const now = new Date()
|
||||
const valid = tokens.filter(t => new Date(t.expiresAt) > now || t.confirmed)
|
||||
if (valid.length !== tokens.length) {
|
||||
saveTokens(valid)
|
||||
}
|
||||
const valid = tokens.filter(t => !t.confirmed && new Date(t.expiresAt) > now)
|
||||
if (valid.length !== tokens.length) saveTokens(valid)
|
||||
})
|
||||
}
|
||||
|
||||
// Run cleanup every hour
|
||||
setInterval(cleanupExpiredTokens, 60 * 60 * 1000)
|
||||
const cleanupTimer = setInterval(cleanupExpiredTokens, 60 * 60 * 1000)
|
||||
cleanupTimer.unref?.()
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
import { existsSync, readFileSync, unlinkSync } from 'fs'
|
||||
import { join } from 'path'
|
||||
import { createToken, reserveToken, completeToken, releaseToken, cleanupExpiredTokens } from './confirmationToken.js'
|
||||
|
||||
const tokensFile = join(process.cwd(), 'server', 'data', 'pending-tokens.json')
|
||||
|
||||
function removeTokensFile() {
|
||||
if (existsSync(tokensFile)) unlinkSync(tokensFile)
|
||||
}
|
||||
|
||||
beforeEach(removeTokensFile)
|
||||
afterEach(removeTokensFile)
|
||||
|
||||
describe('confirmation token lifecycle', () => {
|
||||
it('creates a pending token and reserves it once', async () => {
|
||||
const token = await createToken('contact', { name: 'Test', email: 'test@example.invalid' }, 1)
|
||||
const first = await reserveToken(token)
|
||||
const second = await reserveToken(token)
|
||||
|
||||
expect(first.status).toBe('processing')
|
||||
expect(second).toBeNull()
|
||||
expect(JSON.parse(readFileSync(tokensFile, 'utf8')).find(entry => entry.token === token).status).toBe('processing')
|
||||
})
|
||||
|
||||
it('removes an expired token instead of returning it', async () => {
|
||||
const token = await createToken('contact', { email: 'expired@example.invalid' }, -1)
|
||||
|
||||
expect(await reserveToken(token)).toBeNull()
|
||||
expect(JSON.parse(readFileSync(tokensFile, 'utf8'))).toEqual([])
|
||||
})
|
||||
|
||||
it('removes a successfully processed token and its payload', async () => {
|
||||
const token = await createToken('contact', { email: 'done@example.invalid' })
|
||||
await reserveToken(token)
|
||||
await completeToken(token)
|
||||
|
||||
expect(JSON.parse(readFileSync(tokensFile, 'utf8'))).toEqual([])
|
||||
})
|
||||
|
||||
it('releases a failed processing attempt for a controlled retry', async () => {
|
||||
const token = await createToken('contact', { email: 'retry@example.invalid' })
|
||||
await reserveToken(token)
|
||||
await releaseToken(token)
|
||||
|
||||
expect((await reserveToken(token)).status).toBe('processing')
|
||||
})
|
||||
|
||||
it('allows exactly one parallel reservation', async () => {
|
||||
const token = await createToken('contact', { email: 'parallel@example.invalid' })
|
||||
const results = await Promise.all([reserveToken(token), reserveToken(token)])
|
||||
|
||||
expect(results.filter(Boolean)).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('cleans expired pending and processing entries', async () => {
|
||||
const pending = await createToken('contact', { email: 'pending@example.invalid' }, -1)
|
||||
const processing = await createToken('contact', { email: 'processing@example.invalid' }, -1)
|
||||
await reserveToken(processing)
|
||||
await cleanupExpiredTokens()
|
||||
|
||||
expect(pending).toBeTruthy()
|
||||
expect(JSON.parse(readFileSync(tokensFile, 'utf8'))).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -9,6 +9,18 @@ const BASE_URL = process.env.BASE_URL || 'https://andreknie.de'
|
||||
|
||||
let transporter = null
|
||||
|
||||
export class MailerNotReadyError extends Error {
|
||||
constructor() {
|
||||
super('Mailer ist nicht konfiguriert.')
|
||||
this.name = 'MailerNotReadyError'
|
||||
this.code = 'MAILER_NOT_READY'
|
||||
}
|
||||
}
|
||||
|
||||
export function isMailerReady() {
|
||||
return Boolean(SMTP_HOST && SMTP_USER && SMTP_PASS)
|
||||
}
|
||||
|
||||
function getTransporter() {
|
||||
if (!transporter && SMTP_HOST && SMTP_USER && SMTP_PASS) {
|
||||
transporter = nodemailer.createTransport({
|
||||
@@ -23,10 +35,7 @@ function getTransporter() {
|
||||
|
||||
export async function sendConfirmationEmail(to, type, token) {
|
||||
const t = getTransporter()
|
||||
if (!t) {
|
||||
console.log(`[Mailer] SMTP not configured. Would send ${type} confirmation to ${to}`)
|
||||
return
|
||||
}
|
||||
if (!t) throw new MailerNotReadyError()
|
||||
|
||||
const confirmUrl = `${BASE_URL}/api/${type}/confirm/${token}`
|
||||
const subjects = {
|
||||
@@ -45,10 +54,7 @@ export async function sendConfirmationEmail(to, type, token) {
|
||||
|
||||
export async function sendStakeholderNotification(type, data) {
|
||||
const t = getTransporter()
|
||||
if (!t) {
|
||||
console.log(`[Mailer] SMTP not configured. Would notify stakeholder about ${type}`)
|
||||
return
|
||||
}
|
||||
if (!t) throw new MailerNotReadyError()
|
||||
|
||||
const subjects = {
|
||||
contact: `Neue Kontaktanfrage von ${data.name}`,
|
||||
@@ -80,11 +86,7 @@ export async function sendSpeakerCv(to, lead, pdfPath) {
|
||||
const t = getTransporter()
|
||||
const pdfMissing = !pdfPath || !existsSync(pdfPath)
|
||||
|
||||
if (!t) {
|
||||
console.log(`[Mailer] SMTP not configured. Would send speaker CV to ${to} (pdfMissing=${pdfMissing})`)
|
||||
await notifyStakeholderSpeakerCv(lead, pdfMissing)
|
||||
return { sent: false, pdfMissing }
|
||||
}
|
||||
if (!t) throw new MailerNotReadyError()
|
||||
|
||||
if (!pdfMissing) {
|
||||
await t.sendMail({
|
||||
@@ -112,10 +114,7 @@ async function notifyStakeholderSpeakerCv(lead, pdfMissing) {
|
||||
: 'CV wurde automatisch an den Anfragenden gesendet.',
|
||||
].join('\n')
|
||||
|
||||
if (!t) {
|
||||
console.log(`[Mailer] SMTP not configured. Would notify stakeholder about speaker-cv lead:\n${body}`)
|
||||
return
|
||||
}
|
||||
if (!t) throw new MailerNotReadyError()
|
||||
|
||||
await t.sendMail({
|
||||
from: SMTP_USER,
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { isMailerReady, MailerNotReadyError, sendConfirmationEmail } from './mailer.js'
|
||||
|
||||
describe('mailer readiness', () => {
|
||||
it('reports missing SMTP configuration without exposing credentials', async () => {
|
||||
expect(isMailerReady()).toBe(false)
|
||||
await expect(sendConfirmationEmail('test@example.invalid', 'contact', 'synthetic-token'))
|
||||
.rejects.toBeInstanceOf(MailerNotReadyError)
|
||||
await expect(sendConfirmationEmail('test@example.invalid', 'contact', 'synthetic-token'))
|
||||
.rejects.toMatchObject({ code: 'MAILER_NOT_READY' })
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user