/** * Mobile app release lifecycle: admin CRUD, APK validation, public check/download, telemetry. */ import crypto from 'crypto'; import fs from 'fs'; import path from 'path'; import { config } from '../config'; import { HttpError } from '../utils/httpError'; import { parseApkFile } from '../utils/apkParser'; import { scanUploadedFile } from './virusScanService'; import { getApkMaxUploadBytes, moveApkToPublished, removeApkIfExists, resolveApkStoragePath, sha256File, } from './apkStorageService'; import * as repo from '../repositories/mobileAppReleaseRepository'; import { recordUploadedFile, FILE_INTEGRITY_ROOTS } from './fileIntegrityService'; import type { MobileAppRelease, MobileChannel, MobileReleaseEventType, MobileUpdatePolicy, } from '../models/mobileAppRelease.model'; export class MobileReleaseError extends HttpError { constructor(status: number, message: string, code?: string) { super(status, message, code); this.name = 'MobileReleaseError'; } } /** Deterministic rollout bucket 0–99 from device id. */ export function rolloutBucket(deviceId: string): number { const hash = crypto.createHash('sha256').update(String(deviceId || 'anonymous')).digest(); return hash.readUInt32BE(0) % 100; } export function isRolloutEligible(deviceId: string, rolloutPercent: number): boolean { if (rolloutPercent >= 100) return true; if (rolloutPercent <= 0) return false; return rolloutBucket(deviceId) < rolloutPercent; } export function hashDeviceId(deviceId: string): string { return crypto.createHash('sha256').update(`tloto-device:${deviceId}`).digest('hex').slice(0, 32); } function signDownloadToken(releaseId: string, exp: number): string { const payload = `${releaseId}.${exp}`; const sig = crypto .createHmac('sha256', config.mobileReleases.downloadTokenSecret) .update(payload) .digest('base64url'); return `${payload}.${sig}`; } export function createDownloadToken(releaseId: string): { token: string; expiresAt: number } { const expiresAt = Math.floor(Date.now() / 1000) + config.mobileReleases.downloadTokenTtlSeconds; return { token: signDownloadToken(releaseId, expiresAt), expiresAt }; } export function verifyDownloadToken(token: string, releaseId: string): boolean { const parts = token.split('.'); if (parts.length !== 3) return false; const [id, expStr, sig] = parts; if (id !== releaseId) return false; const exp = parseInt(expStr, 10); if (!Number.isFinite(exp) || exp < Math.floor(Date.now() / 1000)) return false; const expected = signDownloadToken(releaseId, exp); try { return crypto.timingSafeEqual(Buffer.from(token), Buffer.from(expected)); } catch { return false; } } function publicDownloadPath(releaseId: string, token: string): string { const api = config.apiPrefix.replace(/\/$/, ''); return `${api}/app-updates/android/download/${releaseId}?token=${encodeURIComponent(token)}`; } function publicDownloadUrl(releaseId: string, token: string): string { const base = config.app.publicUrl.replace(/\/$/, ''); return `${base}${publicDownloadPath(releaseId, token)}`; } /** Latest published Android APK for the public website (ignores staged rollout). */ export async function getLatestPublicAndroidApk(channel: MobileChannel = 'production'): Promise<{ available: boolean; versionName: string | null; versionCode: number | null; fileSizeBytes: number | null; sha256: string | null; /** Absolute URL using APP_PUBLIC_URL (may differ from the browser origin). */ downloadUrl: string | null; /** Same-origin path — prefer this on the landing page. */ downloadPath: string | null; publishedAt: string | null; packageName: string | null; }> { const latest = await repo.findLatestPublished('android', channel); if (!latest || !latest.storageKey || !latest.sha256) { return { available: false, versionName: null, versionCode: null, fileSizeBytes: null, sha256: null, downloadUrl: null, downloadPath: null, publishedAt: null, packageName: null, }; } const { token } = createDownloadToken(latest.id); return { available: true, versionName: latest.versionName, versionCode: latest.versionCode, fileSizeBytes: latest.fileSizeBytes, sha256: latest.sha256, downloadUrl: publicDownloadUrl(latest.id, token), downloadPath: publicDownloadPath(latest.id, token), publishedAt: latest.publishedAt?.toISOString() ?? null, packageName: latest.packageName, }; } export async function getSettings() { return repo.getSettings(); } export async function updateSettings(input: { minSupportedVersionCode?: number; checkIntervalSeconds?: number; expectedPackageName?: string; }) { return repo.updateSettings(input); } export async function listReleases(filters: Parameters[0]) { return repo.listReleases(filters); } export async function getRelease(id: string) { const release = await repo.findById(id); if (!release) throw new MobileReleaseError(404, 'Release not found'); return release; } export async function createRelease(input: { platform?: 'android' | 'ios'; channel?: MobileChannel; versionName: string; versionCode: number; previousVersionName?: string | null; whatsNew?: string; bugFixes?: string; updatePolicy?: MobileUpdatePolicy; rolloutPercent?: number; createdBy?: string | null; }) { if (input.platform === 'ios') { throw new MobileReleaseError(400, 'iOS IPA distribution is not supported; use App Store / TestFlight'); } try { return await repo.createRelease({ platform: 'android', channel: input.channel ?? 'production', versionName: input.versionName, versionCode: input.versionCode, previousVersionName: input.previousVersionName, whatsNew: input.whatsNew, bugFixes: input.bugFixes, updatePolicy: input.updatePolicy, rolloutPercent: input.rolloutPercent, createdBy: input.createdBy, }); } catch (e) { const msg = e instanceof Error ? e.message : String(e); if (/unique|duplicate/i.test(msg)) { throw new MobileReleaseError(409, 'A release with this versionCode already exists for the channel'); } throw e; } } export async function updateReleaseMeta( id: string, patch: { versionName?: string; previousVersionName?: string | null; whatsNew?: string; bugFixes?: string; updatePolicy?: MobileUpdatePolicy; rolloutPercent?: number; } ) { const existing = await getRelease(id); if (existing.status === 'retired') { throw new MobileReleaseError(400, 'Retired releases cannot be edited'); } const updated = await repo.updateRelease(id, patch); if (!updated) throw new MobileReleaseError(404, 'Release not found'); return updated; } export async function attachApk(id: string, uploadedAbsolutePath: string): Promise { const release = await getRelease(id); if (!['draft', 'pending_validation', 'suspended'].includes(release.status)) { throw new MobileReleaseError(400, 'APK can only be uploaded for draft, pending, or suspended releases'); } const stat = fs.statSync(uploadedAbsolutePath); if (stat.size > getApkMaxUploadBytes()) { removeApkIfExists(`staging/${path.basename(uploadedAbsolutePath)}`); throw new MobileReleaseError(400, 'APK exceeds maximum upload size'); } try { await scanUploadedFile(uploadedAbsolutePath); } catch (e) { removeApkIfExists(`staging/${path.basename(uploadedAbsolutePath)}`); throw new MobileReleaseError(422, e instanceof Error ? e.message : 'Virus scan failed'); } let parsed; try { parsed = await parseApkFile(uploadedAbsolutePath); } catch (e) { removeApkIfExists(`staging/${path.basename(uploadedAbsolutePath)}`); throw new MobileReleaseError(400, e instanceof Error ? e.message : 'Invalid APK'); } const settings = await repo.getSettings(); const expectedPackage = config.mobileReleases.expectedPackage || settings.expectedPackageName; if (parsed.packageName !== expectedPackage) { removeApkIfExists(`staging/${path.basename(uploadedAbsolutePath)}`); throw new MobileReleaseError( 400, `APK package "${parsed.packageName}" does not match expected "${expectedPackage}"` ); } // Draft/pending: adopt APK versionCode/name when they differ (admin often mistypes the form). let nextVersionCode = release.versionCode; if (parsed.versionCode !== release.versionCode) { const conflict = await repo.findByPlatformChannelVersionCode( release.platform, release.channel, parsed.versionCode ); if (conflict && conflict.id !== release.id) { removeApkIfExists(`staging/${path.basename(uploadedAbsolutePath)}`); throw new MobileReleaseError( 409, `APK versionCode ${parsed.versionCode} is already used by another release (${conflict.versionName})` ); } nextVersionCode = parsed.versionCode; } const expectedCert = config.mobileReleases.expectedCertSha256; if (expectedCert) { if (!parsed.signingCertSha256) { removeApkIfExists(`staging/${path.basename(uploadedAbsolutePath)}`); throw new MobileReleaseError(400, 'Could not read APK signing certificate'); } if (parsed.signingCertSha256.toLowerCase() !== expectedCert) { removeApkIfExists(`staging/${path.basename(uploadedAbsolutePath)}`); throw new MobileReleaseError(400, 'APK signing certificate does not match the expected fingerprint'); } } if (release.storageKey) removeApkIfExists(release.storageKey); const stagingKey = `staging/${path.basename(uploadedAbsolutePath)}`; const fileSha = await sha256File(uploadedAbsolutePath); const updated = await repo.updateRelease(id, { packageName: parsed.packageName, versionName: parsed.versionName || release.versionName, versionCode: nextVersionCode, storageKey: stagingKey, fileSizeBytes: stat.size, sha256: fileSha, signingCertSha256: parsed.signingCertSha256, status: release.status === 'draft' ? 'pending_validation' : release.status, }); if (!updated) throw new MobileReleaseError(404, 'Release not found'); return updated; } export async function submitForValidation(id: string) { const release = await getRelease(id); if (!release.storageKey || !release.sha256) { throw new MobileReleaseError(400, 'Upload an APK before submitting for validation'); } if (release.status !== 'draft' && release.status !== 'pending_validation') { throw new MobileReleaseError(400, 'Only draft releases can be submitted'); } const updated = await repo.updateRelease(id, { status: 'pending_validation' }); if (!updated) throw new MobileReleaseError(404, 'Release not found'); return updated; } export async function publish(id: string) { const release = await getRelease(id); if (!['pending_validation', 'suspended', 'draft'].includes(release.status)) { throw new MobileReleaseError(400, 'Release cannot be published from its current status'); } if (!release.storageKey || !release.sha256 || !release.fileSizeBytes) { throw new MobileReleaseError(400, 'APK file is required before publication'); } const settings = await repo.getSettings(); const expectedPackage = config.mobileReleases.expectedPackage || settings.expectedPackageName; if (release.packageName && release.packageName !== expectedPackage) { throw new MobileReleaseError(400, 'Package name mismatch — re-upload the APK'); } const expectedCert = config.mobileReleases.expectedCertSha256; if (expectedCert && release.signingCertSha256?.toLowerCase() !== expectedCert) { throw new MobileReleaseError(400, 'Signing certificate fingerprint mismatch'); } const latest = await repo.findLatestPublished(release.platform, release.channel); if (latest && latest.versionCode >= release.versionCode && latest.id !== release.id) { throw new MobileReleaseError( 400, `versionCode must be strictly greater than the current published release (${latest.versionCode})` ); } let storageKey = release.storageKey; if (storageKey.startsWith('staging/')) { storageKey = moveApkToPublished(storageKey, release.id); try { await recordUploadedFile(FILE_INTEGRITY_ROOTS.apkPublished, `${release.id}.apk`); } catch (e) { console.warn('[mobile-releases] FIM baseline skipped:', e); } } const updated = await repo.updateRelease(id, { storageKey, status: 'published', publishedAt: new Date(), }); if (!updated) throw new MobileReleaseError(404, 'Release not found'); return updated; } export async function suspend(id: string) { const release = await getRelease(id); if (release.status !== 'published') { throw new MobileReleaseError(400, 'Only published releases can be suspended'); } const updated = await repo.updateRelease(id, { status: 'suspended' }); if (!updated) throw new MobileReleaseError(404, 'Release not found'); return updated; } export async function retire(id: string) { const release = await getRelease(id); if (release.status === 'retired') return release; const updated = await repo.updateRelease(id, { status: 'retired' }); if (!updated) throw new MobileReleaseError(404, 'Release not found'); return updated; } export type UpdateCheckResult = { updateAvailable: boolean; blocked: boolean; policy: MobileUpdatePolicy | null; versionName: string | null; versionCode: number | null; whatsNew: string | null; bugFixes: string | null; fileSizeBytes: number | null; sha256: string | null; downloadUrl: string | null; /** Same-origin API path — prefer this on mobile so APP_PUBLIC_URL host mismatches do not apply. */ downloadPath: string | null; minSupportedVersionCode: number; checkIntervalSeconds: number; publishedAt: string | null; packageName: string | null; }; export async function checkAndroidUpdate(input: { versionCode: number; versionName?: string; channel?: MobileChannel; deviceId: string; }): Promise { const channel = input.channel ?? 'production'; const settings = await repo.getSettings(); const latest = await repo.findLatestPublished('android', channel); const mandatory = await repo.findHighestMandatoryPublished('android', channel); const minSupported = settings.minSupportedVersionCode; const blocked = input.versionCode < minSupported; await repo.insertEvent({ releaseId: latest?.id ?? null, eventType: 'check', platform: 'android', channel, clientVersionCode: input.versionCode, deviceIdHash: hashDeviceId(input.deviceId), }); const base: UpdateCheckResult = { updateAvailable: false, blocked, policy: null, versionName: null, versionCode: null, whatsNew: null, bugFixes: null, fileSizeBytes: null, sha256: null, downloadUrl: null, downloadPath: null, minSupportedVersionCode: minSupported, checkIntervalSeconds: settings.checkIntervalSeconds, publishedAt: null, packageName: settings.expectedPackageName, }; if (!latest || latest.versionCode <= input.versionCode) { return base; } if (!isRolloutEligible(input.deviceId, latest.rolloutPercent)) { return base; } const { token } = createDownloadToken(latest.id); let policy: MobileUpdatePolicy = latest.updatePolicy; if (mandatory && mandatory.versionCode > input.versionCode) { policy = 'mandatory'; } if (blocked) policy = 'mandatory'; return { ...base, updateAvailable: true, policy, versionName: latest.versionName, versionCode: latest.versionCode, whatsNew: latest.whatsNew, bugFixes: latest.bugFixes, fileSizeBytes: latest.fileSizeBytes, sha256: latest.sha256, downloadUrl: publicDownloadUrl(latest.id, token), downloadPath: publicDownloadPath(latest.id, token), publishedAt: latest.publishedAt?.toISOString() ?? null, packageName: latest.packageName, }; } export async function openDownloadStream(releaseId: string, token: string): Promise<{ release: MobileAppRelease; absolutePath: string; }> { if (!verifyDownloadToken(token, releaseId)) { throw new MobileReleaseError(403, 'Invalid or expired download token'); } const release = await getRelease(releaseId); if (release.status !== 'published' || !release.storageKey) { throw new MobileReleaseError(404, 'Release is not available for download'); } const absolutePath = resolveApkStoragePath(release.storageKey); if (!fs.existsSync(absolutePath)) { throw new MobileReleaseError(404, 'APK file missing on server'); } await repo.insertEvent({ releaseId, eventType: 'download_start', platform: release.platform, channel: release.channel, }); await repo.incrementCounter(releaseId, 'download_count'); return { release, absolutePath }; } export async function recordClientEvent(input: { eventType: MobileReleaseEventType; releaseId?: string; versionCode?: number; deviceId?: string; userId?: string | null; channel?: MobileChannel; }) { const allowed: MobileReleaseEventType[] = [ 'download_start', 'download_ok', 'download_fail', 'install_confirm', ]; if (!allowed.includes(input.eventType)) { throw new MobileReleaseError(400, 'Unsupported event type'); } // download_count is incremented when the authenticated download stream starts. if (input.releaseId && input.eventType === 'download_fail') { await repo.incrementCounter(input.releaseId, 'download_fail_count'); } if (input.releaseId && input.eventType === 'install_confirm') { await repo.incrementCounter(input.releaseId, 'install_confirm_count'); } await repo.insertEvent({ releaseId: input.releaseId ?? null, eventType: input.eventType, platform: 'android', channel: input.channel ?? 'production', clientVersionCode: input.versionCode ?? null, deviceIdHash: input.deviceId ? hashDeviceId(input.deviceId) : null, userId: input.userId ?? null, }); } export async function getStats() { return repo.getStatsSummary('android'); } /** * Returns whether a client versionCode is allowed to call sensitive APIs. * When blocked, returns the update payload for a 426 response. */ export async function evaluateClientVersionGate(versionCode: number | null): Promise<{ allowed: boolean; update?: UpdateCheckResult; }> { if (versionCode == null || !Number.isFinite(versionCode)) { // Web / unknown clients are not gated by mobile version headers. return { allowed: true }; } const settings = await repo.getSettings(); const mandatory = await repo.findHighestMandatoryPublished('android', 'production'); const latest = await repo.findLatestPublished('android', 'production'); const belowMin = versionCode < settings.minSupportedVersionCode; const behindMandatory = !!mandatory && mandatory.versionCode > versionCode; if (!belowMin && !behindMandatory) return { allowed: true }; const target = mandatory && mandatory.versionCode > versionCode ? mandatory : latest; if (!target) { return { allowed: false, update: { updateAvailable: false, blocked: true, policy: 'mandatory', versionName: null, versionCode: null, whatsNew: null, bugFixes: null, fileSizeBytes: null, sha256: null, downloadUrl: null, downloadPath: null, minSupportedVersionCode: settings.minSupportedVersionCode, checkIntervalSeconds: settings.checkIntervalSeconds, publishedAt: null, packageName: settings.expectedPackageName, }, }; } const { token } = createDownloadToken(target.id); return { allowed: false, update: { updateAvailable: true, blocked: true, policy: 'mandatory', versionName: target.versionName, versionCode: target.versionCode, whatsNew: target.whatsNew, bugFixes: target.bugFixes, fileSizeBytes: target.fileSizeBytes, sha256: target.sha256, downloadUrl: publicDownloadUrl(target.id, token), downloadPath: publicDownloadPath(target.id, token), minSupportedVersionCode: settings.minSupportedVersionCode, checkIntervalSeconds: settings.checkIntervalSeconds, publishedAt: target.publishedAt?.toISOString() ?? null, packageName: target.packageName, }, }; }