Files
weiguang-jewelry-ledger/新账系统/test/web-next-static.test.js
T

203 lines
8.6 KiB
JavaScript

'use strict';
// 新版界面 /next/:资源类型、单页回退、目录限制,以及按模式开启(云端需 WEB_NEXT=1)。
const test = require('node:test'),
assert = require('node:assert/strict'),
fs = require('node:fs'),
http = require('node:http'),
os = require('node:os'),
path = require('node:path');
const { createApp } = require('../server');
const { serveWebNext, webNextEnabled, isNextPath } = require('../server/middleware/web-next');
function fakeDist(t) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'web-next-dist-'));
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
fs.mkdirSync(path.join(dir, 'assets'));
fs.writeFileSync(path.join(dir, 'index.html'), '<!doctype html><title>next</title>');
fs.writeFileSync(path.join(dir, 'assets', 'app-1.js'), 'console.log(1)');
fs.writeFileSync(path.join(dir, 'assets', 'app-1.css'), 'body{}');
fs.writeFileSync(path.join(dir, 'assets', 'data.json'), '{"a":1}');
fs.writeFileSync(path.join(dir, 'assets', 'logo.svg'), '<svg/>');
fs.writeFileSync(path.join(dir, 'assets', 'unknown.bin'), 'x');
fs.writeFileSync(path.join(path.dirname(dir), path.basename(dir) + '-secret.txt'), 'secret');
t.after(() => fs.rmSync(path.join(path.dirname(dir), path.basename(dir) + '-secret.txt'), { force: true }));
return dir;
}
function call(pathname, distDir, isPost = false) {
const res = {
status: null,
headers: null,
body: null,
writeHead(status, headers) {
this.status = status;
this.headers = headers;
},
end(body) {
this.body = Buffer.from(body).toString('utf8');
},
};
try {
serveWebNext(res, pathname, isPost, { distDir });
} catch (error) {
return { status: error.status, error: error.message };
}
return { status: res.status, type: res.headers['Content-Type'], body: res.body };
}
test('isNextPath 只匹配 /next 与 /next/ 开头,不误伤相似前缀', () => {
for (const p of ['/next', '/next/', '/next/create', '/next/assets/a.js']) assert.equal(isNextPath(p), true, p);
for (const p of ['/', '/nextx', '/next.js', '/api/next', '/print/next']) assert.equal(isNextPath(p), false, p);
});
test('资源按扩展名给出正确类型并原样返回字节(JSON 不被二次序列化)', t => {
const dir = fakeDist(t);
assert.deepEqual(call('/next/assets/app-1.js', dir), {
status: 200,
type: 'application/javascript; charset=utf-8',
body: 'console.log(1)',
});
assert.equal(call('/next/assets/app-1.css', dir).type, 'text/css; charset=utf-8');
assert.equal(call('/next/assets/logo.svg', dir).type, 'image/svg+xml');
assert.deepEqual(call('/next/assets/data.json', dir), {
status: 200,
type: 'application/json; charset=utf-8',
body: '{"a":1}',
});
assert.equal(call('/next/index.html', dir).type, 'text/html; charset=utf-8');
});
test('非资源路径回退到 index.html;缺失或未知类型的资源 404,不回退', t => {
const dir = fakeDist(t);
for (const p of ['/next', '/next/', '/next/create', '/next/login', '/next/a/b/c', '/next/assets'])
assert.deepEqual(
call(p, dir),
{ status: 200, type: 'text/html; charset=utf-8', body: '<!doctype html><title>next</title>' },
p,
);
for (const p of ['/next/assets/missing.js', '/next/missing.css', '/next/assets/unknown.bin'])
assert.deepEqual(call(p, dir), { status: 404, error: '地址不存在' }, p);
assert.deepEqual(call('/next/', dir, true), { status: 404, error: '地址不存在' });
});
test('路径限制在 dist 目录内:解码后的 ..、反斜杠与空字节都不能越界', t => {
const dir = fakeDist(t),
secret = '/next/..%2F' + path.basename(dir) + '-secret.txt';
for (const p of [
secret,
'/next/%2e%2e/%2e%2e/package.json',
'/next/assets/..%2f..%2f' + path.basename(dir) + '-secret.txt',
'/next/..%5c..%5cpackage.json',
'/next/a%00.js',
'/next/%E0%A4%A',
]) {
const r = call(p, dir);
assert.notEqual(r.body, 'secret', p);
assert.equal(r.status, 404, p);
}
});
test('webNextEnabled:试用、演示默认开启;云端只在 WEB_NEXT=1 时开启', t => {
const saved = process.env.WEB_NEXT;
t.after(() => (saved === undefined ? delete process.env.WEB_NEXT : (process.env.WEB_NEXT = saved)));
delete process.env.WEB_NEXT;
assert.equal(webNextEnabled({ mode: 'trial' }), true);
assert.equal(webNextEnabled({ mode: 'demo' }), true);
assert.equal(webNextEnabled({ mode: 'production' }), false);
process.env.WEB_NEXT = 'true';
assert.equal(webNextEnabled({ mode: 'production' }), false);
process.env.WEB_NEXT = '1';
assert.equal(webNextEnabled({ mode: 'production' }), true);
});
function request(port, pathname, { host = '127.0.0.1:' + port, method = 'GET', headers = {} } = {}) {
return new Promise((resolve, reject) => {
const req = http.request({ host: '127.0.0.1', port, path: pathname, method, headers: { Host: host, ...headers } });
req.on('response', res => {
const chunks = [];
res.on('data', c => chunks.push(c));
res.on('end', () =>
resolve({ status: res.statusCode, headers: res.headers, body: Buffer.concat(chunks).toString('utf8') }),
);
});
req.on('error', reject);
req.end();
});
}
async function startApp(t, mode, extra = {}) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'web-next-app-'));
const app = createApp({ mode, port: 0, dataDir: dir, feishuConfig: { enabled: false }, ...extra });
await new Promise(r => app.server.listen(0, '127.0.0.1', r));
t.after(async () => {
await new Promise(r => {
app.server.closeAllConnections();
app.server.close(r);
});
app.ledger.close();
fs.rmSync(dir, { recursive: true, force: true });
});
return app.server.address().port;
}
test('HTTP:试用模式提供 /next/ 页面与资源,带安全响应头;旧界面与未知地址行为不变', async t => {
const port = await startApp(t, 'trial');
const index = await request(port, '/next/');
assert.equal(index.status, 200);
assert.match(index.headers['content-type'], /^text\/html/);
assert.match(index.headers['content-security-policy'], /script-src 'self';/);
assert.equal(index.headers['x-content-type-options'], 'nosniff');
const deep = await request(port, '/next/create?draft=1');
assert.equal(deep.body, index.body);
const script = index.body.match(/src="(\/next\/assets\/[^"]+\.js)"/)?.[1];
assert.ok(script, '入口脚本应使用 /next/assets/ 绝对路径');
const js = await request(port, script);
assert.equal(js.status, 200);
assert.match(js.headers['content-type'], /^application\/javascript/);
assert.equal((await request(port, '/next/assets/no-such-file.js')).status, 404);
assert.equal((await request(port, '/next/..%2Fpackage.json')).status, 404);
const old = await request(port, '/');
assert.equal(old.status, 200);
assert.match(old.body, /\/app\.js/);
assert.equal((await request(port, '/nextx')).status, 404);
const post = await request(port, '/next/', {
method: 'POST',
headers: {
Origin: 'http://127.0.0.1:' + port,
'X-Requested-With': 'maimai-ledger',
'Content-Type': 'application/json',
},
});
assert.equal(post.status, 404);
});
test('HTTP:演示模式同样开启 /next/', async t => {
const port = await startApp(t, 'demo');
assert.equal((await request(port, '/next/')).status, 200);
});
test('HTTP:云端模式默认不提供 /next/(按未知地址 404),设置 WEB_NEXT=1 后提供', async t => {
const names = ['PUBLIC_URL', 'DATA_DIR', 'OWNER_INITIAL_PASSWORD', 'ASSISTANT_INITIAL_PASSWORD', 'WEB_NEXT'];
const saved = Object.fromEntries(names.map(name => [name, process.env[name]]));
t.after(() => {
for (const name of names) saved[name] === undefined ? delete process.env[name] : (process.env[name] = saved[name]);
});
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'web-next-prod-'));
t.after(() => fs.rmSync(dataDir, { recursive: true, force: true }));
Object.assign(process.env, {
PUBLIC_URL: 'https://shop.example.test',
DATA_DIR: dataDir,
OWNER_INITIAL_PASSWORD: 'production-owner-pass',
ASSISTANT_INITIAL_PASSWORD: 'production-assistant-pass',
});
delete process.env.WEB_NEXT;
const port = await startApp(t, 'production', { dataDir, host: '127.0.0.1' });
const host = 'shop.example.test';
const off = await request(port, '/next/', { host });
assert.equal(off.status, 404);
assert.deepEqual(JSON.parse(off.body), { error: '地址不存在' });
assert.equal((await request(port, '/', { host })).status, 200);
process.env.WEB_NEXT = '1';
const on = await request(port, '/next/', { host });
assert.equal(on.status, 200);
assert.match(on.headers['content-type'], /^text\/html/);
});