tickets
All repositories: gitoria
10.8 KB
// lib/connections.hl — AN APP IS CONNECTED TO ONE PROJECT (ticket tickets.worldapi.org#21; first app: gitoria).// Statics only. One hl:mpackdb table beside the others (storage/mpackdb/connections.db, UUID keys)://// connectionsTable pk @id index nonce, hash, codeHash, project// { status, nonce, app, label, returnUrl, state, project, createdBy, codeHash, expires, hash, created }//// THE FLOW (README "Connecting an app"):// 1. the app sends the browser to <tickets>/connect?app=gitoria&label=<owner/repo>&return=<url>&state=<opaque>// → a REQUEST (status 'request', an unguessable nonce) and a redirect to /connect/<nonce> (components/connect.hl).// 2. the person logs in (ident), picks a project they are ADMIN of — or makes a new one — and confirms.// The request becomes a connection (status 'waiting') with a ONE-TIME CODE (5 minutes); the page links back to// `return?code=<code>&state=<state>`.// 3. the app exchanges the code on the server: POST /api/connect/exchange { code } → { key, project }.// The connection is 'active'; only the sha256 of the key is stored (`tktc_` + 48 hex, shown once).// 4. the key acts inside THAT ONE project only (lib/api-helpers.hl apiAuth / actorIn): create tickets, comment, change state.// Every write names the person: header `X-Tickets-Identity: <ident public id>`; the person is a tickets user// (they logged in here once and chose a name) and the project's ROLES apply to them as to a token.// 5. the project page shows "connected to <app>: <label>"; an admin's "Disconnect" deletes the row — the key is dead at once.// The return URL is the app's: only https on worldapi.org (and its subdomains) — or an origin listed in// TICKETS_CONNECT_ORIGINS (comma separated, e.g. http://127.0.0.1:8700 for a dev copy). The page shows the host.import { MPackDB } from 'hl:mpackdb'import { now } from 'hl:time'import { randomBytes, sha256 } from 'hl:crypto'import { env } from 'hl:proc'import { storageDir, first, countOf, isHex, plainError } from './util.hl'import { isIdentId, userOfIdentity, nameOfUser, publicUrl } from './users.hl'import { projectRecord, projectRecords, isAdminOf, createProject, userOk, notAdmin } from './projects.hl'static connectionsTable = new MPackDB(file = storageDir + '/connections.db', primaryKey = '@id', indexes = ['nonce', 'hash', 'codeHash', 'project'])static requestTtlMs = 3600000static codeTtlMs = 300000static extraOrigins = () => {v = env('TICKETS_CONNECT_ORIGINS')out = []if (v == null || v.trim() == '') { return out }for (o of v.split(',')) { if (o.trim() != '') { out.push(o.trim()) } }return out}// the characters a return URL may hold: URL-safe, no spaces, no quotes, no '#' (the code goes in the query)static urlChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~/?&=%+,;:@!$()*'// the host (with port) of an absolute URL: everything between '://' and the next '/' or '?'static authorityOf = (url) => {at = url.indexOf('://')if (at < 0) { return '' }rest = url.slice(at + 3)let end = rest.lengths = rest.indexOf('/')if (s >= 0 && s < end) { end = s }q = rest.indexOf('?')if (q >= 0 && q < end) { end = q }return rest.slice(0, end)}// null when the URL may be an app's return address, else the reasonstatic returnError = (url) => {if (url == null || hlTypeName(url) != 'String' || url == '') { return 'the app sent no return address' }if (url.length > 500) { return 'the return address is too long' }let i = 0while (i < url.length) {if (!urlChars.includes(url[i])) { return 'the return address holds a character that is not allowed' }i = i + 1}for (o of extraOrigins()) {if (url == o || url.startsWith(o + '/') || url.startsWith(o + '?')) { return null }}if (!url.startsWith('https://')) { return 'the return address must be https on worldapi.org' }host = authorityOf(url)if (host == '' || host.includes('@') || host.includes(':')) { return 'the return address has an unusual host' }if (host != 'worldapi.org' && !host.endsWith('.worldapi.org')) { return 'the return address must be on worldapi.org' }return null}static hostOf = (url) => { return authorityOf(url) }static sepOf = (url) => { return url.includes('?') ? '&' : '?' }// ---- 1. the request ---------------------------------------------------------------------------// answers { nonce } or { error }static createRequest = (app, label, returnUrl, state) => {a = app == null ? '' : ('' + app).trim()if (a == '') { return { error = 'the app sent no name' } }let bad = plainError(a, 60, 'the app name')if (bad == null) { bad = plainError(label == null ? '' : label, 100, 'the label') }if (bad == null) { bad = plainError(state == null ? '' : state, 200, 'the state') }if (bad == null) { bad = returnError(returnUrl) }if (bad != null) { return { error = bad } }let nonce = randomBytes(16)id = connectionsTable.put({ status = 'request' nonce = nonce app = a label = label == null ? '' : label.trim() returnUrl = returnUrl state = state == null ? '' : state project = '' createdBy = '' codeHash = '' hash = '' expires = now() + requestTtlMs created = now() })if (id == null) { return { error = 'could not store the request: ' + connectionsTable.lastError() } }return { nonce = nonce }}// the open request of a nonce, or null (unknown, used, expired)static requestOf = (nonce) => {if (!isHex(nonce, 64)) { return null }c = first(connectionsTable.find('nonce', nonce))if (c == null || c.status != 'request' || c.expires < now()) { return null }return c}// what the connect page shows of a requeststatic requestView = (c) => {return { app = c.app label = c.label hasLabel = c.label != '' host = hostOf(c.returnUrl) }}// the projects a user is an ADMIN of: [{ id, title, slug }]static adminProjects = (user) => {out = []if (user == null) { return out }for (p of projectRecords()) { if (isAdminOf(p.id, user)) { out.push({ id = p.id title = p.title slug = p.slug }) } }return out}// ---- 2. the confirmation ----------------------------------------------------------------------// `projectId` '' = make a new project titled `title` (the person becomes its admin). Answers { error, forbidden? } or// { url (back to the app, with the one-time code), project (title), slug }static confirmRequest = (nonce, user, projectId, title) => {c = requestOf(nonce)if (c == null) { return { error = 'this request is used up or expired — start again from the app' } }if (!userOk(user)) { return { error = 'log in with ident and choose a display name first' } }let p = nullif (projectId == null || projectId == '') {r = createProject(user, title, '', '')if (r.error != null) { return { error = r.error } }p = projectRecord(r.project.id)} else {p = projectRecord('' + projectId)if (p == null) { return { error = 'no such project' } }if (!isAdminOf(p.id, user)) { return notAdmin }}// a second connection of the same app and label to the same project replaces the first: its key diesfor (o of connectionsOf(p.id, true)) { if (o.app == c.app && o.label == c.label && o.id != c.id) { connectionsTable.delete(o.id) } }code = randomBytes(24)c.status = 'waiting'c.nonce = ''c.project = p.idc.createdBy = user.idc.codeHash = sha256(code)c.expires = now() + codeTtlMsconnectionsTable.update(c.id, c)let url = c.returnUrl + sepOf(c.returnUrl) + 'code=' + codeif (c.state != '') { url = url + '&state=' + encodeURIComponent(c.state) }return { url = url project = p.title slug = p.slug }}// ---- 3. the exchange --------------------------------------------------------------------------// answers { key, project (slug), title, api } or { error }static exchangeConnectCode = (code) => {if (!isHex(code, 200)) { return { error = 'that is not a connection code' } }c = first(connectionsTable.find('codeHash', sha256(code)))if (c == null || c.status != 'waiting' || c.expires < now()) { return { error = 'unknown, used or expired code — connect again' } }p = projectRecord(c.project)if (p == null) { return { error = 'the project is gone' } }let key = 'tktc_' + randomBytes(24)c.status = 'active'c.hash = sha256(key)c.codeHash = ''c.expires = 0c.connected = now()connectionsTable.update(c.id, c)return { key = key project = p.slug title = p.title api = publicUrl + '/api/projects/' + p.slug }}// ---- 4. the key -------------------------------------------------------------------------------static isKeyHeader = (header) => {if (header == null || hlTypeName(header) != 'String') { return false }h = header.trim()return (h.startsWith('Bearer ') || h.startsWith('bearer ')) && h.slice(7).trim().startsWith('tktc_')}// `Authorization: Bearer tktc_…` → the ACTIVE connection, or nullstatic connectionOfKey = (header) => {if (!isKeyHeader(header)) { return null }key = header.trim().slice(7).trim()if (key.length != 53) { return null }c = first(connectionsTable.find('hash', sha256(key)))if (c == null || c.status != 'active') { return null }return c}// the person an app write names (`X-Tickets-Identity`): { user } or { error }static personOf = (identity) => {if (identity == null || hlTypeName(identity) != 'String' || !isIdentId(identity.trim())) {return { error = 'a write through a connection names the person: header X-Tickets-Identity: <their ident id>' }}u = userOfIdentity(identity.trim())if (u == null || u.name == '') { return { error = 'that person has not logged in to tickets yet — they log in once and choose a display name' } }return { user = u }}// ---- 5. the project page ----------------------------------------------------------------------// the connections of a project: [{ id, app, label, by, when }]; `all` = also the waiting onesstatic connectionsOf = (projectId, all) => {out = []rows = connectionsTable.find('project', projectId)if (countOf(rows) == 0) { return out }for (c of rows) { if (all || c.status == 'active') { out.push(c) } }return out}static connectionRows = (projectId) => {out = []for (c of connectionsOf(projectId, false)) {out.push({ id = c.id app = c.app label = c.label hasLabel = c.label != '' by = nameOfUser(c.createdBy) text = c.app + (c.label != '' ? ': ' + c.label : '') })}return out}// an admin ends a connection; the key is dead at once. answers { connections } or { error, forbidden? }static disconnect = (projectId, actor, connectionId) => {p = projectRecord(projectId)if (p == null) { return { error = 'no such project' } }if (!userOk(actor)) { return { error = 'log in with ident and choose a display name first' } }if (!isAdminOf(p.id, actor)) { return notAdmin }if (connectionId == null || hlTypeName(connectionId) != 'String' || connectionId == '') { return { error = 'no such connection' } }c = connectionsTable.fetch(connectionId)if (c == null || c.project != p.id) { return { error = 'no such connection' } }connectionsTable.delete(c.id)return { connections = connectionRows(p.id) }}
Branches
Latest commits
- d74a5482sync components.hybriel 134b4e3: MdEditor builds an editor put into the page at once, redraws a surface put in anew (F5, hybriel#211)mre
- 9d02c540sync components.hybriel 6b0936a: the 'edited' foldable drops the theme's border and marginmre
- 22751914sync components.hybriel 8d79ff7: bubble hugs its content, quiet 'edited' label; gate checksmre
- c8452453sync components 9a: shared Icon (icons/icons.hl), md-editor toolbar icons + single focus ring (components f4-icons ba96735)mre
- 52ba11e8sync-components: copy icons/icons.hl + README (F4); testsmre
- 138d198dmd-editor.hl: verbatim copy of components f3-mdvalue (an older text handed back is kept)mre
- 18d2df60md-editor.hl: verbatim copy of components f3-mdvalue (an outside value change is shown by the editor)mre
- f6764bedreports/H1-hydrate.mdmre
- 1bbbf0edtests/browser.mjs: wait for hydration before clicking the login button on / (device B)mre
- 6f503cfctests/cdp.mjs: HL_CPU_THROTTLE=<rate> optional CPU throttling for gate runsmre
- e17e2855re-vendor Hybriel 5406d146 (hl:web batches 9+10: #72 emits while the socket is closed delivered after reconnect, browser boot linear, faster list appends; contains int 6–14 + m406)mre
- a6ddccd2re-vendor Hybriel 6f8a0689 (int 6–11: streaming cursors, #203 index heal + close() fix, fd403 listDir/cursor fds, hl:time browser side, hl:web batches 5+6)mre
- 81e036b7docker-compose: nofile 65536 (Hybriel int 6+ boot opened >1024 files in the tracker)mre
- 5d8d2cf6deploy: backup copies index files first and *.mpack data last (hot-copy skew, hybriel #203)mre
- 58e8c02cmission 024: report, LOG, STATUS, e2e fixmre
- 50778073tests/e2e-route-marker.mjs: first paint marker, comments post/edit redrawmre
- c5203298mission 024: MainMenu marks the page from the route (layouts 0bcc629 main-menu.hl); browser-side marker removed; gate: marker in the server HTMLmre
- b1a4c270re-vendor Hybriel master f9614007: bin/ (git-ignored) and plugins wholemre
- 866397a0mission 023: theme from layouts 76f99f6 (current marker, menu count badge), components from 3794c59 (MdEditor keys); Inbox count as badge, current by address; gates and E2E; reportmre
- 7ed2e5e5deploy.sh: a gate without a 'passed,' line (check-theme) no longer ends the script silently (grep under pipefail), as gitoria/layoutsmre