// Branchwell: open Git hosting. Clone, pull and push over HTTPS; BioLock sign-in; commits and branches // are kept or removed by votes. One Worker, one D1 database, one Durable Object per repository. import type { Env } from './env'; import { page, esc, ago, sizeText, markdown, diffHtml, SITE, SECURITY } from './html'; import { handleAuth, currentAccount, canVote, pusherFromBasic, RESERVED, sha256, randomId, type Account } from './auth'; import { featuresApi, featureVote, WIDGET_JS } from './features'; import { ODOMETER_CSS, ODOMETER_JS, APP_JS } from './static'; import * as C from './content'; import { isText } from './repo'; export { RepoDO } from './repo'; // Every repository lives under an owner: a company account (org) or a person, as owner/project. const OWNER_RE = /^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?$/; const PROJ_RE = /^[a-z0-9][a-z0-9._-]{0,62}$/; const FULL_RE = /^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?\/[a-z0-9][a-z0-9._-]{0,62}$/; const VIEWS = new Set(['tree', 'blob', 'raw', 'commits', 'commit', 'branches', 'for']); const GIT_RE = /^\/([a-z0-9][a-z0-9-]{0,39})\/([a-z0-9][a-z0-9._-]{0,62}?)(?:\.git)?\/(info\/refs|git-upload-pack|git-receive-pack)$/; const OLD_GIT_RE = /^\/([a-z0-9][a-z0-9._-]{0,62}?)(?:\.git)?\/(info\/refs|git-upload-pack|git-receive-pack)$/; const json = (b: unknown, s = 200, h: Record = {}) => new Response(JSON.stringify(b), { status: s, headers: { 'content-type': 'application/json', 'cache-control': 'no-store', ...h } }); // do_name is the storage key. Older repos keep the flat name they were first pushed under. const stub = (env: Env, doName: string) => env.REPO.get(env.REPO.idFromName(doName.toLowerCase())); type RepoRow = { name: string; owner: string; do_name: string; description: string; created_by: string; created_at: number; updated_at: number; private: number }; type Org = { handle: string; name: string; domain: string | null; about: string | null; created_at: number }; const asset = (body: string, type: string) => new Response(body, { headers: { 'content-type': type, 'cache-control': 'public, max-age=3600', 'access-control-allow-origin': '*' } }); const APP = ['/assets/app.js']; const RENAMED: Record = { hellolightwell: 'lightwell' }; async function repoRow(env: Env, name: string) { return env.DB.prepare('SELECT name, owner, COALESCE(do_name, name) AS do_name, description, created_by, created_at, updated_at, COALESCE(private, 0) AS private FROM repos WHERE name = ?').bind(name.toLowerCase()).first(); } const orgRow = (env: Env, handle: string) => env.DB.prepare('SELECT handle, name, domain, about, created_at FROM orgs WHERE handle = ?').bind(handle.toLowerCase()).first(); async function myOrgs(env: Env, me: Account) { return (await env.DB.prepare('SELECT o.handle, o.name, o.domain, o.about, o.created_at FROM org_members m JOIN orgs o ON o.handle = m.org WHERE m.account_id = ? ORDER BY o.name').bind(me.id).all()).results; } async function canCreateUnder(env: Env, owner: string, by: Account) { if (owner === by.handle.toLowerCase()) return true; return !!(await env.DB.prepare('SELECT 1 AS x FROM org_members WHERE org = ? AND account_id = ?').bind(owner, by.id).first('x')); } // Private repositories exist only for the owner and members of the owning program. A push key made for one // repository counts only there. Everyone else is told the repository does not exist. async function canSee(env: Env, row: RepoRow, who: Account | null): Promise { if (!row.private) return true; if (!who || (who.keyRepo && who.keyRepo !== row.name.toLowerCase())) return false; return canCreateUnder(env, (row.owner || row.name.split('/')[0]).toLowerCase(), who); } const PUBLIC = 'COALESCE(private, 0) = 0'; // Programs with projects, all of them private, stay out of public lists. const HIDDEN_ORG = '(NOT EXISTS (SELECT 1 FROM repos r WHERE r.owner = o.handle) OR EXISTS (SELECT 1 FROM repos r WHERE r.owner = o.handle AND COALESCE(r.private, 0) = 0))'; async function createRepo(env: Env, owner: string, project: string, description: string, by: Account, isPrivate = false): Promise { owner = owner.toLowerCase(); project = project.toLowerCase().replace(/\.git$/, ''); if (!PROJ_RE.test(project) || VIEWS.has(project)) return 'Use 1 to 63 lowercase letters, numbers, dots, dashes or underscores.'; if (!(await canCreateUnder(env, owner, by))) return `You can start projects under your own name, or under a program you belong to. ${owner} isn't one of those.`; const name = owner + '/' + project; if (await repoRow(env, name)) return 'That name is taken.'; if (owner === by.handle.toLowerCase()) { const n = await env.DB.prepare('SELECT COUNT(*) AS n FROM repos WHERE created_by = ? AND owner = ? AND created_at > ?').bind(by.handle, owner, Date.now() - 864e5).first('n'); if ((n || 0) >= 5) return 'You can make 5 projects a day. Try again tomorrow.'; } await env.DB.prepare('INSERT INTO repos (name, owner, do_name, description, created_by, created_at, private) VALUES (?, ?, ?, ?, ?, ?, ?)').bind(name, owner, name, description.slice(0, 300), by.handle, Date.now(), isPrivate ? 1 : 0).run(); await stub(env, name).init(name); return null; } export default { async fetch(req: Request, env: Env, ctx: ExecutionContext): Promise { const url = new URL(req.url); if (url.hostname === 'www.branchwell.ai') return Response.redirect(SITE + url.pathname + url.search, 301); const path = decodeURIComponent(url.pathname); // Programs that changed their handle: old addresses move to the new one. const seg = url.pathname.split('/')[1]?.toLowerCase().replace(/\.git$/, ''); if (seg && RENAMED[seg]) { const first = url.pathname.split('/')[1]; return Response.redirect(SITE + '/' + RENAMED[seg] + (first.toLowerCase().endsWith('.git') ? '.git' : '') + url.pathname.slice(1 + first.length) + url.search, 301); } try { // ---------- Git over HTTPS ---------- const g = url.pathname.match(GIT_RE); if (g) return await git(req, env, ctx, g[1] + '/' + g[2], g[3], url); const og = url.pathname.match(OLD_GIT_RE); if (og) { // Old one-part addresses (branchwell.ai/sunlaid.git) now live at the company's research project. const to = await repoRow(env, og[1].toLowerCase() + '/research'); if (to && !to.private) return Response.redirect(`${SITE}/${to.name}.git/${og[2]}${url.search}`, 301); return new Response(`Repositories now live under an owner, like https://branchwell.ai/sunlaid/research.git\n`, { status: 404, headers: { 'content-type': 'text/plain' } }); } // ---------- assets and APIs ---------- if (path === '/assets/app.js') return asset(APP_JS, 'text/javascript; charset=utf-8'); if (path === '/assets/visitor-odometer.v1.js') return asset(ODOMETER_JS, 'text/javascript; charset=utf-8'); if (path === '/assets/visitor-odometer.v1.css') return asset(ODOMETER_CSS, 'text/css; charset=utf-8'); if (path === '/widget/features.v1.js') return asset(WIDGET_JS, 'text/javascript; charset=utf-8'); if (path === '/robots.txt') return new Response(`User-agent: *\nAllow: /\nDisallow: /api/\n`, { headers: { 'content-type': 'text/plain' } }); if (path === '/favicon.ico' || path === '/favicon.svg') return new Response(null, { status: 404 }); if (path.startsWith('/api/auth/')) return await handleAuth(req, env, path.slice(10)); if (path === '/api/features') return await featuresApi(req, env, url); if (path === '/api/feature-vote' && req.method === 'POST') return await featureVote(req, env); if (path === '/api/vote' && req.method === 'POST') return await vote(req, env); if (path === '/api/repos' && req.method === 'POST') return await apiCreateRepo(req, env); if (path === '/api/repos' && req.method === 'GET') return await apiListRepos(env, url); if ((path === '/api/programs' || path === '/api/companies') && req.method === 'GET') return await apiCompanies(env); if (path === '/api/keys/request' && req.method === 'POST') return await keyRequest(req, env); if (path === '/api/keys/approve' && req.method === 'POST') return await keyApprove(req, env); if (path === '/api/keys/poll' && req.method === 'POST') return await keyPoll(req, env); if (path.startsWith('/api/')) return json({ error: 'Not found' }, 404); // ---------- pages ---------- const me = await currentAccount(req, env); const P = (title: string, body: string, extra: Partial[0]> = {}) => page({ title, body, path: url.pathname, me, scripts: APP, ...extra }); switch (path.replace(/\/$/, '') || '/') { case '/': { const repos = await env.DB.prepare(`SELECT COUNT(*) AS n FROM repos WHERE ${PUBLIC}`).first('n'); const companies = await env.DB.prepare('SELECT COUNT(*) AS n FROM orgs').first('n'); return P('Branchwell: open Git hosting where votes decide', C.home({ repos: repos || 0, companies: companies || 0 }), { head: '', description: 'Branchwell hosts open Git repositories. Anyone can pull, anyone signed in can push straight to a branch, and 3 votes keep or remove each commit.' }); } case '/how-to-pull': return P('How to pull', C.howToPull, { current: '/how-to-pull', description: 'Clone and pull any Branchwell repository with plain Git. No account needed.' }); case '/how-to-contribute': return P('How to contribute', C.howToContribute, { current: '/how-to-contribute', description: 'Sign in with BioLock, make a push key and push straight to a branch. No pull requests.' }); case '/rules': return P('How votes work', C.rules, { current: '/rules', description: '3 votes down removes a commit or branch. 3 votes up keeps it for good. Everything else stays.' }); case '/features': return P('New features, voted in', C.features, { current: '/features', description: 'Add a New badge with thumbs up and down to any app. 3 up keeps a feature, 3 down switches it off.' }); case '/privacy': return P('Privacy', C.privacy, { description: 'What Branchwell keeps and what it never does.' }); case '/source': return Response.redirect(SITE + '/branchwell/source', 302); case '/repos': return reposPage(env, P); case '/programs': return companiesPage(env, P); case '/companies': return Response.redirect(SITE + '/programs', 301); case '/research': return researchPage(env, P); case '/signin': return P('Sign in', signinBody(me), { noindex: true }); case '/approve-key': return approveKeyPage(env, url, me, P); case '/add-device': return P('Add this device', `
BioLock

