cmvr-wms/mobile-app/scripts/ota-server.mjs
lixiaolong 5cee6482f8 feat(assistant): 优化业务助手功能和移动应用配置
- 实现业务确认单条目的移出和恢复功能
- 添加报价匹配明细中的跳过处理选项
- 重构移动应用的环境配置使用默认开发配置
- 更新移动应用Android版本号策略
- 替换到货操作组件为独立的操作组件
- 添加安装配置检查脚本
- 增强测试覆盖包括条目移出恢复和报价跳过场景
2026-10-20 15:35:58 +08:00

68 lines
4.5 KiB
JavaScript

import http from 'node:http';
import { readFile, realpath } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
export function createOtaServer({ root, environments = ['dev', 'prod'], downloadDirectory }) {
if (!environments.length || environments.some(value => !['dev', 'prod'].includes(value))) throw Error('Invalid OTA environment allowlist');
if (downloadDirectory && (environments.length !== 1 || environments[0] !== 'dev')) throw Error('APK downloads are development-only');
if (downloadDirectory) downloadDirectory = path.resolve(downloadDirectory);
root = path.resolve(root);
const server = http.createServer(async (req, res) => {
const common = { 'expo-protocol-version': '1', 'expo-sfv-version': '0',
'expo-manifest-filters': '', 'expo-server-defined-headers': '', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' };
const send = (status, body, headers = {}) => { res.writeHead(status, { ...common, ...headers }); res.end(req.method === 'HEAD' ? undefined : body); };
if (!['GET', 'HEAD'].includes(req.method)) return send(405, 'Method not allowed');
try {
const url = new URL(req.url, 'http://localhost');
const download = /^\/downloads\/(cmvr-wms-dev-[a-zA-Z0-9-]+\.apk)$/.exec(url.pathname);
if (download && downloadDirectory) {
const dir = await realpath(downloadDirectory);
const file = await realpath(path.join(dir, download[1]));
if (path.dirname(file) !== dir) throw Error('Invalid download path');
return send(200, await readFile(file), { 'content-type': 'application/vnd.android.package-archive',
'content-disposition': `attachment; filename="${download[1]}"` });
}
const update = /^\/updates\/(dev|prod)$/.exec(url.pathname);
if (update) {
if (!environments.includes(update[1])) return send(404, 'Not found');
if (req.headers['expo-protocol-version'] && req.headers['expo-protocol-version'] !== '1') return send(406, 'Unsupported update protocol');
const platform = req.headers['expo-platform'];
const runtime = req.headers['expo-runtime-version'];
if (platform !== 'android' || typeof runtime !== 'string' || !/^[\w.-]{1,200}$/.test(runtime)) return send(400, 'Invalid platform/runtime');
let pointer;
try { pointer = JSON.parse(await readFile(path.join(root, update[1], platform, runtime, 'current.json'), 'utf8')); }
catch (error) {
if (error.code !== 'ENOENT') throw error;
return send(200, '--empty--\r\n', { 'content-type': 'multipart/mixed; boundary=empty' });
}
if (!/^[0-9a-f-]{36}$/.test(pointer.id)) throw Error('Invalid release pointer');
const dir = path.join(root, 'releases', pointer.id);
const [manifest, signature] = await Promise.all([readFile(path.join(dir, 'manifest.json')), readFile(path.join(dir, 'signature.txt'), 'utf8')]);
const parsed = JSON.parse(manifest);
if (parsed.runtimeVersion !== runtime || parsed.metadata.environment !== update[1]) throw Error('Release/environment mismatch');
return send(200, manifest, { 'content-type': 'application/expo+json', 'expo-signature': signature });
}
const asset = /^\/assets\/([a-f0-9]{64})$/.exec(url.pathname);
if (asset) {
const dir = await realpath(path.join(root, 'assets'));
const file = await realpath(path.join(dir, asset[1]));
if (path.dirname(file) !== dir) throw Error('Invalid asset path');
const [data, contentType] = await Promise.all([readFile(file), readFile(file + '.type', 'utf8')]);
return send(200, data, { 'content-type': contentType.trim(), 'cache-control': 'public, max-age=31536000, immutable' });
}
if (url.pathname === '/health') return send(200, 'ok', { 'content-type': 'text/plain' });
return send(404, 'Not found');
} catch (error) { return send(error.code === 'ENOENT' ? 404 : 500, 'Update unavailable'); }
});
server.requestTimeout = 15000;
server.headersTimeout = 10000;
server.maxHeadersCount = 50;
return server;
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const server = createOtaServer({ root: process.env.OTA_DATA_DIR || './ota-data',
environments: process.env.OTA_ENVIRONMENT ? [process.env.OTA_ENVIRONMENT] : ['dev', 'prod'] });
server.listen(Number(process.env.OTA_PORT || 8090), process.env.OTA_HOST || '127.0.0.1', () => console.log('Internal OTA server ready'));
}