Files
order-notification-automation/tests/assistant/attachments.test.cjs
T

60 lines
2.4 KiB
JavaScript

'use strict';
const { test } = require('node:test'),
assert = require('node:assert/strict');
const { parse } = require('../../src/modules/assistant/attachments.cjs');
function pdf(text) {
const stream = 'BT /F1 12 Tf 72 720 Td (' + text + ') Tj ET',
parts = ['%PDF-1.4\n'],
objects = [
'<< /Type /Catalog /Pages 2 0 R >>',
'<< /Type /Pages /Kids [3 0 R] /Count 1 >>',
'<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 4 0 R >> >> /Contents 5 0 R >>',
'<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>',
'<< /Length ' + stream.length + ' >>\nstream\n' + stream + '\nendstream',
];
const offsets = [0];
for (const [i, obj] of objects.entries()) {
offsets.push(Buffer.byteLength(parts.join('')));
parts.push(i + 1 + ' 0 obj\n' + obj + '\nendobj\n');
}
const xref = Buffer.byteLength(parts.join(''));
parts.push(
'xref\n0 6\n0000000000 65535 f \n' +
offsets
.slice(1)
.map((x) => String(x).padStart(10, '0') + ' 00000 n \n')
.join('') +
'trailer\n<< /Size 6 /Root 1 0 R >>\nstartxref\n' +
xref +
'\n%%EOF',
);
return Buffer.from(parts.join(''));
}
module.exports = { pdf };
test(
'attachments parse local text/CSV and real PDF, reject binary, oversized and malformed files',
{ timeout: 30000 },
async () => {
const upload = (name, bytes) => parse({ name, data: bytes.toString('base64') });
assert.equal(
(await upload('中文日志.log', Buffer.from('设备正常\nA=1'))).content,
'设备正常\nA=1',
);
assert.match((await upload('表格.csv', Buffer.from('型号,数量\nABC,12'))).content, /ABC,12/);
const result = await upload('evidence.pdf', pdf('Attachment PDF Evidence'));
assert.match(result.content, /Attachment PDF Evidence/);
assert.equal(result.kind, 'pdf');
await assert.rejects(upload('scan.pdf', pdf('')), /没有可提取的文字/);
for (const [name, bytes] of [
['file.exe', Buffer.from('a')],
['binary.txt', Buffer.from([0, 0, 1, 2])],
['bad.pdf', Buffer.from('not PDF')],
['huge.txt', Buffer.from('x'.repeat(20001))],
['large.log', Buffer.alloc(2 * 1024 * 1024 + 1, 65)],
])
await assert.rejects(upload(name, bytes));
await assert.rejects(parse({ name: '../secret.txt', data: 'YWJj' }));
await assert.rejects(parse({ name: 'file.txt', data: 'not-base64' }));
},
);