Add this device

Use this device's fingerprint or face reader to sign in to your Branchwell account from now on.

The link works once and only for 10 minutes. If it has expired, make a new one on a device where you are signed in.

`, { noindex: true }); case '/account': return me ? accountPage(env, me, P) : Response.redirect(SITE + '/signin?back=/account', 302); case '/new': return P('New project', newRepoBody(me, me ? await myOrgs(env, me) : []), { noindex: true }); case '/feature-vote': return featureVotePage(env, url, me, P); } // ---------- repository pages ---------- const o = url.pathname.match(/^\/([a-z0-9][a-z0-9-]{0,39})\/?$/); if (o && !RESERVED.has(o[1])) { const r = await ownerPage(env, o[1], me, P); if (r) return r; } const m = url.pathname.match(/^\/([a-z0-9][a-z0-9-]{0,39})\/([a-z0-9][a-z0-9._-]{0,62}?)(?:\.git)?(?:\/(tree|blob|raw|commits|commit|branches|for)(?:\/(.*))?)?\/?$/); if (m && !RESERVED.has(m[1])) { const row = await repoRow(env, m[1] + '/' + m[2]); if (row && await canSee(env, row, me)) return await repoPage(env, req, url, me, row, m[3] || '', m[4] ? decodeURIComponent(m[4]) : '', P); } return page({ title: 'Not found', path: url.pathname, me, noindex: true, body: '

We couldn\'t find that page

It may have moved, or a vote may have removed it.

HomeAll repositories

' }).then404(); } catch (e) { console.error(e); return new Response('Something went wrong on our side. Please try again.', { status: 500 }); } }, }; declare global { interface Response { then404(): Response } } Response.prototype.then404 = function (this: Response) { return new Response(this.body, { status: 404, headers: this.headers }); }; // ---------------- Git ---------------- async function git(req: Request, env: Env, ctx: ExecutionContext, name: string, op: string, url: URL): Promise { name = name.toLowerCase(); const service = op === 'info/refs' ? url.searchParams.get('service') : op; const write = service === 'git-receive-pack'; let pusher: Account | null = req.headers.get('authorization') ? await pusherFromBasic(req, env) : null; if (write) { if (!pusher) return new Response('Sign in at https://branchwell.ai/account and make a push key. Use your Branchwell name as the username and the push key as the password.\n', { status: 401, headers: { 'www-authenticate': 'Basic realm="Branchwell"', 'content-type': 'text/plain' } }); } const notFound = () => new Response(`Repository ${name} not found on Branchwell.\n`, { status: 404, headers: { 'content-type': 'text/plain', 'cache-control': 'no-store' } }); let row = await repoRow(env, name); // A private repository answers 404 to anyone who isn't a member, for reads and pushes alike. if (row && !(await canSee(env, row, pusher))) return notFound(); // A key limited to one repository can't push anywhere else, or start new repositories. if (write && pusher?.keyRepo && pusher.keyRepo !== name) return notFound(); if (!row) { if (!write || !pusher) return notFound(); const [owner, project] = name.split('/'); const err = await createRepo(env, owner, project, '', pusher); if (err) return new Response(err + '\n', { status: 403, headers: { 'content-type': 'text/plain' } }); row = await repoRow(env, name); } if (!row) return new Response('Not found\n', { status: 404 }); const target = new URL('https://repo/' + (op === 'info/refs' ? 'info/refs' : op) + url.search); const headers = new Headers({ 'content-type': req.headers.get('content-type') || '' }); headers.set('x-repo', row.name); if (row.private) headers.set('x-private', '1'); if (pusher) headers.set('x-pusher', JSON.stringify({ id: pusher.id, handle: pusher.handle })); let body: BodyInit | null = null; if (req.method === 'POST') { let buf = new Uint8Array(await req.arrayBuffer()); if ((req.headers.get('content-encoding') || '').includes('gzip')) buf = new Uint8Array(await new Response(new Blob([buf]).stream().pipeThrough(new DecompressionStream('gzip'))).arrayBuffer()); body = buf; } const res = await stub(env, row.do_name).fetch(new Request(target, { method: req.method, headers, body })); if (write && req.method === 'POST') ctx.waitUntil(env.DB.prepare('UPDATE repos SET updated_at = ? WHERE name = ?').bind(Date.now(), name).run()); return res; } // ---------------- APIs ---------------- async function vote(req: Request, env: Env): Promise { if (req.headers.get('origin') !== new URL(req.url).origin) return json({ error: 'Bad origin.' }, 403); const me = await currentAccount(req, env); if (!me) return json({ error: 'Sign in with BioLock to vote.' }, 401); const b = await req.json<{ repo: string; kind: string; target: string; value: number }>().catch(() => null); if (!b || !FULL_RE.test(b.repo || '') || (b.kind !== 'commit' && b.kind !== 'branch') || !b.target) return json({ error: 'Bad vote.' }, 400); const row = await repoRow(env, b.repo); if (!row || !(await canSee(env, row, me))) return json({ error: 'No such repository.' }, 404); const r = await stub(env, row.do_name).vote(b.kind, String(b.target).slice(0, 120), { id: me.id, handle: me.handle, canVote: canVote(me) }, Number(b.value) || 0); return json(r); } // ---------------- API for apps (OpenTalon and others) ---------------- const cors = { 'access-control-allow-origin': '*' }; async function apiListRepos(env: Env, url: URL): Promise { const owner = (url.searchParams.get('owner') || '').toLowerCase(); const q = owner ? env.DB.prepare(`SELECT name, owner, description, created_at, updated_at FROM repos WHERE owner = ? AND ${PUBLIC} ORDER BY name`).bind(owner) : env.DB.prepare(`SELECT name, owner, description, created_at, updated_at FROM repos WHERE ${PUBLIC} ORDER BY name LIMIT 5000`); const rows = (await q.all<{ name: string; owner: string; description: string; created_at: number; updated_at: number }>()).results; return json({ repos: rows.map((r) => ({ ...r, clone_url: `${SITE}/${r.name}.git`, web_url: `${SITE}/${r.name}` })) }, 200, cors); } async function apiCompanies(env: Env): Promise { const rows = (await env.DB.prepare(`SELECT handle, name, domain FROM orgs o WHERE ${HIDDEN_ORG} ORDER BY name COLLATE NOCASE`).all<{ handle: string; name: string; domain: string }>()).results; const list = rows.map((o) => ({ ...o, web_url: `${SITE}/${o.handle}` })); return json({ programs: list, companies: list }, 200, cors); } // Desktop apps get a push key without a browser session: the app asks, the person approves on a signed-in // device (BioLock), and the app picks up a new push key once. Requests last 10 minutes. const CODE_CHARS = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; async function keyRequest(req: Request, env: Env): Promise { const b = await req.json<{ name?: string }>().catch(() => ({} as { name?: string })); const name = String(b.name || 'App').replace(/[^\w .()-]/g, '').slice(0, 60) || 'App'; const ip = await sha256((req.headers.get('cf-connecting-ip') || '') + (env.IP_SALT || '')); const n = await env.DB.prepare('SELECT COUNT(*) AS n FROM key_requests WHERE ip_hash = ? AND created_at > ?').bind(ip, Date.now() - 3600_000).first('n'); if ((n || 0) >= 20) return json({ error: 'Too many requests. Try again in an hour.' }, 429); const requestId = randomId(32); const r = crypto.getRandomValues(new Uint8Array(8)); const code = Array.from(r, (x) => CODE_CHARS[x % CODE_CHARS.length]).join('').replace(/^(.{4})/, '$1-'); await env.DB.prepare('DELETE FROM key_requests WHERE expires_at < ?').bind(Date.now() - 3600_000).run(); await env.DB.prepare('INSERT INTO key_requests (id, code, name, status, ip_hash, created_at, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?)') .bind(await sha256(requestId), code, name, 'pending', ip, Date.now(), Date.now() + 600_000).run(); return json({ request_id: requestId, code, approve_url: `${SITE}/approve-key?code=${code}`, expires_in: 600, interval: 3 }); } async function keyApprove(req: Request, env: Env): Promise { if (req.headers.get('origin') !== new URL(req.url).origin) return json({ error: 'Bad origin.' }, 403); const me = await currentAccount(req, env); if (!me) return json({ error: 'Sign in with BioLock first.' }, 401); const b = await req.json<{ code?: string; deny?: boolean }>().catch(() => ({} as { code?: string; deny?: boolean })); const r = await env.DB.prepare("UPDATE key_requests SET status = ?, account_id = ? WHERE code = ? AND status = 'pending' AND expires_at > ?") .bind(b.deny ? 'denied' : 'approved', me.id, String(b.code || '').toUpperCase(), Date.now()).run(); if ((r.meta.changes || 0) !== 1) return json({ error: 'That code has expired or was already used.' }, 400); return json({ ok: true }); } async function keyPoll(req: Request, env: Env): Promise { const b = await req.json<{ request_id?: string }>().catch(() => ({} as { request_id?: string })); const id = await sha256(String(b.request_id || '')); const row = await env.DB.prepare('SELECT name, status, account_id, expires_at FROM key_requests WHERE id = ?').bind(id).first<{ name: string; status: string; account_id: string; expires_at: number }>(); if (!row) return json({ status: 'unknown' }, 404); if (row.status === 'denied') return json({ status: 'denied' }); if (row.status === 'done') return json({ status: 'done' }); if (row.status === 'pending') return json({ status: Date.now() > row.expires_at ? 'expired' : 'pending' }); // Approved: make the key now, hand it over once. const claimed = await env.DB.prepare("UPDATE key_requests SET status = 'done' WHERE id = ? AND status = 'approved'").bind(id).run(); if ((claimed.meta.changes || 0) !== 1) return json({ status: 'done' }); const acct = await env.DB.prepare('SELECT handle FROM accounts WHERE id = ?').bind(row.account_id).first('handle'); const key = 'bw_push_' + randomId(24).replace(/[-_]/g, 'x'); await env.DB.prepare('INSERT INTO push_keys (id, account_id, name, hash, created_at) VALUES (?, ?, ?, ?, ?)').bind(randomId(9), row.account_id, row.name, await sha256(key), Date.now()).run(); return json({ status: 'approved', username: acct, key }); } async function approveKeyPage(env: Env, url: URL, me: Account | null, P: PFn) { const code = (url.searchParams.get('code') || '').toUpperCase().replace(/[^A-Z0-9-]/g, '').slice(0, 9); const back = encodeURIComponent('/approve-key?code=' + code); const row = code ? await env.DB.prepare('SELECT name, status, expires_at FROM key_requests WHERE code = ?').bind(code).first<{ name: string; status: string; expires_at: number }>() : null; const live = row && row.status === 'pending' && row.expires_at > Date.now(); const body = !me ? `

