import { createHash, createPublicKey, randomUUID, verify } from 'node:crypto'; import { mkdir, rename, open, rm } from 'node:fs/promises'; import { dirname } from 'node:path'; export class UpdateError extends Error {} const MAX_PACKAGE_BYTES = 64 * 1024 * 1024; const REQUIRED = new Set(['version','instance_id','product_id','customer_id','current_version','platform','arch','channel','server_time','expires_at','policy_revision','policy_enabled','recommended_version','minimum_supported_version','enforce_after','mandatory','required_now','update_available','download_allowed','release_id','sha256','size_bytes','message']); const instant = value => { if (typeof value !== 'string' || !value.endsWith('Z')) throw new UpdateError('invalid_time'); const n = Date.parse(value); if (!Number.isFinite(n)) throw new UpdateError('invalid_time'); return n; }; const decode = value => { if (typeof value !== 'string' || !value || !/^[A-Za-z0-9+/]+$/.test(value)) throw new UpdateError('invalid_signature'); return Buffer.from(value, 'base64'); }; export function verifyCheck(envelope, publicKeys, expectedInstance, { now = Date.now(), previous = null, expectedPlatform = null, expectedArch = null, expectedChannel = null, expectedCurrentVersion = null } = {}) { if (!envelope || typeof envelope.payload !== 'string' || typeof envelope.key_id !== 'string') throw new UpdateError('invalid_payload'); let raw, p; try { raw = decode(envelope.payload); p = JSON.parse(raw.toString('utf8')); } catch { throw new UpdateError('invalid_payload'); } if (!p || p.version !== 'update-v1' || p.instance_id !== expectedInstance || (expectedPlatform !== null && p.platform !== expectedPlatform) || (expectedArch !== null && p.arch !== expectedArch) || (expectedChannel !== null && p.channel !== expectedChannel) || (expectedCurrentVersion !== null && p.current_version !== expectedCurrentVersion) || REQUIRED.size !== Object.keys(p).length || [...REQUIRED].some(k => !(k in p))) throw new UpdateError('invalid_context'); const pem = publicKeys[envelope.key_id]; if (!pem) throw new UpdateError('unknown_key'); const key = createPublicKey(pem); if (key.asymmetricKeyType !== 'ec' || key.asymmetricKeyDetails?.namedCurve !== 'prime256v1') throw new UpdateError('invalid_key'); if (!verify('sha256', raw, key, decode(envelope.signature))) throw new UpdateError('invalid_signature'); const server = instant(p.server_time), expiry = instant(p.expires_at); if (expiry <= now || expiry - server > 900000 || Math.abs(server - now) > 300000) throw new UpdateError('expired_or_clock_skew'); if (!Number.isSafeInteger(p.policy_revision) || p.policy_revision < 0 || (previous && p.policy_revision < previous.policy_revision)) throw new UpdateError('policy_rollback'); if (!Number.isSafeInteger(p.size_bytes) || p.size_bytes < 0 || !Number.isSafeInteger(p.release_id) || p.release_id < 0) throw new UpdateError('invalid_release'); return { payload: p, signature: decode(envelope.signature) }; } export class UpdateClient { constructor({ baseUrl, instanceId, secret, publicKeys, state = null, fetchImpl = fetch, clock = () => Date.now() }) { const u = new URL(baseUrl); if (u.protocol !== 'https:' || u.pathname !== '/' || u.search || u.hash) throw new Error('base_url_must_be_https_origin'); this.baseUrl = u; this.instanceId = instanceId; this.secret = secret; this.publicKeys = publicKeys; this.state = state; this.fetch = fetchImpl; this.clock = clock; } scope(platform, arch, channel) { return JSON.stringify([this.instanceId, platform, arch, channel]); } previous(platform, arch, channel) { const stored = this.state?.load?.(); if (!stored) return null; const key = this.scope(platform, arch, channel); if (stored.scope === key) return stored; return stored.scopes?.[key] ?? null; } async check(currentVersion, platform, arch, channel) { const response = await this.fetch(new URL(`api/v1/instances/${this.instanceId}/updates/check`, this.baseUrl), { method: 'POST', redirect: 'error', headers: {'content-type':'application/json'}, body: JSON.stringify({secret:this.secret,current_version:currentVersion,platform,arch,channel}) }); if (!response.ok) throw new UpdateError(`check_http_${response.status}`); const result = verifyCheck((await response.json()).data, this.publicKeys, this.instanceId, { now: this.clock(), previous: this.previous(platform, arch, channel), expectedPlatform: platform, expectedArch: arch, expectedChannel: channel, expectedCurrentVersion: currentVersion }); if (this.state) { const scope = this.scope(platform, arch, channel); const stored = this.state.load?.() ?? {}; const scopes = { ...(stored.scopes ?? {}) }; const entry = { scope, instance_id:this.instanceId, policy_revision:result.payload.policy_revision, server_time:result.payload.server_time, accepted_at:this.clock() }; scopes[scope] = entry; this.state.saveAtomic?.({ ...entry, scopes }); } return result; } async download(result, destination, { signal = null, timeoutMs = 30000 } = {}) { const p = result.payload; if (!p.download_allowed || !p.update_available || !p.release_id) throw new UpdateError('download_not_allowed'); const controller = new AbortController(); const timer = setTimeout(() => controller.abort(new UpdateError('download_timeout')), timeoutMs); const abort = () => controller.abort(signal.reason); if (signal) { if (signal.aborted) abort(); else signal.addEventListener('abort', abort, { once:true }); } let response = null; let tmp = null; try { if (!Number.isSafeInteger(p.size_bytes) || p.size_bytes < 0 || p.size_bytes > MAX_PACKAGE_BYTES) throw new UpdateError('package_too_large'); response = await this.fetch(new URL(`api/v1/customers/${p.customer_id}/releases/${p.release_id}/download`, this.baseUrl), { method:'POST', redirect:'error', signal:controller.signal, headers:{'content-type':'application/json'}, body:JSON.stringify({instance_id:this.instanceId,secret:this.secret}) }); if (response.status !== 200) throw new UpdateError(`download_http_${response.status}`); await mkdir(dirname(destination), { recursive:true }); tmp = `${destination}.tmp-${randomUUID()}`; let total = 0; const hash = createHash('sha256'); const file = await open(tmp, 'wx'); try { for await (const chunk of response.body) { total += chunk.length; if (total > p.size_bytes || total > MAX_PACKAGE_BYTES) throw new UpdateError('package_too_large'); hash.update(chunk); await file.write(chunk); } } finally { await file.close(); } if (total !== p.size_bytes || hash.digest('hex').toLowerCase() !== p.sha256.toLowerCase()) throw new UpdateError('package_integrity_failed'); await rename(tmp, destination); tmp = null; return destination; } catch (error) { controller.abort(); try { await response?.body?.cancel?.(); } catch {} if (tmp) await rm(tmp, { force:true }); throw error; } finally { clearTimeout(timer); signal?.removeEventListener('abort', abort); } } install(packagePath, installer) { return installer(packagePath); } }