323 lines
20 KiB
JavaScript
323 lines
20 KiB
JavaScript
const test = require('node:test');
|
|
const assert = require('node:assert/strict');
|
|
const express = require('express');
|
|
const fs = require('node:fs');
|
|
const path = require('node:path');
|
|
const vm = require('node:vm');
|
|
const { createRequire } = require('node:module');
|
|
const { createRobotRouter, parseDocumentIds } = require('./robots');
|
|
|
|
const pdf = Buffer.from('%PDF-1.4\nrobot manual\n%%EOF\n');
|
|
const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aLl8AAAAASUVORK5CYII=', 'base64');
|
|
|
|
async function fixture(t, { answer, role = 'asset', maxBytes = 1024 * 1024 } = {}) {
|
|
const queries = [], transactions = [];
|
|
class Request {
|
|
constructor(transaction) { this.transaction = transaction; this.inputs = {}; }
|
|
input(name, _type, value) { this.inputs[name] = value; return this; }
|
|
async query(query) {
|
|
const call = { query, inputs: this.inputs, transaction: this.transaction };
|
|
queries.push(call);
|
|
const result = answer?.(call);
|
|
if (result !== undefined) return result;
|
|
if (query.includes('SELECT TypeId, Name FROM dbo.RobotTypes')) return { recordset: [{ TypeId: this.inputs.typeId, Name: 'Cộng tác' }] };
|
|
if (query.includes('INSERT INTO dbo.Robots')) return { recordset: [{ RobotId: 17 }] };
|
|
if (query.includes('INSERT INTO dbo.Documents')) return { recordset: [{ DocumentId: 51 }] };
|
|
if (query.includes('SELECT DocumentId FROM dbo.Documents')) return { recordset: [{ DocumentId: this.inputs.documentId }] };
|
|
if (query.includes('SELECT RobotId FROM dbo.Robots')) return { recordset: [{ RobotId: 17 }] };
|
|
if (query.includes('COUNT(*) AS DocumentCount')) return { recordset: [{ DocumentCount: 2 }] };
|
|
return { recordset: [] };
|
|
}
|
|
}
|
|
class Transaction {
|
|
constructor() { transactions.push(this); }
|
|
async begin() { this.begun = true; }
|
|
async commit() { this.committed = true; }
|
|
async rollback() { this.rolledBack = true; }
|
|
}
|
|
const app = express();
|
|
app.use(express.json());
|
|
app.use((_req, res, next) => {
|
|
res.setHeader('Cache-Control', 'no-store'); next();
|
|
});
|
|
app.use((req, _res, next) => { req.user = { UserId: 1, Role: role }; next(); });
|
|
app.use('/api/robots', createRobotRouter({
|
|
getPool: () => ({ request: () => new Request() }),
|
|
sql: { ...require('mssql'), Request, Transaction },
|
|
requireManage(req, res, next) {
|
|
if (!['asset', 'admin'].includes(req.user.Role)) return res.status(403).json({ success: false });
|
|
next();
|
|
},
|
|
documentMaxBytes: maxBytes, documentMaxMb: 1,
|
|
isPdfBuffer: buffer => buffer.subarray(0, 5).toString() === '%PDF-' && buffer.includes(Buffer.from('%%EOF')),
|
|
sanitizeDocumentFileName: name => name.replace(/[\\/\r\n]/g, '_'),
|
|
sendInternalError: (res, _error, message) => res.status(500).json({ success: false, message })
|
|
}));
|
|
const server = app.listen(0, '127.0.0.1');
|
|
await new Promise(resolve => server.once('listening', resolve));
|
|
t.after(() => { server.closeAllConnections(); return new Promise(resolve => server.close(resolve)); });
|
|
return { queries, transactions, request: (suffix = '', options) => fetch(`http://127.0.0.1:${server.address().port}/api/robots${suffix}`, options) };
|
|
}
|
|
|
|
function form(extra = {}) {
|
|
const body = new FormData();
|
|
for (const [key, value] of Object.entries({ name: 'Robot hàn', model: 'CR10', typeId: '1', documentIds: '[3,2,3]', ...extra })) {
|
|
if (value !== undefined) body.append(key, value);
|
|
}
|
|
return body;
|
|
}
|
|
|
|
test('creating a robot saves its avatar, new PDFs and existing links in one transaction', async t => {
|
|
const f = await fixture(t);
|
|
const body = form();
|
|
body.append('avatar', new Blob([png], { type: 'image/png' }), 'robot.png');
|
|
body.append('documents', new Blob([pdf], { type: 'application/pdf' }), 'manual.pdf');
|
|
const response = await f.request('', { method: 'POST', body });
|
|
assert.equal(response.status, 201);
|
|
assert.equal((await response.json()).data.RobotId, 17);
|
|
assert.equal(f.transactions[0].committed, true);
|
|
assert.ok(f.queries.every(query => query.transaction === f.transactions[0]));
|
|
const robot = f.queries.find(q => q.query.includes('INSERT INTO dbo.Robots'));
|
|
assert.equal(robot.inputs.name, 'Robot hàn');
|
|
assert.equal(robot.inputs.typeId, 1);
|
|
assert.equal(robot.inputs.type, 'Cộng tác');
|
|
assert.deepEqual(robot.inputs.avatarData, png);
|
|
const links = f.queries.filter(q => q.query.includes('INSERT INTO dbo.RobotDocuments'));
|
|
assert.deepEqual(links.map(q => q.inputs.documentId), [2, 3, 51]);
|
|
assert.equal(f.queries.filter(q => q.query.includes('INSERT INTO dbo.Documents')).length, 1);
|
|
});
|
|
|
|
test('a PDF storage failure rolls back robot metadata and every link', async t => {
|
|
const f = await fixture(t, { answer({ query }) {
|
|
if (query.includes('INSERT INTO dbo.Documents')) throw new Error('Storage failed');
|
|
} });
|
|
const body = form(); body.append('documents', new Blob([pdf], { type: 'application/pdf' }), 'manual.pdf');
|
|
assert.equal((await f.request('', { method: 'POST', body })).status, 500);
|
|
assert.equal(f.transactions[0].rolledBack, true);
|
|
assert.equal(f.transactions[0].committed, undefined);
|
|
assert.equal(f.queries.some(q => q.query.includes('INSERT INTO dbo.RobotDocuments')), false);
|
|
});
|
|
|
|
test('a missing library PDF rejects the whole save before inserting a robot', async t => {
|
|
const f = await fixture(t, { answer: ({ query }) => query.includes('SELECT DocumentId FROM dbo.Documents') ? { recordset: [] } : undefined });
|
|
assert.equal((await f.request('', { method: 'POST', body: form() })).status, 400);
|
|
assert.equal(f.transactions[0].rolledBack, true);
|
|
assert.equal(f.queries.some(q => q.query.includes('INSERT')), false);
|
|
});
|
|
|
|
test('editing replaces selected links while retaining the avatar unless requested', async t => {
|
|
const f = await fixture(t);
|
|
assert.equal((await f.request('/17', { method: 'PUT', body: form({ documentIds: '[8]' }) })).status, 200);
|
|
const update = f.queries.find(q => q.query.includes('UPDATE dbo.Robots'));
|
|
assert.equal(update.inputs.replaceAvatar, false);
|
|
assert.match(update.query, /ELSE AvatarData END/);
|
|
assert.ok(f.queries.some(q => q.query.includes('DELETE FROM dbo.RobotDocuments')));
|
|
assert.deepEqual(f.queries.filter(q => q.query.includes('INSERT INTO dbo.RobotDocuments')).map(q => q.inputs.documentId), [8]);
|
|
assert.equal(f.queries.some(q => q.query.includes('DELETE FROM dbo.Documents')), false);
|
|
});
|
|
|
|
test('partial edits preserve document links and can explicitly remove the avatar', async t => {
|
|
const f = await fixture(t);
|
|
assert.equal((await f.request('/17', { method: 'PUT', body: form({ documentIds: undefined, removeAvatar: 'true' }) })).status, 200);
|
|
const update = f.queries.find(q => q.query.includes('UPDATE dbo.Robots'));
|
|
assert.equal(update.inputs.replaceAvatar, true);
|
|
assert.equal(update.inputs.avatarData, null);
|
|
assert.equal(f.queries.some(q => q.query.includes('DELETE FROM dbo.RobotDocuments')), false);
|
|
});
|
|
|
|
test('forged image/PDF contents and oversized avatars are rejected before database access', async t => {
|
|
const f = await fixture(t);
|
|
for (const [field, type, name, bytes] of [
|
|
['avatar', 'image/png', 'bad.png', Buffer.from('not an image')],
|
|
['documents', 'application/pdf', 'bad.pdf', Buffer.from('not a PDF')],
|
|
['avatar', 'image/png', 'large.png', Buffer.alloc(5 * 1024 * 1024 + 1)]
|
|
]) {
|
|
const body = form(); body.append(field, new Blob([bytes], { type }), name);
|
|
assert.equal((await f.request('', { method: 'POST', body })).status, 400);
|
|
}
|
|
assert.equal(f.queries.length, 0);
|
|
assert.equal(f.transactions.length, 0);
|
|
});
|
|
|
|
test('PDF size configuration, image extensions and upload counts are enforced', async t => {
|
|
const f = await fixture(t, { maxBytes: 20 });
|
|
const oversizedPdf = form(); oversizedPdf.append('documents', new Blob([pdf], { type: 'application/pdf' }), 'manual.pdf');
|
|
const svg = form(); svg.append('avatar', new Blob(['<svg/>'], { type: 'image/svg+xml' }), 'image.svg');
|
|
const many = form();
|
|
for (let i = 0; i < 11; i++) many.append('documents', new Blob([pdf], { type: 'application/pdf' }), `${i}.pdf`);
|
|
for (const body of [oversizedPdf, svg, many]) assert.equal((await f.request('', { method: 'POST', body })).status, 400);
|
|
assert.equal(f.transactions.length, 0);
|
|
});
|
|
|
|
test('invalid metadata and document IDs return useful errors without writes', async t => {
|
|
const f = await fixture(t);
|
|
for (const extra of [{ name: ' ' }, { model: '' }, { typeId: undefined }, { typeId: '0' }, { typeId: '2147483648' }, { documentIds: 'invalid' },
|
|
{ documentIds: '[0]' }, { documentIds: '["3 OR 1=1"]' }, { documentIds: '[2147483648]' }]) {
|
|
assert.equal((await f.request('', { method: 'POST', body: form(extra) })).status, 400);
|
|
}
|
|
assert.equal((await f.request('', { method: 'POST' })).status, 400);
|
|
assert.equal((await f.request('/17x', { method: 'PUT', body: form() })).status, 400);
|
|
assert.equal(f.transactions.length, 0);
|
|
assert.throws(() => parseDocumentIds(Array.from({ length: 101 }, (_, i) => i + 1)));
|
|
});
|
|
|
|
test('missing robots cannot be edited or silently recreated', async t => {
|
|
const f = await fixture(t, { answer: ({ query }) => query.includes('SELECT RobotId FROM dbo.Robots') ? { recordset: [] } : undefined });
|
|
assert.equal((await f.request('/17', { method: 'PUT', body: form() })).status, 404);
|
|
assert.equal(f.transactions[0].rolledBack, true);
|
|
assert.equal(f.queries.some(q => q.query.includes('UPDATE') && !q.query.includes('UPDLOCK')), false);
|
|
});
|
|
|
|
test('ordinary users can read robot data but cannot add, update or delete robots', async t => {
|
|
const f = await fixture(t, { role: 'user' });
|
|
assert.equal((await f.request()).status, 200);
|
|
for (const [method, suffix] of [['POST', ''], ['PUT', '/17'], ['DELETE', '/17']]) {
|
|
assert.equal((await f.request(suffix, { method, ...(method === 'DELETE' ? {} : { body: form() }) })).status, 403);
|
|
}
|
|
assert.equal(f.transactions.length, 0);
|
|
assert.equal(f.queries.length, 1);
|
|
});
|
|
|
|
test('avatar endpoints return the stored bytes and safe content type', async t => {
|
|
const f = await fixture(t, { answer: ({ query }) => query.includes('SELECT AvatarData') ? { recordset: [{ AvatarData: png, AvatarMimeType: 'image/png' }] } : undefined });
|
|
const response = await f.request('/17/avatar');
|
|
assert.equal(response.status, 200);
|
|
assert.equal(response.headers.get('content-type'), 'image/png');
|
|
assert.equal(response.headers.get('x-content-type-options'), 'nosniff');
|
|
assert.equal(response.headers.get('cache-control'), 'no-store');
|
|
assert.deepEqual(Buffer.from(await response.arrayBuffer()), png);
|
|
});
|
|
|
|
test('deleting a robot never deletes shared PDF documents', async t => {
|
|
const f = await fixture(t, { answer: ({ query }) => query.startsWith('DELETE FROM dbo.Robots') ? { recordset: [{ RobotId: 17 }] } : undefined });
|
|
assert.equal((await f.request('/17', { method: 'DELETE' })).status, 200);
|
|
assert.equal(f.queries.length, 1);
|
|
assert.match(f.queries[0].query, /^DELETE FROM dbo.Robots/);
|
|
assert.doesNotMatch(f.queries[0].query, /DELETE FROM (?:dbo\.)?Documents/);
|
|
});
|
|
|
|
test('robot cards escape user content, search name/model/type, and hide edit actions for viewers', () => {
|
|
const source = fs.readFileSync(path.join(__dirname, '../public/js/app.js'), 'utf8');
|
|
const context = vm.createContext({ document: { addEventListener() {} }, window: { fetch() {} }, console });
|
|
vm.runInContext(`${source}\nglobalThis.manager = Object.create(AccountManager.prototype);`, context);
|
|
const manager = context.manager;
|
|
Object.assign(manager, { robots: [{ RobotId: 17, Name: '<script>Robot</script>', Model: 'CR10', TypeId: 1, Type: 'Cộng tác', DocumentCount: 2 }],
|
|
robotTypes: [{ TypeId: 1, Name: 'Cộng tác', RobotCount: 1 }],
|
|
apiBase: '/api', currentUser: { Role: 'user' }, robotPage: 1, robotPageSize: 12, robotSearchTerm: '', robotTypeFilter: '',
|
|
robotLoadError: '', escapeHtml: value => String(value ?? '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"') });
|
|
let html = manager.getRobotsContent();
|
|
assert.match(html, /<script>Robot/);
|
|
assert.doesNotMatch(html, /<script>Robot/);
|
|
assert.match(html, /2 tài liệu/);
|
|
assert.doesNotMatch(html, /data-robot-action="edit"|data-robot-action="delete"|id="addRobotBtn"/);
|
|
manager.currentUser.Role = 'admin';
|
|
assert.match(manager.getRobotsContent(), /data-robot-action="edit"/);
|
|
for (const keyword of ['robot', 'cr10', 'cộng tác']) {
|
|
manager.robotSearchTerm = keyword; assert.equal(manager.getFilteredRobots().length, 1);
|
|
}
|
|
manager.robotTypeFilter = 'AMR'; assert.equal(manager.getFilteredRobots().length, 0);
|
|
manager.robotTypeFilter = '1'; assert.equal(manager.getFilteredRobots().length, 1);
|
|
manager.robotSearchTerm = ''; manager.robotTypeFilter = ''; manager.robotLoadError = 'Server unavailable';
|
|
html = manager.getRobotsContent(); assert.match(html, /role="alert"/); assert.match(html, /Server unavailable/);
|
|
});
|
|
|
|
function serverWithPool(pool) {
|
|
const serverPath = path.join(__dirname, 'server.js');
|
|
const serverRequire = createRequire(serverPath);
|
|
const sandbox = {
|
|
require: name => name === 'dotenv' ? { config() {} } : serverRequire(name),
|
|
module: { exports: {} }, __dirname, __filename: serverPath, Buffer, URL, console,
|
|
process: { env: { NODE_ENV: 'test', DATA_ENCRYPTION_SECRET: 'robot-tests-only-key-with-more-than-32-characters' }, on() {} },
|
|
robotTestPool: pool
|
|
};
|
|
vm.runInNewContext(`${fs.readFileSync(serverPath, 'utf8')}\npool = robotTestPool;`, sandbox, { filename: serverPath });
|
|
return sandbox.module.exports.app;
|
|
}
|
|
|
|
test('all robot endpoints require an authenticated session in the production application', async t => {
|
|
const app = serverWithPool(null);
|
|
const server = app.listen(0, '127.0.0.1'); await new Promise(resolve => server.once('listening', resolve));
|
|
t.after(() => { server.closeAllConnections(); return new Promise(resolve => server.close(resolve)); });
|
|
const base = `http://127.0.0.1:${server.address().port}/api/robots`;
|
|
for (const [method, suffix] of [['GET', ''], ['GET', '/17'], ['GET', '/17/avatar'], ['POST', ''], ['PUT', '/17'], ['DELETE', '/17'],
|
|
['GET', '/types'], ['POST', '/types'], ['PUT', '/types/1'], ['DELETE', '/types/1']]) {
|
|
const response = await fetch(`${base}${suffix}`, { method, headers: { 'X-User-Id': '1', 'X-User-Role': 'admin' } });
|
|
assert.equal(response.status, 401);
|
|
}
|
|
});
|
|
|
|
test('a deleted or unknown robot type rejects the save before inserting robot data', async t => {
|
|
const f = await fixture(t, { answer: ({ query }) => query.includes('SELECT TypeId, Name FROM dbo.RobotTypes') ? { recordset: [] } : undefined });
|
|
assert.equal((await f.request('', { method: 'POST', body: form() })).status, 400);
|
|
assert.equal(f.transactions[0].rolledBack, true);
|
|
assert.equal(f.queries.some(q => q.query.includes('INSERT')), false);
|
|
});
|
|
|
|
test('viewers can read the type catalog but cannot create, rename or delete types', async t => {
|
|
const f = await fixture(t, { role: 'user' });
|
|
assert.equal((await f.request('/types')).status, 200);
|
|
for (const [method, suffix] of [['POST', '/types'], ['PUT', '/types/1'], ['DELETE', '/types/1']]) {
|
|
assert.equal((await f.request(suffix, { method, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'AMR' }) })).status, 403);
|
|
}
|
|
assert.equal(f.queries.length, 1);
|
|
assert.equal(f.transactions.length, 0);
|
|
});
|
|
|
|
test('type input is validated and duplicate type names return a conflict', async t => {
|
|
const f = await fixture(t, { answer({ query }) {
|
|
if (query.includes('INSERT INTO dbo.RobotTypes')) throw Object.assign(new Error('duplicate'), { number: 2627 });
|
|
} });
|
|
for (const body of [{ name: '' }, { name: ' ' }, { name: 'a'.repeat(101) }, { name: [] }, { name: 'AMR', description: 'a'.repeat(501) }]) {
|
|
assert.equal((await f.request('/types', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })).status, 400);
|
|
}
|
|
assert.equal(f.queries.length, 0);
|
|
assert.equal((await f.request('/types', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'AMR' }) })).status, 409);
|
|
});
|
|
|
|
test('renaming a type updates the catalog and robot display values atomically', async t => {
|
|
const f = await fixture(t, { answer: ({ query }) => query.includes('UPDATE dbo.RobotTypes') ? { recordset: [{ TypeId: 1, Name: 'Cộng tác mới' }] } : undefined });
|
|
const response = await f.request('/types/1', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'Cộng tác mới', description: 'New description' }) });
|
|
assert.equal(response.status, 200);
|
|
assert.equal(f.transactions[0].committed, true);
|
|
assert.ok(f.queries.every(call => call.transaction === f.transactions[0]));
|
|
assert.ok(f.queries.some(call => call.query.includes('UPDATE dbo.Robots SET Type = @name') && call.inputs.name === 'Cộng tác mới'));
|
|
});
|
|
|
|
test('rename failures roll back; used types cannot be deleted, and missing types return 404', async t => {
|
|
const failed = await fixture(t, { answer({ query }) {
|
|
if (query.includes('UPDATE dbo.RobotTypes')) return { recordset: [{ TypeId: 1 }] };
|
|
if (query.includes('UPDATE dbo.Robots')) throw new Error('Storage failure');
|
|
} });
|
|
assert.equal((await failed.request('/types/1', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'Rename' }) })).status, 500);
|
|
assert.equal(failed.transactions[0].rolledBack, true);
|
|
for (const mode of ['used', 'missing', 'unused']) {
|
|
const f = await fixture(t, { answer({ query }) {
|
|
if (query.includes('DELETE FROM dbo.RobotTypes')) {
|
|
if (mode === 'used') throw Object.assign(new Error('FK conflict'), { number: 547 });
|
|
return { recordset: mode === 'unused' ? [{ TypeId: 1 }] : [] };
|
|
}
|
|
} });
|
|
assert.equal((await f.request('/types/1', { method: 'DELETE' })).status, mode === 'used' ? 409 : mode === 'missing' ? 404 : 200);
|
|
}
|
|
});
|
|
|
|
test('document deletion blocks robot links and concurrent foreign-key conflicts while retaining owner permissions', async () => {
|
|
for (const mode of ['linked', 'unlinked', 'concurrent', 'other-owner']) {
|
|
let calls = 0;
|
|
const app = serverWithPool({ request() {
|
|
return { input() { return this; }, async query(query) {
|
|
calls++;
|
|
if (query.startsWith('SELECT')) return { recordset: [{ DocumentId: 3, UploadedBy: mode === 'other-owner' ? 2 : 1 }] };
|
|
assert.match(query, /NOT EXISTS \(SELECT 1 FROM dbo.RobotDocuments/);
|
|
if (mode === 'concurrent') throw Object.assign(new Error('FK conflict'), { number: 547 });
|
|
return { recordset: mode === 'unlinked' ? [{ DocumentId: 3 }] : [] };
|
|
} };
|
|
} });
|
|
const route = app.router.stack.find(layer => layer.route?.path === '/api/documents/:id' && layer.route.methods.delete).route;
|
|
const response = { statusCode: 200, status(code) { this.statusCode = code; return this; }, json(body) { this.body = body; return this; } };
|
|
await route.stack.at(-1).handle({ params: { id: '3' }, user: { UserId: 1, Role: 'user' } }, response);
|
|
assert.equal(response.statusCode, mode === 'other-owner' ? 403 : mode === 'unlinked' ? 200 : 409);
|
|
assert.equal(calls, mode === 'other-owner' ? 1 : 2);
|
|
}
|
|
});
|