Sign in with BioLock to approve this.

Sign in

` : !live ? '

That code has expired or was already used. Ask the app for a new one.

' : `

${esc(row!.name)} is asking for a push key for your account ${esc(me.handle)}, so it can pull and push your projects here.

Check the app shows the same code: ${esc(code)}

You can remove the key any time on your account page.

`; return P('Approve an app', `
Push key

Approve an app

${body}
`, { noindex: true }); } async function apiCreateRepo(req: Request, env: Env): Promise { if (req.headers.get('origin') !== new URL(req.url).origin) return json({ error: 'Bad origin.' }, 403); const me = await currentAccount(req, env); if (!me) return json({ error: 'Sign in first.' }, 401); const b = await req.json<{ owner: string; name: string; description: string; private?: boolean }>().catch(() => ({ owner: '', name: '', description: '', private: false })); const owner = String(b.owner || me.handle).toLowerCase(), project = String(b.name || '').toLowerCase(); if (!OWNER_RE.test(owner)) return json({ error: 'Pick who owns it.' }, 400); const err = await createRepo(env, owner, project, String(b.description || ''), me, b.private === true); if (err) return json({ error: err }, 400); return json({ ok: true, name: owner + '/' + project }); } // ---------------- pages ---------------- type PFn = (title: string, body: string, extra?: Record) => Response; async function reposPage(env: Env, P: PFn) { const rows = (await env.DB.prepare(`SELECT name, description, created_by, created_at, updated_at FROM repos WHERE ${PUBLIC} ORDER BY COALESCE(updated_at, created_at) DESC LIMIT 1000`).all<{ name: string; description: string; created_by: string; created_at: number; updated_at: number }>()).results; const list = rows.length ? `${rows.map((r) => ``).join('')}
RepositoryAboutUpdated
${esc(r.name)}${esc(r.description || '')}${ago(r.updated_at || r.created_at)}
` : '

No repositories yet.

'; return P('Repositories', `
Repositories

