Jobley / website / src / util.js
| 1 | // Small helpers shared by the API handlers: JSON responses, ids, hashing, validation, |
| 2 | // Turnstile and the per-IP rate limit. No dependencies; runs on Workers and on Node 22. |
| 3 | import { APP, LIMITS } from './config.js'; |
| 4 | |
| 5 | export const now = () => new Date().toISOString(); |
| 6 | |
| 7 | export function json(body, status = 200, headers = {}) { |
| 8 | return new Response(JSON.stringify(body), { |
| 9 | status, |
| 10 | headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff', ...headers }, |
| 11 | }); |
| 12 | } |
| 13 | export const fail = (status, error, message, extra = {}) => json({ ok: false, error, message, ...extra }, status); |
| 14 | |
| 15 | const ALPHABET = 'abcdefghjkmnpqrstuvwxyz23456789'; // no look-alikes |
| 16 | export function randomId(prefix, length = 10) { |
| 17 | const bytes = crypto.getRandomValues(new Uint8Array(length)); |
| 18 | let out = ''; |
| 19 | for (const b of bytes) out += ALPHABET[b % ALPHABET.length]; |
| 20 | return `${prefix}_${out}`; |
| 21 | } |
| 22 | export function randomToken(kind) { |
| 23 | const bytes = crypto.getRandomValues(new Uint8Array(32)); |
| 24 | return `${APP.prefix}_${kind}_` + [...bytes].map((b) => b.toString(16).padStart(2, '0')).join(''); |
| 25 | } |
| 26 | export async function sha256(text) { |
| 27 | const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text)); |
| 28 | return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join(''); |
| 29 | } |
| 30 | // Compares two secrets without leaking where they differ: both are hashed first. |
| 31 | export async function sameSecret(a, b) { |
| 32 | const [x, y] = await Promise.all([sha256(String(a)), sha256(String(b))]); |
| 33 | let diff = 0; |
| 34 | for (let i = 0; i < x.length; i++) diff |= x.charCodeAt(i) ^ y.charCodeAt(i); |
| 35 | return diff === 0; |
| 36 | } |
| 37 | |
| 38 | export async function readJson(request) { |
| 39 | const type = request.headers.get('content-type') || ''; |
| 40 | if (!type.toLowerCase().includes('application/json')) return { error: fail(415, 'unsupported_media_type', 'Send JSON with Content-Type: application/json.') }; |
| 41 | const text = await request.text(); |
| 42 | if (new TextEncoder().encode(text).length > LIMITS.bodyBytes) return { error: fail(413, 'too_large', 'That is more than we can accept in one request.') }; |
| 43 | try { |
| 44 | const body = JSON.parse(text); |
| 45 | if (!body || typeof body !== 'object' || Array.isArray(body)) throw new Error('not an object'); |
| 46 | return { body }; |
| 47 | } catch { |
| 48 | return { error: fail(400, 'bad_json', 'The request body is not valid JSON.') }; |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | // ---- Validation. Each check returns the cleaned value and records a message under the field name. |
| 53 | export class Checker { |
| 54 | constructor(body) { this.body = body; this.fields = {}; } |
| 55 | bad(name, message) { if (!this.fields[name]) this.fields[name] = message; return undefined; } |
| 56 | get ok() { return Object.keys(this.fields).length === 0; } |
| 57 | text(name, { min = 0, max, required = false, label = name, multiline = false } = {}) { |
| 58 | let v = this.body[name]; |
| 59 | if (v === undefined || v === null) v = ''; |
| 60 | if (typeof v !== 'string') return this.bad(name, `${label} must be text.`); |
| 61 | // Drop control characters; keep new lines only where they make sense. |
| 62 | v = v.replace(/\r\n?/g, '\n').replace(multiline ? /[\u0000-\u0008\u000B-\u001F\u007F]/g : /[\u0000-\u001F\u007F]/g, multiline ? '' : ' ').trim(); |
| 63 | if (!multiline) v = v.replace(/\s+/g, ' '); |
| 64 | if (!v) return required ? this.bad(name, `${label} is required.`) : null; |
| 65 | if (v.length < min) return this.bad(name, `${label} needs at least ${min} characters.`); |
| 66 | if (v.length > max) return this.bad(name, `${label} can be at most ${max} characters.`); |
| 67 | return v; |
| 68 | } |
| 69 | email(name, { required = true, label = 'Email' } = {}) { |
| 70 | const v = this.text(name, { max: 254, required, label }); |
| 71 | if (!v) return v; |
| 72 | if (!/^[^\s@<>"',;]+@[^\s@<>"',;]+\.[^\s@<>"',;.]{2,}$/.test(v)) return this.bad(name, `${label} does not look like an email address.`); |
| 73 | return v; |
| 74 | } |
| 75 | url(name, { required = false, max = 500, label = name } = {}) { |
| 76 | const v = this.text(name, { max, required, label }); |
| 77 | if (!v) return v; |
| 78 | const clean = cleanUrl(v); |
| 79 | if (!clean) return this.bad(name, `${label} must be a full https:// link.`); |
| 80 | return clean; |
| 81 | } |
| 82 | links(name, { maxItems = 5, label = 'Links' } = {}) { |
| 83 | let v = this.body[name]; |
| 84 | if (v === undefined || v === null || v === '') return []; |
| 85 | if (typeof v === 'string') v = v.split(/[\s,]+/).filter(Boolean); |
| 86 | if (!Array.isArray(v)) return this.bad(name, `${label} must be a list of links.`); |
| 87 | if (v.length > maxItems) return this.bad(name, `${label}: at most ${maxItems}.`); |
| 88 | const out = []; |
| 89 | for (const item of v) { |
| 90 | const clean = typeof item === 'string' && item.length <= 300 ? cleanUrl(item.trim()) : null; |
| 91 | if (!clean) return this.bad(name, `${label}: each one must be a full https:// link.`); |
| 92 | out.push(clean); |
| 93 | } |
| 94 | return out; |
| 95 | } |
| 96 | choice(name, allowed, { required = true, label = name } = {}) { |
| 97 | const v = this.body[name]; |
| 98 | if (v === undefined || v === null || v === '') return required ? this.bad(name, `${label} is required.`) : null; |
| 99 | if (typeof v !== 'string' || !Object.prototype.hasOwnProperty.call(allowed, v)) return this.bad(name, `${label} is not one of the choices.`); |
| 100 | return v; |
| 101 | } |
| 102 | int(name, { min, max, required = true, label = name } = {}) { |
| 103 | let v = this.body[name]; |
| 104 | if (v === undefined || v === null || v === '') return required ? this.bad(name, `${label} is required.`) : null; |
| 105 | if (typeof v === 'string' && /^\d{1,9}$/.test(v.trim())) v = Number(v.trim()); |
| 106 | if (typeof v !== 'number' || !Number.isInteger(v)) return this.bad(name, `${label} must be a whole number.`); |
| 107 | if (v < min || v > max) return this.bad(name, `${label} must be between ${min} and ${max}.`); |
| 108 | return v; |
| 109 | } |
| 110 | yes(name, message) { |
| 111 | if (this.body[name] !== true) return this.bad(name, message); |
| 112 | return true; |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | export function cleanUrl(value) { |
| 117 | try { |
| 118 | const u = new URL(value); |
| 119 | if (u.protocol !== 'https:' || !u.hostname.includes('.') || u.username || u.password) return null; |
| 120 | return u.toString(); |
| 121 | } catch { |
| 122 | return null; |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | export function clientIp(request) { |
| 127 | return request.headers.get('cf-connecting-ip') || (request.headers.get('x-forwarded-for') || '').split(',')[0].trim() || '0.0.0.0'; |
| 128 | } |
| 129 | export async function ipHash(request, env) { |
| 130 | const salt = env.IP_SALT || env.ADMIN_TOKEN || 'dev-salt'; |
| 131 | return (await sha256(`${salt}|${clientIp(request)}`)).slice(0, 32); |
| 132 | } |
| 133 | |
| 134 | // Fixed one-hour window per IP hash and form. Returns true when the request is allowed. |
| 135 | export async function allow(env, hash, bucket, limit, at = Date.now()) { |
| 136 | const windowStart = Math.floor(at / 3600000) * 3600000; |
| 137 | const row = await env.DB.prepare( |
| 138 | `INSERT INTO rate_limits (key, count, window_start) VALUES (?1, 1, ?2) |
| 139 | ON CONFLICT(key) DO UPDATE SET |
| 140 | count = CASE WHEN window_start < ?2 THEN 1 ELSE count + 1 END, |
| 141 | window_start = ?2 |
| 142 | RETURNING count`, |
| 143 | ).bind(`${bucket}:${hash}`, windowStart).first(); |
| 144 | return (row?.count ?? 1) <= limit; |
| 145 | } |
| 146 | |
| 147 | // Cloudflare Turnstile. With no secret the API refuses public writes, unless ALLOW_NO_TURNSTILE=1 |
| 148 | // (local development and tests only). |
| 149 | export async function turnstile(request, env, token) { |
| 150 | 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.') }; |
| 151 | if (typeof token !== 'string' || !token || token.length > 2048) return { ok: false, error: fail(400, 'challenge_required', 'Please complete the check and try again.') }; |
| 152 | const form = new URLSearchParams({ secret: env.TURNSTILE_SECRET, response: token, remoteip: clientIp(request) }); |
| 153 | try { |
| 154 | const res = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', { method: 'POST', body: form }); |
| 155 | const data = await res.json(); |
| 156 | if (data && data.success === true) return { ok: true }; |
| 157 | } catch { /* falls through */ } |
| 158 | return { ok: false, error: fail(400, 'challenge_failed', 'The check did not pass. Please reload the page and try again.') }; |
| 159 | } |
| 160 | |
| 161 | export function slug(text) { |
| 162 | return String(text).toLowerCase().normalize('NFKD').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 60); |
| 163 | } |
| 164 | export function escapeHtml(s) { |
| 165 | return String(s ?? '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, '''); |
| 166 | } |