OpenTalon / app / native / runtime / task-files.cjs
| 1 | const { createHash, randomUUID } = require('node:crypto') |
| 2 | const { extname } = require('node:path') |
| 3 | const { AppError } = require('./contracts.cjs') |
| 4 | |
| 5 | const maxBytes = 10 * 1024 * 1024 |
| 6 | const videoExtensions = new Set('3g2 3gp 3gpp asf avi dv f4v flv m2ts m4v mkv mov mp4 mpe mpeg mpg mts mxf ogv rm rmvb vob webm wmv'.split(' ')) |
| 7 | const columns = 'id, task_id AS taskId, name, content_type AS contentType, byte_count AS byteCount, sha256, created_at AS createdAt' |
| 8 | |
| 9 | function migrate(store) { |
| 10 | store.db.exec('BEGIN IMMEDIATE') |
| 11 | try { |
| 12 | store.db.exec(` |
| 13 | CREATE TABLE task_files ( |
| 14 | id TEXT PRIMARY KEY, |
| 15 | task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE, |
| 16 | name TEXT NOT NULL, |
| 17 | content_type TEXT NOT NULL, |
| 18 | byte_count INTEGER NOT NULL CHECK(byte_count BETWEEN 0 AND ${maxBytes}), |
| 19 | sha256 TEXT NOT NULL, |
| 20 | created_at TEXT NOT NULL, |
| 21 | bytes BLOB NOT NULL CHECK(length(bytes) = byte_count) |
| 22 | ) STRICT; |
| 23 | CREATE INDEX task_files_by_task ON task_files(task_id, created_at, id); |
| 24 | PRAGMA user_version=14; |
| 25 | `) |
| 26 | store.db.prepare('INSERT INTO schema_migrations VALUES (?,?)').run(14, new Date().toISOString()) |
| 27 | store.db.exec('COMMIT') |
| 28 | } catch (error) { |
| 29 | store.db.exec('ROLLBACK') |
| 30 | throw error |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | function validate({ name, contentType, base64 }) { |
| 35 | if (typeof name !== 'string' || !name.trim() || name === '.' || name === '..' || |
| 36 | !name.isWellFormed() || Buffer.byteLength(name) > 240 || /[/\\:\p{Cc}]/u.test(name)) |
| 37 | throw new AppError('INVALID_ARGUMENT', 'Choose a file with a valid filename of up to 240 bytes.') |
| 38 | if (typeof contentType !== 'string' || !/^[\w.+-]+\/[\w.+-]+$/.test(contentType) || contentType.length > 150) |
| 39 | throw new AppError('INVALID_ARGUMENT', 'Use a valid media type for the file.') |
| 40 | if (contentType.toLowerCase().startsWith('video/') || videoExtensions.has(extname(name.trim()).slice(1).toLowerCase())) |
| 41 | throw new AppError('INVALID_ARGUMENT', 'Video files cannot be attached.') |
| 42 | if (typeof base64 !== 'string' || base64.length > Math.ceil(maxBytes / 3) * 4) |
| 43 | throw new AppError('INVALID_ARGUMENT', 'Files can be up to 10 MB each.') |
| 44 | const bytes = Buffer.from(base64, 'base64') |
| 45 | if (bytes.length > maxBytes || bytes.toString('base64') !== base64) |
| 46 | throw new AppError('INVALID_ARGUMENT', 'Use valid base64 for a file up to 10 MB.') |
| 47 | // Common video containers can be identified even if a provider mislabels them. |
| 48 | const magic = bytes.subarray(0, 12).toString('latin1') |
| 49 | if (magic.startsWith('FLV\x01') || magic.startsWith('RIFF') && magic.slice(8) === 'AVI ' || |
| 50 | (magic.slice(4, 8) === 'ftyp' && /^(avc1|mp4[12]|M4V |qt |3g[p2])/.test(magic.slice(8)))) |
| 51 | throw new AppError('INVALID_ARGUMENT', 'Video files cannot be attached.') |
| 52 | return bytes |
| 53 | } |
| 54 | |
| 55 | function insert(store, metadata, bytes) { |
| 56 | const { id, taskId, name, contentType, byteCount, sha256, createdAt } = metadata |
| 57 | store.db.prepare('INSERT INTO task_files VALUES (?,?,?,?,?,?,?,?)') |
| 58 | .run(id, taskId, name, contentType, byteCount, sha256, createdAt, bytes) |
| 59 | } |
| 60 | |
| 61 | function attach(store, input) { |
| 62 | const task = store.task(input.taskId) |
| 63 | if (task.deleted) throw new AppError('IN_TRASH', 'Restore the task before attaching a file.') |
| 64 | const bytes = validate(input) |
| 65 | const attachment = { |
| 66 | id: randomUUID(), taskId: task.id, name: input.name, contentType: input.contentType, |
| 67 | byteCount: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex'), |
| 68 | createdAt: new Date().toISOString(), |
| 69 | } |
| 70 | insert(store, attachment, bytes) |
| 71 | return attachment |
| 72 | } |
| 73 | |
| 74 | function list(store, taskId) { |
| 75 | if (taskId === undefined) return store.db.prepare(`SELECT ${columns} FROM task_files ORDER BY created_at,id`).all() |
| 76 | return store.db.prepare(`SELECT ${columns} FROM task_files WHERE task_id=? ORDER BY created_at,id`).all(taskId) |
| 77 | } |
| 78 | |
| 79 | function encode({ bytes, ...attachment }) { |
| 80 | return { ...attachment, base64: Buffer.from(bytes).toString('base64') } |
| 81 | } |
| 82 | |
| 83 | function read(store, taskId, fileId) { |
| 84 | const row = store.db.prepare(`SELECT ${columns}, bytes FROM task_files WHERE task_id=? AND id=?`).get(taskId, fileId) |
| 85 | if (!row) throw new AppError('NOT_FOUND', 'This file is no longer attached to the task.') |
| 86 | return encode(row) |
| 87 | } |
| 88 | |
| 89 | function exportRows(store) { |
| 90 | return store.db.prepare(`SELECT ${columns}, bytes FROM task_files ORDER BY created_at,id`).all().map(encode) |
| 91 | } |
| 92 | |
| 93 | function validateRows(rows, tasks) { |
| 94 | const taskIds = new Set(tasks.map(task => task.id)) |
| 95 | const fileIds = new Set() |
| 96 | if (!Array.isArray(rows)) throw new AppError('INVALID_BACKUP', 'This backup is missing the task files table.') |
| 97 | for (const row of rows) { |
| 98 | const bytes = validate(row ?? {}) |
| 99 | if (typeof row.id !== 'string' || !/^[a-f0-9-]{36}$/.test(row.id) || fileIds.has(row.id) || |
| 100 | !taskIds.has(row.taskId) || !Number.isFinite(Date.parse(row.createdAt)) || |
| 101 | bytes.length !== row.byteCount || createHash('sha256').update(bytes).digest('hex') !== row.sha256) |
| 102 | throw new AppError('INVALID_BACKUP', 'This backup contains an invalid task file.') |
| 103 | fileIds.add(row.id) |
| 104 | } |
| 105 | } |
| 106 | |
| 107 | function restoreRows(store, rows) { |
| 108 | for (const row of rows) insert(store, row, Buffer.from(row.base64, 'base64')) |
| 109 | } |
| 110 | |
| 111 | module.exports = { migrate, attach, list, read, exportRows, validateRows, restoreRows } |