Everything here is open

Pull any of these with plain Git. Sign in to push, vote, or start your own.

${list}`, { current: '/repos', description: 'Every repository on Branchwell. All public, all open to pull.' }); } function signinBody(me: Account | null) { if (me) return `

You're signed in as ${esc(me.handle)}

Your account

`; return `
Sign in

BioLock only

Sign in with BioLock: the fingerprint or face reader on this device. No passwords, no email, no codes.

New here?

Pick a public name, then use your fingerprint or face to lock it to this device.

3 to 30 lowercase letters, numbers or dashes.

`; } async function accountPage(env: Env, me: Account, P: PFn) { const keys = (await env.DB.prepare('SELECT id, name, created_at, last_used FROM push_keys WHERE account_id = ? ORDER BY created_at DESC').bind(me.id).all<{ id: string; name: string; created_at: number; last_used: number }>()).results; const orgs = await myOrgs(env, me); const pks = (await env.DB.prepare('SELECT created_at, last_used FROM passkeys WHERE account_id = ? ORDER BY created_at').bind(me.id).all<{ created_at: number; last_used: number }>()).results; const wait = canVote(me) ? '

You can vote.

' : `

You can vote from ${new Date(me.created_at + 864e5).toUTCString().slice(0, 22)} UTC. New accounts wait a day so votes stay fair.

