Branchwell

Jobley / website / tools / dev-server.mjs

1// Local development server: the static site plus the Pages Functions, on Node's built-in SQLite
2// instead of D1 (tools/d1-local.mjs). It sends the same Content-Security-Policy as _headers, so a
3// page that would break the CSP in production breaks here too.
4//
5// npm run dev http://localhost:8788, database in .dev/jobley.sqlite
6// PORT=9000 DB_FILE=:memory: DEV_SESSION_TOKEN=… node --experimental-sqlite tools/dev-server.mjs
7//
8// People sign in with passkeys. So the app tests and local work can reach the admin API without one,
9// the dev server (never production) starts with a curator session for DEV_SESSION_TOKEN, printed at
10// start. PASSKEY_RP_ID and PASSKEY_ORIGIN point passkeys at a local host. Turnstile is off locally
11// (ALLOW_NO_TURNSTILE=1) unless TURNSTILE_SECRET and TURNSTILE_SITE_KEY are set.
12import { createServer } from 'node:http';
13import { existsSync, mkdirSync, readFileSync, statSync } from 'node:fs';
14import { dirname, extname, join, normalize } from 'node:path';
15import { fileURLToPath } from 'node:url';
16import { migrate, openD1 } from './d1-local.mjs';
17import { handle } from '../src/api.js';
18import { sha256 } from '../src/util.js';
19import { onRequest as middleware, isRetiredNativeRoute } from '../functions/_middleware.js';
20
21const root = join(dirname(fileURLToPath(import.meta.url)), '..');
22const port = Number(process.env.PORT || 8788);
23const dbFile = process.env.DB_FILE || join(root, '.dev', 'jobley.sqlite');
24if (dbFile !== ':memory:') mkdirSync(dirname(dbFile), { recursive: true });
25
26const 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' };
27const HIDDEN = /^\/(tools|functions|src|migrations|test|node_modules|\.|package|wrangler|README)/;
28const csp = (readFileSync(join(root, '_headers'), 'utf8').match(/Content-Security-Policy: (.+)/) || [])[1];
29
30const redirects = readFileSync(join(root, '_redirects'), 'utf8').split('\n')
31 .filter(line => line.trim() && !line.startsWith('#'))
32 .map(line => {
33 const [source, target, status] = line.trim().split(/\s+/);
34 const pattern = new RegExp('^' + source.replaceAll('.', '\\.').replaceAll('*', '.*') + '$');
35 return { pattern, target, status: Number(status) };
36 });
37
38function asset(pathname) {
39 let p = normalize(decodeURIComponent(pathname));
40 if (HIDDEN.test(p)) return null;
41 const tries = p.endsWith('/') ? [p + 'index.html'] : extname(p) ? [p] : [p + '.html', p + '/index.html'];
42 for (const t of tries) {
43 const file = join(root, t);
44 if (file.startsWith(root) && existsSync(file) && statSync(file).isFile()) return file;
45 }
46 return null;
47}
48function staticResponse(pathname) {
49 const file = asset(pathname);
50 const headers = { 'referrer-policy': 'strict-origin-when-cross-origin', 'x-content-type-options': 'nosniff', ...(csp ? { 'content-security-policy': csp } : {}) };
51 if (!file) return new Response(readFileSync(join(root, '404.html')), { status: 404, headers: { ...headers, 'content-type': TYPES['.html'] } });
52 return new Response(readFileSync(file), { headers: { ...headers, 'content-type': TYPES[extname(file)] || 'application/octet-stream' } });
53}
54
55const env = {
56 DB: migrate(openD1(dbFile), join(root, 'migrations')),
57 PASSKEY_RP_ID: process.env.PASSKEY_RP_ID,
58 PASSKEY_ORIGIN: process.env.PASSKEY_ORIGIN,
59 TURNSTILE_SECRET: process.env.TURNSTILE_SECRET,
60 TURNSTILE_SITE_KEY: process.env.TURNSTILE_SITE_KEY,
61 ALLOW_NO_TURNSTILE: process.env.TURNSTILE_SECRET ? undefined : '1',
62 ASSETS: { fetch: async (request) => staticResponse(new URL(request.url).pathname) },
63};
64
65const devSessionToken = process.env.DEV_SESSION_TOKEN || 'dev-admin-token-not-for-production-0000';
66await 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')`)
67 .bind(await sha256(devSessionToken), new Date().toISOString()).run();
68
69async function route(request) {
70 const url = new URL(request.url);
71 const path = url.pathname;
72 if (path.startsWith('/api/')) return handle(request, env);
73 const redirect = redirects.find(({ pattern }) => pattern.test(path));
74 if (redirect) return Response.redirect(new URL(redirect.target, url), redirect.status);
75 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) });
76 if (!path.endsWith('/') && !extname(path) && existsSync(join(root, path, 'index.html'))) return Response.redirect(new URL(path + '/' + url.search, url), 308);
77 return staticResponse(path);
78}
79
80createServer(async (req, res) => {
81 try {
82 const chunks = [];
83 for await (const c of req) chunks.push(c);
84 const headers = new Headers();
85 for (const [k, v] of Object.entries(req.headers)) if (typeof v === 'string') headers.set(k, v);
86 if (!headers.has('cf-connecting-ip')) headers.set('cf-connecting-ip', req.socket.remoteAddress || '127.0.0.1');
87 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 });
88 const response = await route(request);
89 res.writeHead(response.status, Object.fromEntries(response.headers));
90 res.end(Buffer.from(await response.arrayBuffer()));
91 } catch (err) {
92 console.error(err);
93 res.writeHead(500).end('dev server error');
94 }
95}).listen(port, () => console.log(`http://localhost:${port} (db ${dbFile}, dev curator session ${devSessionToken})`));