mirror of
https://gitlab.com/vyla-entertainment/home.git
synced 2026-11-16 15:17:21 -05:00
Signed per-component updater, release 1.1.55
This commit is contained in:
163
update-client.js
163
update-client.js
@@ -1,5 +1,14 @@
|
||||
const https = require('https');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const crypto = require('crypto');
|
||||
|
||||
const UPDATE_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
|
||||
MCowBQYDK2VwAyEAKIuPPzTCGdTksi7hp+V4urau6mMQt2XhNlEfRVbjNZ4=
|
||||
-----END PUBLIC KEY-----`;
|
||||
const MIN_CHECK_INTERVAL_MS = 15 * 60 * 1000;
|
||||
const MAX_RETRY_AFTER_MS = 120000;
|
||||
const MAX_BACKOFF_MS = 6 * 60 * 60 * 1000;
|
||||
|
||||
const GITLAB_GROUP = 'vyla-entertainment';
|
||||
const GITLAB_REPO = 'home';
|
||||
@@ -25,25 +34,81 @@ function isAllowedHost(url) {
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeTag(v) {
|
||||
return String(v || '').replace(/^v/, '').trim();
|
||||
}
|
||||
|
||||
function canonicalManifest(manifest) {
|
||||
const parts = Object.keys(manifest.components || {}).sort().map((name) => {
|
||||
const c = manifest.components[name];
|
||||
return `${name}:${c.file}:${c.sha256}:${c.id}:${c.size}`;
|
||||
});
|
||||
return ['vyla-manifest-v2', normalizeTag(manifest.version), manifest.sha256, ...parts].join('\n');
|
||||
}
|
||||
|
||||
function verifyManifest(manifest) {
|
||||
if (!manifest || typeof manifest.signature !== 'string' || !manifest.components) return false;
|
||||
try {
|
||||
return crypto.verify(null, Buffer.from(canonicalManifest(manifest)), UPDATE_PUBLIC_KEY, Buffer.from(manifest.signature, 'base64'));
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
class UpdateClient {
|
||||
constructor(appDataPath, token = null) {
|
||||
this.appDataPath = appDataPath;
|
||||
this.token = token || process.env.GITLAB_TOKEN || process.env.VYLA_GITLAB_TOKEN || null;
|
||||
}
|
||||
|
||||
fetchJson(url) {
|
||||
cachePath() {
|
||||
return path.join(this.appDataPath, 'update-cache.json');
|
||||
}
|
||||
|
||||
readCache() {
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(this.cachePath(), 'utf8'));
|
||||
} catch (e) {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
writeCache(patch) {
|
||||
try {
|
||||
fs.mkdirSync(this.appDataPath, { recursive: true });
|
||||
fs.writeFileSync(this.cachePath(), JSON.stringify({ ...this.readCache(), ...patch }), 'utf8');
|
||||
} catch (e) { }
|
||||
}
|
||||
|
||||
recordFailure() {
|
||||
const failures = (this.readCache().failures || 0) + 1;
|
||||
const delay = Math.min(5 * 60 * 1000 * 2 ** (failures - 1), MAX_BACKOFF_MS);
|
||||
this.writeCache({ failures, blockedUntil: Date.now() + delay });
|
||||
}
|
||||
|
||||
recordSuccess() {
|
||||
this.writeCache({ failures: 0, blockedUntil: 0 });
|
||||
}
|
||||
|
||||
cacheUsable(release) {
|
||||
return !!release && !!release.components && verifyManifest(release.manifest);
|
||||
}
|
||||
|
||||
fetchJson(url, etag = null, attempt = 0) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const urlObj = new URL(url);
|
||||
const headers = {
|
||||
'User-Agent': 'VylaHome-Client',
|
||||
'Accept': 'application/json',
|
||||
'Cache-Control': 'no-cache',
|
||||
'Pragma': 'no-cache'
|
||||
'Cache-Control': 'no-cache'
|
||||
};
|
||||
|
||||
if (this.token) {
|
||||
headers['PRIVATE-TOKEN'] = this.token;
|
||||
}
|
||||
if (etag) {
|
||||
headers['If-None-Match'] = etag;
|
||||
}
|
||||
|
||||
const requestOptions = {
|
||||
hostname: urlObj.hostname,
|
||||
@@ -58,12 +123,23 @@ class UpdateClient {
|
||||
let data = '';
|
||||
res.on('data', (chunk) => { data += chunk; });
|
||||
res.on('end', () => {
|
||||
if (res.statusCode === 304) {
|
||||
resolve({ notModified: true, etag });
|
||||
return;
|
||||
}
|
||||
if ((res.statusCode === 429 || res.statusCode >= 500) && attempt < 3) {
|
||||
const retryAfter = parseInt(res.headers['retry-after'], 10);
|
||||
const base = Number.isFinite(retryAfter) ? retryAfter * 1000 : 1000 * 2 ** attempt;
|
||||
const wait = Math.min(base, MAX_RETRY_AFTER_MS) + Math.floor(Math.random() * 1000);
|
||||
setTimeout(() => this.fetchJson(url, etag, attempt + 1).then(resolve, reject), wait);
|
||||
return;
|
||||
}
|
||||
if (res.statusCode !== 200) {
|
||||
reject(new Error(`HTTP ${res.statusCode}: ${res.statusMessage}`));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
resolve(JSON.parse(data));
|
||||
resolve({ data: JSON.parse(data), etag: res.headers.etag || null });
|
||||
} catch (e) {
|
||||
reject(new Error('Invalid JSON response'));
|
||||
}
|
||||
@@ -120,7 +196,13 @@ class UpdateClient {
|
||||
}
|
||||
|
||||
if (res.statusCode !== 200) {
|
||||
reject(new Error(`HTTP ${res.statusCode}: ${res.statusMessage}`));
|
||||
res.resume();
|
||||
const err = new Error(`HTTP ${res.statusCode}: ${res.statusMessage}`);
|
||||
const retryAfter = parseInt(res.headers['retry-after'], 10);
|
||||
if (Number.isFinite(retryAfter)) {
|
||||
err.retryAfterMs = Math.min(retryAfter * 1000, MAX_RETRY_AFTER_MS);
|
||||
}
|
||||
reject(err);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -236,12 +318,32 @@ class UpdateClient {
|
||||
});
|
||||
}
|
||||
|
||||
async checkForUpdates() {
|
||||
const query = `?per_page=20&order_by=released_at&sort=desc&cb=${Date.now()}`;
|
||||
const releases = await this.fetchJson(RELEASES_API + query);
|
||||
if (!releases || releases.length === 0) {
|
||||
async checkForUpdates(force = false) {
|
||||
const cache = this.readCache();
|
||||
const now = Date.now();
|
||||
|
||||
if (!force && cache.blockedUntil && now < cache.blockedUntil) {
|
||||
return null;
|
||||
}
|
||||
if (!force && cache.checkedAt && now - cache.checkedAt < MIN_CHECK_INTERVAL_MS && this.cacheUsable(cache.release)) {
|
||||
return cache.release;
|
||||
}
|
||||
|
||||
const listUrl = `${RELEASES_API}?per_page=20&order_by=released_at&sort=desc`;
|
||||
let result = await this.fetchJson(listUrl, force ? null : cache.etag);
|
||||
if (result.notModified) {
|
||||
if (this.cacheUsable(cache.release)) {
|
||||
this.writeCache({ checkedAt: now });
|
||||
return cache.release;
|
||||
}
|
||||
result = await this.fetchJson(listUrl, null);
|
||||
}
|
||||
|
||||
const releases = result.data;
|
||||
if (!Array.isArray(releases) || releases.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const verParts = (v) => String(v || '').replace(/^v/, '').split(/[.\-+]/).map((n) => parseInt(n, 10) || 0);
|
||||
const cmp = (a, b) => {
|
||||
const x = verParts(a);
|
||||
@@ -252,25 +354,41 @@ class UpdateClient {
|
||||
return 0;
|
||||
};
|
||||
const release = releases.slice().sort((a, b) => cmp(b.tag_name, a.tag_name))[0];
|
||||
const links = release.assets && release.assets.links ? release.assets.links : [];
|
||||
const manifestAsset = links.find((a) => a.name === 'manifest.json');
|
||||
|
||||
const payloadAsset = (release.assets && release.assets.links ? release.assets.links : []).find(a => a.name === 'update-payload.zip');
|
||||
const manifestAsset = (release.assets && release.assets.links ? release.assets.links : []).find(a => a.name === 'manifest.json');
|
||||
|
||||
if (!payloadAsset) {
|
||||
return null;
|
||||
if (!manifestAsset) {
|
||||
throw new Error(`Release ${release.tag_name} has no manifest.json.`);
|
||||
}
|
||||
|
||||
let sha256 = null;
|
||||
if (manifestAsset) {
|
||||
const manifest = await this.fetchAssetJson(manifestAsset.url);
|
||||
sha256 = manifest.sha256 || null;
|
||||
const manifest = await this.fetchAssetJson(manifestAsset.url);
|
||||
if (!manifest.components) {
|
||||
throw new Error(`Release ${release.tag_name} has no signed component manifest.`);
|
||||
}
|
||||
if (!verifyManifest(manifest)) {
|
||||
throw new Error('Update manifest signature is invalid.');
|
||||
}
|
||||
if (normalizeTag(manifest.version) !== normalizeTag(release.tag_name)) {
|
||||
throw new Error('Update manifest version does not match the release tag.');
|
||||
}
|
||||
|
||||
return {
|
||||
const components = {};
|
||||
for (const [name, c] of Object.entries(manifest.components)) {
|
||||
const link = links.find((a) => a.name === c.file);
|
||||
if (!link) {
|
||||
throw new Error(`Release is missing asset ${c.file}.`);
|
||||
}
|
||||
components[name] = { url: link.url, sha256: c.sha256, id: c.id, size: c.size };
|
||||
}
|
||||
|
||||
const out = {
|
||||
version: release.tag_name,
|
||||
url: payloadAsset.url,
|
||||
sha256
|
||||
sha256: manifest.sha256 || null,
|
||||
manifest,
|
||||
components
|
||||
};
|
||||
this.writeCache({ checkedAt: now, etag: result.etag || null, release: out });
|
||||
return out;
|
||||
}
|
||||
|
||||
async downloadUpdate(release, destPath, onProgress) {
|
||||
@@ -279,4 +397,7 @@ class UpdateClient {
|
||||
}
|
||||
}
|
||||
|
||||
UpdateClient.canonicalManifest = canonicalManifest;
|
||||
UpdateClient.verifyManifest = verifyManifest;
|
||||
|
||||
module.exports = UpdateClient;
|
||||
|
||||
Reference in New Issue
Block a user