cmvr-wms/mobile-app/scripts/publish-update.mjs

66 lines
5.3 KiB
JavaScript
Raw Normal View History

import { readFile, writeFile, mkdir, rename, realpath } from 'node:fs/promises';
import path from 'node:path';
import { createHash, randomUUID, sign, verify, X509Certificate } from 'node:crypto';
import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';
const require = createRequire(import.meta.url);
const { internal } = require('../config/environment.cjs');
const types = { png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', webp: 'image/webp',
ttf: 'font/ttf', otf: 'font/otf', json: 'application/json', hbc: 'application/javascript', js: 'application/javascript' };
export async function publishUpdate({ exportDir, root, origin, environment, runtimeVersion, keyFile, keyPassphrase, certificateFile, expoConfig }) {
if (!['dev', 'prod'].includes(environment) || !/^[\w.-]{1,200}$/.test(runtimeVersion || '')) throw Error('Explicit environment/runtime required');
origin = internal(origin, environment === 'dev', environment === 'prod');
if (new URL(origin).pathname !== '/') throw Error('OTA origin must not have a path');
exportDir = await realpath(exportDir); root = path.resolve(root);
const metadata = JSON.parse(await readFile(path.join(exportDir, 'metadata.json'), 'utf8'));
const exported = metadata.fileMetadata?.android;
if (!exported?.bundle || !Array.isArray(exported.assets)) throw Error('Run Expo Android export first');
if (expoConfig.extra?.environment !== environment) throw Error('Export environment mismatch');
if (expoConfig.runtimeVersion !== runtimeVersion) throw Error('Export/native runtime mismatch; resolve the fingerprint before publishing');
let releaseNotes=[];
try{releaseNotes=JSON.parse(await readFile(path.join(exportDir,'update-notes.json'),'utf8'));}catch(error){if(error.code!=='ENOENT')throw error;}
if(!Array.isArray(releaseNotes)||releaseNotes.length>20||releaseNotes.some(note=>typeof note!=='string'||note.length>1000))throw Error('Invalid update notes');
const key = await readFile(keyFile);
const certificate = new X509Certificate(await readFile(certificateFile));
if (Date.now() < Date.parse(certificate.validFrom) || Date.now() >= Date.parse(certificate.validTo)) throw Error('Signing certificate expired/not yet valid');
const assetsDir = path.join(root, 'assets'); await mkdir(assetsDir, { recursive: true });
async function asset(relative, ext, launch = false) {
const source = await realpath(path.resolve(exportDir, relative));
if (!source.startsWith(exportDir + path.sep)) throw Error('Asset escapes export directory');
const bytes = await readFile(source);
const digest = createHash('sha256').update(bytes).digest(); const hex = digest.toString('hex');
const contentType = launch ? 'application/javascript' : (types[ext] || 'application/octet-stream');
// Exclusive creates keep existing hashed assets immutable.
await writeFile(path.join(assetsDir, hex), bytes, { flag: 'wx' }).catch(e => { if (e.code !== 'EEXIST') throw e; });
await writeFile(path.join(assetsDir, hex + '.type'), contentType, { flag: 'wx' }).catch(e => { if (e.code !== 'EEXIST') throw e; });
return { key: path.basename(relative, path.extname(relative)), hash: digest.toString('base64url'), contentType,
url: `${origin}/assets/${hex}`, ...(!launch ? { fileExtension: '.' + ext } : {}) };
}
const id = randomUUID();
const manifest = { id, createdAt: new Date().toISOString(), runtimeVersion,
launchAsset: await asset(exported.bundle, 'js', true),
assets: await Promise.all(exported.assets.map(a => asset(a.path, a.ext))),
metadata: { environment, releaseNotes }, extra: { expoClient: expoConfig } };
const body = JSON.stringify(manifest);
const signature = sign('RSA-SHA256', Buffer.from(body), keyPassphrase ? { key, passphrase: keyPassphrase } : key);
if (!verify('RSA-SHA256', Buffer.from(body), certificate.publicKey, signature)) throw Error('Signing key does not match embedded certificate');
const releaseDir = path.join(root, 'releases', id); await mkdir(releaseDir, { recursive: true });
await writeFile(path.join(releaseDir, 'manifest.json'), body, { flag: 'wx' });
await writeFile(path.join(releaseDir, 'signature.txt'), `sig="${signature.toString('base64')}", keyid="${environment}", alg="rsa-v1_5-sha256"`, { flag: 'wx' });
const channelDir = path.join(root, environment, 'android', runtimeVersion); await mkdir(channelDir, { recursive: true });
const temp = path.join(channelDir, `${id}.tmp`);
await writeFile(temp, JSON.stringify({ id })); await rename(temp, path.join(channelDir, 'current.json'));
return manifest;
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const [exportDir, configFile, runtimeVersion] = process.argv.slice(2);
if (!exportDir || !configFile || !runtimeVersion) throw Error('Usage: npm run ota:publish -- <export-dir> <resolved-config.json> <native-fingerprint>');
const config = JSON.parse(await readFile(configFile, 'utf8'));
const manifest = await publishUpdate({ exportDir, root: process.env.OTA_DATA_DIR || './ota-data',
origin: process.env.APP_UPDATE_ORIGIN, environment: process.env.APP_ENV || 'dev', runtimeVersion,
keyFile: process.env.OTA_PRIVATE_KEY, keyPassphrase: process.env.OTA_KEY_PASSPHRASE,
certificateFile: process.env.OTA_CERTIFICATE, expoConfig: config });
console.log(`Published local release ${manifest.id}; no network deployment performed`);
}