// The board. Serves the harbour and a JSON API over the Hub's store, behind GitLab sign-in. // Approvers record Gas, Tunda and Tolak here; the Hub carries them out. See docs/SPEC.md → M2, M3. import http from 'node:http'; import { randomBytes, createHash } from 'node:crypto'; import { readFileSync, existsSync } from 'node:fs'; import { execFile } from 'node:child_process'; import { promisify } from 'node:util'; import path from 'node:path'; import { Store } from './store.ts'; import { ROOT, HOME, loadReviewer } from './review.ts'; import { loadHubConfig } from './hub.ts'; import { viewAjuan, visible, type BoardConfig, type Viewer } from './boardview.ts'; import { decide, allowedActions, type Action } from './decide.ts'; import { decideRelease } from './release.ts'; import type { Ajuan } from './store.ts'; const run = promisify(execFile); const STATIC = path.join(ROOT, 'board'); const SESSION_HOURS = 12; const COOKIE = 'labuh_session'; export function loadBoardConfig(): BoardConfig { return JSON.parse(readFileSync(path.join(HOME, 'board.json'), 'utf8')); } // Sessions live in the Hub's database so a board restart keeps people signed in. Each one // remembers which watched projects were checked at sign-in (`checked`); once the Hub watches a // project the session never checked, the session ends and the next sign-in checks it. function sessions(store: Store, watched: string[]) { store.db.exec(`CREATE TABLE IF NOT EXISTS board_sessions ( id TEXT PRIMARY KEY, username TEXT NOT NULL, name TEXT NOT NULL, approver INTEGER NOT NULL, projects TEXT NOT NULL, expires_at INTEGER NOT NULL)`); const cols = new Set((store.db.prepare('PRAGMA table_info(board_sessions)').all() as Array<{ name: string }>).map((c) => c.name)); if (!cols.has('checked')) store.db.exec("ALTER TABLE board_sessions ADD COLUMN checked TEXT NOT NULL DEFAULT '[]'"); const hash = (id: string) => createHash('sha256').update(id).digest('hex'); return { create(v: Viewer): string { const id = randomBytes(32).toString('hex'); store.db.prepare('DELETE FROM board_sessions WHERE expires_at < ?').run(Date.now()); store.db .prepare('INSERT INTO board_sessions (id, username, name, approver, projects, checked, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?)') .run(hash(id), v.username, v.name, v.approver ? 1 : 0, JSON.stringify(v.projects), JSON.stringify(watched), Date.now() + SESSION_HOURS * 3600_000); return id; }, get(id: string | undefined): Viewer | null { if (!id) return null; const row = store.db.prepare('SELECT * FROM board_sessions WHERE id = ? AND expires_at > ?').get(hash(id), Date.now()) as any; if (!row) return null; const checked = new Set(JSON.parse(row.checked) as string[]); if (watched.some((p) => !checked.has(p))) return null; return { username: row.username, name: row.name, approver: !!row.approver, projects: JSON.parse(row.projects) }; }, drop(id: string | undefined) { if (id) store.db.prepare('DELETE FROM board_sessions WHERE id = ?').run(hash(id)); }, }; } function cookies(req: http.IncomingMessage): Record { return Object.fromEntries((req.headers.cookie ?? '').split(';').map((c) => c.trim().split('=')).filter((p) => p.length === 2)) as Record; } const b64url = (b: Buffer) => b.toString('base64url'); async function oauthSecret(): Promise { if (process.env.LABUH_OAUTH_SECRET) return process.env.LABUH_OAUTH_SECRET; try { return (await run('security', ['find-generic-password', '-s', 'labuh-oauth-secret', '-w'])).stdout.trim(); } catch { throw new Error('no OAuth secret: set LABUH_OAUTH_SECRET or the Keychain item labuh-oauth-secret'); } } async function gitlabJson(url: string, token: string): Promise { const r = await fetch(url, { headers: { Authorization: `Bearer ${token}` } }); return r.ok ? r.json() : null; } const HEADERS = { 'Content-Security-Policy': "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src https://fonts.gstatic.com; img-src 'self' data:; frame-ancestors 'none'; base-uri 'none'; form-action 'self'", 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'same-origin', }; const TYPES: Record = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.svg': 'image/svg+xml' }; const escapeHtml = (s: string) => s.replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]!); const PAGE_HEAD = ``; const BRAND_MARK = `
labuh
`; // The rubric as a plain page with an anchor per rule (`## R9 · …` → #r9). function rubricPage(md: string): string { const body = md .split('\n') .map((line) => { const h = line.match(/^(#{1,3})\s+(.*)$/); if (!h) return line.trim() ? `

