gitoria
All repositories: gitoria
10.8 KB
// lib/api.hl — THE FUNCTION ROUTES (project.hl wires them): thin wrappers — check the request and the session, call the// topic, answer. The plumbing (JSON / Markdown / plain answers, redirects, the ssh guard, `?next=`) is lib/api-helpers.hl.// /api/repos, /api/repos/:slug the public reads (repos.hl; Accept: text/markdown → the Markdown read view)// /login/callback the login button's return (users.hl)// /settings/connect, /settings/connected connecting a repo to a tickets project (tickets.hl)// /__git/keys, /__git/access what the sshd container asks (sshkeys.hl, repos.hl)// (The git protocol's routes are lib/transport.hl gitTransport.)// A route that WRITES THE SESSION gets the request and the framework's session store BY REFERENCE (`&req`, `&sessions`,// from project.hl): copied into a second call, the session inside `req` would be a copy too and the write would be lost.import { Response } from 'hl:http1'import { randomBytes } from 'hl:crypto'import { NL, px, slugOfHost } from './util.hl'import { userOfLoginCode } from './users.hl'import { repoRows, repoRow, repoBySlug, repoFor, orgFor, ownsRepo, mayPush, mayRead } from './repos.hl'import { fullNameError, repoDocument, listDocument } from './repos-helpers.hl'import { forwardOf } from './forwards.hl'import { userIdOfSession } from './users.hl'import { connectHref, finishConnect } from './tickets.hl'import { keyLine } from './sshkeys.hl'import { reply, fail, wantsMarkdown, markdownReply, textReply, goTo, sshGuard, repoOfRequest, safeNext } from './api-helpers.hl'// ---- the API: reads are public (creating a repo is a web action for now) ------------------------static apiRepos = (route, req) => {if (req.method != 'GET') { return fail(405, 'GET only') }rows = repoRows(userIdOfSession(req.session))if (wantsMarkdown(req)) { return markdownReply(listDocument(rows)) }return reply(200, { repos = rows })}static apiRepo = (route, req) => {if (req.method != 'GET') { return fail(405, 'GET only') }row = repoRow(route.params.slug, userIdOfSession(req.session))if (row == null) { return fail(404, 'no such repository') }if (wantsMarkdown(req)) { return markdownReply(repoDocument(row)) }return reply(200, row)}// ---- NOTHING ELSE (mission MG, as ident's notFoundPage): the last route of project.hl answers a path no route knows with the// shell's 404 page (components/notfound.hl) — status 404, the page rendered by the framework with the request's session and hoststatic notFoundPage = (route, req, &srv, pageComponent) => {m = { route = { pattern = route.route.pattern component = pageComponent } kind = 'component' params = { path = req.path } path = req.path }res = srv.page(m, req.session, srv.hostOf(req.headers['host']), srv.requestHeaders(req.headers))res.status = 404return res}// `/:orepo` (GO34): on an organization's address (one the viewer may see) the first segment is a repo's Readme page, rendered like the 404 page is (a function route:// a stray single-segment path on any other address keeps its real 404 status — /.env, /host.js, a private organization's /x)static orgRepoPage = (route, req, &srv, pageComponent, missingComponent) => {h = req.headers['host']label = slugOfHost(h == null ? '' : h.split(':')[0])if (label == '' || orgFor(label, userIdOfSession(req.session)) == null) { return notFoundPage(route, req, &srv, missingComponent) }m = { route = { pattern = route.route.pattern component = pageComponent } kind = 'component' params = { orepo = req.path.slice(1) } path = req.path }return srv.page(m, req.session, srv.hostOf(h), srv.requestHeaders(req.headers))}static notFoundApi = (route, req) => { return fail(404, 'no such endpoint') }// ---- THE LOGIN BUTTON'S RETURN (ident README "How apps use ident") ----------------------------// ident sends the browser back with ?ident_code= (and our ?next=); the code is exchanged here (users.hl userOfLoginCode),// the user goes into THIS browser's session (`req.session`, the cookie's — hybriel #11; minted when it brought none),// then → `?next=` (api-helpers.hl safeNext). A FAILED LOGIN is a page (components/loginfailed.hl): the reason is parked// in the session, then → /login/failed.static loginFailed = (&req, &sessions, why) => {let s = req.sessionfresh = s == nullif (fresh) { s = sessions.mint() }s.data.loginError = whysessions.save(s)res = new Response('login failed: ' + why, { status = 302 headers = { 'Location' = '/login/failed' 'Cache-Control' = 'no-store' 'Content-Type' = 'text/plain; charset=utf-8' 'X-Content-Type-Options' = 'nosniff' } })if (fresh) { res.headers['Set-Cookie'] = sessions.cookieHeader(s.id) }return res}static loginCallback = (route, &req, &sessions) => {if (req.method != 'GET') { return loginFailed(&req, &sessions, 'GET only') }q = req.query != null ? req.query : {}code = q.ident_codeif (code == null || code == '') { return loginFailed(&req, &sessions, 'ident sent no login code') }x = userOfLoginCode(code)if (x.error != null) { return loginFailed(&req, &sessions, x.error) }// THE SAME SESSION, NEVER SIGNED OUT (ident#28): a good code signs the session the browser already has in (a second tab or an installed// app may not store a new cookie, and a session we signed out would leave it anonymous); none yet → minted herelet s = req.sessionif (s == null) { s = sessions.mint() }s.user = { id = x.user.id }s.data.tag = randomBytes(16)s.data.loginError = nullsessions.save(s)res = new Response('logged in', { status = 302 headers = { 'Location' = safeNext(q.next) 'Cache-Control' = 'no-store' 'Content-Type' = 'text/plain; charset=utf-8' 'X-Content-Type-Options' = 'nosniff' 'Set-Cookie' = sessions.cookieHeader(s.id) } })return res}// ---- ONE LOGIN FOR THE MAIN ADDRESS AND EVERY REPO ADDRESS ---------------------------------------------------------------------// Nothing here: hl:web (batch 20) does it. The session cookie carries `Domain=.<host>` (project.hl sessionDomain); among several gitoriasid// cookies the signed-in one wins and is re-issued with the Domain (the stray host-only copy expires), and a signed-in cookie is re-issued when its// attributes change (a login from before the Domain was set moves to it on its next request) and otherwise once a day. Gate: tests/browser.mjs "gitoria#24".// ---- CONNECT A REPO TO A TICKETS PROJECT (gitoria#18; tickets.hl, components/settings.hl) ----------------------------// /settings/connect: the owner's click → a fresh nonce parked in the session (bound to the repo) → tickets' /connect.// /settings/connected: tickets' return with ?code&state → tickets.hl finishConnect (nonce, exchange, key stored per// repo) → back to /settings. A failure is a note on the settings page.static connectStart = (route, &req, &sessions) => {if (req.method != 'GET') { return fail(405, 'GET only') }repo = repoOfRequest(route, req)if (repo == null) { return fail(404, 'no such repository') }s = req.sessionif (s == null || !ownsRepo(repo.slug, s)) { return goTo(px(repo.slug) + '/settings') }nonce = randomBytes(16)s.data.connectState = repo.slug + '.' + nonces.data.connectNote = nullsessions.save(s)return goTo(connectHref(repo.slug, nonce))}// One log line for every end of the connect flow (docker logs of the gitoria container): "connect-back <slug> <outcome> ..." and// never the code, the state value or a key. `state` only says whether tickets brought one.static connectLog = (slug, outcome, hasState) => {console.log('connect-back ' + slug + ' ' + outcome + ' state=' + (hasState ? 'present' : 'absent'))}static notSignedInNote = 'The connection to tickets did not finish: this browser is not signed in to gitoria as the repo owner. Sign in and press Connect again.'static connectBack = (route, &req, &sessions) => {if (req.method != 'GET') { return fail(405, 'GET only') }repo = repoOfRequest(route, req)if (repo == null) { return fail(404, 'no such repository') }q = req.query != null ? req.query : {}hasState = q.state != nulllet s = req.sessionif (s == null || userIdOfSession(s) == null || !ownsRepo(repo.slug, s)) {// nothing is exchanged; the code is dropped. The browser is told why on the settings page: a session-less browser gets a fresh// session that carries the note (like loginFailed), a session that exists keeps itself and gets the notewhy = s == null ? 'no-session' : (userIdOfSession(s) == null ? 'session-not-signed-in' : 'not-owner')connectLog(repo.slug, 'refused reason=' + why, hasState)fresh = s == nullif (fresh) { s = sessions.mint() }s.data.connectNote = notSignedInNotesessions.save(s)res = goTo(px(repo.slug) + '/settings')if (fresh) { res.headers['Set-Cookie'] = sessions.cookieHeader(s.id) }return res}want = s.data.connectStates.data.connectState = nullnote = finishConnect(repo.slug, want, q)s.data.connectNote = note == '' ? null : notesessions.save(s)if (note == '') {connectLog(repo.slug, 'connected', hasState)} else if (q.error != null && q.code == null) {connectLog(repo.slug, 'tickets-error', hasState)} else if (want == null || want != repo.slug + '.' + q.state) {connectLog(repo.slug, 'state-mismatch', hasState)} else {connectLog(repo.slug, 'exchange-failed', hasState)}return goTo(px(repo.slug) + '/settings')}// ---- WHAT THE SSHD CONTAINER ASKS (ticket gitoria#7; docker/sshd) — only with the shared secret (api-helpers.hl sshGuard)// GET /__git/keys?type=<ssh-ed25519>&key=<base64> sshd AuthorizedKeysCommand: the authorized_keys line for a known key// (sshkeys.hl keyLine), empty for an unknown one// GET /__git/access?user=<id>&slug=<slug>&write=0|1 gitoria-shell before it starts git: `ok` or 403. Read = every repo (public);// write = the repo's owner only (repos.hl mayPush — the same rule as the token on HTTPS, transport.hl)static gitKeys = (route, req) => {no = sshGuard(req)if (no != null) { return no }q = req.query != null ? req.query : {}return textReply(200, keyLine(q.type, q.key))}static gitAccess = (route, req) => {no = sshGuard(req)if (no != null) { return no }q = req.query != null ? req.query : {}slug = q.slugif (slug == null || hlTypeName(slug) != 'String' || fullNameError(slug) != null) { return textReply(404, 'no such repository' + NL) }let repo = repoBySlug(slug)if (repo == null && forwardOf(slug) != null) { repo = repoBySlug(forwardOf(slug)) }// the asker is the key's user: a repo they may not see does not exist for them (404, as over HTTPS)if (repo == null || !mayRead(q.user, repo)) { return textReply(404, 'no such repository' + NL) }if (q.write == '1' && !mayPush(q.user, repo)) { return textReply(403, 'only the owner or a member of this repository can push to it' + NL) }// the sshd container runs git in the repo's real folder: tell it the name (it differs after a move)return textReply(200, 'ok ' + repo.slug + NL)}
Branches
- f1-broken-json
- f2-api-bugs
- gp-gate-ports
- heap-revert
- hl25-records
- ident-chooser-selector
- mainmain branch
- p51-public-pr-reads
- records-1112
- s25-no-session-on-login-error
- v59
- w52-person-approval
- w52b-approval-followup
- w52c-header-phone
- w53-pulls-speed-pr
- w54-repo-rename-pr
- w55-rename-org
- w56-owner-members
- w62-pr-close
- w63-force-push
- w64-org-slash
Latest commits
- c50d17efKeep function-route not-found style in shared stylesheetmre
- e42d78d3Preserve ticket state CSS and document function-route style gapmre
- c6b7154eWIP gitoria#26: move styles into nested component blocksmre
- 77a2c31cgitoria#31: plain declarations instead of needless let in lib/ and tools/ (103 let removed, 137 kept because reassigned); no other changemre
- 4b98ab62gitoria: an ident access key (idt_) works as the git password; read key clones only, bad key 401, ident down 503 (ident#27); gate tests/ident-access-gitoria.mjs in deploy.shmre
- 1185f686gitoria#36: a failed return from tickets shows a note on the settings page and leaves one log line per outcome; no code is exchangedmre
- 5d2c385agitoria: the sign-in callback keeps the session it finds and signs it in (same cookie, nothing signed out; ident#28); security gate 71+5 failing → 76 passed; deploy.sh runs tests/private.mjs toomre
- 241ef3f9deploy.sh: rebuild the sshd image before up -d (GO34c)mre
- 821cdbb1gitoria#34b: styles, create-repo tool, docs, push/ssh gates sign in through the selector, shots scriptmre
- a81abdc9gitoria#34: org page via function route, member-reachable orgs, selects, reportmre
- 17f031f0gitoria#34: private repos, organizations, members, move tool, gatemre
- 71b69343gitoria#23: the sidebar's Repositories link was a 404 after any in-page navigation (static menu re-evaluated publicUrl in the browser); the menu is an instance property now; gate taps it after a tab, folder, filemre
- 90b4f728gitoria#25: restore the homepage cache and the parsed-blocks cache (they store data under immutable keys, no HTML); the page key, the framework readme key and the textHash key stay removedmre
- a487248cgitoria#25: remove every cache that hid the page build (page key, Markdown render key, homepage cache, parsed-blocks cache) and the gate that only tested themmre
- 12f2f4fegitoria: re-vendor Hybriel set-day27b, a startup fault in on Error exits 1mre
- c21c084egitoria: write the standby service out in full so the boot gate can read the main servicemre
- e307d69agitoria: say what is per process during the hand-overmre
- f0cbe6a6gitoria: standby service on port 45014 and a deploy that hands over through it without a gapmre
- 727cd083gitoria#25: README: vendor notes for Hybriel c1b1010f and the page cachemre
- 61b72dedgitoria#25: re-vendor Hybriel master c1b1010f (W149 page cache), key the repo Readme page by slug and main commit, extend the readme-cache gatemre