`; return P('Your account', `
Your account

${esc(me.handle)}

${wait}

Push keys

Git can't use BioLock, so make a push key for each computer. Use your name as the username and the key as the password.

${keys.length ? `${keys.map((k) => ``).join('')}
${esc(k.name)}
made ${ago(k.created_at)}${k.last_used ? ', used ' + ago(k.last_used) : ', not used yet'}
` : ''}

Your devices

BioLock is on ${pks.length} device${pks.length === 1 ? '' : 's'} for this account. To add another phone or computer, make a one-time link here and open it there.

${orgs.length ? `

Your programs

${orgs.map((o) => `${esc(o.name)}`).join(' · ')}

` : ''}

Get started

git clone https://branchwell.ai/sunlaid/research.git

How to contribute · New repository

`, { noindex: true }); } function newRepoBody(me: Account | null, orgs: Org[]) { if (!me) return `

Start a project

Sign in with BioLock first.

Sign in

`; return `
New project

Start a project

Projects are public unless you make them private. Anyone can pull a public project and anyone signed in can push to it.

Or just push to a new name: git push https://branchwell.ai/${esc(me.handle)}/my-project.git main

`; } async function featureVotePage(env: Env, url: URL, me: Account | null, P: PFn) { const app = (url.searchParams.get('app') || '').toLowerCase(), feature = (url.searchParams.get('feature') || '').toLowerCase(); const f = await env.DB.prepare('SELECT status, up, down FROM features WHERE app = ? AND feature = ?').bind(app, feature).first<{ status: string; up: number; down: number }>(); if (!f) return P('Feature vote', '

We couldn\'t find that feature

', { noindex: true }); const back = encodeURIComponent(url.pathname + url.search); const v = url.searchParams.get('v') === 'down' ? -1 : 1; const body = !me ? `

Sign in with BioLock to vote.

Sign in

` : f.status !== 'new' ? `

${f.status === 'kept' ? 'This feature already got 3 thumbs up. It stays for good.' : 'This feature got 3 thumbs down and is switched off.'}

` : `

3 thumbs up keeps it for good. 3 thumbs down switches it off.

`; return P('Vote on a new feature', `
New feature

${esc(feature.replace(/[-_.]/g, ' '))}

in ${esc(app)}