${escapeHtml(line)}

` : ''; const id = h[2].match(/^(R\d+)\b/)?.[1].toLowerCase(); return `${escapeHtml(h[2])}`; }) .join('\n'); return `${PAGE_HEAD}Rubrik Labuh
${body}
`; } const ACTIONS: Action[] = ['gas', 'tunda', 'tolak', 'close', 'undo']; async function readJson(req: http.IncomingMessage, limit = 2048): Promise { let body = ''; for await (const chunk of req) { body += chunk; if (body.length > limit) throw Object.assign(new Error('too large'), { status: 413 }); } try { return JSON.parse(body || '{}'); } catch { throw Object.assign(new Error('bad json'), { status: 400 }); } } export function createBoard(store: Store, cfg: BoardConfig, projects: string[], opts: { devUser?: string; log?: (l: string) => void; graceSeconds?: number; gasMode?: 'dry' | 'live' } = {}) { const log = opts.log ?? (() => {}); const graceSeconds = opts.graceSeconds ?? 15; const origin = new URL(cfg.publicUrl).origin; const actionState = (a: Ajuan) => { const pending = store.pendingActions(a.id); const taken = pending.some((e) => e.attempts > 0); const gas = pending.find((e) => e.kind === 'gas'); const close = pending.find((e) => e.kind === 'close'); return { taken, gasQueuedAt: gas ? Number(gas.payload.at) : null, closeQueuedAt: close ? Number(close.payload.at) : null, graceSeconds, allowed: allowedActions(a, taken, !!close), dry: opts.gasMode !== 'live' }; }; const sess = sessions(store, projects); const pending = new Map(); const reviewer = loadReviewer(); const secure = cfg.publicUrl.startsWith('https://'); const redirectUri = `${cfg.publicUrl}/auth/callback`; const devUser = opts.devUser && cfg.host === '127.0.0.1' ? opts.devUser : null; if (devUser) log(`sign-in dilewati untuk ${devUser} (hanya di 127.0.0.1)`); const setSession = (res: http.ServerResponse, id: string | null) => { const attrs = `Path=/; HttpOnly; SameSite=Lax${secure ? '; Secure' : ''}`; res.setHeader('Set-Cookie', id ? `${COOKIE}=${id}; ${attrs}; Max-Age=${SESSION_HOURS * 3600}` : `${COOKIE}=; ${attrs}; Max-Age=0`); }; const send = (res: http.ServerResponse, status: number, type: string, body: string | Buffer, extra: Record = {}) => { res.writeHead(status, { ...HEADERS, 'Content-Type': type, 'Cache-Control': 'no-store', ...extra }); res.end(body); }; const json = (res: http.ServerResponse, status: number, data: unknown) => send(res, status, 'application/json; charset=utf-8', JSON.stringify(data)); const page = (res: http.ServerResponse, status: number, title: string, text: string, action = '') => send(res, status, TYPES['.html'], `${PAGE_HEAD}Labuh
${BRAND_MARK}

${escapeHtml(title)}

${escapeHtml(text)}

