Files
Orchestrator/privat/CV/andreknie.de/server/services/confirmationToken.js
T
ankn b46de6dc7d
Deploy CV Site (andreknie.de) / deploy (push) Canceled after 0s
ci: migrate GitHub actions to Gitea actions
2026-07-22 15:42:06 +02:00

90 lines
2.5 KiB
JavaScript

import crypto from 'crypto'
import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'fs'
import { join, dirname } from 'path'
import { fileURLToPath } from 'url'
import { Mutex } from 'async-mutex'
const __dirname = dirname(fileURLToPath(import.meta.url))
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() {
if (!existsSync(TOKENS_FILE)) return []
try { return JSON.parse(readFileSync(TOKENS_FILE, 'utf-8')) }
catch { return [] }
}
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 () => {
const tokens = loadTokens()
tokens.push({
token,
type,
data,
createdAt: new Date().toISOString(),
expiresAt: new Date(Date.now() + expiresInHours * 60 * 60 * 1000).toISOString(),
confirmed: false,
})
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) {
return await tokenMutex.runExclusive(async () => {
const tokens = loadTokens()
const idx = tokens.findIndex(t => t.token === token && !t.confirmed)
if (idx === -1) return null
const entry = tokens[idx]
if (new Date(entry.expiresAt) < new Date()) {
// Expired — remove it
tokens.splice(idx, 1)
saveTokens(tokens)
return null
}
// Mark as confirmed
tokens[idx].confirmed = true
saveTokens(tokens)
return entry
})
}
/**
* Clean up expired tokens (run periodically).
*/
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)
}
})
}
// Run cleanup every hour
setInterval(cleanupExpiredTokens, 60 * 60 * 1000)