82 lines
2.2 KiB
JavaScript
82 lines
2.2 KiB
JavaScript
import crypto from 'crypto'
|
|
import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'fs'
|
|
import { join, dirname } from 'path'
|
|
import { fileURLToPath } from 'url'
|
|
|
|
const __dirname = dirname(fileURLToPath(import.meta.url))
|
|
const DATA_DIR = join(__dirname, '..', 'data')
|
|
const TOKENS_FILE = join(DATA_DIR, 'pending-tokens.json')
|
|
|
|
// 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 function createToken(type, data, expiresInHours = 48) {
|
|
const token = crypto.randomUUID()
|
|
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 function verifyToken(token) {
|
|
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 function cleanupExpiredTokens() {
|
|
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)
|