${body}
`, { noindex: true }); } // ---------------- owners and companies ---------------- type ProjRow = { name: string; description: string; updated_at: number; created_at: number; private?: number }; const projTable = (rows: ProjRow[], showOwner = false) => rows.length ? `${rows.map((r) => ``).join('')}
${esc(showOwner ? r.name : r.name.split('/')[1])}${r.private ? ' private' : ''}${r.description ? `
${esc(r.description)}` : ''}
${ago(r.updated_at || r.created_at)}
` : '

No projects yet.

'; async function ownerPage(env: Env, handle: string, me: Account | null, P: PFn): Promise { const org = await orgRow(env, handle); const person = org ? null : await env.DB.prepare('SELECT handle, created_at FROM accounts WHERE handle = ?').bind(handle).first<{ handle: string; created_at: number }>(); if (!org && !person) return null; const member = !!(me && (await canCreateUnder(env, handle, me))); const all = (await env.DB.prepare('SELECT name, description, updated_at, created_at, COALESCE(private, 0) AS private FROM repos WHERE owner = ? ORDER BY name').bind(handle).all()).results; const rows = member ? all : all.filter((r) => !r.private); // A program whose only projects are private doesn't exist to outsiders. if (!member && all.length && !rows.length) return null; const title = org ? org.name : handle; const site = org?.domain ? `

${esc(org.domain)}

` : ''; return P(title, `
${org ? 'Program' : 'Person'}

${esc(title)}

${org?.about ? `

${esc(org.about)}

` : ''}${site}

${rows.length} project${rows.length === 1 ? '' : 's'}. ${rows.some((r) => r.private) ? 'Private ones are marked; only members see them.' : 'Every one is public: pull it with plain Git, push to it once you sign in.'}

${member ? '' : ''}

Projects

${projTable(rows)}`, { description: org ? `${org.name} on Branchwell: every project, open to pull and to push.` : `${handle} on Branchwell.` }); } async function companiesPage(env: Env, P: PFn) { const orgs = (await env.DB.prepare(`SELECT o.handle, o.name, o.domain, o.about, (SELECT COUNT(*) FROM repos r WHERE r.owner = o.handle AND COALESCE(r.private, 0) = 0) AS n FROM orgs o WHERE ${HIDDEN_ORG} ORDER BY o.name COLLATE NOCASE`).all()).results; const cards = orgs.map((o) => `

${esc(o.name)}

${o.domain ? esc(o.domain) + ' · ' : ''}${o.n} project${o.n === 1 ? '' : 's'}

`).join(''); return P('Programs', `
Programs

Every program, in the open

Each program has its own account here, and its projects live inside it. Everything is public: pull any project, or sign in and push.

${cards}
`, { current: '/programs', description: 'Every program on Branchwell, each with its own account and open projects.' }); } async function researchPage(env: Env, P: PFn) { const rows = (await env.DB.prepare("SELECT r.name, o.name AS org, o.domain, r.updated_at, r.created_at FROM repos r JOIN orgs o ON o.handle = r.owner WHERE r.name LIKE '%/research' AND COALESCE(r.private, 0) = 0 ORDER BY o.name COLLATE NOCASE").all<{ name: string; org: string; domain: string; updated_at: number; created_at: number }>()).results; const list = `${rows.map((r) => ``).join('')}
ProgramClone
${esc(r.org)}${r.domain ? `
${esc(r.domain)}` : ''}
git clone https://branchwell.ai/${esc(r.name)}.git
`; return P('Research', `
Research

Every program's research

Each program keeps its research in its own project: the full plan behind it, and every public source summarized in plain words with a link to the original. It is all public domain. Pull it, read it, add to it.

${list}`, { current: '/research', description: 'The research behind every program on Branchwell, one open project each. Public domain.' }); } // ---------------- repository views ---------------- const voteBox = (repo: string, kind: string, target: string, up: number, down: number, mine?: number) => `
`; const statusTag = (s?: string) => s ? `${s === 'system' ? 'removal' : esc(s)}` : ''; const MIME: Record = { png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', avif: 'image/avif', pdf: 'application/pdf', json: 'application/json; charset=utf-8', mp4: 'video/mp4', webm: 'video/webm', mp3: 'audio/mpeg', zip: 'application/zip' }; async function repoPage(env: Env, req: Request, url: URL, me: Account | null, row: RepoRow, view: string, rest: string, P: PFn): Promise { const s = stub(env, row.do_name); const ov = await s.overview(); const branchNames = (ov.branches as { name: string; status: string }[]).filter((b) => b.status !== 'removed').map((b) => b.name); // Split "/" where ref may contain slashes. const split = (x: string) => { const parts = x.split('/').filter((p, i) => p || i === 0); for (let i = parts.length; i > 0; i--) { const ref = parts.slice(0, i).join('/'); if (branchNames.includes(ref)) return { ref, path: parts.slice(i).join('/') }; } return { ref: parts[0] || ov.defaultBranch, path: parts.slice(1).join('/') }; }; const R = esc(row.name); const tabs = (cur: string, ref: string) => ``; const branchPicker = (ref: string, kind: string) => branchNames.length > 1 ? `
` : `${esc(ref)}`; const ownerName = row.name.split('/')[0]; const org = await orgRow(env, ownerName); const siteLink = org?.domain ? `

Website: ${esc(org.domain)}

` : ''; const head = (title: string) => `

${esc(org?.name || ownerName)} / ${esc(row.name.split('/')[1])}${org?.domain ? ` · ${esc(org.domain)}` : ''}${title}

`; const cloneBox = `
git clone https://branchwell.ai/${R}.git
`; if (ov.empty) { return P(row.name, `
${head('')}Project

${esc(row.name.split('/')[1])}

${esc(row.description || 'This repository is empty. Push the first commit.')}

${siteLink}
git clone https://branchwell.ai/${R}.git
cd ${esc(row.name.split('/')[1])}
echo "# ${R}" > README.md
git add README.md
git commit -m "First commit"
git push -u origin main

How to contribute

