// Local development server: the static site plus the Pages Functions, on Node's built-in SQLite // instead of D1 (tools/d1-local.mjs). It sends the same Content-Security-Policy as _headers, so a // page that would break the CSP in production breaks here too. // // npm run dev http://localhost:8788, database in .dev/jobley.sqlite // PORT=9000 DB_FILE=:memory: DEV_SESSION_TOKEN=… node --experimental-sqlite tools/dev-server.mjs // // People sign in with passkeys. So the app tests and local work can reach the admin API without one, // the dev server (never production) starts with a curator session for DEV_SESSION_TOKEN, printed at // start. PASSKEY_RP_ID and PASSKEY_ORIGIN point passkeys at a local host. Turnstile is off locally // (ALLOW_NO_TURNSTILE=1) unless TURNSTILE_SECRET and TURNSTILE_SITE_KEY are set. import { createServer } from 'node:http'; import { existsSync, mkdirSync, readFileSync, statSync } from 'node:fs'; import { dirname, extname, join, normalize } from 'node:path'; import { fileURLToPath } from 'node:url'; import { migrate, openD1 } from './d1-local.mjs'; import { handle } from '../src/api.js'; import { sha256 } from '../src/util.js'; import { onRequest as middleware, isRetiredNativeRoute } from '../functions/_middleware.js'; const root = join(dirname(fileURLToPath(import.meta.url)), '..'); const port = Number(process.env.PORT || 8788); const dbFile = process.env.DB_FILE || join(root, '.dev', 'jobley.sqlite'); if (dbFile !== ':memory:') mkdirSync(dirname(dbFile), { recursive: true }); const TYPES = { '.html': 'text/html; charset=utf-8', '.css': 'text/css; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.json': 'application/json', '.svg': 'image/svg+xml', '.png': 'image/png', '.webp': 'image/webp', '.gif': 'image/gif', '.woff2': 'font/woff2', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml; charset=utf-8' }; const HIDDEN = /^\/(tools|functions|src|migrations|test|node_modules|\.|package|wrangler|README)/; const csp = (readFileSync(join(root, '_headers'), 'utf8').match(/Content-Security-Policy: (.+)/) || [])[1]; const redirects = readFileSync(join(root, '_redirects'), 'utf8').split('\n') .filter(line => line.trim() && !line.startsWith('#')) .map(line => { const [source, target, status] = line.trim().split(/\s+/); const pattern = new RegExp('^' + source.replaceAll('.', '\\.').replaceAll('*', '.*') + '$'); return { pattern, target, status: Number(status) }; }); function asset(pathname) { let p = normalize(decodeURIComponent(pathname)); if (HIDDEN.test(p)) return null; const tries = p.endsWith('/') ? [p + 'index.html'] : extname(p) ? [p] : [p + '.html', p + '/index.html']; for (const t of tries) { const file = join(root, t); if (file.startsWith(root) && existsSync(file) && statSync(file).isFile()) return file; } return null; } function staticResponse(pathname) { const file = asset(pathname); const headers = { 'referrer-policy': 'strict-origin-when-cross-origin', 'x-content-type-options': 'nosniff', ...(csp ? { 'content-security-policy': csp } : {}) }; if (!file) return new Response(readFileSync(join(root, '404.html')), { status: 404, headers: { ...headers, 'content-type': TYPES['.html'] } }); return new Response(readFileSync(file), { headers: { ...headers, 'content-type': TYPES[extname(file)] || 'application/octet-stream' } }); } const env = { DB: migrate(openD1(dbFile), join(root, 'migrations')), PASSKEY_RP_ID: process.env.PASSKEY_RP_ID, PASSKEY_ORIGIN: process.env.PASSKEY_ORIGIN, TURNSTILE_SECRET: process.env.TURNSTILE_SECRET, TURNSTILE_SITE_KEY: process.env.TURNSTILE_SITE_KEY, ALLOW_NO_TURNSTILE: process.env.TURNSTILE_SECRET ? undefined : '1', ASSETS: { fetch: async (request) => staticResponse(new URL(request.url).pathname) }, }; const devSessionToken = process.env.DEV_SESSION_TOKEN || 'dev-admin-token-not-for-production-0000'; await env.DB.prepare(`INSERT OR REPLACE INTO sessions (token_hash, role, user_id, created_at, expires_at) VALUES (?, 'curator', 'curator', ?, '9999-12-31T00:00:00.000Z')`) .bind(await sha256(devSessionToken), new Date().toISOString()).run(); async function route(request) { const url = new URL(request.url); const path = url.pathname; if (path.startsWith('/api/')) return handle(request, env); const redirect = redirects.find(({ pattern }) => pattern.test(path)); if (redirect) return Response.redirect(new URL(redirect.target, url), redirect.status); if (path === '/analytics-consent.gif' || path === '/.well-known/apple-app-site-association' || path === '/passkey' || path === '/passkey/' || isRetiredNativeRoute(path)) return middleware({ request, env, next: async () => staticResponse(path) }); if (!path.endsWith('/') && !extname(path) && existsSync(join(root, path, 'index.html'))) return Response.redirect(new URL(path + '/' + url.search, url), 308); return staticResponse(path); } createServer(async (req, res) => { try { const chunks = []; for await (const c of req) chunks.push(c); const headers = new Headers(); for (const [k, v] of Object.entries(req.headers)) if (typeof v === 'string') headers.set(k, v); if (!headers.has('cf-connecting-ip')) headers.set('cf-connecting-ip', req.socket.remoteAddress || '127.0.0.1'); const request = new Request(`http://${req.headers.host}${req.url}`, { method: req.method, headers, body: chunks.length && !['GET', 'HEAD'].includes(req.method) ? Buffer.concat(chunks) : undefined }); const response = await route(request); res.writeHead(response.status, Object.fromEntries(response.headers)); res.end(Buffer.from(await response.arrayBuffer())); } catch (err) { console.error(err); res.writeHead(500).end('dev server error'); } }).listen(port, () => console.log(`http://localhost:${port} (db ${dbFile}, dev curator session ${devSessionToken})`));