This commit is contained in:
@@ -0,0 +1,110 @@
|
||||
'use strict';
|
||||
const sharp = require('sharp');
|
||||
const { randomUUID, createHash } = require('node:crypto');
|
||||
const { pool, transaction } = require('./db');
|
||||
const broker = require('./broker');
|
||||
const { client, bucket, unavailable } = require('./storage');
|
||||
const MAX_BYTES = 10485760, MAX_PIXELS = 40000000;
|
||||
sharp.cache(false);
|
||||
function fail(status, code, message) { throw Object.assign(new Error(message), { status, code }); }
|
||||
function visible(row) {
|
||||
const { object_key, staging_key, ...data } = row;
|
||||
return data;
|
||||
}
|
||||
function readLimited(req) {
|
||||
return new Promise((resolve, reject) => {
|
||||
let size = 0, failed = false;
|
||||
const chunks = [];
|
||||
const tooLarge = () => {
|
||||
failed = true;
|
||||
reject(Object.assign(new Error('File exceeds 10 MiB'), { status: 413, code: 'payload_too_large' }));
|
||||
};
|
||||
if (Number(req.headers['content-length'] || 0) > MAX_BYTES) { req.resume(); tooLarge(); return; }
|
||||
req.on('data', chunk => {
|
||||
if (failed) return;
|
||||
size += chunk.length;
|
||||
if (size > MAX_BYTES) { chunks.length = 0; tooLarge(); }
|
||||
else chunks.push(chunk);
|
||||
});
|
||||
req.on('end', () => { if (!failed) resolve(Buffer.concat(chunks)); });
|
||||
req.on('error', () => reject(Object.assign(new Error('Upload interrupted'), { status: 400, code: 'invalid_request' })));
|
||||
});
|
||||
}
|
||||
async function validateImage(bytes, contentType) {
|
||||
// Reject other formats before asking the image decoder to process them.
|
||||
const png = bytes.length >= 8 && bytes.subarray(0, 8).equals(Buffer.from([137,80,78,71,13,10,26,10]));
|
||||
const jpeg = bytes.length >= 3 && bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255;
|
||||
if ((!png && !jpeg) || (png ? 'image/png' : 'image/jpeg') !== contentType)
|
||||
fail(415, 'unsupported_media_type', 'Expected a matching PNG or JPEG');
|
||||
try {
|
||||
const decoder = sharp(bytes, { limitInputPixels: MAX_PIXELS, failOn: 'warning' });
|
||||
const info = await decoder.metadata();
|
||||
if (!info.width || !info.height || info.width * info.height > MAX_PIXELS)
|
||||
fail(413, 'payload_too_large', 'Image exceeds 40 million pixels');
|
||||
if (!['png', 'jpeg'].includes(info.format)) fail(415, 'unsupported_media_type', 'Unsupported image');
|
||||
// Full decoding detects truncated/corrupt payloads; the raw result is discarded.
|
||||
// Pixel limit is enforced before allocation. Original bytes are never transformed.
|
||||
await decoder.raw().toBuffer();
|
||||
} catch (error) {
|
||||
if (error.status) throw error;
|
||||
if (/pixel limit/i.test(error.message)) fail(413, 'payload_too_large', 'Image exceeds 40 million pixels');
|
||||
fail(415, 'unsupported_media_type', 'Corrupt image');
|
||||
}
|
||||
}
|
||||
async function upload(req, query, chat, user) {
|
||||
const filename = query.get('filename');
|
||||
if (query.getAll('filename').length !== 1 || !filename || !filename.isWellFormed() ||
|
||||
/^[\p{White_Space}\uFEFF]*$/u.test(filename) || [...filename].length > 255 || /[\/\\\p{Cc}]/u.test(filename))
|
||||
fail(400, 'invalid_request', 'Invalid filename');
|
||||
const contentType = req.headers['content-type']?.split(';')[0].trim().toLowerCase();
|
||||
if (!['image/png', 'image/jpeg'].includes(contentType)) fail(415, 'unsupported_media_type', 'Expected PNG or JPEG');
|
||||
const bytes = await readLimited(req);
|
||||
await validateImage(bytes, contentType);
|
||||
const id = randomUUID(), objectKey = 'staging/' + id;
|
||||
const checksum = createHash('sha256').update(bytes).digest('hex');
|
||||
try { await client.putObject(bucket, objectKey, bytes, bytes.length, { 'Content-Type': contentType }); }
|
||||
catch { throw unavailable(); }
|
||||
let accepted;
|
||||
try {
|
||||
accepted = await transaction(async db => {
|
||||
const row = (await db.query(`INSERT INTO attachments
|
||||
(id,chat_id,owner_id,filename,content_type,size_bytes,sha256,object_key,staging_key,status)
|
||||
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,'queued') RETURNING *`,
|
||||
[id,chat.id,user.id,filename,contentType,bytes.length,checksum,'originals/'+id+'/v1',objectKey])).rows[0];
|
||||
const job = (await db.query('INSERT INTO attachment_jobs(id,attachment_id) VALUES($1,$2) RETURNING *',
|
||||
[randomUUID(),id])).rows[0];
|
||||
return {row,job};
|
||||
});
|
||||
} catch (error) {
|
||||
await client.removeObject(bucket,objectKey).catch(() => {});
|
||||
throw error;
|
||||
}
|
||||
// No 202 until the persistent job has a publisher confirm. A failed publish
|
||||
// leaves an unconfirmed queued row; grade 3 has no outbox/reconciler.
|
||||
try { await broker.publish(accepted.job); }
|
||||
catch { throw Object.assign(new Error('Broker unavailable'),{status:503,code:'unavailable'}); }
|
||||
return visible(accepted.row);
|
||||
}
|
||||
|
||||
async function accessible(id, user) {
|
||||
const result = await pool.query(`SELECT a.* FROM attachments a WHERE a.id=$1 AND EXISTS
|
||||
(SELECT 1 FROM chat_members WHERE chat_id=a.chat_id AND user_id=$2)`, [id, user.id]);
|
||||
if (!result.rowCount) fail(404, 'not_found', 'Object not found');
|
||||
return result.rows[0];
|
||||
}
|
||||
async function download(row) {
|
||||
try {
|
||||
const stream = await client.getObject(bucket, row.object_key);
|
||||
const chunks = [];
|
||||
let size = 0;
|
||||
for await (const chunk of stream) {
|
||||
size += chunk.length;
|
||||
if (size > MAX_BYTES) { stream.destroy(); throw new Error(); }
|
||||
chunks.push(chunk);
|
||||
}
|
||||
const bytes = Buffer.concat(chunks);
|
||||
if (bytes.length !== row.size_bytes || createHash('sha256').update(bytes).digest('hex') !== row.sha256) throw new Error();
|
||||
return bytes;
|
||||
} catch { throw unavailable(); }
|
||||
}
|
||||
module.exports = { upload, accessible, visible, download, validateImage };
|
||||
Reference in New Issue
Block a user