Files

95 lines
2.9 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 = process.env.CONFIRMATION_TOKEN_FILE || join(DATA_DIR, 'pending-tokens.json')
const tokenMutex = new Mutex()
mkdirSync(dirname(TOKENS_FILE), { 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')
}
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(),
status: 'pending',
})
saveTokens(tokens)
})
return 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.status || (t.confirmed ? 'completed' : 'pending')) === 'pending')
if (idx === -1) return null
const entry = tokens[idx]
if (new Date(entry.expiresAt) <= new Date()) {
tokens.splice(idx, 1)
saveTokens(tokens)
return null
}
tokens[idx].status = 'processing'
saveTokens(tokens)
return entry
})
}
/** 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 => !t.confirmed && new Date(t.expiresAt) > now)
if (valid.length !== tokens.length) saveTokens(valid)
})
}
const cleanupTimer = setInterval(cleanupExpiredTokens, 60 * 60 * 1000)
cleanupTimer.unref?.()