/** * Tests for `npx scribase ota` (PS3.1): arguments, the deploy flow (set up * when needed, config and env written once, the secret key only in the child * process), roll back and status, with no network and in-memory files. */ import { describe, it } from 'node:test'; import assert from 'node:assert/strict'; import { CONFIG_FILE, CONFIG_TEMPLATE, formatOta, otaMain, parseOtaArgs, runOta } from '../src/cli/capabilities/ota.js'; import type { OtaIo, OtaStatus } from '../src/cli/capabilities/ota.js'; import { InitError } from '../src/cli/init.js'; const ROOT = '/work/app'; const STATE = JSON.stringify({ organization_id: 'acme', project_id: 'shop', environment_id: 'production', api_url: 'https://api.example.test' }); const SECRET = 'sb_secret_abcdefghijklmnopqrstuvwxyz0123456789'; const URL_BASE = 'https://api.example.test/v1/organizations/acme/projects/shop/environments/production'; const RELEASE = { id: '0199a000-0000-7000-8000-000000000002', platform: 'ios', channel: 'production', target_app_version: '1.x.x', fingerprint_hash: null, enabled: true, force_update: false, rollout_percent: 100, message: 'fix login', created_at_epoch_seconds: 1759200000, }; function status(overrides: Partial = {}): OtaStatus { return { enabled: true, conflict: false, update_url: 'https://acme-shop.scribase.app/functions/v1/ota', bucket: 'ota-bundles', releases: 1, latest: [RELEASE as OtaStatus['latest'][number]], ...overrides, }; } type Answer = { status: number; body: unknown }; function fakeIo(routes: Record, files: Record = {}, runCode = 0) { const store: Record = { [`${ROOT}/.scribase/project.json`]: STATE, ...files }; const calls: { method: string; url: string; body: unknown; auth: string | null }[] = []; const runs: { command: string; args: string[]; env: Record }[] = []; const logs: string[] = []; const io: OtaIo = { cwd: ROOT, env: { SCRIBASE_ACCESS_TOKEN: 'pat_token' }, fetch: (async (url: string | URL | Request, init?: RequestInit) => { const method = init?.method ?? 'GET'; const path = String(url).slice(URL_BASE.length); calls.push({ method, url: String(url), body: init?.body ? JSON.parse(String(init.body)) : undefined, auth: new Headers(init?.headers).get('authorization') }); const entry = routes[`${method} ${path}`]; const answer = Array.isArray(entry) ? entry.shift() : entry; if (!answer) return new Response('{"code":"not_found","detail":"no route"}', { status: 404 }); return new Response(JSON.stringify(answer.body), { status: answer.status }); }) as typeof fetch, readFile: (path) => store[path] ?? null, writeFile: (path, contents) => { store[path] = contents; }, credentials: () => ({}), log: (line) => logs.push(line), run: async (command, args, env) => { runs.push({ command, args, env }); return runCode; }, }; return { io, calls, runs, store, logs }; } describe('scribase ota arguments', () => { it('reads the action, platform, channel and deploy flags', () => { assert.deepEqual(parseOtaArgs(['deploy', '-p', 'ios', '-m', 'fix', '-r', '25', '-f']), { action: 'deploy', platform: 'ios', channel: 'production', passthrough: ['-m', 'fix', '-r', '25', '-f'], json: false, }); assert.equal(parseOtaArgs(['rollback', '--platform', 'android', '-c', 'beta']).channel, 'beta'); assert.equal(parseOtaArgs(['status', '--json']).json, true); }); it('refuses a missing platform, an unknown one, a bad channel and unknown flags', () => { assert.throws(() => parseOtaArgs(['deploy']), InitError); assert.throws(() => parseOtaArgs(['deploy', '-p', 'web']), InitError); assert.throws(() => parseOtaArgs(['rollback', '-p', 'ios', '-c', 'a/b']), InitError); assert.throws(() => parseOtaArgs(['status', '--secret', 'x']), InitError); assert.throws(() => parseOtaArgs(['rollback', '-p', 'ios', '-m', 'x']), InitError); assert.throws(() => parseOtaArgs(['publish']), InitError); assert.throws(() => parseOtaArgs(['deploy', '-p']), InitError); }); }); describe('scribase ota deploy', () => { it('sets OTA up when needed, writes the config and the public URL, and gives the key only to the child', async () => { const { io, calls, runs, store } = fakeIo({ 'GET /ota': [ { status: 200, body: status({ enabled: false, latest: [], releases: 0 }) }, { status: 200, body: status() }, ], 'POST /ota': { status: 200, body: status({ latest: [], releases: 0 }) }, 'GET /api-keys': { status: 200, body: { api_url: 'https://acme-shop.scribase.app/', secret_key: SECRET, anon_key: 'anon' } }, }); const result = await runOta(parseOtaArgs(['deploy', '-p', 'ios', '-m', 'fix login']), io); assert.equal(result.action, 'deploy'); assert.ok(result.action === 'deploy' && result.set_up && result.config_written); assert.deepEqual(result.action === 'deploy' && result.env_written, ['EXPO_PUBLIC_HOT_UPDATER_URL']); assert.equal(result.action === 'deploy' && result.release?.id, RELEASE.id); assert.equal(store[`${ROOT}/${CONFIG_FILE}`], CONFIG_TEMPLATE); assert.match(store[`${ROOT}/.env`] ?? '', /EXPO_PUBLIC_HOT_UPDATER_URL=.*functions\/v1\/ota/); for (const contents of Object.values(store)) assert.ok(!contents.includes(SECRET), 'the secret key is never written'); assert.equal(runs.length, 1); assert.deepEqual(runs[0]?.args, ['--yes', 'hot-updater@0.36.16', 'deploy', '-p', 'ios', '-c', 'production', '-m', 'fix login']); assert.equal(runs[0]?.env.HOT_UPDATER_SUPABASE_SERVICE_ROLE_KEY, SECRET); assert.equal(runs[0]?.env.HOT_UPDATER_SUPABASE_URL, 'https://acme-shop.scribase.app'); assert.equal(runs[0]?.env.HOT_UPDATER_SUPABASE_BUCKET_NAME, 'ota-bundles'); assert.ok(calls.every((call) => call.auth === 'Bearer pat_token')); assert.deepEqual(calls.map((call) => `${call.method} ${call.url.slice(URL_BASE.length)}`), ['GET /ota', 'POST /ota', 'GET /api-keys', 'GET /ota']); }); it('keeps an existing config and env value and does not set up twice', async () => { const { io, calls, store } = fakeIo( { 'GET /ota': { status: 200, body: status() }, 'GET /api-keys': { status: 200, body: { api_url: 'https://acme-shop.scribase.app', service_role_key: 'eyJ.service.jwt' } }, }, { [`${ROOT}/${CONFIG_FILE}`]: '// mine', [`${ROOT}/.env.local`]: 'EXPO_PUBLIC_HOT_UPDATER_URL=https://acme-shop.scribase.app/functions/v1/ota\n', }, ); const result = await runOta(parseOtaArgs(['deploy', '-p', 'ios']), io); assert.ok(result.action === 'deploy' && !result.set_up && !result.config_written && result.env_written.length === 0); assert.equal(store[`${ROOT}/${CONFIG_FILE}`], '// mine'); assert.ok(!calls.some((call) => call.method === 'POST')); }); it('stops on a foreign bundles table, a role without the key, or a failed upload', async () => { await assert.rejects( runOta(parseOtaArgs(['deploy', '-p', 'ios']), fakeIo({ 'GET /ota': { status: 200, body: status({ enabled: false, conflict: true }) } }).io), /own public.bundles/, ); await assert.rejects( runOta( parseOtaArgs(['deploy', '-p', 'ios']), fakeIo({ 'GET /ota': { status: 200, body: status() }, 'GET /api-keys': { status: 200, body: { api_url: 'https://x', secret_key: null } } }).io, ), /secret key/, ); await assert.rejects( runOta( parseOtaArgs(['deploy', '-p', 'android']), fakeIo({ 'GET /ota': { status: 200, body: status() }, 'GET /api-keys': { status: 200, body: { api_url: 'https://x', secret_key: SECRET } } }, {}, 1).io, ), /exited with code 1/, ); }); }); describe('scribase ota rollback and status', () => { it('rolls back the newest release and names what devices go back to', async () => { const { io, calls } = fakeIo({ 'POST /ota/rollback': { status: 200, body: { turned_off: RELEASE.id, now_serving: null, platform: 'ios', channel: 'production' } }, }); const result = await runOta(parseOtaArgs(['rollback', '-p', 'ios']), io); assert.deepEqual(calls[0]?.body, { platform: 'ios', channel: 'production' }); assert.match(formatOta(result), /go back to the bundle built into the app/); }); it('prints the published releases, or how to start', async () => { const on = await runOta(parseOtaArgs(['status']), fakeIo({ 'GET /ota': { status: 200, body: status() } }).io); assert.match(formatOta(on), /ios production: 0199a000-0000-7000-8000-000000000002 \(on for 100% of devices, app 1\.x\.x\)/); const off = await runOta(parseOtaArgs(['status']), fakeIo({ 'GET /ota': { status: 200, body: status({ enabled: false }) } }).io); assert.match(formatOta(off), /not set up yet/); }); it('prints the API refusal and exits 1; help exits 0', async () => { const lines: string[] = []; const code = await otaMain( ['rollback', '-p', 'ios'], fakeIo({ 'POST /ota/rollback': { status: 409, body: { code: 'nothing_to_roll_back', detail: 'no release is on for ios on the production channel' } } }).io, (text) => lines.push(text), ); assert.equal(code, 1); assert.match(lines.join(''), /no release is on for ios \(HTTP 409\)|no release is on for ios on the production channel \(HTTP 409\)/); assert.equal(await otaMain(['--help'], fakeIo({}).io, () => undefined), 0); }); });