${action}
`); const viewerOf = (req: http.IncomingMessage): Viewer | null => { // Approver rights follow board.json on every request, so adding or removing one needs no new sign-in. const v = sess.get(cookies(req)[COOKIE]); if (v) return { ...v, approver: cfg.approvers.includes(v.username) }; return devUser ? { username: devUser, name: devUser, approver: cfg.approvers.includes(devUser), projects } : null; }; async function callback(url: URL, res: http.ServerResponse) { const state = url.searchParams.get('state') ?? ''; const code = url.searchParams.get('code'); const p = pending.get(state); pending.delete(state); if (!p || !code || Date.now() - p.at > 10 * 60_000) return page(res, 400, 'Masuk gagal', 'Sesi masuk sudah kedaluwarsa. Coba lagi.', 'Masuk dengan GitLab'); const r = await fetch('https://gitlab.com/oauth/token', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ client_id: cfg.gitlabClientId!, client_secret: await oauthSecret(), code, grant_type: 'authorization_code', redirect_uri: redirectUri, code_verifier: p.verifier }), }); if (!r.ok) return page(res, 502, 'Masuk gagal', `GitLab menolak penukaran kode (HTTP ${r.status}).`); const token = (await r.json()).access_token as string; const me = await gitlabJson('https://gitlab.com/api/v4/user', token); if (!me) return page(res, 502, 'Masuk gagal', 'Profil GitLab tidak bisa dibaca.'); const readable: string[] = []; for (const project of projects) if (await gitlabJson(`https://gitlab.com/api/v4/projects/${encodeURIComponent(project)}`, token)) readable.push(project); // The GitLab token is not kept: access is decided once, at sign-in. if (!readable.length) return page(res, 403, 'Belum ada akses', `Akun @${me.username} belum punya akses ke project yang dipantau Labuh.`); const viewer = { username: me.username, name: me.name, approver: cfg.approvers.includes(me.username), projects: readable }; setSession(res, sess.create(viewer)); log(`masuk: @${me.username}${viewer.approver ? ' (approver)' : ''}`); res.writeHead(302, { Location: '/' }); res.end(); } return http.createServer(async (req, res) => { try { const url = new URL(req.url ?? '/', cfg.publicUrl); if (req.method === 'GET' && (url.pathname === '/board.css' || url.pathname === '/board.js')) { return send(res, 200, TYPES[path.extname(url.pathname)], readFileSync(path.join(STATIC, url.pathname.slice(1))), { 'Cache-Control': 'no-cache' }); } if (url.pathname === '/auth/login') { if (!cfg.gitlabClientId) return page(res, 503, 'Belum bisa masuk', 'Aplikasi OAuth GitLab belum diisi di board.json.'); const state = b64url(randomBytes(16)); const verifier = b64url(randomBytes(32)); pending.set(state, { verifier, at: Date.now() }); const q = new URLSearchParams({ client_id: cfg.gitlabClientId, redirect_uri: redirectUri, response_type: 'code', state, scope: 'read_api', code_challenge: b64url(createHash('sha256').update(verifier).digest()), code_challenge_method: 'S256' }); res.writeHead(302, { Location: `https://gitlab.com/oauth/authorize?${q}` }); return res.end(); } if (url.pathname === '/auth/callback') return await callback(url, res); if (url.pathname === '/auth/logout' && req.method === 'POST') { sess.drop(cookies(req)[COOKIE]); setSession(res, null); res.writeHead(303, { Location: '/' }); return res.end(); } const viewer = viewerOf(req); if (!viewer) { if (url.pathname.startsWith('/api/')) return json(res, 401, { error: 'sign in' }); return page(res, 401, 'Labuh', `Antrean deploy dan review ${reviewer.name}. Masuk dengan akun GitLab yang punya akses ke repo-nya.`, 'Masuk dengan GitLab'); } if (url.pathname === '/') return send(res, 200, TYPES['.html'], readFileSync(path.join(STATIC, 'index.html'))); if (url.pathname === '/rubric') return send(res, 200, TYPES['.html'], rubricPage(readFileSync(path.resolve(HOME, reviewer.rubric), 'utf8'))); if (url.pathname === '/api/board') { const now = Date.now(); const ajuan = store .allAjuan() .filter((a) => visible(a, cfg, viewer, now)) .map((a) => viewAjuan(a, store.events(a.id), cfg, viewer, actionState(a), a.deploy_state === 'awaiting_release' && a.target_branch ? store.openRelease(a.project, a.target_branch) ?? null : null, reviewer.name)); return json(res, 200, { viewer: { username: viewer.username, name: viewer.name, approver: viewer.approver }, reviewer: reviewer.name, lanes: [...cfg.lanes.map((l) => l.name), 'Lainnya'], ajuan, at: new Date(now).toISOString() }); } const act = url.pathname.match(/^\/api\/ajuan\/(\d+)\/action$/); if (act && req.method === 'POST') { // Cookies are SameSite=Lax; a same-origin JSON request is required on top, so no form or // link on another site can act for a signed-in approver. if (req.headers.origin !== origin || !String(req.headers['content-type'] ?? '').startsWith('application/json')) return json(res, 403, { error: 'Permintaan ditolak.' }); if (!viewer.approver) return json(res, 403, { error: 'Hanya approver yang bisa.' }); const a = store.ajuanById(Number(act[1])); if (!a || !viewer.projects.includes(a.project)) return json(res, 404, { error: 'Ajuan tidak ada.' }); const body = await readJson(req); if (!ACTIONS.includes(body.action)) return json(res, 400, { error: 'Aksi tidak dikenal.' }); const r = decide(store, a.id, body.action, viewer.username, { sha: typeof body.sha === 'string' ? body.sha : undefined, note: typeof body.note === 'string' ? body.note : undefined }); log(`${body.action} ${a.project} !${a.iid} oleh @${viewer.username}: ${r.ok ? r.text : r.error}`); return r.ok ? json(res, 200, { ok: true, text: r.text }) : json(res, r.status, { error: r.error }); } const rel = url.pathname.match(/^\/api\/release\/(\d+)\/action$/); if (rel && req.method === 'POST') { if (req.headers.origin !== origin || !String(req.headers['content-type'] ?? '').startsWith('application/json')) return json(res, 403, { error: 'Permintaan ditolak.' }); if (!viewer.approver) return json(res, 403, { error: 'Hanya approver yang bisa.' }); const r = store.releaseById(Number(rel[1])); if (!r || !viewer.projects.includes(r.project)) return json(res, 404, { error: 'Usulan rilis tidak ada.' }); const body = await readJson(req); if (body.action !== 'release' && body.action !== 'undo') return json(res, 400, { error: 'Aksi tidak dikenal.' }); const out = decideRelease(store, r.id, body.action, viewer.username, typeof body.tag === 'string' ? body.tag : undefined); log(`rilis ${body.action} ${r.project} ${r.branch} oleh @${viewer.username}: ${out.ok ? out.text : out.error}`); return out.ok ? json(res, 200, { ok: true, text: out.text }) : json(res, out.status, { error: out.error }); } return json(res, 404, { error: 'not found' }); } catch (e: any) { log(`error: ${String(e?.message ?? e).slice(0, 300)}`); if (!res.headersSent) json(res, e?.status ?? 500, { error: e?.status ? 'Permintaan tidak valid.' : 'internal' }); } }); } async function main() { const cfg = loadBoardConfig(); const hub = loadHubConfig(HOME); const dbPath = process.env.LABUH_BOARD_DB ?? path.join(HOME, '.work', 'hub', 'labuh.db'); if (!existsSync(dbPath)) throw new Error(`Store belum ada (${dbPath}); jalankan Hub dulu.`); const log = (l: string) => console.log(`${new Date().toISOString().slice(11, 19)} ${l}`); const server = createBoard(new Store(dbPath), cfg, hub.projects, { devUser: process.env.LABUH_BOARD_DEV_USER, log, graceSeconds: hub.gas?.graceSeconds, gasMode: hub.gas?.mode }); server.listen(cfg.port, cfg.host, () => log(`board di ${cfg.publicUrl} (listen ${cfg.host}:${cfg.port})`)); } if (import.meta.url === `file://${process.argv[1]}`) { main().catch((e) => { console.error(String(e?.message ?? e)); process.exit(1); }); }