// Small helpers shared by the API handlers: JSON responses, ids, hashing, validation, // Turnstile and the per-IP rate limit. No dependencies; runs on Workers and on Node 22. import { APP, LIMITS } from './config.js'; export const now = () => new Date().toISOString(); export function json(body, status = 200, headers = {}) { return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff', ...headers }, }); } export const fail = (status, error, message, extra = {}) => json({ ok: false, error, message, ...extra }, status); const ALPHABET = 'abcdefghjkmnpqrstuvwxyz23456789'; // no look-alikes export function randomId(prefix, length = 10) { const bytes = crypto.getRandomValues(new Uint8Array(length)); let out = ''; for (const b of bytes) out += ALPHABET[b % ALPHABET.length]; return `${prefix}_${out}`; } export function randomToken(kind) { const bytes = crypto.getRandomValues(new Uint8Array(32)); return `${APP.prefix}_${kind}_` + [...bytes].map((b) => b.toString(16).padStart(2, '0')).join(''); } export async function sha256(text) { const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text)); return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join(''); } // Compares two secrets without leaking where they differ: both are hashed first. export async function sameSecret(a, b) { const [x, y] = await Promise.all([sha256(String(a)), sha256(String(b))]); let diff = 0; for (let i = 0; i < x.length; i++) diff |= x.charCodeAt(i) ^ y.charCodeAt(i); return diff === 0; } export async function readJson(request) { const type = request.headers.get('content-type') || ''; if (!type.toLowerCase().includes('application/json')) return { error: fail(415, 'unsupported_media_type', 'Send JSON with Content-Type: application/json.') }; const text = await request.text(); if (new TextEncoder().encode(text).length > LIMITS.bodyBytes) return { error: fail(413, 'too_large', 'That is more than we can accept in one request.') }; try { const body = JSON.parse(text); if (!body || typeof body !== 'object' || Array.isArray(body)) throw new Error('not an object'); return { body }; } catch { return { error: fail(400, 'bad_json', 'The request body is not valid JSON.') }; } } // ---- Validation. Each check returns the cleaned value and records a message under the field name. export class Checker { constructor(body) { this.body = body; this.fields = {}; } bad(name, message) { if (!this.fields[name]) this.fields[name] = message; return undefined; } get ok() { return Object.keys(this.fields).length === 0; } text(name, { min = 0, max, required = false, label = name, multiline = false } = {}) { let v = this.body[name]; if (v === undefined || v === null) v = ''; if (typeof v !== 'string') return this.bad(name, `${label} must be text.`); // Drop control characters; keep new lines only where they make sense. v = v.replace(/\r\n?/g, '\n').replace(multiline ? /[\u0000-\u0008\u000B-\u001F\u007F]/g : /[\u0000-\u001F\u007F]/g, multiline ? '' : ' ').trim(); if (!multiline) v = v.replace(/\s+/g, ' '); if (!v) return required ? this.bad(name, `${label} is required.`) : null; if (v.length < min) return this.bad(name, `${label} needs at least ${min} characters.`); if (v.length > max) return this.bad(name, `${label} can be at most ${max} characters.`); return v; } email(name, { required = true, label = 'Email' } = {}) { const v = this.text(name, { max: 254, required, label }); if (!v) return v; if (!/^[^\s@<>"',;]+@[^\s@<>"',;]+\.[^\s@<>"',;.]{2,}$/.test(v)) return this.bad(name, `${label} does not look like an email address.`); return v; } url(name, { required = false, max = 500, label = name } = {}) { const v = this.text(name, { max, required, label }); if (!v) return v; const clean = cleanUrl(v); if (!clean) return this.bad(name, `${label} must be a full https:// link.`); return clean; } links(name, { maxItems = 5, label = 'Links' } = {}) { let v = this.body[name]; if (v === undefined || v === null || v === '') return []; if (typeof v === 'string') v = v.split(/[\s,]+/).filter(Boolean); if (!Array.isArray(v)) return this.bad(name, `${label} must be a list of links.`); if (v.length > maxItems) return this.bad(name, `${label}: at most ${maxItems}.`); const out = []; for (const item of v) { const clean = typeof item === 'string' && item.length <= 300 ? cleanUrl(item.trim()) : null; if (!clean) return this.bad(name, `${label}: each one must be a full https:// link.`); out.push(clean); } return out; } choice(name, allowed, { required = true, label = name } = {}) { const v = this.body[name]; if (v === undefined || v === null || v === '') return required ? this.bad(name, `${label} is required.`) : null; if (typeof v !== 'string' || !Object.prototype.hasOwnProperty.call(allowed, v)) return this.bad(name, `${label} is not one of the choices.`); return v; } int(name, { min, max, required = true, label = name } = {}) { let v = this.body[name]; if (v === undefined || v === null || v === '') return required ? this.bad(name, `${label} is required.`) : null; if (typeof v === 'string' && /^\d{1,9}$/.test(v.trim())) v = Number(v.trim()); if (typeof v !== 'number' || !Number.isInteger(v)) return this.bad(name, `${label} must be a whole number.`); if (v < min || v > max) return this.bad(name, `${label} must be between ${min} and ${max}.`); return v; } yes(name, message) { if (this.body[name] !== true) return this.bad(name, message); return true; } } export function cleanUrl(value) { try { const u = new URL(value); if (u.protocol !== 'https:' || !u.hostname.includes('.') || u.username || u.password) return null; return u.toString(); } catch { return null; } } export function clientIp(request) { return request.headers.get('cf-connecting-ip') || (request.headers.get('x-forwarded-for') || '').split(',')[0].trim() || '0.0.0.0'; } export async function ipHash(request, env) { const salt = env.IP_SALT || env.ADMIN_TOKEN || 'dev-salt'; return (await sha256(`${salt}|${clientIp(request)}`)).slice(0, 32); } // Fixed one-hour window per IP hash and form. Returns true when the request is allowed. export async function allow(env, hash, bucket, limit, at = Date.now()) { const windowStart = Math.floor(at / 3600000) * 3600000; const row = await env.DB.prepare( `INSERT INTO rate_limits (key, count, window_start) VALUES (?1, 1, ?2) ON CONFLICT(key) DO UPDATE SET count = CASE WHEN window_start < ?2 THEN 1 ELSE count + 1 END, window_start = ?2 RETURNING count`, ).bind(`${bucket}:${hash}`, windowStart).first(); return (row?.count ?? 1) <= limit; } // Cloudflare Turnstile. With no secret the API refuses public writes, unless ALLOW_NO_TURNSTILE=1 // (local development and tests only). export async function turnstile(request, env, token) { if (!env.TURNSTILE_SECRET) return env.ALLOW_NO_TURNSTILE === '1' ? { ok: true } : { ok: false, error: fail(503, 'not_configured', 'The form is not ready yet. Please try again later.') }; if (typeof token !== 'string' || !token || token.length > 2048) return { ok: false, error: fail(400, 'challenge_required', 'Please complete the check and try again.') }; const form = new URLSearchParams({ secret: env.TURNSTILE_SECRET, response: token, remoteip: clientIp(request) }); try { const res = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', { method: 'POST', body: form }); const data = await res.json(); if (data && data.success === true) return { ok: true }; } catch { /* falls through */ } return { ok: false, error: fail(400, 'challenge_failed', 'The check did not pass. Please reload the page and try again.') }; } export function slug(text) { return String(text).toLowerCase().normalize('NFKD').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 60); } export function escapeHtml(s) { return String(s ?? '').replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"').replace(/'/g, '''); }