tickets
All repositories: gitoria
14.8 KB
// lib/api-helpers.hl — the plumbing of the function routes (lib/api.hl): query strings, bodies, answers, who is// calling (token or app key), the Markdown Accept check, the small HTML page. Statics only; no topic logic here.import { Response } from 'hl:http1'import { jsonErrorAt } from './jsoncheck.hl'import { userOfBearer, ensureUser, userRecord, setUserName } from './users.hl'import { check } from './ident-access.hl'import { connectionOfKey, personOf } from './connections.hl'import { states, stateOf } from './tickets-helpers.hl'import { partsOf, isUtf8 } from './multipart.hl'import { maxCommentBytes, maxFiles } from './attachments.hl'// SECURITY HEADERS of every answer these function routes make (mission ST; pages are hl:web's): nothing is sniffed into a type it// is not, nothing is framed, no Referer leaves a page that was opened from an answer, and a CSP that allows nothing (an answer is data)static secHeaders = { 'X-Content-Type-Options' = 'nosniff' 'X-Frame-Options' = 'DENY' 'Referrer-Policy' = 'no-referrer' 'Content-Security-Policy' = "default-src 'none'; frame-ancestors 'none'" }// the same, plus `own` (the answer's own headers win)static hdr = (own) => {out = {}for (k of secHeaders.keys()) { out[k] = secHeaders[k] }for (k of own.keys()) { out[k] = own[k] }return out}static jsonHeaders = hdr({ 'Content-Type' = 'application/json; charset=utf-8' })// the largest JSON body the API reads (mission ST): jsoncheck.hl walks a body character by character IN HYBRIEL, so a multi-megabyte// body from any token holder held the single-threaded server for minutes. Texts are far smaller (a comment's files travel as multipart).static maxJsonBytes = 1048576static reply = (status, value) => {return new Response(JSON.stringify(value), { status = status headers = jsonHeaders })}static fail = (status, message) => { return reply(status, { error = message }) }// `?a=1&b=x` of a request path → { a = '1', b = 'x' } ('+' is a space; hl:http1// has already percent-decoded the path)static queryOf = (path) => {out = {}q = path.indexOf('?')if (q < 0) { return out }for (pair of path.slice(q + 1).split('&')) {if (pair != '') {eq = pair.indexOf('=')if (eq < 0) { out[pair] = '' } else { out[pair.slice(0, eq)] = pair.slice(eq + 1).replaceAll('+', ' ') }}}return out}// the request body as JSON, or null when it is notstatic bodyOf = (req) => {if (req.body == null || req.body == '') { return null }return JSON.parse(req.body)}// THE API IS STRICT (ticket #10): a malformed report must not be filed half-read. A body// is a JSON object whose keys are all in `required` or `optional`, every value is a// String, and every required one is non-empty after trimming. Answers null (fine) or// { error, field } — the first offence, naming the field.// (a list has no concat() in this build — NotCallable, hybriel #6's family)static allowedOf = (required, optional) => {all = []for (k of required) { all.push(k) }for (k of optional) { all.push(k) }return all.join(', ')}static bodyError = (b, required, optional) => {if (b == null || hlTypeName(b) != 'Hybrid' || b.length != null) {return { error = 'the body must be a JSON object' field = '' }}for (k of b.keys()) {// ticket #7: the author is the token's user — a body that still names one is refused// (not silently ignored), so a client learns that its field does nothingif (k == 'author') {return { error = "no field 'author' any more: the author is the user of your API token" field = 'author' }}if (!required.includes(k) && !optional.includes(k)) {return { error = "unknown field '" + k + "' (allowed: " + allowedOf(required, optional) + ')' field = k }}if (hlTypeName(b[k]) != 'String') {return { error = "field '" + k + "' must be a string, not " + hlTypeName(b[k]) field = k }}}for (k of required) {if (b[k] == null) { return { error = "field '" + k + "' is required" field = k } }if (b[k].trim() == '') { return { error = "field '" + k + "' must not be empty" field = k } }}return null}static refuse = (e) => { return reply(e.tooBig == true ? 413 : 400, e) }// ticket #7: an API write without a valid token (missing, malformed, unknown, revoked) → 401static unauthorized = () => { return unauthorizedFor('an API write') }// ticket #26: the event stream says what it is that needs the tokenstatic unauthorizedFor = (what) => {return new Response(JSON.stringify({ error = what + ' needs Authorization: Bearer <token> — log in with ident and create a token on /you' }), { status = 401 headers = hdr({ 'Content-Type' = 'application/json; charset=utf-8' 'WWW-Authenticate' = 'Bearer' }) })}// a POST body, checked: { body } or { bad } (bad = the 400 answer's value).// Invalid JSON is refused by jsoncheck.hl BEFORE JSON.parse ever sees it (ticket #15,// workaround for hybriel #12: an uncaught JSON.parse would answer 500 with source paths).static readBody = (req, required, optional) => {if (req.body != null && req.body != '' && req.body.length > maxJsonBytes) { return { bad = { error = 'the body is ' + req.body.length + ' characters: a JSON body may have at most ' + maxJsonBytes field = '' tooBig = true } } }if (req.body != null && req.body != '') {at = jsonErrorAt(req.body)if (at >= 0) { return { bad = { error = 'invalid JSON at character ' + at } } }}b = bodyOf(req)return { body = b bad = bodyError(b, required, optional) }}// a refusal of a topic function: 403 when the role is missing, else 400static denied = (r) => {if (r.forbidden == true) { return reply(403, { error = r.error field = r.field }) }return refuse({ error = r.error field = r.field })}// ---- who is calling --------------------------------------------------------------------------------// WRITES NEED A TOKEN (ticket #7): `Authorization: Bearer <token>` (users.hl; a logged-in user// makes tokens on /you). No / bad / revoked token → 401, checked BEFORE the body.// An IDENT ACCESS KEY (ident#27): `Authorization: Bearer idt_…` is asked of ident on every call (lib/ident-access.hl). The identity's// tickets user is the one its login made (users.hl ensureUser; made now when the identity never logged in here — a new user gets// the identity's name from ident as its display name, because nobody can type one for a key). `read` keys may only GET / HEAD (403// otherwise); a bad key is 401, ident not answering 503 (nothing is written). Answers null (not an idt_ header: the old ways go on),// { user } or { response } (the refusal).static identActorOf = (req) => {h = req.headers['authorization']if (h == null || hlTypeName(h) != 'String') { return null }t = h.trim()if (t.length < 12 || t.slice(0, 7).toLowerCase() != 'bearer ' || !t.slice(7).trim().startsWith('idt_')) { return null }who = check(req)if (!who.ok) {hs = who.status == 401 ? { 'Content-Type' = 'application/json; charset=utf-8' 'WWW-Authenticate' = 'Bearer' } : { 'Content-Type' = 'application/json; charset=utf-8' }return { response = new Response(JSON.stringify({ error = who.error }), { status = who.status headers = hdr(hs) }) }}if (who.access != 'write' && req.method != 'GET' && req.method != 'HEAD') {return { response = reply(403, { error = 'this access key is read-only' field = '' }) }}let u = ensureUser(who.identity)if (u == null) { return { response = reply(500, { error = 'could not store the user' field = '' }) } }if (u.name == '' && who.name != null && who.name != '') {setUserName(u.id, who.name)u = userRecord(u.id)}return { user = u }}// the answer for a call that has no good identity: the idt_ refusal, else the plain 401static authDenied = (a, what) => {if (a != null && a.response != null) { return a.response }return unauthorizedFor(what)}// the token's user of an API write, or null (→ 401); an idt_ key's refusal is { response }static apiUser = (req) => {ia = identActorOf(req)if (ia != null) { return ia.user != null ? ia.user : ia }return userOfBearer(req.headers['authorization'])}// WHO WRITES, for the endpoints an app's KEY may also use (ticket #21: create a ticket, comment, change the state):// { user } for a user's token, { conn } for a project key (connections.hl), { response } for a refused idt_ key, null = 401static apiAuth = (req) => {ia = identActorOf(req)if (ia != null) { return ia }h = req.headers['authorization']u = userOfBearer(h)if (u != null) { return { user = u } }c = connectionOfKey(h)return c != null ? { conn = c } : null}// the acting user inside project `projectId`: { user } or { response }. A key reaches ITS project only and names the// person by `X-Tickets-Identity`; the project's roles then decide as for any user.static actorIn = (auth, req, projectId) => {if (auth.user != null) { return { user = auth.user } }if (projectId == null || auth.conn.project != projectId) { return { response = reply(403, { error = 'this key belongs to another project' field = '' }) } }a = personOf(req.headers['x-tickets-identity'])if (a.error != null) { return { response = reply(403, { error = a.error field = '' }) } }return { user = a.user }}// ---- list filters ----------------------------------------------------------------------------------static stateFilter = (q) => {if (q.state == null || q.state == '') { return { state = null } }st = stateOf(q.state)if (st == null) { return { bad = fail(400, 'unknown state — one of: ' + states.join(', ')) } }return { state = st }}// the filters of a list, for the Markdown heading ('' = none)static filterLabel = (project, state) => {parts = []if (project != null) { parts.push('project ' + project) }if (state != null) { parts.push('state ' + state) }return parts.join(', ')}// ---- THE MARKDOWN READ VIEW's request side (ticket #6; the documents: lib/mdview.hl) -----------------// does the request ask for Markdown? `Accept` names text/markdown with q > 0 and prefers it to// application/json (a higher q, or the same q and listed first). No Accept / */* → JSON.static qOf = (part) => {let q = 1for (p of part.split(';')) {kv = p.trim()if (kv.startsWith('q=')) { q = toNumber(kv.slice(2)) }}return q == null ? 0 : q}static wantsMarkdown = (req) => {h = req.headers['accept']if (h == null || hlTypeName(h) != 'String') { return false }let md = -1let js = -1let mdAt = -1let jsAt = -1let i = 0for (part of h.toLowerCase().split(',')) {type = part.split(';')[0].trim()if (type == 'text/markdown' && mdAt < 0) {md = qOf(part)mdAt = i}if (type == 'application/json' && jsAt < 0) {js = qOf(part)jsAt = i}i = i + 1}if (md <= 0) { return false }if (js < 0) { return true }return md > js || (md == js && mdAt < jsAt)}static markdownReply = (text) => {return new Response(text, { status = 200 headers = hdr({ 'Content-Type' = 'text/markdown; charset=utf-8' 'Vary' = 'Accept' }) })}// ---- A COMMENT WITH FILES (tickets#27, mission 017): POST …/comments as multipart/form-data -----------------------------// fields: `text` (optional when there are files) and any number of file parts named `file` (or `files`, `file[]`, `files[]`), e.g.// `curl -H "Authorization: Bearer $T" -F 'text=390 px' -F [email protected] …/comments`. Answers { text, files ([{ name, type, bytes }]) }// or { bad } (the answer: 413 for a body over the limit, else 400 naming the field). The limits per file / per comment and the// content check are lib/attachments.hl's (addComment).static fileFields = ['file', 'files', 'file[]', 'files[]']static commentFormOf = (req) => {if (req.bytes != null && hlTypeName(req.bytes) == 'Bytes' && req.bytes.length > maxCommentBytes + 1048576) {return { bad = reply(413, { error = 'the body is ' + req.bytes.length + ' bytes: the files of one comment may have at most 25 MB together' field = 'files' }) }}p = partsOf(req)if (p.error != null) { return { bad = refuse({ error = p.error field = '' }) } }let text = nullfiles = []for (part of p.parts) {if (part.name == 'author') { return { bad = refuse({ error = "no field 'author' any more: the author is the user of your API token" field = 'author' }) } }if (fileFields.includes(part.name) && part.filename != null) {files.push({ name = part.filename type = part.type bytes = part.bytes })} else if (part.name == 'text' && part.filename == null) {if (text != null) { return { bad = refuse({ error = "field 'text' is given twice" field = 'text' }) } }if (!isUtf8(part.bytes)) { return { bad = refuse({ error = "field 'text' is not UTF-8" field = 'text' }) } }text = part.bytes.toString()} else {return { bad = refuse({ error = "unknown field '" + part.name + "' (allowed: text, and files as file=@path)" field = part.name }) }}}if (files.length > maxFiles) { return { bad = refuse({ error = 'at most ' + maxFiles + ' files per comment (' + files.length + ' given)' field = 'files' }) } }return { text = text != null ? text : '' files = files }}// ---- answers that are not JSON ---------------------------------------------------------------------// an attachment's bytes (tickets#27): a picture inline, any other file as a download; its type is the one its CONTENT showed// (lib/attachments.hl); nosniff + a sandbox policy, so nothing in it can run; private to the browser that fetched itstatic fileReply = (f) => {disp = (f.image ? 'inline' : 'attachment') + '; filename=' + DQ + asciiName(f.name) + DQ + "; filename*=UTF-8''" + encodeURIComponent(f.name)return new Response(f.bytes, { status = 200 headers = { 'Content-Type' = f.type 'Content-Disposition' = disp 'X-Content-Type-Options' = 'nosniff' 'Content-Security-Policy' = "default-src 'none'; img-src 'self'; style-src 'unsafe-inline'; sandbox" 'Cache-Control' = 'private, max-age=86400' 'Cross-Origin-Resource-Policy' = 'same-origin' } })}static DQ = '"'// a name for the plain `filename=` (ASCII only; the exact one rides in filename*)static asciiName = (name) => {let out = ''let i = 0while (i < name.length) {c = name.slice(i, i + 1)k = c.charCodeAt(0)out = out + (k >= 32 && k < 127 && c != '"' ? c : '_')i = i + 1}return out}// a refusal of /connect or /login/callback: the browser goes to the app's error page (components/problem.hl, tickets#42), which names the reason// by `code` (lib/problems.hl); `area` is 'login' or 'connect'static problemRedirect = (area, code) => {to = '/' + area + '/failed/' + codereturn new Response('continue at ' + to, { status = 302 headers = hdr({ 'Location' = to 'Cache-Control' = 'no-store' 'Content-Type' = 'text/plain; charset=utf-8' }) })}// a page that moved for good (301) / a page that names nothing (404), as plain textstatic moved = (to) => {return new Response('moved to ' + to, { status = 301 headers = hdr({ 'Location' = to 'Content-Type' = 'text/plain; charset=utf-8' }) })}static missing = (message) => { return new Response(message, { status = 404 headers = hdr({ 'Content-Type' = 'text/plain; charset=utf-8' }) }) }
Branches
Latest commits
- 0788e65f|||PR re-vendor Hybriel day72mre
- 8a7f475aMerge branch 'records-t33' into mainTickets
- e685d0c2|||PR records: PROCEDURES merge callmre
- b42aff2b|||PR records: GO 2026-11-23, workers L33 O34, PROCEDURES.mdmre
- ed091d44Merge branch 'records' into mainTickets
- 180c0cdb|||PR records: ticket move live (M32), hybriel#439mre
- 497cae7bMerge branch 'm32-move' into mainTickets
- 772e0696|||PR Allow project admins to move tickets between their projectsmre
- be92a560Merge branch 'records' into mainTickets
- 0daf2ea8|||PR records: PR-only workflow, #50 donemre
- 0185d0b6Log PR 1 deploymre
- f5bf16e2Mission 031: deploy PR 1mre
- c69cd5f3Merge branch 'pr-flow' into mainTickets
- cc56798cLog gitoria PR-only requestmre
- d876d0b2|||PR README: changes land as PRsmre
- fd83ac1fconductor: caramboleyo is the user, not owner/creatorApollo
- 3b858c91Log backup hard-link fixmre
- 7f6b37a0deploy.sh backup: tar --hard-dereference (hard links broke mpackdb sidecars on restore)mre
- e93711d9Log E30 livemre
- 59c02e4dMerge e30: preserve edited state note labels in Markdownmre