tickets
All repositories: gitoria
12.0 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 } from './users.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'static jsonHeaders = { 'Content-Type' = 'application/json; charset=utf-8' }static 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 != '') {let 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(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 = { '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 != '') {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.// the token's user of an API write, or null (→ 401)static apiUser = (req) => { 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), null = 401 (checked before the body)static apiAuth = (req) => {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(';')) {let 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(',')) {let 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 = { '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) {let c = name.slice(i, i + 1)let k = c.charCodeAt(0)out = out + (k >= 32 && k < 127 && c != '"' ? c : '_')i = i + 1}return out}// a small HTML page (the login callback, /connect): a title and one messagestatic htmlPage = (status, title, text) => {body = '<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>tickets | ' + title + '</title><style>body{margin:0;padding:1.5rem 1rem;font:16px/1.5 system-ui,sans-serif;color:rgb(195, 200, 205);background:rgb(25, 30, 35)}main{max-width:34rem;margin:0 auto;display:grid;gap:1rem}h1{margin:0;font-size:1.3rem;color:rgb(245, 250, 255)}p{margin:0}a{color:#c586c0}.error{color:#f44747}</style></head><body><main><h1>' + title + '</h1><p id="error" class="error">' + text.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>') + '</p><p><a id="home" href="/">back to the tickets</a></p></main></body></html>'return new Response(body, { status = status headers = { 'Content-Type' = 'text/html; charset=utf-8' 'Cache-Control' = 'no-store' } })}// 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 = { 'Location' = to 'Content-Type' = 'text/plain; charset=utf-8' } })}static missing = (message) => { return new Response(message, { status = 404 headers = { 'Content-Type' = 'text/plain; charset=utf-8' } }) }
Branches
Latest commits
- 31cabfccmission 021: E2E script, report, LOG, STATUSmre
- 6aea8683editor look: .empty rule only for p.empty, files off where tickets has no upload, state note one line, events test scrolls the editor into view; synced md-editor (components d702d76+6f27ad3); gate 377/0, events 52/0mre
- dce6ffa6Merge branch 'w28-deflake'mre
- 536092a1tickets (mission 019): de-flake the m016 comment clicks (B: unliked) — calmClick waits until the button stops moving; test only, no app changemre
- 9c5fd42amission 020: attachments E2E proof (lisbeth Chrome, real-data copy), reportmre
- 1206404fREADME attachments, report 018, LOG/STATUSmre
- 3d9e7f3ctests: m017 gate fixes (list count, waits before delete clicks); gate 373/0mre
- dd41d5bcre-sync components 15be2ac; mission 018mre
- 420ad1bbtickets (mission 017 WIP, tickets#27): comment attachments — lib/attachments.hl (storage/attachments, limits, type by content, members-only GET /api/attachments/:id, delete drops, edit keeps), multipart POST …/comments (lib/multipart.hl), Respond block in FilesUpload (blocks verbatim from components w27c 1f8d79d), gate m017 checks written (not yet run); report, LOG, STATUSmre
- a7a1380dmission brief 017mre
- f83d9c0dtickets (mission 016): report reports/016-comments-block.md, LOG, STATUS, README gate countmre
- eef80f55tickets (mission 016): comments through the shared Comments block (layouts#2) — edit (author, earlier versions kept), delete (author, asks; leaves one line in the history), like (members, toggle) on the server (lib/comments.hl, append-only tables), faces + API …/comments/:comment/{edit,delete,like}, push commentChanged; every run of comments is a block in place in the history; Markdown fields on the Hybriel MdEditor (shared/md-editor.js retired: it took over the block's <md-editor>); blocks copied verbatim from components.hybriel 9db927d (tools/sync-components.sh); gates browser 351/0 (old 326/0), events 52/0 (old 52/0)mre
- eb7aeeb9mission brief 016mre
- e4c34759paths: projects moved into /media/STORAGE/projects/WorldAPI/mre
- 26efb23freport w6-events (events test)mre
- c6bfab04mission 015: re-vendor Hybriel 0f396652 (static build), reportmre
- b7ec5981mission brief 015mre
- 5dc68731docker-compose: init: true (hybriel#156, PID 1 ignored SIGTERM, every restart waited 10 s)mre
- 8a460b16mission 014: Apollo's 'stream opened right after the start gets no live events' is not a tickets bug — events.mjs checks early streamsmre
- 6309ca81mission brief 014mre