gitoria

tickets

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit6aea86836aea8683editor 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/0mre6aea8683/lib/attachments.hl

9.4 KB

  1. // lib/attachments.hl — FILES ATTACHED TO A COMMENT (tickets#27, mission 017): pictures and other files that come with a comment — from
  2. // the page (the Comments block's form inside the shared FilesUpload, face `commentWithFiles`) or the API (multipart/form-data, lib/multipart.hl).
  3. // Statics only, the server realm.
  4. // attachmentsTable pk @id index @event { event (events @id of the comment), ticket, project (projects @id: who may fetch),
  5. // user (users @id), n (its place in the comment, 0 …), name (cleaned), type (from the CONTENT), image (true =
  6. // a PNG / JPEG / GIF / WebP picture), size (bytes), file (the stored file's name), created, deleted (0, or when) }
  7. // THE BYTES: one file each in `filesDir` = storage/attachments/ (beside storage/mpackdb, so a deploy backup of storage/ has them;
  8. // TICKETS_ATTACHMENTS moves it), named by 32 random hex digits — never by the user's name.
  9. // LIMITS: at most `maxFiles` files per comment, `maxFileBytes` each (the page's FilesUpload says so before sending; the web framework's
  10. // uploadMax in project.hl is the same number), `maxCommentBytes` together. An empty file is refused.
  11. // 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
  12. // 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
  13. // download. SVG and HTML are never served as such (no script can run from an attachment).
  14. // 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
  15. // public, its attachments are not: a non-member sees the names and sizes only. A DELETED comment drops its attachments: their bytes
  16. // are removed from storage, the rows stay (marked deleted), the address answers 404. An EDIT keeps them (it changes the text only).
  17. import { MPackDB } from 'hl:mpackdb'
  18. import { writeFile, readBytes, mkDir, remove, exists } from 'hl:fs'
  19. import { randomBytes } from 'hl:crypto'
  20. import { now } from 'hl:time'
  21. import { env } from 'hl:proc'
  22. import { storageDir, countOf } from './util.hl'
  23. import { isMember } from './projects.hl'
  24. static attachmentsTable = new MPackDB(file = storageDir + '/attachments.db', primaryKey = '@id', indexes = ['@event'])
  25. static filesDir = env('TICKETS_ATTACHMENTS') != null ? env('TICKETS_ATTACHMENTS') : storageDir + '/../attachments'
  26. static maxFiles = 10
  27. static maxFileBytes = 10485760
  28. static maxCommentBytes = 26214400
  29. static pictureKinds = ['png', 'jpg', 'jpeg', 'gif', 'webp']
  30. static textKinds = ['txt', 'md', 'log', 'csv', 'json']
  31. // ---- checking what came in ---------------------------------------------------------------------------
  32. // `files` = a list of { name, type, bytes } (the face's uploads, the API's file parts). Answers { files } (checked, in order:
  33. // { name, type, image, size, bytes }) or { error, field }.
  34. static checkFiles = (files) => {
  35. out = []
  36. if (files == null) { return { files = out } }
  37. if (hlTypeName(files) != 'Hybrid' || files.length == null) { return { error = 'the attachments must be a list of files' field = 'files' } }
  38. if (files.length > maxFiles) { return { error = 'at most ' + maxFiles + ' files per comment (' + files.length + ' given)' field = 'files' } }
  39. let total = 0
  40. for (f of files) {
  41. if (f == null || hlTypeName(f) != 'Hybrid' || hlTypeName(f.bytes) != 'Bytes') { return { error = 'an attachment came without its bytes' field = 'files' } }
  42. let name = cleanName(f.name)
  43. let size = f.bytes.length
  44. if (size == 0) { return { error = name + ' is empty' field = 'files' } }
  45. 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 } }
  46. total = total + size
  47. let kind = kindOf(f.bytes, name)
  48. 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' } }
  49. out.push({ name = name type = kind.type image = kind.image size = size bytes = f.bytes })
  50. }
  51. if (total > maxCommentBytes) { return { error = 'the files of one comment may have at most 25 MB together (' + total + ' bytes given)' field = 'files' tooBig = true } }
  52. return { files = out }
  53. }
  54. // the name shown and sent back: no folders, no control characters or quotes, at most 120 characters; '' → 'file'
  55. static cleanName = (raw) => {
  56. let s = raw == null ? '' : '' + raw
  57. cut = s.lastIndexOf('/') > s.lastIndexOf(BS) ? s.lastIndexOf('/') : s.lastIndexOf(BS)
  58. if (cut >= 0) { s = s.slice(cut + 1) }
  59. let out = ''
  60. let i = 0
  61. while (i < s.length) {
  62. let c = s.slice(i, i + 1)
  63. let k = c.charCodeAt(0)
  64. if (k >= 32 && k != 127 && c != '"' && c != BS) { out = out + c }
  65. i = i + 1
  66. }
  67. out = out.trim()
  68. if (out.length > 120) { out = out.slice(0, 120) }
  69. return out == '' ? 'file' : out
  70. }
  71. static BS = 'x\y'.slice(1, 2)
  72. static extOf = (name) => {
  73. dot = name.lastIndexOf('.')
  74. return dot > 0 ? name.slice(dot + 1).toLowerCase() : ''
  75. }
  76. static claimsPicture = (name, type) => {
  77. t = type == null ? '' : ('' + type).toLowerCase()
  78. return pictureKinds.includes(extOf(name)) || t == 'image/png' || t == 'image/jpeg' || t == 'image/gif' || t == 'image/webp'
  79. }
  80. // do the first bytes of `b` read `sig` (numbers; -1 = any byte)?
  81. static startsWithBytes = (b, sig, at) => {
  82. if (b.length < at + sig.length) { return false }
  83. let i = 0
  84. while (i < sig.length) {
  85. if (sig[i] >= 0 && b[at + i] != sig[i]) { return false }
  86. i = i + 1
  87. }
  88. return true
  89. }
  90. // THE TYPE FROM THE CONTENT: { type, image }
  91. static kindOf = (b, name) => {
  92. if (startsWithBytes(b, [137, 80, 78, 71, 13, 10, 26, 10], 0)) { return { type = 'image/png' image = true } }
  93. if (startsWithBytes(b, [255, 216, 255], 0)) { return { type = 'image/jpeg' image = true } }
  94. if (startsWithBytes(b, [71, 73, 70, 56, -1, 97], 0) && (b[4] == 55 || b[4] == 57)) { return { type = 'image/gif' image = true } }
  95. if (startsWithBytes(b, [82, 73, 70, 70], 0) && startsWithBytes(b, [87, 69, 66, 80], 8)) { return { type = 'image/webp' image = true } }
  96. if (startsWithBytes(b, [37, 80, 68, 70, 45], 0)) { return { type = 'application/pdf' image = false } }
  97. if (textKinds.includes(extOf(name))) { return { type = 'text/plain; charset=utf-8' image = false } }
  98. return { type = 'application/octet-stream' image = false }
  99. }
  100. // ---- writing ------------------------------------------------------------------------------------------
  101. // the checked files of comment `eventId` (ticket record `t`, by `user`): bytes to filesDir, one row each. Answers null or { error }.
  102. static storeFiles = (eventId, t, user, checked) => {
  103. if (checked.length == 0) { return null }
  104. mkDir(filesDir)
  105. let n = 0
  106. for (f of checked) {
  107. let file = randomBytes(16)
  108. writeFile(filesDir + '/' + file, f.bytes)
  109. if (!exists(filesDir + '/' + file)) { return { error = 'could not store ' + f.name } }
  110. 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 })
  111. if (id == null) { return { error = 'could not store ' + f.name + ': ' + attachmentsTable.lastError() } }
  112. n = n + 1
  113. }
  114. return null
  115. }
  116. // a deleted comment drops its files: the bytes go, the rows stay marked
  117. static dropFiles = (eventId) => {
  118. for (a of liveRowsOf(eventId)) {
  119. remove(filesDir + '/' + a.file)
  120. rec = {}
  121. for (k of a.keys()) { rec[k] = a[k] }
  122. rec.deleted = now()
  123. attachmentsTable.update(a.id, rec)
  124. }
  125. }
  126. // ---- reading ------------------------------------------------------------------------------------------
  127. // the attachments of a comment that are still there, in their order
  128. static liveRowsOf = (eventId) => {
  129. out = []
  130. found = attachmentsTable.find('event', eventId)
  131. if (countOf(found) == 0) { return out }
  132. for (a of found) { if (a.deleted == 0) { out.push(a) } }
  133. let i = 1
  134. while (i < out.length) {
  135. let cur = out[i]
  136. let j = i - 1
  137. while (j >= 0 && out[j].n > cur.n) {
  138. out[j + 1] = out[j]
  139. j = j - 1
  140. }
  141. out[j + 1] = cur
  142. i = i + 1
  143. }
  144. return out
  145. }
  146. // what the JSON API and the pages show of each: { id, name, type, size, image, url } (url: relative, members only)
  147. static attachmentsOf = (eventId) => {
  148. out = []
  149. 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 }) }
  150. return out
  151. }
  152. // ---- serving ------------------------------------------------------------------------------------------
  153. // the attachment `id` for a reader: `user` (a users record, or null) or `keyProject` (the project @id of an app key, or null).
  154. // Answers { file: { bytes, type, name, image } } or { status, error }.
  155. static attachmentFor = (id, user, keyProject) => {
  156. a = id == null || hlTypeName(id) != 'String' || id == '' ? null : attachmentsTable.fetch(id)
  157. if (a == null || a.deleted != 0) { return { status = 404 error = 'no such attachment' } }
  158. if (user == null && keyProject == null) { return { status = 401 error = 'attachments are for the members of the project: log in, or send Authorization: Bearer <token>' } }
  159. ok = (user != null && isMember(a.project, user)) || (keyProject != null && keyProject == a.project)
  160. if (!ok) { return { status = 403 error = 'only the members of the project can fetch its attachments' } }
  161. path = filesDir + '/' + a.file
  162. if (!exists(path)) { return { status = 404 error = 'the file of this attachment is gone' } }
  163. return { file = { bytes = readBytes(path) type = a.type name = a.name image = a.image } }
  164. }

Branches

Latest commits

  • 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
  • c1161469mission 013: GitHub pipe tables on ticket pages (lib/markdown.hl + View + CSS) and re-vendor hybriel master a832f73bmre