tickets
All repositories: gitoria
9.1 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 (tickets#37): anyone who may see the comment the file belongs to. Reading a ticket and its comments is public, so the// files are too: no sign-in needed (a session, a token or an app key is accepted but not required). Only an unknown file, or one whose// comment was deleted, answers 404. 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'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, open to everyone who sees the comment)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 any reader (the comment it belongs to is public, so no sign-in is needed).// Answers { file: { bytes, type, name, image } } or { status, error }.static attachmentFor = (id) => {a = id == null || hlTypeName(id) != 'String' || id == '' ? null : attachmentsTable.fetch(id)if (a == null || a.deleted != 0) { return { status = 404 error = 'no such attachment' } }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
- 8a69999cident#28: /login/callback never signs out the session it finds; a valid code puts the user on the same sessionmre
- 337e9b21tickets#37: a comment's files are open to everyone who can read the commentmre
- 1800600ftickets: write the standby service out in full so the boot gate can read the main servicemre
- 8179d287tickets: standby service on its port plus 10 and a deploy that hands over through it without a gapmre
- 0398145ctickets: the table grid rule is marked functional for check-thememre
- 40fddc20tickets takes components e54f83a: tables get thin grey lines from the theme, desktop toolbar stays one row with the Table button, F4 check counts 11 buttonsmre
- c1b77d61tickets#35: text typed before the editor is built is taken in once by the build (the input handler no longer writes it to the field first, which doubled the first letters); the gate failure shows the surfacemre
- 32bf1873tickets#35: the gate types right after the load with the CPU slowed, no waitingmre
- 64ea9ca2tickets#35: text typed into the reply editor before the page has finished starting is kept; the gate types right after loadmre
- ccd3a327tickets: the security gate expects frame-src to be exactly the ident address (the sign-in frame), still no wildcard or selfmre
- 4348dbabident#31: the selector's sign-in returns to the page the user started on (return attribute = the login callback with next), gate checkmre
- 66ef3005Merge branch 'iw-ident-widget'mre
- bc0ad663tickets: a gap between your name and Log out in the phone header (they touched); gate checks itmre
- 2f818d46UX2: report, LOG line, e2e fixes, gate pause after loadmre
- af3ef7c4gate: the legacy state line says progressmre
- 62480a00tickets#33: a state change with a note is a comment card in the feed (same framework rendering, can be liked, edited, deleted), its state line stands alone; gate checks for a new comment with and without a state change, at once and after a reloadmre
- 4ae80007UX: Respond is one composer (state in its footer, button says what happens); New ticket / New project windows in the list heading row; project form shared; theme copied from layouts; gates and a lisbeth e2emre
- f03b438atickets header: the selector alone top right plus your name and Log out as before the theme missions; the user icon is gonemre
- 81f10e4eident selector back in the header (creator 2026-10-24): selector top right signed in and out on phone and desktop, no second Log in button, new gate checks (WIP: gates not re-run after the last edits)mre
- e9f428e7tools: reown-authors (tracker#36: every author that is not Caramboleyo or Apollo becomes the project's conductor; antcolony, miserit-anthar, hybrilior, termuplex stay) and a read-only author surveymre