tickets
All repositories: gitoria
9.4 KB
// lib/attachments.hl — FILES ATTACHED TO A COMMENT (tickets#27, mission 017): pictures and other files that come with a comment — from// the page (the Comments block's form inside the shared FilesUpload, face `commentWithFiles`) or the API (multipart/form-data, lib/multipart.hl).// Statics only, the server realm.// attachmentsTable pk @id index @event { event (events @id of the comment), ticket, project (projects @id: who may fetch),// user (users @id), n (its place in the comment, 0 …), name (cleaned), type (from the CONTENT), image (true =// a PNG / JPEG / GIF / WebP picture), size (bytes), file (the stored file's name), created, deleted (0, or when) }// THE BYTES: one file each in `filesDir` = storage/attachments/ (beside storage/mpackdb, so a deploy backup of storage/ has them;// TICKETS_ATTACHMENTS moves it), named by 32 random hex digits — never by the user's name.// LIMITS: at most `maxFiles` files per comment, `maxFileBytes` each (the page's FilesUpload says so before sending; the web framework's// uploadMax in project.hl is the same number), `maxCommentBytes` together. An empty file is refused.// THE CONTENT DECIDES THE TYPE: a picture is recognised by its first bytes (PNG, JPEG, GIF, WebP), a PDF too; a file that CLAIMS to be a// picture (its name or its type says png / jpeg / gif / webp) but is not one is refused. Everything else is a plain file, served as a// download. SVG and HTML are never served as such (no script can run from an attachment).// WHO MAY FETCH: the members of the ticket's project (a session, a user's API token, or the project's app key) — reading a ticket is// public, its attachments are not: a non-member sees the names and sizes only. A DELETED comment drops its attachments: their bytes// are removed from storage, the rows stay (marked deleted), the address answers 404. An EDIT keeps them (it changes the text only).import { MPackDB } from 'hl:mpackdb'import { writeFile, readBytes, mkDir, remove, exists } from 'hl:fs'import { randomBytes } from 'hl:crypto'import { now } from 'hl:time'import { env } from 'hl:proc'import { storageDir, countOf } from './util.hl'import { isMember } from './projects.hl'static attachmentsTable = new MPackDB(file = storageDir + '/attachments.db', primaryKey = '@id', indexes = ['@event'])static filesDir = env('TICKETS_ATTACHMENTS') != null ? env('TICKETS_ATTACHMENTS') : storageDir + '/../attachments'static maxFiles = 10static maxFileBytes = 10485760static maxCommentBytes = 26214400static pictureKinds = ['png', 'jpg', 'jpeg', 'gif', 'webp']static textKinds = ['txt', 'md', 'log', 'csv', 'json']// ---- checking what came in ---------------------------------------------------------------------------// `files` = a list of { name, type, bytes } (the face's uploads, the API's file parts). Answers { files } (checked, in order:// { name, type, image, size, bytes }) or { error, field }.static checkFiles = (files) => {out = []if (files == null) { return { files = out } }if (hlTypeName(files) != 'Hybrid' || files.length == null) { return { error = 'the attachments must be a list of files' field = 'files' } }if (files.length > maxFiles) { return { error = 'at most ' + maxFiles + ' files per comment (' + files.length + ' given)' field = 'files' } }let total = 0for (f of files) {if (f == null || hlTypeName(f) != 'Hybrid' || hlTypeName(f.bytes) != 'Bytes') { return { error = 'an attachment came without its bytes' field = 'files' } }let name = cleanName(f.name)let size = f.bytes.lengthif (size == 0) { return { error = name + ' is empty' field = 'files' } }if (size > maxFileBytes) { return { error = name + ' is too big: ' + size + ' bytes, a file may have at most 10 MB (' + maxFileBytes + ' bytes)' field = 'files' tooBig = true } }total = total + sizelet kind = kindOf(f.bytes, name)if (claimsPicture(name, f.type) && !kind.image) { return { error = name + ' is not a PNG, JPEG, GIF or WebP picture (its content was checked)' field = 'files' } }out.push({ name = name type = kind.type image = kind.image size = size bytes = f.bytes })}if (total > maxCommentBytes) { return { error = 'the files of one comment may have at most 25 MB together (' + total + ' bytes given)' field = 'files' tooBig = true } }return { files = out }}// the name shown and sent back: no folders, no control characters or quotes, at most 120 characters; '' → 'file'static cleanName = (raw) => {let s = raw == null ? '' : '' + rawcut = s.lastIndexOf('/') > s.lastIndexOf(BS) ? s.lastIndexOf('/') : s.lastIndexOf(BS)if (cut >= 0) { s = s.slice(cut + 1) }let out = ''let i = 0while (i < s.length) {let c = s.slice(i, i + 1)let k = c.charCodeAt(0)if (k >= 32 && k != 127 && c != '"' && c != BS) { out = out + c }i = i + 1}out = out.trim()if (out.length > 120) { out = out.slice(0, 120) }return out == '' ? 'file' : out}static BS = 'x\y'.slice(1, 2)static extOf = (name) => {dot = name.lastIndexOf('.')return dot > 0 ? name.slice(dot + 1).toLowerCase() : ''}static claimsPicture = (name, type) => {t = type == null ? '' : ('' + type).toLowerCase()return pictureKinds.includes(extOf(name)) || t == 'image/png' || t == 'image/jpeg' || t == 'image/gif' || t == 'image/webp'}// do the first bytes of `b` read `sig` (numbers; -1 = any byte)?static startsWithBytes = (b, sig, at) => {if (b.length < at + sig.length) { return false }let i = 0while (i < sig.length) {if (sig[i] >= 0 && b[at + i] != sig[i]) { return false }i = i + 1}return true}// THE TYPE FROM THE CONTENT: { type, image }static kindOf = (b, name) => {if (startsWithBytes(b, [137, 80, 78, 71, 13, 10, 26, 10], 0)) { return { type = 'image/png' image = true } }if (startsWithBytes(b, [255, 216, 255], 0)) { return { type = 'image/jpeg' image = true } }if (startsWithBytes(b, [71, 73, 70, 56, -1, 97], 0) && (b[4] == 55 || b[4] == 57)) { return { type = 'image/gif' image = true } }if (startsWithBytes(b, [82, 73, 70, 70], 0) && startsWithBytes(b, [87, 69, 66, 80], 8)) { return { type = 'image/webp' image = true } }if (startsWithBytes(b, [37, 80, 68, 70, 45], 0)) { return { type = 'application/pdf' image = false } }if (textKinds.includes(extOf(name))) { return { type = 'text/plain; charset=utf-8' image = false } }return { type = 'application/octet-stream' image = false }}// ---- writing ------------------------------------------------------------------------------------------// the checked files of comment `eventId` (ticket record `t`, by `user`): bytes to filesDir, one row each. Answers null or { error }.static storeFiles = (eventId, t, user, checked) => {if (checked.length == 0) { return null }mkDir(filesDir)let n = 0for (f of checked) {let file = randomBytes(16)writeFile(filesDir + '/' + file, f.bytes)if (!exists(filesDir + '/' + file)) { return { error = 'could not store ' + f.name } }id = attachmentsTable.put({ event = eventId ticket = t.id project = t.project user = user.id n = n name = f.name type = f.type image = f.image size = f.size file = file created = now() deleted = 0 })if (id == null) { return { error = 'could not store ' + f.name + ': ' + attachmentsTable.lastError() } }n = n + 1}return null}// a deleted comment drops its files: the bytes go, the rows stay markedstatic dropFiles = (eventId) => {for (a of liveRowsOf(eventId)) {remove(filesDir + '/' + a.file)rec = {}for (k of a.keys()) { rec[k] = a[k] }rec.deleted = now()attachmentsTable.update(a.id, rec)}}// ---- reading ------------------------------------------------------------------------------------------// the attachments of a comment that are still there, in their orderstatic liveRowsOf = (eventId) => {out = []found = attachmentsTable.find('event', eventId)if (countOf(found) == 0) { return out }for (a of found) { if (a.deleted == 0) { out.push(a) } }let i = 1while (i < out.length) {let cur = out[i]let j = i - 1while (j >= 0 && out[j].n > cur.n) {out[j + 1] = out[j]j = j - 1}out[j + 1] = curi = i + 1}return out}// what the JSON API and the pages show of each: { id, name, type, size, image, url } (url: relative, members only)static attachmentsOf = (eventId) => {out = []for (a of liveRowsOf(eventId)) { out.push({ id = a.id name = a.name type = a.type size = a.size image = a.image url = '/api/attachments/' + a.id }) }return out}// ---- serving ------------------------------------------------------------------------------------------// the attachment `id` for a reader: `user` (a users record, or null) or `keyProject` (the project @id of an app key, or null).// Answers { file: { bytes, type, name, image } } or { status, error }.static attachmentFor = (id, user, keyProject) => {a = id == null || hlTypeName(id) != 'String' || id == '' ? null : attachmentsTable.fetch(id)if (a == null || a.deleted != 0) { return { status = 404 error = 'no such attachment' } }if (user == null && keyProject == null) { return { status = 401 error = 'attachments are for the members of the project: log in, or send Authorization: Bearer <token>' } }ok = (user != null && isMember(a.project, user)) || (keyProject != null && keyProject == a.project)if (!ok) { return { status = 403 error = 'only the members of the project can fetch its attachments' } }path = filesDir + '/' + a.fileif (!exists(path)) { return { status = 404 error = 'the file of this attachment is gone' } }return { file = { bytes = readBytes(path) type = a.type name = a.name image = a.image } }}
Branches
Latest commits
- 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
- c1161469mission 013: GitHub pipe tables on ticket pages (lib/markdown.hl + View + CSS) and re-vendor hybriel master a832f73bmre
- a30b5d12mission brief (w13)mre
- b50a6f93w9 (tickets): re-vendor hybriel 9f912f3b (#146 emit in a lib static, #147) — the 12 live-push emits in lib/api.hl compile as they are; cold start (#148): tests wait TICKETS_COLD_MS for every start, deploy.sh gates browser + events and waits up to 120 s for the URL, container /tmp tmpfs + hybriel-cache volume; events-client stops at EVENTS_MAX inside a chunk; connect.mjs ports by env. bin/hybriel sha256 7421907868ac07d8a7d08296b083c6f8b20407d0e099ce4bebbf7ae053d9060a. Gates (8720–8739): browser 315/0 (+ all-cold 315/0), events 48/0 cold, connect 60/0, short-id 19/0; real-data copy old 0e8a41c vs new: 2,425 reads + 72 writes identical after masking ?v hashes, offline at, route order; event stream on the copy delivers. Not deployed.mre
- 43be6578w9: re-vendor hybriel master edfd400a; event stream imports sseStart/sseSend/sseAlive from hl:http1 (hybriel#144), useTransport gone; tools/import.hl plain declarations. BLOCKED: hybriel-native refuses `emit client` in a static (lib/api.hl) — the server does not compile on edfd400a, gates fail at start; scratch copy without those emits: events 48/0, gate 254 ok up to the first live pushmre
- 0e8a41caw6 (ticket #26): event stream for programs — GET /api/events (Server-Sent Events)mre
- bb64d57cmission 012 (ticket #25 API part): every /api/projects/<x>/… route takes the project's id (12-char record id) as well as its slug, same answers byte for byte; tickets stay under their project, no global /api/tickets/<x>. gate 315/0 (old code: the 13 id checks fail), connect 60/0, live-data copy old vs new 1,484 identical, slug vs id 772 identicalmre
- 7538b034mission 011 (ticket #25 web part): short page URLs /<slug> and /<slug>/<number>; /projects/<slug>, /projects/<slug>/<n>, /projects/<slug>/tickets/<n> and /tickets/<ref> answer 301 (current slug); slug pages moved behind hl:web's own routes after construction (they answered /__hl/* and /components/*.hl); reserved slugs refused; API paths unchanged. gate 293/0, connect 60/0, live-data copy 187/0, API old vs new: only page links differmre