feat(privat/CV): sync to latest upstream (cv-upstream/main, 30f9608b)
This commit is contained in:
@@ -0,0 +1,81 @@
|
||||
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)
|
||||
Reference in New Issue
Block a user