`); } if (view === 'for') { // /owner/project/for/: sites link here from every page. We find the file that builds that // page (path, path/index.html, path.html, also under a / folder) and open it, or the repo itself. const ref = ov.defaultBranch; const page = rest.replace(/^\/+|\/+$/g, '').replace(/\.\.+/g, ''); const org = await orgRow(env, row.name.split('/')[0]); const bases = ['', ...(org?.domain ? [org.domain + '/', 'domain-sites/' + org.domain + '/', 'public/', 'site/'] : ['public/', 'site/'])]; const names = page ? [page + '/index.html', page + '.html', page + '/index.htm', page] : ['index.html', 'README.md']; for (const b of bases) for (const n of names) { const t = await s.listTree(ref, b + n); if (t && t.kind === 'blob') return Response.redirect(`${SITE}/${row.name}/blob/${ref}/${b + n}`, 302); if (t && n === page && page) return Response.redirect(`${SITE}/${row.name}/tree/${ref}/${b + n}`, 302); } return Response.redirect(`${SITE}/${row.name}`, 302); } if (view === '' || view === 'tree') { const { ref, path } = view === '' ? { ref: ov.defaultBranch, path: '' } : split(rest); const t = await s.listTree(ref, path); if (!t) return P('Not found', `${head('')}

That folder isn't on ${esc(ref)}. It may have been removed by a vote.

`, { noindex: true }).then404(); if (t.kind === 'blob') return Response.redirect(`${SITE}/${row.name}/blob/${ref}/${path}`, 302); const crumbs = path.split('/').filter(Boolean).map((p, i, a) => ` / ${esc(p)}`).join(''); const rows = t.entries.map((e) => `${e.dir ? '📁' : '📄'} ${esc(e.name)}${e.dir ? '' : sizeText(e.size)}`).join(''); const readme = t.entries.find((e) => !e.dir && /^readme(\.md|\.markdown|\.txt)?$/i.test(e.name)); let readmeHtml = ''; if (readme) { const b = await s.readBlob(ref, (path ? path + '/' : '') + readme.name); if (b && isText(b.data)) { const dir = path ? path + '/' : ''; const text = new TextDecoder().decode(b.data); readmeHtml = `
${/\.txt$/i.test(readme.name) ? `
${esc(text)}
` : markdown(text, `/${row.name}/blob/${ref}/${dir}`, `/${row.name}/raw/${ref}/${dir}`)}
`; } } const top = view === '' ? `
${esc(org?.name || ownerName)} project

${esc(row.name.split('/')[1])}

${row.description ? `

${esc(row.description)}

` : ''}${cloneBox}${siteLink}

${(ov.commits as { n: number }).n || 0} commit${(ov.commits as { n: number }).n === 1 ? '' : 's'} pushed here · ${(ov.commits as { open: number }).open || 0} open to votes · ${(ov.commits as { removed: number }).removed || 0} removed by votes${ov.updatedAt ? ' · updated ' + ago(ov.updatedAt) : ''}

` : head(crumbs); const last = t.last ? `

Latest: ${esc(t.last.subject)} by ${esc(t.last.author)}, ${ago(t.last.time * 1000)}

` : ''; const extra = view === '' && row.name === 'branchwell/research' ? C.research() : ''; return P(view === '' ? row.name : `${path || ref} · ${row.name}`, `${top}
${tabs('files', ref)}${branchPicker(ref, 'tree')}
${last}${rows}
${readmeHtml}${extra}`, { description: row.description || `The ${row.name} repository on Branchwell. Open to pull and to push.`, noindex: view !== '' }); } if (view === 'blob' || view === 'raw') { const { ref, path } = split(rest); const b = await s.readBlob(ref, path); if (!b) return P('Not found', `${head('')}

That file isn't on ${esc(ref)}. It may have been removed by a vote.

`, { noindex: true }).then404(); const ext = (path.split('.').pop() || '').toLowerCase(); if (view === 'raw') { const type = MIME[ext] || (isText(b.data) ? 'text/plain; charset=utf-8' : 'application/octet-stream'); return new Response(b.data, { headers: { 'content-type': type, 'cache-control': row.private ? 'private, no-store' : 'public, max-age=300', 'content-security-policy': 'sandbox', 'x-content-type-options': 'nosniff', etag: `"${b.sha}"` } }); } const crumbs = path.split('/').map((p, i, a) => i === a.length - 1 ? ` / ${esc(p)}` : ` / ${esc(p)}`).join(''); const raw = `/${R}/raw/${esc(ref)}/${esc(path)}`; let content: string; if (/^(png|jpe?g|gif|webp|avif)$/.test(ext)) content = `
${esc(path)}
`; else if (!isText(b.data)) content = `

This file isn't text (${sizeText(b.data.length)}). Download it.

`; else { const text = new TextDecoder().decode(b.data); const dir = path.includes('/') ? path.slice(0, path.lastIndexOf('/') + 1) : ''; if (/^(md|markdown)$/.test(ext) && url.searchParams.get('plain') === null) content = `

Show the source

${markdown(text, `/${row.name}/blob/${ref}/${dir}`, `/${row.name}/raw/${ref}/${dir}`)}
`; else { const lines = text.replace(/\n$/, '').split('\n'); content = `
${lines.slice(0, 20000).map((l, i) => ``).join('')}
${i + 1}${esc(l) || ' '}
`; } } return P(`${path} · ${row.name}`, `${head(crumbs)}
${tabs('files', ref)}Raw ${sizeText(b.data.length)} on ${esc(ref)}
${content}`, { noindex: true }); } if (view === 'commits') { const { ref } = split(rest || ov.defaultBranch); const pageN = Math.max(0, parseInt(url.searchParams.get('page') || '0', 10) || 0); const lg = (await s.log(ref, pageN * 30, 30)) as { commits: unknown[]; more: boolean } | null; if (!lg) return P('Not found', `${head('')}

There's no branch called ${esc(ref)}. It may have been removed by a vote.

`, { noindex: true }).then404(); type CRow = { sha: string; subject: string; author: string; time: number; meta: { status: string; up: number; down: number; pusher: string; pushed_at: number; note: string } | null }; const commits = lg.commits as unknown as CRow[]; const mine: Record = me ? await s.myVotes(me.id, 'commit', commits.filter((c) => c.meta?.status === 'new').map((c) => c.sha)) : {}; const rows = commits.map((c) => { const m = c.meta; const who = m && m.pusher && m.pusher !== 'branchwell' ? `pushed by ${esc(m.pusher)}` : esc(c.author); const v = m && m.status === 'new' ? voteBox(row.name, 'commit', c.sha, m.up, m.down, mine[c.sha]) : m && (m.status === 'kept' || m.status === 'removed') ? `👍 ${m.up} 👎 ${m.down}` : ''; return `${esc(c.subject || '(no message)')} ${statusTag(m?.status)}
${c.sha.slice(0, 8)} ${who}, ${ago(c.time * 1000)}${v}`; }).join(''); const nav = `

${pageN > 0 ? `Newer` : ''}${lg.more ? `Older` : ''}

`; return P(`Commits on ${ref} · ${row.name}`, `${head(' / commits')}
${tabs('commits', ref)}${branchPicker(ref, 'commits')}

New commits are open to votes. 3 down takes one back out; 3 up keeps it for good. How votes work

${rows}
${nav}`, { noindex: true }); } if (view === 'commit') { const info = await s.commitInfo(rest); if (!info) return P('Not found', `${head('')}

We couldn't find that commit.

`, { noindex: true }).then404(); const m = info.meta as { status: string; up: number; down: number; pusher: string; pushed_at: number; note: string; branch: string } | null; const mine = me && m?.status === 'new' ? (await s.myVotes(me.id, 'commit', [info.sha]))[info.sha] : undefined; const voters = (info.voters as { handle: string; value: number }[]); const c = info.commit; const msgBody = c.message.split('\n').slice(1).join('\n').trim(); const diffs = (info.diffs as { path: string; status: string; before: string | null; after: string | null }[]).map((d) => `

${esc(d.path)} ${d.status}

${d.before === null || d.after === null ? '

Not a text file.

' : diffHtml(d.before, d.after)}
`).join(''); const more = info.files.length > info.diffs.length ? `

${info.files.length - info.diffs.length} more files changed.

` : ''; const noteLine = m?.status === 'removed' ? `
This commit was voted down and taken back out of ${esc(m.branch)}: ${esc(m.note || '')}.
` : m?.status === 'system' ? `
Branchwell made this commit to take ${esc((m.note || '').slice(0, 8))} back out after 3 votes down.
` : ''; return P(`${c.message.split('\n')[0]} · ${row.name}`, `${head(` / commits / ${info.sha.slice(0, 8)}`)}

${esc(c.message.split('\n')[0] || '(no message)')} ${statusTag(m?.status)}

${msgBody ? `
${esc(msgBody)}
` : ''}

${m && m.pusher !== 'branchwell' ? `Pushed by ${esc(m.pusher)} to ${esc(m.branch)} ${ago(m.pushed_at)} · ` : ''}written by ${esc(c.author.replace(/\s*<.*$/, ''))} · ${info.sha}${c.parents.length ? ` · parent ${c.parents[0].slice(0, 8)}` : ''}

${noteLine}${m?.status === 'new' ? `
${voteBox(row.name, 'commit', info.sha, m.up, m.down, mine)}
` : ''} ${voters.length ? `

Votes: ${voters.map((v) => `${esc(v.handle)} ${v.value > 0 ? '👍' : '👎'}`).join(', ')}

` : ''}

${info.files.length} file${info.files.length === 1 ? '' : 's'} changed

${diffs}${more}

Browse files at this commit

`, { noindex: true }); } if (view === 'branches') { type BRow = { name: string; status: string; up: number; down: number; created_by: string; created_at: number; removed_at: number; last_sha: string }; const all = ov.branches as unknown as BRow[]; const mine: Record = me ? await s.myVotes(me.id, 'branch', all.filter((b) => b.status === 'new').map((b) => b.name)) : {}; const rows = all.map((b) => `${b.status === 'removed' ? `${esc(b.name)}` : `${esc(b.name)}`} ${b.name === ov.defaultBranch ? 'main branch' : statusTag(b.status)}
opened by ${esc(b.created_by || 'unknown')} ${ago(b.created_at)}${b.removed_at ? ', removed ' + ago(b.removed_at) : ''} ${b.status === 'new' && b.name !== ov.defaultBranch ? voteBox(row.name, 'branch', b.name, b.up, b.down, mine[b.name]) : b.status === 'removed' || b.name === ov.defaultBranch ? '' : `👍 ${b.up} 👎 ${b.down}`}`).join(''); return P(`Branches · ${row.name}`, `${head(' / branches')}
${tabs('branches', ov.defaultBranch)}

Anyone can open a branch: git push origin HEAD:your-idea. 3 votes down removes a branch; 3 up keeps it. The main branch always stays.

${rows}
`, { noindex: true }); } return new Response('Not found', { status: 404 }); } void SECURITY;