From 747d5f3e97bfea9ea264480f44dfe42a043b9362 Mon Sep 17 00:00:00 2001 From: Rafael Augusto Date: Thu, 3 Dec 2026 11:18:39 -0300 Subject: [PATCH 1/3] Publish signed bundles to Otto and report the first confirmed launch --- docs/guide/cli.md | 10 ++++ docs/pt-BR/guide/cli.md | 10 ++++ packages/ota-cli/README.md | 10 ++++ packages/ota-cli/src/cli.ts | 18 ++++++ packages/ota-cli/src/publish.ts | 60 +++++++++++++++++++ .../test/cli-pack-verify-serve.test.ts | 27 ++++++++- packages/ota-nativescript/src/client.ts | 9 ++- packages/ota-nativescript/src/staging.ts | 5 +- .../test/staging-and-client.test.ts | 44 +++++++++++++- 9 files changed, 186 insertions(+), 7 deletions(-) create mode 100644 packages/ota-cli/src/publish.ts diff --git a/docs/guide/cli.md b/docs/guide/cli.md index 492d926..19614f9 100644 --- a/docs/guide/cli.md +++ b/docs/guide/cli.md @@ -95,3 +95,13 @@ Verifies: ## `ota-ns serve` Starts the local HTTP/TLS fixture server for device and simulator testing. See [Fault-injection server](/guide/fixture-server) for full mode documentation. + +## `ota-ns publish` + +In Otto Console, register the application ID, pin the release public key from `ota-ns keygen`, and create an app publishing token. Set `OTTO_TOKEN` in your shell or CI secret store, then send a bundle previously produced by `ota-ns pack`. + +```sh +ota-ns publish --bundle ./dist-ota --endpoint https://otto.getcortexlabs.com/api/publish --channel beta +``` + +Choose `beta` or `production`. The CLI checks the signed inventory against the files before sending them. Otto verifies the manifest signature with the pinned key. The server accepts up to 32 MiB of files per bundle. Retrying the same publication keeps subsequent pauses and rollbacks in effect. Use `--json` for a machine-readable receipt. diff --git a/docs/pt-BR/guide/cli.md b/docs/pt-BR/guide/cli.md index 1fe8a42..5029487 100644 --- a/docs/pt-BR/guide/cli.md +++ b/docs/pt-BR/guide/cli.md @@ -41,3 +41,13 @@ ota-ns verify --bundle ./dist-ota/ota-105 --config ./ota.config.json \ ## `ota-ns serve` Inicia o servidor local HTTP/TLS com 9 modos de resposta e injeção de falha. Veja [Servidor local de falhas](/pt-BR/guide/fixture-server). + +## `ota-ns publish` + +No Otto Console, cadastre o identificador do app, fixe a chave pública de release exibida por `ota-ns keygen` e crie um token de publicação. Salve o token como `OTTO_TOKEN` no terminal ou nos secrets da CI. Envie um pacote gerado por `ota-ns pack`. + +```sh +ota-ns publish --bundle ./dist-ota --endpoint https://otto.getcortexlabs.com/api/publish --channel beta +``` + +Escolha `beta` ou `production`. A CLI confere os arquivos do pacote antes do envio. O Otto verifica a assinatura do manifesto com a chave fixada. O servidor aceita até 32 MiB de arquivos por pacote. Repetir a mesma publicação preserva pausas e rollbacks feitos depois. Use `--json` para obter o recibo em JSON. diff --git a/packages/ota-cli/README.md b/packages/ota-cli/README.md index b6a88e6..447f6a3 100644 --- a/packages/ota-cli/README.md +++ b/packages/ota-cli/README.md @@ -25,3 +25,13 @@ ota-ns serve --bundle ./dist-ota/ota-105 --private-key ~/.ota-keys/prod-2026.pri ## License MIT + +## Publish to Otto Console + +Register your app in Otto Console, pin the public key used by `pack` and save the app publishing token as `OTTO_TOKEN` in your local environment or CI secret store. Keep the private release key on the machine that signs the bundle. + +```sh +ota-ns publish --bundle ./dist-ota --endpoint https://otto.getcortexlabs.com/api/publish --channel beta +``` + +Use the publishing endpoint for your installation. A successful upload activates the release on the chosen channel for its platform, target build and runtime fingerprint. Retrying the same signed release and channel is idempotent. The Console can promote the release to production, pause delivery or issue a rollback directive. diff --git a/packages/ota-cli/src/cli.ts b/packages/ota-cli/src/cli.ts index 3be52d3..34af599 100644 --- a/packages/ota-cli/src/cli.ts +++ b/packages/ota-cli/src/cli.ts @@ -11,6 +11,7 @@ import { } from './fingerprint.js'; import { generateEd25519Keypair } from './keygen.js'; import { packOtaBundle } from './pack.js'; +import { publishPackedBundle } from './publish.js'; import { FIXTURE_SERVER_MODES, startFixtureServer, type FixtureServerMode } from './serve.js'; import { verifyPackedBundle } from './verify.js'; @@ -107,6 +108,8 @@ Usage: [--project ] [--bundle-dir ] [--baseline ] [--app-id ] [--target-build ] [--runtime-contract ] [--allow-drift] [--allow-snapshot] + ota-ns publish --bundle --endpoint --channel + Reads the app publishing token from OTTO_TOKEN. ota-ns verify --bundle (--public-key | --config ) [--key-id ] [--baseline ] [--app-id ] [--platform ] [--target-build ] [--runtime-contract ] @@ -249,6 +252,21 @@ export async function runCli( return 0; } + case 'publish': { + const channel = requireStringFlag(flags, 'channel'); + const releaseId = await publishPackedBundle( + requireStringFlag(flags, 'bundle'), + requireStringFlag(flags, 'endpoint'), + channel, + ); + io.stdout( + flags.json + ? JSON.stringify({ releaseId, channel }) + : `Published ${releaseId} to ${channel}.`, + ); + return 0; + } + case 'verify': { const bundleDir = requireStringFlag(flags, 'bundle'); const platformFlag = getStringFlag(flags, 'platform'); diff --git a/packages/ota-cli/src/publish.ts b/packages/ota-cli/src/publish.ts new file mode 100644 index 0000000..9186617 --- /dev/null +++ b/packages/ota-cli/src/publish.ts @@ -0,0 +1,60 @@ +import { createHash } from 'node:crypto'; +import { readFileSync, realpathSync, statSync } from 'node:fs'; +import path from 'node:path'; +import { validateSignedManifest } from '@getcortexlabs/ota-protocol'; + +export async function publishPackedBundle(bundle: string, endpoint: string, channel: string) { + const url = new URL(endpoint); + const loopback = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname); + if ( + url.username || + url.password || + (url.protocol !== 'https:' && !(loopback && url.protocol === 'http:')) + ) { + throw new Error('Use an HTTPS publishing endpoint, or HTTP on loopback for local development.'); + } + if (channel !== 'beta' && channel !== 'production') throw new Error('Choose beta or production.'); + const token = process.env.OTTO_TOKEN; + if (!token) throw new Error('Set OTTO_TOKEN to the app publishing token from Otto Console.'); + const root = realpathSync(bundle); + const manifestPath = path.join(root, 'manifest.json'); + if ( + realpathSync(manifestPath) !== manifestPath || + statSync(manifestPath).size > 8 * 1024 * 1024 + ) { + throw new Error('Expected a local manifest.json of at most 8 MiB.'); + } + const signed = validateSignedManifest(JSON.parse(readFileSync(manifestPath, 'utf8'))); + if ( + signed.manifest.files.length > 10000 || + signed.manifest.files.reduce((bytes, file) => bytes + file.size, 0) > 32 * 1024 * 1024 + ) { + throw new Error('Otto accepts up to 10,000 files and 32 MiB per release.'); + } + const directory = path.join(root, 'files'); + const files = signed.manifest.files.map((entry) => { + const file = path.join(directory, entry.path); + if (realpathSync(file) !== file || statSync(file).size !== entry.size) { + throw new Error('File no longer matches the manifest: ' + entry.path); + } + const bytes = readFileSync(file); + if (createHash('sha256').update(bytes).digest('hex') !== entry.sha256) { + throw new Error('File hash mismatch: ' + entry.path); + } + return { path: entry.path, data: bytes.toString('base64') }; + }); + const response = await fetch(url, { + method: 'POST', + headers: { authorization: 'Bearer ' + token, 'content-type': 'application/json' }, + body: JSON.stringify({ signed, files, channel }), + redirect: 'error', + signal: AbortSignal.timeout(120000), + }); + if (!response.ok) + throw new Error('Publish failed (HTTP ' + response.status + '): ' + response.statusText); + const receipt = (await response.json()) as { releaseId?: string; channel?: string }; + if (receipt.releaseId !== signed.manifest.releaseId || receipt.channel !== channel) { + throw new Error('The server did not confirm the requested release and channel.'); + } + return signed.manifest.releaseId; +} diff --git a/packages/ota-cli/test/cli-pack-verify-serve.test.ts b/packages/ota-cli/test/cli-pack-verify-serve.test.ts index c26e552..873cb3a 100644 --- a/packages/ota-cli/test/cli-pack-verify-serve.test.ts +++ b/packages/ota-cli/test/cli-pack-verify-serve.test.ts @@ -2,7 +2,7 @@ import crypto from 'node:crypto'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; -import { afterEach, describe, expect, it } from 'vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; import { OTA_ERROR_CODES, OtaError, @@ -60,6 +60,8 @@ describe('CLI keygen, pack, verify and local fixture server (#12)', () => { const tempDirs: string[] = []; afterEach(() => { + vi.unstubAllEnvs(); + vi.unstubAllGlobals(); for (const dir of tempDirs.splice(0)) { fs.rmSync(dir, { recursive: true, force: true }); } @@ -184,6 +186,29 @@ describe('CLI keygen, pack, verify and local fixture server (#12)', () => { ), ).toBe(0); + vi.stubEnv('OTTO_TOKEN', 'test-token'); + const endpoint = 'https://updates.example.com/api/publish'; + const publish = vi.fn(async (url: URL, init: RequestInit) => { + expect(url.href).toBe(endpoint); + expect(init.redirect).toBe('error'); + expect(init.headers).toMatchObject({ authorization: 'Bearer test-token' }); + const payload = JSON.parse(String(init.body)); + expect(payload.files).toHaveLength(payload.signed.manifest.files.length); + return Response.json({ + releaseId: payload.signed.manifest.releaseId, + channel: payload.channel, + }); + }); + vi.stubGlobal('fetch', publish); + expect( + await runCli( + ['publish', '--bundle', outDir, '--endpoint', endpoint, '--channel', 'beta', '--json'], + io, + ), + ).toBe(0); + expect(JSON.parse(logs.pop()!)).toEqual({ releaseId: 'ota-105', channel: 'beta' }); + expect(publish).toHaveBeenCalledOnce(); + // 5. Mutate a native permission -> fingerprint --baseline returns exit code 2, and pack MUST refuse by default write( path.join(root, 'App_Resources/iOS/Info.plist'), diff --git a/packages/ota-nativescript/src/client.ts b/packages/ota-nativescript/src/client.ts index 51eb026..7022944 100644 --- a/packages/ota-nativescript/src/client.ts +++ b/packages/ota-nativescript/src/client.ts @@ -182,8 +182,11 @@ export function createOtaUpdates(options: OtaUpdatesOptions = {}): OtaUpdatesApi const shouldReportRemotely = options.reportEventsRemotely ?? Boolean(resolvedConfig?.eventsEndpoint); - if (shouldReportRemotely && resolvedClient?.reportEvent) { - void resolvedClient.reportEvent(event).catch(() => undefined); + if (shouldReportRemotely) { + // markReady() usually precedes the first update check on a cold launch. + void Promise.resolve() + .then(() => requireClient().reportEvent?.(event)) + .catch(() => undefined); } } @@ -197,7 +200,7 @@ export function createOtaUpdates(options: OtaUpdatesOptions = {}): OtaUpdatesApi runtimeContract: string; channel: string; } { - const cfg = resolvedConfig ?? nativeGetEmbeddedConfig(); + const cfg = (resolvedConfig ??= nativeGetEmbeddedConfig()); return { protocolVersion: PROTOCOL_VERSION, timestamp: now(), diff --git a/packages/ota-nativescript/src/staging.ts b/packages/ota-nativescript/src/staging.ts index 09e2e10..a57dc98 100644 --- a/packages/ota-nativescript/src/staging.ts +++ b/packages/ota-nativescript/src/staging.ts @@ -62,7 +62,10 @@ function normalizeSlashPath(p: string): string { function joinUrl(baseUrl: string, relativePath: string): string { const normalizedBase = baseUrl.endsWith('/') ? baseUrl : `${baseUrl}/`; - return new URL(relativePath, normalizedBase).toString(); + return new URL( + relativePath.split('/').map(encodeURIComponent).join('/'), + normalizedBase, + ).toString(); } export class StagingManager { diff --git a/packages/ota-nativescript/test/staging-and-client.test.ts b/packages/ota-nativescript/test/staging-and-client.test.ts index a238c61..fb14cfb 100644 --- a/packages/ota-nativescript/test/staging-and-client.test.ts +++ b/packages/ota-nativescript/test/staging-and-client.test.ts @@ -2,7 +2,7 @@ import crypto from 'node:crypto'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; -import { afterEach, describe, expect, it } from 'vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; import { HttpUpdateClient, OTA_ERROR_CODES, @@ -222,14 +222,54 @@ describe('staging manager, HttpUpdateClient, GC and public SDK API (#8, #10)', ( const tempDirs: string[] = []; afterEach(() => { + vi.unstubAllGlobals(); for (const dir of tempDirs.splice(0)) { fs.rmSync(dir, { recursive: true, force: true }); } }); + it('sends a cold-launch receipt even when markReady precedes the first check', async () => { + const fetchMock = vi.fn(async () => new Response(null, { status: 204 })); + vi.stubGlobal('fetch', fetchMock); + const sdk = createOtaUpdates({ + platform: 'ios', + config: { + appId: 'com.example.desk', + endpoint: 'https://updates.example.com/check', + eventsEndpoint: 'https://updates.example.com/events', + channel: 'beta', + runtimeContract: 'ios-v1', + publicKeys: { test: Buffer.alloc(32).toString('base64') }, + }, + bootBridge: { + markReady: () => true, + getBootInfo: () => ({ + source: 'embedded', + releaseId: null, + bundlePath: '/app', + binaryVersion: '1', + targetBuild: '1', + runtimeContract: 'ios-v1', + pendingConfirmation: false, + launchAttempts: 1, + lastRecovery: null, + }), + }, + }); + expect(sdk.markReady()).toBe(true); + await vi.waitFor(() => + expect(fetchMock).toHaveBeenCalledWith( + 'https://updates.example.com/events', + expect.objectContaining({ body: expect.stringContaining('startup_confirmed') }), + ), + ); + }); + it('downloads, verifies, atomically stages a signed release, emits events and collects garbage', async () => { const baseUrl = 'https://updates.example.com'; const files = makeBundleFiles('ota-105'); + files['assets/receipt #1.png'] = files['assets/badge.png']!; + delete files['assets/badge.png']; const manifest = buildManifest('ota-105', files); const reportedEvents: unknown[] = []; @@ -268,7 +308,7 @@ describe('staging manager, HttpUpdateClient, GC and public SDK API (#8, #10)', ( if (url.startsWith(`${baseUrl}/releases/ota-105/files/`)) { const rel = url.slice(`${baseUrl}/releases/ota-105/files/`.length); - const data = files[rel]; + const data = files[decodeURIComponent(rel)]; if (data) return { body: data }; } From a386aa3197a7d2c33d904490d340f17721acd41d Mon Sep 17 00:00:00 2001 From: Rafael Augusto Date: Thu, 3 Dec 2026 15:47:42 -0300 Subject: [PATCH 2/3] Support custom Otto channels and native fingerprint publication --- docs/guide/cli.md | 22 +++- docs/pt-BR/guide/cli.md | 22 +++- packages/ota-cli/src/cli.ts | 3 +- packages/ota-cli/src/publish.ts | 100 +++++++++++++++++- .../test/cli-pack-verify-serve.test.ts | 66 ++++++++++++ 5 files changed, 206 insertions(+), 7 deletions(-) diff --git a/docs/guide/cli.md b/docs/guide/cli.md index 19614f9..31b72b1 100644 --- a/docs/guide/cli.md +++ b/docs/guide/cli.md @@ -104,4 +104,24 @@ In Otto Console, register the application ID, pin the release public key from `o ota-ns publish --bundle ./dist-ota --endpoint https://otto.getcortexlabs.com/api/publish --channel beta ``` -Choose `beta` or `production`. The CLI checks the signed inventory against the files before sending them. Otto verifies the manifest signature with the pinned key. The server accepts up to 32 MiB of files per bundle. Retrying the same publication keeps subsequent pauses and rollbacks in effect. Use `--json` for a machine-readable receipt. +New apps start with `beta` and `production`. Owners can create more channels in **Settings → App**. Use a registered, active channel name: lowercase letters, numbers and hyphens, beginning with a letter, up to 48 characters; `all` is reserved. The SDK must use the same channel name. The CLI checks the signed inventory against the files before sending them. Otto verifies the manifest signature with the pinned key. The server accepts up to 32 MiB of files per bundle. Retrying the same publication keeps subsequent pauses and rollbacks in effect. Use `--json` for a machine-readable receipt. + +Attach the fingerprint for the exact native build when publishing: + +```sh +ota-ns publish --bundle ./dist-ota --endpoint https://otto.getcortexlabs.com/api/publish --channel internal --fingerprint ./ota.baseline.ios.json +``` + +`--fingerprint` accepts the raw JSON saved by `ota-ns fingerprint --write-baseline`. The CLI checks its section hashes, runtime contract, platform and target build before sending it. Otto repeats those checks and saves the report with the publication. The optional report is separate from the signed bundle and does not change its signature. Up to 2 MiB and 10,000 fingerprint entries are accepted. Private signing keys stay local. + +### Operating a release in Console + +**Releases → Compare** compares two signed file inventories from the same platform: added, changed, removed and identical files, bundle sizes, signing key IDs and native targets. Identical bytes are a potential reuse opportunity; actual reuse depends on files present on each device. + +**Releases → Compatibility** shows native delivery routes, recent real check outcomes and a simulation using the same decision rules as `/api/check`. The simulation issues no directive and stores no report. Real checks are aggregated by UTC hour and outcome, with up to 2,000 groups per app for 7 days; the Console shows the latest 200 groups. Installation IDs are used for rollout calculations but are not stored in these diagnostics. These counts are requests, not unique devices. + +Import another fingerprint in this view to compare runtime, native plugins, native resources, generated metadata and static bindings. Browser import also accepts the `{ fingerprint, diff }` output of `fingerprint --json`. A `static-only` report is incomplete: rebuild natively and regenerate it before deciding compatibility. Reports are supplied by the team and are not attestation of an installed binary. Each app retains up to 100 distinct native reports. + +**Activity** retains SDK download bytes, reused bytes/files, staging duration, startup attempts and fallback destination. Aggregates follow the active filters across all retained matching events, not just the current page; Overview uses the last 24 hours. Older reports without metrics remain visible and are excluded from those aggregates. Lifecycle reports are best effort, not unique-device adoption or billing metrics. + +Archiving a channel stops new publishing and update directives through it, while preserving history and downloaded bundles. Restoring resumes its saved delivery rules. Owners manage channels; publishers can dispatch releases and import native reports; viewers can inspect and simulate. Up to 20 channels, including archived channels, can exist per app. diff --git a/docs/pt-BR/guide/cli.md b/docs/pt-BR/guide/cli.md index 5029487..9d9edfb 100644 --- a/docs/pt-BR/guide/cli.md +++ b/docs/pt-BR/guide/cli.md @@ -50,4 +50,24 @@ No Otto Console, cadastre o identificador do app, fixe a chave pública de relea ota-ns publish --bundle ./dist-ota --endpoint https://otto.getcortexlabs.com/api/publish --channel beta ``` -Escolha `beta` ou `production`. A CLI confere os arquivos do pacote antes do envio. O Otto verifica a assinatura do manifesto com a chave fixada. O servidor aceita até 32 MiB de arquivos por pacote. Repetir a mesma publicação preserva pausas e rollbacks feitos depois. Use `--json` para obter o recibo em JSON. +Novos apps começam com `beta` e `production`. Responsáveis podem criar outros canais em **Configurações → App**. Use um canal cadastrado e ativo: letras minúsculas, números e hífens, começando por letra, até 48 caracteres; `all` é reservado. O SDK precisa usar exatamente o mesmo nome. A CLI confere os arquivos do pacote antes do envio. O Otto verifica a assinatura do manifesto com a chave fixada. O servidor aceita até 32 MiB de arquivos por pacote. Repetir a mesma publicação preserva pausas e rollbacks feitos depois. Use `--json` para obter o recibo em JSON. + +Anexe o fingerprint do build nativo exato ao publicar: + +```sh +ota-ns publish --bundle ./dist-ota --endpoint https://otto.getcortexlabs.com/api/publish --channel internal --fingerprint ./ota.baseline.ios.json +``` + +`--fingerprint` aceita o JSON original salvo por `ota-ns fingerprint --write-baseline`. A CLI confere os hashes das seções, contrato de runtime, plataforma e build alvo antes do envio. O Otto repete a conferência e salva o relatório junto da publicação. O relatório opcional fica separado do pacote assinado e não altera sua assinatura. O limite é de 2 MiB e 10.000 entradas. Chaves privadas de assinatura continuam locais. + +### Operando uma release no Console + +**Releases → Comparar** compara inventários assinados da mesma plataforma: arquivos adicionados, alterados, removidos e idênticos, tamanhos dos pacotes, IDs das chaves e destinos nativos. Bytes idênticos indicam potencial de reuso; o reuso real depende dos arquivos presentes em cada aparelho. + +**Releases → Compatibilidade** reúne rotas nativas, resultados de consultas reais e uma simulação com as mesmas regras de `/api/check`. O ensaio não emite diretivas nem salva relatos. Consultas reais são agrupadas por hora UTC e resultado: até 2.000 grupos por app por 7 dias, com os últimos 200 exibidos no Console. IDs de instalação entram no cálculo de rollout, mas não são armazenados nesses diagnósticos. As contagens representam consultas, não aparelhos únicos. + +Importe outro fingerprint nessa tela para comparar runtime, plugins nativos, recursos nativos, metadados gerados e bindings estáticos. A importação pelo navegador também aceita o resultado `{ fingerprint, diff }` de `fingerprint --json`. Um relatório `static-only` está incompleto: faça o build nativo e gere novamente antes de decidir a compatibilidade. Os relatórios são fornecidos pela equipe e não atestam um binário instalado. Cada app guarda até 100 relatórios nativos distintos. + +**Atividade** preserva bytes baixados e reaproveitados, arquivos, duração de preparação, tentativas de inicialização e destino da recuperação automática. As métricas seguem os filtros em todos os eventos retidos, não apenas na página atual; a Visão geral usa as últimas 24 horas. Relatos antigos sem métricas continuam visíveis e ficam fora dos totais. O envio é best effort: não são métricas de adoção por aparelhos únicos ou faturamento. + +Arquivar um canal interrompe novas publicações e diretivas por ele, preservando histórico e pacotes baixados. Restaurar retoma as regras de entrega salvas. Responsáveis gerenciam canais; publicadores despacham releases e importam relatórios nativos; leitores consultam e simulam. Cada app pode ter até 20 canais, incluindo os arquivados. diff --git a/packages/ota-cli/src/cli.ts b/packages/ota-cli/src/cli.ts index 34af599..81fe76b 100644 --- a/packages/ota-cli/src/cli.ts +++ b/packages/ota-cli/src/cli.ts @@ -108,7 +108,7 @@ Usage: [--project ] [--bundle-dir ] [--baseline ] [--app-id ] [--target-build ] [--runtime-contract ] [--allow-drift] [--allow-snapshot] - ota-ns publish --bundle --endpoint --channel + ota-ns publish --bundle --endpoint --channel [--fingerprint ] Reads the app publishing token from OTTO_TOKEN. ota-ns verify --bundle (--public-key | --config ) [--key-id ] [--baseline ] [--app-id ] [--platform ] @@ -258,6 +258,7 @@ export async function runCli( requireStringFlag(flags, 'bundle'), requireStringFlag(flags, 'endpoint'), channel, + getStringFlag(flags, 'fingerprint'), ); io.stdout( flags.json diff --git a/packages/ota-cli/src/publish.ts b/packages/ota-cli/src/publish.ts index 9186617..688a197 100644 --- a/packages/ota-cli/src/publish.ts +++ b/packages/ota-cli/src/publish.ts @@ -1,9 +1,14 @@ import { createHash } from 'node:crypto'; import { readFileSync, realpathSync, statSync } from 'node:fs'; import path from 'node:path'; -import { validateSignedManifest } from '@getcortexlabs/ota-protocol'; +import { canonicalizeJson, validateSignedManifest } from '@getcortexlabs/ota-protocol'; -export async function publishPackedBundle(bundle: string, endpoint: string, channel: string) { +export async function publishPackedBundle( + bundle: string, + endpoint: string, + channel: string, + fingerprintPath?: string, +) { const url = new URL(endpoint); const loopback = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname); if ( @@ -13,7 +18,10 @@ export async function publishPackedBundle(bundle: string, endpoint: string, chan ) { throw new Error('Use an HTTPS publishing endpoint, or HTTP on loopback for local development.'); } - if (channel !== 'beta' && channel !== 'production') throw new Error('Choose beta or production.'); + if (channel === 'all' || !/^[a-z][a-z0-9-]{0,47}$/.test(channel)) + throw new Error( + 'Use a channel name with lowercase letters, numbers and hyphens (up to 48 characters); all is reserved.', + ); const token = process.env.OTTO_TOKEN; if (!token) throw new Error('Set OTTO_TOKEN to the app publishing token from Otto Console.'); const root = realpathSync(bundle); @@ -31,6 +39,17 @@ export async function publishPackedBundle(bundle: string, endpoint: string, chan ) { throw new Error('Otto accepts up to 10,000 files and 32 MiB per release.'); } + const fingerprint = fingerprintPath ? readPublishFingerprint(fingerprintPath) : undefined; + if ( + fingerprint && + (fingerprint.platform !== signed.manifest.platform || + fingerprint.targetBuild !== signed.manifest.targetBuild || + fingerprint.runtimeContract !== signed.manifest.runtimeContract) + ) { + throw new Error( + 'Fingerprint does not match the published platform, build and runtime contract.', + ); + } const directory = path.join(root, 'files'); const files = signed.manifest.files.map((entry) => { const file = path.join(directory, entry.path); @@ -46,7 +65,7 @@ export async function publishPackedBundle(bundle: string, endpoint: string, chan const response = await fetch(url, { method: 'POST', headers: { authorization: 'Bearer ' + token, 'content-type': 'application/json' }, - body: JSON.stringify({ signed, files, channel }), + body: JSON.stringify({ signed, files, channel, ...(fingerprint ? { fingerprint } : {}) }), redirect: 'error', signal: AbortSignal.timeout(120000), }); @@ -58,3 +77,76 @@ export async function publishPackedBundle(bundle: string, endpoint: string, chan } return signed.manifest.releaseId; } + +function readPublishFingerprint(file: string) { + if (statSync(file).size > 2 * 1024 * 1024) throw new Error('Fingerprint exceeds 2 MiB.'); + const source = JSON.parse(readFileSync(file, 'utf8')); + if ( + !source || + source.schemaVersion !== 1 || + !['ios', 'android'].includes(source.platform) || + !['build-artifacts', 'static-only'].includes(source.metadataSource) + ) + throw new Error('Invalid fingerprint report.'); + const names = [ + 'runtime', + 'nativePlugins', + 'nativeConfigAndResources', + 'generatedMetadata', + 'staticBindings', + ]; + const sections: Record }> = {}; + const hash = (value: unknown) => + createHash('sha256').update(canonicalizeJson(value)).digest('hex'); + let count = 0; + for (const name of names) { + const entries = source.sections?.[name]?.entries; + if (!entries || typeof entries !== 'object' || Array.isArray(entries)) + throw new Error('Invalid fingerprint section.'); + for (const [key, value] of Object.entries(entries)) { + if ( + ++count > 10000 || + !key || + key.length > 512 || + typeof value !== 'string' || + !value || + value.length > 2048 + ) + throw new Error('Invalid fingerprint entry.'); + } + const digest = hash(entries); + if (digest !== source.sections[name]!.hash) + throw new Error('Fingerprint section hash mismatch.'); + sections[name] = { hash: digest, entries }; + } + const composite = hash({ + schemaVersion: 1, + platform: source.platform, + ...Object.fromEntries(names.map((name) => [name, sections[name]!.hash])), + }); + if (source.runtimeContract !== source.platform + '-rc-' + composite.slice(0, 16)) + throw new Error('Fingerprint runtime contract mismatch.'); + for (const field of ['binaryVersion', 'targetBuild']) + if ( + source[field] !== null && + (typeof source[field] !== 'string' || !source[field] || source[field].length > 160) + ) + throw new Error('Invalid fingerprint build identity.'); + if ( + typeof source.createdAt !== 'string' || + source.createdAt.length > 40 || + !Number.isFinite(Date.parse(source.createdAt)) + ) + throw new Error('Invalid fingerprint date.'); + // Send only the report contract, never unrelated fields from a supplied JSON file. + return { + schemaVersion: 1, + platform: source.platform as string, + runtimeContract: source.runtimeContract as string, + binaryVersion: source.binaryVersion as string | null, + targetBuild: source.targetBuild as string | null, + metadataSource: source.metadataSource as string, + sections, + createdAt: source.createdAt as string, + }; +} diff --git a/packages/ota-cli/test/cli-pack-verify-serve.test.ts b/packages/ota-cli/test/cli-pack-verify-serve.test.ts index 873cb3a..1c99e59 100644 --- a/packages/ota-cli/test/cli-pack-verify-serve.test.ts +++ b/packages/ota-cli/test/cli-pack-verify-serve.test.ts @@ -209,6 +209,72 @@ describe('CLI keygen, pack, verify and local fixture server (#12)', () => { expect(JSON.parse(logs.pop()!)).toEqual({ releaseId: 'ota-105', channel: 'beta' }); expect(publish).toHaveBeenCalledOnce(); + // Custom app channels and a verified native report travel with the publication. + write(baselinePath, JSON.stringify({ ...baseline, unrelatedSecret: 'must-stay-local' })); + expect( + await runCli( + [ + 'publish', + '--bundle', + outDir, + '--endpoint', + endpoint, + '--channel', + 'internal-qa', + '--fingerprint', + baselinePath, + '--json', + ], + io, + ), + ).toBe(0); + const attached = JSON.parse(String(publish.mock.calls.at(-1)![1].body)); + expect(attached.channel).toBe('internal-qa'); + expect(attached.fingerprint).toEqual(baseline); + expect(attached.fingerprint).not.toHaveProperty('unrelatedSecret'); + expect(JSON.parse(logs.pop()!)).toEqual({ releaseId: 'ota-105', channel: 'internal-qa' }); + + const calls = publish.mock.calls.length; + for (const channel of ['all', 'UPPER', '../beta', 'a'.repeat(49)]) { + expect( + await runCli( + ['publish', '--bundle', outDir, '--endpoint', endpoint, '--channel', channel], + io, + ), + ).toBe(1); + } + for (const fingerprint of [ + { ...baseline, targetBuild: 'different-build' }, + { ...baseline, runtimeContract: 'wrong-contract' }, + { + ...baseline, + sections: { + ...baseline.sections, + runtime: { ...baseline.sections.runtime, hash: 'wrong' }, + }, + }, + ]) { + write(baselinePath, JSON.stringify(fingerprint)); + expect( + await runCli( + [ + 'publish', + '--bundle', + outDir, + '--endpoint', + endpoint, + '--channel', + 'beta', + '--fingerprint', + baselinePath, + ], + io, + ), + ).toBe(1); + } + expect(publish).toHaveBeenCalledTimes(calls); + write(baselinePath, JSON.stringify(baseline)); + // 5. Mutate a native permission -> fingerprint --baseline returns exit code 2, and pack MUST refuse by default write( path.join(root, 'App_Resources/iOS/Info.plist'), From 6b754fd7428884866956cd079b3f42de917c0261 Mon Sep 17 00:00:00 2001 From: Rafael Augusto Date: Thu, 3 Dec 2026 19:26:07 -0300 Subject: [PATCH 3/3] feat: report installation identity and document Otto operations --- README.md | 6 +- docs/.vitepress/config.ts | 4 +- docs/.vitepress/sidebar.ts | 3 +- docs/guide/api.md | 10 ++- docs/guide/index.md | 2 +- docs/guide/otto.md | 66 +++++++++++++++++++ docs/guide/protocol.md | 10 ++- docs/guide/roadmap.md | 4 +- docs/guide/validation.md | 21 ++++++ docs/pt-BR/guide/api.md | 10 ++- docs/pt-BR/guide/otto.md | 66 +++++++++++++++++++ docs/pt-BR/guide/protocol.md | 8 ++- docs/pt-BR/guide/roadmap.md | 4 +- docs/pt-BR/guide/validation.md | 21 ++++++ packages/ota-cli/README.md | 4 +- packages/ota-cli/package.json | 2 +- packages/ota-nativescript/README.md | 10 ++- packages/ota-nativescript/package.json | 2 +- packages/ota-nativescript/src/client.ts | 9 ++- .../test/staging-and-client.test.ts | 19 +++++- packages/protocol/README.md | 2 +- packages/protocol/package.json | 2 +- packages/protocol/src/types.ts | 7 ++ packages/protocol/src/validation.ts | 31 +++++++++ packages/protocol/test/validation.test.ts | 57 ++++++++++++++++ 25 files changed, 352 insertions(+), 28 deletions(-) create mode 100644 docs/guide/otto.md create mode 100644 docs/pt-BR/guide/otto.md diff --git a/README.md b/README.md index a58edd6..375dbf3 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@

- Documentation · Roadmap (#1) · Support matrix · Milestones + Documentation · Roadmap (#1) · Support matrix · Milestones

```ts @@ -38,9 +38,9 @@ Shipping JavaScript over the air in NativeScript breaks in three specific ways w `ota-nativescript` addresses those directly. Minimal native bootstrappers on iOS and Android select the active bundle before V8 starts, without forking `@nativescript/ios` or `@nativescript/android` and without hand-editing generated `platforms/` folders. Bundles are staged atomically as complete, Ed25519-signed packages verified against a per-platform runtime contract, activated on the next full process launch, and rolled back offline if startup fails before `markReady()`. -The SDK stays independent of any specific UI library or hosting backend. It speaks a server-agnostic HTTP contract tested locally via a fixture server; [Orbit](https://github.com/getcortexlabs/orbit-docs) integration and Mavis CLI setup come separately once the on-device SDK holds on release builds. +The SDK stays independent of any specific UI library or hosting backend. It speaks a server-agnostic HTTP contract tested locally via a fixture server; [Otto](https://otto.getcortexlabs.com) provides the hosted console, app-scoped publishing, channels and delivery telemetry. The SDK also works with self-hosted Otto or any compatible server. -**Current status (M0–M3 + `#15`, `#16`, `#17` verified).** All v0.1 milestones plus NativeScript 9.1 `@nativescript/vite` production support ([#15](https://github.com/getcortexlabs/ota-nativescript/issues/15)), Android V8 snapshot compatibility rules & `codeCache` verification ([#16](https://github.com/getcortexlabs/ota-nativescript/issues/16)), and content-addressed file reuse across releases ([#17](https://github.com/getcortexlabs/ota-nativescript/issues/17)) are delivered and verified 8/8 on both **Webpack 5** (`fixtures/vue-mavis-app`, NativeScript-Vue 3 + Mavis + Jolt) and **Vite 8 / Rolldown** (`fixtures/vite-app`, native ESM + `require(esm)` + `ns:util` + Web Worker) running on iOS 26.2 Simulator (`@nativescript/ios` `9.1.1`) and a physical Xiaomi `M2103K19PG` Android 16 / API 36 device (`@nativescript/android` `9.1.3`, signed R8 `minifyEnabled true` APK). Full operational docs and interactive Jolt Web labs live at [ota-ns.getcortexlabs.com](https://ota-ns.getcortexlabs.com/guide/). Follow roadmap & ecosystem integrations in [#1](https://github.com/getcortexlabs/ota-nativescript/issues/1). +**Current status (M0–M3 + `#15`, `#16`, `#17` verified).** All v0.1 milestones plus NativeScript 9.1 `@nativescript/vite` production support ([#15](https://github.com/getcortexlabs/ota-nativescript/issues/15)), Android V8 snapshot compatibility rules & `codeCache` verification ([#16](https://github.com/getcortexlabs/ota-nativescript/issues/16)), and content-addressed file reuse across releases ([#17](https://github.com/getcortexlabs/ota-nativescript/issues/17)) are delivered and verified 8/8 on both **Webpack 5** (`fixtures/vue-mavis-app`, NativeScript-Vue 3 + Mavis + Jolt) and **Vite 8 / Rolldown** (`fixtures/vite-app`, native ESM + `require(esm)` + `ns:util` + Web Worker) running on iOS 26.2 Simulator (`@nativescript/ios` `9.1.1`) and a physical Xiaomi `M2103K19PG` Android 16 / API 36 device (`@nativescript/android` `9.1.3`, signed R8 `minifyEnabled true` APK). Full operational docs and interactive Jolt Web labs live at [otto.getcortexlabs.com/docs](https://otto.getcortexlabs.com/docs/guide/). Follow roadmap & ecosystem integrations in [#1](https://github.com/getcortexlabs/ota-nativescript/issues/1). ## How it works diff --git a/docs/.vitepress/config.ts b/docs/.vitepress/config.ts index 478f9d4..8e51fb2 100644 --- a/docs/.vitepress/config.ts +++ b/docs/.vitepress/config.ts @@ -13,8 +13,8 @@ export default defineConfig({ ['link', { rel: 'icon', type: 'image/png', sizes: '192x192', href: '/favicon-192.png' }], ['link', { rel: 'apple-touch-icon', sizes: '180x180', href: '/apple-touch-icon.png' }], ['meta', { name: 'theme-color', content: '#0c100f' }], - ['meta', { property: 'og:image', content: 'https://ota-ns.getcortexlabs.com/logo.png' }], - ['meta', { name: 'twitter:image', content: 'https://ota-ns.getcortexlabs.com/logo.png' }], + ['meta', { property: 'og:image', content: 'https://otto.getcortexlabs.com/docs/logo.png' }], + ['meta', { name: 'twitter:image', content: 'https://otto.getcortexlabs.com/docs/logo.png' }], ], themeConfig: { logo: { diff --git a/docs/.vitepress/sidebar.ts b/docs/.vitepress/sidebar.ts index a6b0123..18178f3 100644 --- a/docs/.vitepress/sidebar.ts +++ b/docs/.vitepress/sidebar.ts @@ -28,7 +28,7 @@ export const SIDEBAR_GROUPS: SidebarGroupMeta[] = [ { id: 'operations', title: ['Operations & release', 'Operação e release'], - slugs: ['store-policy', 'support-matrix', 'validation'], + slugs: ['otto', 'store-policy', 'support-matrix', 'validation'], }, { id: 'reference', @@ -48,6 +48,7 @@ const pageTitles: Record = { fingerprinting: ['Runtime fingerprinting', 'Fingerprint de compatibilidade'], cli: ['CLI reference (ota-ns)', 'Referência da CLI (ota-ns)'], 'fixture-server': ['Fault-injection server', 'Servidor local de falhas'], + otto: ['Operating Otto', 'Operando o Otto'], 'store-policy': ['Store policy boundaries', 'Regras das lojas'], 'support-matrix': ['Support matrix', 'Matriz de suporte'], validation: ['Device validation (8/8)', 'Validação em devices (8/8)'], diff --git a/docs/guide/api.md b/docs/guide/api.md index 7554e38..54b9803 100644 --- a/docs/guide/api.md +++ b/docs/guide/api.md @@ -82,7 +82,7 @@ Removes any release directories in `releases/` not referenced by active, `confir ### `updates.onEvent(listener): () => void` -Subscribes to structured `OtaLifecycleEvent` updates (`check_started`, `download_progress`, `staged`, `boot_confirmed`, `recovery_triggered`, `error`) and returns an unsubscribe function. +Subscribes to structured `OtaLifecycleEvent` updates (`download_completed`, `validation_failed`, `staged`, `startup_confirmed`, `recovered_fallback`) and returns an unsubscribe function. ## Error codes (`OTA_ERROR_CODES`) @@ -91,3 +91,11 @@ All verification, compatibility, download and staging failures throw `OtaError` - **Crypto & protocol:** `SIGNATURE_INVALID`, `KEY_NOT_FOUND`, `MANIFEST_INVALID`, `DIRECTIVE_INVALID`, `DIRECTIVE_RELEASE_MISMATCH`, `REPLAY_DETECTED`, `INSECURE_URL` - **Compatibility:** `PLATFORM_MISMATCH`, `APP_ID_MISMATCH`, `TARGET_BUILD_MISMATCH`, `RUNTIME_CONTRACT_MISMATCH`, `PROTOCOL_VERSION_UNSUPPORTED` - **Integrity & staging:** `HASH_MISMATCH`, `SIZE_MISMATCH`, `MISSING_FILE`, `UNEXPECTED_FILE`, `UNSAFE_PATH`, `BUNDLE_TOO_LARGE`, `DOWNLOAD_FAILED`, `STORAGE_IO_ERROR`, `RELEASE_BLOCKLISTED` + +## Installation references and remote reports + +Create one `createOtaUpdates({ installId })` instance with a random app-scoped UUID persisted across launches, and use that instance for `markReady()` and checks. [Operating Otto](./otto#observed-installations) includes a NativeScript persistence example. The default singleton does not invent an installation identity. + +The optional ID accompanies checks and lifecycle reports. Checks also report a timestamp and nullable confirmed/prepared release IDs. `recovered_fallback.recoveredAt` preserves the native recovery time, while its `timestamp` is the report time. Telemetry failure never blocks offline startup confirmation or recovery. A new SDK build is required for these optional observation fields; legacy reports stay valid and anonymous when no ID is supplied. + +`download_completed` includes downloaded/reused bytes, file counts and staging duration. `validation_failed` carries a stable error code. `staged` identifies the prepared release/directive. `startup_confirmed` reports the actual boot source and release. `recovered_fallback` identifies the failed release and fallback destination. Download progress is the `onProgress` callback, not a separate lifecycle event. diff --git a/docs/guide/index.md b/docs/guide/index.md index 45197cb..5672d0c 100644 --- a/docs/guide/index.md +++ b/docs/guide/index.md @@ -20,7 +20,7 @@ Treating OTA updates in NativeScript as a JavaScript file copy breaks in three c ## Server-agnostic by design -The on-device SDK speaks an explicit, signed HTTP contract (`POST /check`, signed `manifest.json`, immutable file URLs, optional `POST /events`). You can host releases on static object storage + any backend, test locally with `ota-ns serve`, or connect Orbit once the hosted control plane lands. +The on-device SDK speaks an explicit, signed HTTP contract (`POST /check`, signed `manifest.json`, immutable file URLs, optional `POST /events`). You can host releases on static object storage + any backend, test locally with `ota-ns serve`, or connect Otto for workspaces, channels, signed delivery directives and the Console. See [Operating Otto](./otto). ## What can ship over the air diff --git a/docs/guide/otto.md b/docs/guide/otto.md new file mode 100644 index 0000000..15b4bb3 --- /dev/null +++ b/docs/guide/otto.md @@ -0,0 +1,66 @@ +# Operating Otto + +Otto puts the public site, Console, documentation and API under one origin: `https://otto.getcortexlabs.com`, `/dashboard`, `/docs` and `/api`. A self-hosted installation uses the same paths on its own domain. The domain is the intended canonical address; verify the deployment before connecting production apps. + +## First delivery + +Create an account, verify its email and create a workspace. The workspace selector opens existing workspaces; **New workspace** below that selector creates another. Owners manage apps, access, signing keys, tokens and storage. Publishers manage deliveries; viewers inspect the workspace. + +Register the app identifier and platforms in the Console. In **Settings → App & integrations**, register your release public key, create a scoped publishing token, choose a channel and copy the generated `ota.config.json`. Keep the release private key in your signing environment. The app trusts both the release key and Otto's delivery public key; never put a publishing token in the app. + +Build the store binary with its native runtime fingerprint. Use `ota-ns pack` and `ota-ns verify`, then publish: + +```sh +# Supply OTTO_TOKEN through your secret manager or shell environment. +ota-ns publish --bundle ./dist-ota \ + --endpoint https://otto.getcortexlabs.com/api/publish --channel beta +``` + +The Console offers delivery/pause/rollback, per-channel rollout percentages, native compatibility comparison and a request simulator. A compatible OTA changes JavaScript and assets. Changes to native dependencies, permissions or the native contract require a new store binary. + +## Observed installations + +**Activity → Installations** shows the latest reported running version, startup confirmation, prepared release, recent failure and last contact. Counts cover references seen in the selected period, with a 30-day retention window and a limit of 10,000 references per app. They are not people, a count of every installed app, or proof of ongoing device health. Anonymous SDK reports still appear in the delivery log. + +Opt in with a random UUID persisted by your app. Use a separate identifier per app; do not use an email address, advertising identifier or hardware identifier. For example, with NativeScript's platform types available: + +```ts +import { ApplicationSettings, isAndroid } from '@nativescript/core'; +import { createOtaUpdates } from '@getcortexlabs/ota-nativescript'; + +let installId = ApplicationSettings.getString('otto.installation'); +if (!installId) { + installId = isAndroid ? java.util.UUID.randomUUID().toString() : NSUUID.UUID().UUIDString; + ApplicationSettings.setString('otto.installation', installId); +} +const updates = createOtaUpdates({ installId }); +// Use this instance for markReady(), checkAndStage() and event subscriptions. +``` + +Otto derives a platform/app-scoped HMAC reference and stores that reference rather than the raw ID. Reinstallation or restored app data may change identity semantics. Out-of-order reports remain in the log but cannot rewind a newer running state. A staged release is not counted as adoption. Recovery timestamps reflect when native recovery happened, even if reported later. + +These lifecycle identity extensions require an SDK build that contains them. Older versions may send `installId` only on checks and remain anonymous in lifecycle events. The signed manifest and directive formats are unchanged. + +## Delivery protection + +**Settings → Delivery protection** is off by default. Choose a time window, a failure percentage and at least three affected installation references. Only distinct identified clients offered the same active delivery sequence and reporting within the configured window contribute. Repeated reports cannot multiply the sample. Anonymous reports and failures from older delivery sequences cannot trigger a pause. + +Automatic pause is a separate opt-in requiring the app name. Reports come from public clients and are not attested; this is a best-effort operational signal, not abuse-resistant device attestation. A pause stops new update directives, not downloads already staged on a device. Review the release before resuming manually. + +**Activity → Alerts** lists the latest 100 alerts, with 90-day retention and a cap of 1,000 per app. Acknowledging an alert records review without changing delivery. Email is optional and subscribes only the verified owner who saves the setting. Failed sends retry with backoff up to five attempts. “Accepted by transport” does not prove inbox delivery. + +## Storage and retirement + +**Settings → Release storage** lets owners pin, retire, restore and clean up artifacts. A current route remains protected even when its channel is archived or delivery is paused. Recently observed running, confirmed, staged and recovery versions are protected too. + +Retirement stops redispatch and republication. Cleanup requires 30 days since retirement, expiration of the last offer/download's 30-day lease, no protected reference and a fresh server-checked plan. Pin releases needed by clients that can stay offline longer. Observations cannot account for every offline device. + +Cleanup deletes bundle bytes and frees the workspace allowance, retaining the signed manifest, immutable release ID and audit history. A purged ID cannot be republished, downloads return HTTP 410, and restore is unavailable. SQLite can reuse freed pages without shrinking its file immediately. Native fingerprints can be deleted only without live bundle/installation references and without a pin. + +## Hosting acceptance + +Run one Node server with a persistent local SQLite volume behind HTTPS. Back up using SQLite's online backup API, not a lone copy of an active WAL database. Verify restore in a separate data directory before upgrading. Never place the data directory or SMTP credentials in a public static directory. + +Set `OTTO_ORIGIN`, `OTTO_DATA_DIR`, transactional SMTP and the verified administrator list. The private Otto repository includes the container, backup and deployment checks. `OTTO_MAIL_MODE=file` is a loopback-only local outbox, not production delivery. + +Before declaring the hosted service ready, validate HTTPS and the intended origin, persistent data across restarts, account verification/recovery and invitation mail, a real CLI publish, signed checks, a cold launch on iOS/Android and the Console's matching reports. The local suite cannot prove DNS, TLS termination, real inbox delivery or the host's backup schedule. diff --git a/docs/guide/protocol.md b/docs/guide/protocol.md index cf3b190..299d576 100644 --- a/docs/guide/protocol.md +++ b/docs/guide/protocol.md @@ -1,6 +1,6 @@ # Signed wire protocol -`@getcortexlabs/ota-protocol` defines the server-agnostic HTTP contract and state schemas shared by the CLI, the on-device SDK, and any update server (including `ota-ns serve` and future Orbit integration). +`@getcortexlabs/ota-protocol` defines the server-agnostic HTTP contract and state schemas shared by the CLI, the on-device SDK, and any update server (including `ota-ns serve` and Otto). ## Three distinct concepts @@ -30,8 +30,14 @@ Domain separation guarantees a signed manifest can never be reinterpreted as a s | `POST /check` | Client sends `UpdateCheckRequest` (`appId`, `platform`, `binaryVersion`, `targetBuild`, `runtimeContract`, `channel`, `currentReleaseId`, `currentDirectiveSeq`); server returns `{ protocolVersion: 1, status: "none" }` or `{ protocolVersion: 1, status: "directive", signedDirective }`. | | `GET ` | Returns `SignedManifest` (`{ manifest, signature }`). | | `GET /` | Streams exact immutable bytes for each file listed in `manifest.files`. | -| `POST /events` (optional) | Receives best-effort `OtaLifecycleEvent` telemetry (`check_started`, `download_progress`, `staged`, `boot_confirmed`, `recovery_triggered`, `error`). | +| `POST /events` (optional) | Receives best-effort `OtaLifecycleEvent` telemetry (`download_completed`, `validation_failed`, `staged`, `startup_confirmed`, `recovered_fallback`). | ## Cross-platform golden vectors `packages/protocol/test/vectors.json` holds RFC 8032 Ed25519 golden vectors verified identically across Node.js `crypto`, Apple `CryptoKit` (iOS) and Google Tink `Ed25519Verify` (Android). + +## Optional observation fields + +`UpdateCheckRequest` may include `installId`, a UTC `timestamp`, nullable `confirmedReleaseId` and nullable `stagedReleaseId`. Lifecycle events may include the same app-scoped `installId`; recovery events may include the actual native `recoveredAt`. Missing fields are left unknown. These extensions do not alter signed manifests/directives or protocol version 1. Treat client reports as untrusted operational observations, never attestation. + +Otto exposes this contract under `/api/check?app=` and `/api/events?app=`. The protocol paths above describe the portable contract; use the endpoints generated for your app. diff --git a/docs/guide/roadmap.md b/docs/guide/roadmap.md index db7ea5b..4c69b4d 100644 --- a/docs/guide/roadmap.md +++ b/docs/guide/roadmap.md @@ -14,5 +14,5 @@ All four v0.1 milestones (**M0** through **M3**) are delivered and proven on iOS ## Next ecosystem integrations -- **Orbit control plane (`getcortexlabs/orbit#698`)** — hosted channels, gradual percentage rollouts, monotonic `directiveSeq` issuance, immutable artifact storage and `POST /events` telemetry aggregation on top of `@getcortexlabs/ota-protocol`. -- **Mavis CLI guided setup (`getcortexlabs/mavis-ui#493`)** — `init` / `publish` commands wrapping `ota-ns keygen`, `fingerprint`, `pack`, `verify` and direct upload to Orbit. +- **Otto Console** — workspaces, teams, channels, immutable publishing, gradual rollouts, delivery diagnosis, native fingerprints, reports and observed installations. Optional protection and guarded cleanup live in app settings. Domain and SMTP acceptance depend on the hosting environment being configured. See [Operating Otto](./otto). +- **Mavis CLI guided setup (`getcortexlabs/mavis-ui#493`)** — `init` / `publish` commands wrapping `ota-ns keygen`, `fingerprint`, `pack`, `verify` and direct upload to Otto. diff --git a/docs/guide/validation.md b/docs/guide/validation.md index 0aa1563..2ac6f4a 100644 --- a/docs/guide/validation.md +++ b/docs/guide/validation.md @@ -36,3 +36,24 @@ The same eight release scenarios were executed on `@nativescript/vite` `8.0.24` | ----------- | ------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------- | | **iOS** | iOS 26.2 Simulator Release (`@nativescript/ios` `9.1.1`) | `ios-rc-b33e2dbc087bfb5c` (`build-artifacts`) | **5/7 files reused** (`2,407,282 B` / **99.45%** saved via APFS CoW; only `13,419 B` downloaded) | N/A (`v8SnapshotDetected: false`) | `ota-vite-lazy-C_yMXjFC.mjs`, `require-esm:vite-lazy:ota-v2`, `ns:util(format)`, `vite-worker:ota-v2`, `16x16` PNG, `970,712 B` TTF | | | **Android** | Physical Xiaomi `M2103K19PG` Android 16 / API 36, signed R8 APK (`@nativescript/android` `9.1.3`) | `android-rc-fd93f6a518dac292` (`build-artifacts`, `android:v8CodeCache=enabled`, `android:v8Snapshot=disabled`) | **6/8 files reused** (`2,319,114 B` / **99.41%** saved; only `13,755 B` downloaded) | `v8SnapshotDetected: false`, isolated `.cache` verified (`codeCacheFilesCount: 1` in both `embedded/app` and `releases/ota-v2/app`) | `ota-vite-lazy-C_yMXjFC.mjs`, `require-esm:vite-lazy:ota-v2`, `ns:util(format)`, `vite-worker:ota-v2`, `16x16` PNG, `970,712 B` TTF | | + +## Otto Console integration acceptance — December 3, 2026 + +This acceptance used an isolated Otto Node/SQLite server and a separate test app ID. It extends the earlier bundler matrix; it does not certify a public hosted deployment or repeat every earlier fault-injection case. + +| Flow | Android physical device | iOS Simulator | +| ---------------------------------------------------------------------------------------------- | ----------------------- | ------------------- | +| Release binary connects and reports a persistent installation reference | Passed, signed R8 APK | Passed, Release app | +| CLI publishes signed release; SDK verifies, reuses files and stages it | Passed | Passed | +| Cold launch activates and confirms the OTA's JavaScript, asset, lazy module and worker changes | Passed | Passed | +| Intentional crash before `markReady()` recovers the last confirmed release without the server | Passed | Passed | +| Reconnection reports the native recovery time and the same installation reference | Passed | Passed | +| New signed server rollback directive activates the embedded bundle on next launch | Passed | Passed | + +Runtime versions: NativeScript Android 9.1.3, iOS 9.1.1, Core 9.1.4 and `@nativescript/vite` 8.0.24. Android ran on the physical Xiaomi M2103K19PG (Android 16); iOS ran in the iOS 26.2 Simulator. This is not physical iPhone acceptance. + +The Console observed exactly two installation references and confirmed both good releases before rollback. Across four downloads (good and intentionally failing candidate on each platform), reports recorded 3,633,966 downloaded bytes and 5,838,632 reused bytes, with 17 reused files out of 28. Counts come from retained SDK reports, not a network billing meter. The recovery timestamps matched the native evidence even when the server was offline during recovery. + +The matching service checks cover legacy migration, workspace authorization, quotas, native compatibility, out-of-order reports, observation limits, artifact protection/grace periods, stale cleanup plans, immutable purged IDs, distinct-installation protection thresholds, automatic pause and alerts-only modes, local mail queue delivery, deployment validation and online backup integrity. Browser checks covered 1440/390/320 px, Portuguese, reduced motion, recovery details and reversible storage controls. A locally built Docker container preserved its account, workspace and session after restart. + +Still requires the configured hosting environment: DNS/HTTPS, real SMTP and inbox delivery, off-host backup scheduling, and production persistence/restore acceptance. The local outbox test sends no external email. diff --git a/docs/pt-BR/guide/api.md b/docs/pt-BR/guide/api.md index cdc1f48..d48ce9a 100644 --- a/docs/pt-BR/guide/api.md +++ b/docs/pt-BR/guide/api.md @@ -15,4 +15,12 @@ import { updates, OtaError, OTA_ERROR_CODES } from '@getcortexlabs/ota-nativescr - **`updates.downloadAndStage(directive, options?): Promise`** — baixa o manifesto, reutiliza localmente arquivos inalterados com `sha256` + `size` idênticos (APFS CoW no iOS; cópia isolada no Android), baixa o delta restante em `staging/`, valida 100% do inventário, promove atomicamente para `releases/` e executa GC (retornando `bytesDownloaded`, `bytesReused`, `fileCount` e `reusedFileCount`). - **`updates.checkAndStage(options?): Promise`** — executa `check()` + `downloadAndStage()` com proteção single-flight. - **`updates.collectGarbage(): Promise`** — remove releases não referenciadas em disco. -- **`updates.onEvent(listener): () => void`** — assina eventos estruturados de telemetria (`check_started`, `download_progress`, `staged`, `boot_confirmed`, `recovery_triggered`, `error`). +- **`updates.onEvent(listener): () => void`** — assina eventos estruturados de telemetria (`download_completed`, `validation_failed`, `staged`, `startup_confirmed`, `recovered_fallback`). + +## Referências de instalação e relatos remotos + +Crie uma instância `createOtaUpdates({ installId })` com UUID aleatório por app, persistido entre aberturas, e use essa instância para `markReady()` e consultas. [Operando o Otto](./otto#instalacoes-observadas) traz o exemplo de persistência no NativeScript. O singleton padrão não inventa uma identidade de instalação. + +O ID opcional acompanha consultas e eventos. As consultas também informam timestamp e IDs anuláveis de release confirmada/preparada. `recovered_fallback.recoveredAt` preserva a data nativa da recuperação; `timestamp` indica quando o relato foi emitido. Falha na telemetria não impede confirmação ou recuperação offline. Esses campos exigem uma versão do SDK que os contenha; relatos antigos continuam válidos e anônimos quando não há ID. + +`download_completed` inclui bytes baixados/reutilizados, arquivos e duração. `validation_failed` traz o código estável do erro. `staged` identifica release/diretiva preparada. `startup_confirmed` informa origem e versão realmente inicializadas. `recovered_fallback` informa a release que falhou e o destino recuperado. Progresso de download é o callback `onProgress`, não um evento de ciclo de vida separado. diff --git a/docs/pt-BR/guide/otto.md b/docs/pt-BR/guide/otto.md new file mode 100644 index 0000000..5d93053 --- /dev/null +++ b/docs/pt-BR/guide/otto.md @@ -0,0 +1,66 @@ +# Operando o Otto + +O Otto reúne apresentação, Console, documentação e API na mesma origem: `https://otto.getcortexlabs.com`, `/dashboard`, `/docs` e `/api`. A instalação própria usa os mesmos caminhos no domínio escolhido. Esse é o endereço canônico pretendido; confira a hospedagem antes de conectar apps de produção. + +## Primeira entrega + +Crie a conta, confirme o e-mail e crie um workspace. O seletor troca entre workspaces; **Novo workspace**, logo abaixo desse seletor, permite criar outro. O responsável gerencia apps, acesso, chaves, tokens e armazenamento. Publicadores gerenciam entregas; leitores acompanham o workspace. + +Cadastre o identificador e as plataformas do app. Em **Configurações → App e integrações**, registre a chave pública de releases, crie um token de publicação, escolha o canal e copie o `ota.config.json` gerado. A chave privada fica no ambiente de assinatura. O app confia na chave da release e na chave pública de entregas do Otto; nunca embarque o token de publicação. + +Gere o binário da loja com seu fingerprint nativo. Use `ota-ns pack`, `ota-ns verify` e publique: + +```sh +# Forneça OTTO_TOKEN pelo gerenciador de segredos ou ambiente do shell. +ota-ns publish --bundle ./dist-ota \ + --endpoint https://otto.getcortexlabs.com/api/publish --channel beta +``` + +O Console permite entregar, pausar, fazer rollback, ajustar o percentual por canal, comparar compatibilidade nativa e simular consultas. OTA compatível altera JavaScript e assets. Dependências nativas, permissões e mudanças no contrato exigem outro binário na loja. + +## Instalações observadas + +**Atividade → Instalações** mostra a última versão em execução informada, confirmação de início, próxima release preparada, falha recente e último contato. As contagens usam referências vistas no período escolhido, com retenção de 30 dias e limite de 10.000 por app. Não são pessoas nem toda a base instalada, e não comprovam saúde contínua. Relatos anônimos seguem no livro de entregas. + +Para habilitar, persista um UUID aleatório no app e passe como `installId`. Use uma identidade separada por app; nunca e-mail, identificador de publicidade ou hardware. Com os tipos de plataforma do NativeScript disponíveis: + +```ts +import { ApplicationSettings, isAndroid } from '@nativescript/core'; +import { createOtaUpdates } from '@getcortexlabs/ota-nativescript'; + +let installId = ApplicationSettings.getString('otto.installation'); +if (!installId) { + installId = isAndroid ? java.util.UUID.randomUUID().toString() : NSUUID.UUID().UUIDString; + ApplicationSettings.setString('otto.installation', installId); +} +const updates = createOtaUpdates({ installId }); +// Use esta instância para markReady(), checkAndStage() e eventos. +``` + +O Otto deriva uma referência HMAC por app/plataforma e guarda essa referência, não o ID original. Reinstalação ou restauração de dados podem alterar a identidade. Relatos fora de ordem ficam no histórico sem substituir um estado mais recente. Release preparada ainda não é adoção. Recuperações carregam a data em que aconteceram no código nativo, mesmo se relatadas depois. + +As extensões de identidade nos eventos exigem uma versão do SDK que as contenha. Versões antigas podem enviar `installId` só nas consultas e continuar anônimas nos eventos. O formato assinado de manifestos e diretivas não mudou. + +## Proteção das entregas + +**Configurações → Proteção das entregas** começa desligada. Escolha uma janela, percentual de falhas e pelo menos três referências afetadas. Só entram referências distintas que receberam a mesma sequência ativa e relataram dentro da janela. Reenvios não multiplicam a amostra. Eventos anônimos ou de sequências antigas não acionam pausa. + +A pausa automática é uma opção separada, confirmada pelo nome do app. Relatos públicos dos clientes não são atestados: o sinal é de melhor esforço, sem resistência a identidades falsas. Pausar interrompe novas diretivas; não apaga pacotes já preparados. Revise antes de retomar manualmente. + +**Atividade → Alertas** exibe os últimos 100 alertas, retidos por 90 dias até o limite de 1.000 por app. Marcar como visto registra a revisão e não retoma a entrega. O e-mail é opcional e inscreve apenas o responsável confirmado que salva a configuração. Falhas de envio têm até cinco tentativas com intervalos crescentes. “Aceito pelo transporte” não comprova chegada à caixa de entrada. + +## Armazenamento e retirada + +**Configurações → Armazenamento de releases** permite fixar, retirar, restaurar e limpar artefatos. Rotas continuam protegidas quando pausadas ou em canais arquivados. Versões observadas em execução, confirmadas, preparadas e de recuperação também ficam protegidas. + +Retirar impede novo despacho e republicação. Limpar exige 30 dias desde a retirada, expiração da proteção de 30 dias da última oferta/download, ausência de referências e um plano conferido novamente pelo servidor. Fixe versões necessárias a clientes que passam mais tempo offline: observações não cobrem todos os aparelhos desconectados. + +A limpeza exclui os bytes e libera a cota do workspace, preservando manifesto, ID imutável e auditoria. Um ID limpo não pode ser republicado; downloads retornam HTTP 410 e não há restauração. O SQLite pode reutilizar páginas sem reduzir o arquivo imediatamente. Fingerprints nativos só podem ser excluídos sem referência de pacote/instalação e sem fixação. + +## Aceitação da hospedagem + +Execute um servidor Node com volume SQLite local persistente atrás de HTTPS. Use o backup online do SQLite, não uma cópia isolada do banco com WAL ativo. Valide a restauração em outro diretório antes de atualizar. Não exponha dados nem credenciais no diretório público. + +Configure `OTTO_ORIGIN`, `OTTO_DATA_DIR`, SMTP transacional e a lista de administradores com e-mail confirmado. O repositório privado inclui contêiner, backup e verificações de ambiente. `OTTO_MAIL_MODE=file` é uma caixa local exclusiva de loopback, não envio de produção. + +Antes de considerar o serviço hospedado pronto, valide HTTPS/origem, persistência após reinício, e-mails reais de confirmação/recuperação/convite, publicação pela CLI, consultas assinadas, abertura a frio em iOS/Android e os relatos correspondentes no Console. A suíte local não comprova DNS, TLS, chegada à caixa de entrada nem a rotina de backup do servidor. diff --git a/docs/pt-BR/guide/protocol.md b/docs/pt-BR/guide/protocol.md index 6b6ffa0..7941fcd 100644 --- a/docs/pt-BR/guide/protocol.md +++ b/docs/pt-BR/guide/protocol.md @@ -1,6 +1,6 @@ # Protocolo assinado -`@getcortexlabs/ota-protocol` define o contrato HTTP agnóstico de servidor compartilhado pela CLI, pelo SDK embarcado e por qualquer servidor de releases (como `ota-ns serve` e a futura integração com o Orbit). +`@getcortexlabs/ota-protocol` define o contrato HTTP agnóstico de servidor compartilhado pela CLI, pelo SDK embarcado e por qualquer servidor de releases (como `ota-ns serve` e o Otto). ## Três conceitos separados @@ -18,3 +18,9 @@ Para voltar de `ota-105` (`directiveSeq: 12`) para `ota-104`, o servidor emite u - Diretivas: `ota-nativescript:directive:v1\n` + `canonicalizeJson(directive)` Vetores dourados RFC 8032 em `packages/protocol/test/vectors.json` são validados de forma idêntica em Node.js, Apple `CryptoKit` e Google Tink. + +## Campos opcionais de observação + +`UpdateCheckRequest` pode incluir `installId`, `timestamp` UTC e IDs anuláveis `confirmedReleaseId` e `stagedReleaseId`. Eventos podem incluir o mesmo `installId` por app; recuperações podem incluir a data nativa `recoveredAt`. Campos ausentes ficam desconhecidos. Essas extensões não alteram manifestos/diretivas assinados nem a versão 1 do protocolo. Relatos de clientes são observações não confiáveis para atestação. + +O Otto expõe o contrato em `/api/check?app=` e `/api/events?app=`. Os caminhos do protocolo são portáveis; use os endpoints gerados para seu app. Os eventos são `download_completed`, `validation_failed`, `staged`, `startup_confirmed` e `recovered_fallback`. diff --git a/docs/pt-BR/guide/roadmap.md b/docs/pt-BR/guide/roadmap.md index a21d516..e95ca92 100644 --- a/docs/pt-BR/guide/roadmap.md +++ b/docs/pt-BR/guide/roadmap.md @@ -14,5 +14,5 @@ Todos os quatro marcos da v0.1 (**M0** a **M3**) estão concluídos e validados ## Próximas integrações de ecossistema -- **Orbit control plane (`getcortexlabs/orbit#698`)** — canais gerenciados, rollouts percentuais graduais, diretivas com `directiveSeq` monotônico e métricas de telemetria (`POST /events`) sobre `@getcortexlabs/ota-protocol`. -- **CLI da Mavis (`getcortexlabs/mavis-ui#493`)** — comandos guiados `init` / `publish` encapsulando `ota-ns keygen`, `fingerprint`, `pack`, `verify` e upload direto para o Orbit. +- **Otto Console** — workspaces, equipe, canais, publicação imutável, rollouts graduais, diagnóstico de entrega, fingerprints nativos, relatos e instalações observadas. Proteção opcional e limpeza com carência ficam nas configurações do app. A validação do domínio e SMTP depende da configuração da hospedagem. Veja [Operando o Otto](./otto). +- **CLI da Mavis (`getcortexlabs/mavis-ui#493`)** — comandos guiados `init` / `publish` encapsulando `ota-ns keygen`, `fingerprint`, `pack`, `verify` e upload direto para o Otto. diff --git a/docs/pt-BR/guide/validation.md b/docs/pt-BR/guide/validation.md index ad3e499..d5b77a4 100644 --- a/docs/pt-BR/guide/validation.md +++ b/docs/pt-BR/guide/validation.md @@ -30,3 +30,24 @@ Os mesmos oito cenários release foram executados em `@nativescript/vite` `8.0.2 | ----------- | ---------------------------------------------------------------------------------------------------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------- | | **iOS** | Simulador iOS 26.2 Release (`@nativescript/ios` `9.1.1`) | `ios-rc-b33e2dbc087bfb5c` | **5/7 arquivos reutilizados** (`2.407.282 B` / **99,45%** economizados via APFS CoW; só `13.419 B` baixados) | N/A (`v8SnapshotDetected: false`) | `ota-vite-lazy-C_yMXjFC.mjs`, `require-esm:vite-lazy:ota-v2`, `ns:util(format)`, `vite-worker:ota-v2`, PNG `16x16`, TTF `970.712 B` | | | **Android** | **Xiaomi físico `M2103K19PG`** Android 16 / API 36, APK release R8 (`@nativescript/android` `9.1.3`) | `android-rc-fd93f6a518dac292` | **6/8 arquivos reutilizados** (`2.319.114 B` / **99,41%** economizados; só `13.755 B` baixados) | `v8SnapshotDetected: false`, `.cache` isolado por release (`codeCacheFilesCount: 1` em `embedded/app` e `releases/ota-v2/app`) | `ota-vite-lazy-C_yMXjFC.mjs`, `require-esm:vite-lazy:ota-v2`, `ns:util(format)`, `vite-worker:ota-v2`, PNG `16x16`, TTF `970.712 B` | | + +## Aceitação da integração com Otto Console — 3 de dezembro de 2026 + +A aceitação usou um servidor Otto Node/SQLite isolado e um identificador de app separado. Complementa a matriz anterior de bundlers; não certifica hospedagem pública nem repete todos os cenários anteriores de injeção de falhas. + +| Fluxo | Android físico | Simulador iOS | +| ------------------------------------------------------------------------------------------ | --------------------------- | ------------------- | +| Binário Release conecta e relata referência persistente de instalação | Passou, APK assinado com R8 | Passou, app Release | +| CLI publica release assinada; SDK verifica, reutiliza arquivos e prepara | Passou | Passou | +| Abertura a frio ativa e confirma mudanças de JavaScript, asset, módulo lazy e worker | Passou | Passou | +| Falha intencional antes de `markReady()` recupera a última release confirmada sem servidor | Passou | Passou | +| Reconexão relata a data nativa da recuperação e a mesma referência de instalação | Passou | Passou | +| Nova diretiva assinada de rollback ativa o bundle embutido na próxima abertura | Passou | Passou | + +Versões: NativeScript Android 9.1.3, iOS 9.1.1, Core 9.1.4 e `@nativescript/vite` 8.0.24. Android no Xiaomi M2103K19PG físico (Android 16); iOS no Simulator 26.2. Não é aceitação em iPhone físico. + +O Console observou exatamente duas referências e confirmou as duas releases boas antes do rollback. Nos quatro downloads (release boa e candidata com falha em cada plataforma), os relatos registraram 3.633.966 bytes baixados e 5.838.632 reutilizados, com 17 arquivos reutilizados de 28. São dados relatados pelo SDK, não medição de cobrança de rede. As datas de recuperação bateram com a evidência nativa mesmo com o servidor desligado durante o fallback. + +Os testes do serviço cobrem migração legada, autorização por workspace, cotas, compatibilidade nativa, relatos fora de ordem, limites de observação, referências/carências de limpeza, planos desatualizados, IDs limpos imutáveis, limites por instalações distintas, pausa automática e modo só-alerta, fila local de e-mail, configuração e integridade do backup online. O navegador foi conferido em 1440/390/320 px, português, movimento reduzido, detalhes de recuperação e controles reversíveis de armazenamento. O contêiner Docker local preservou conta, workspace e sessão após reinício. + +Ainda depende da hospedagem configurada: DNS/HTTPS, SMTP e caixa de entrada reais, rotina de backup fora do servidor e aceitação da persistência/restauração em produção. O teste de caixa local não envia e-mail externo. diff --git a/packages/ota-cli/README.md b/packages/ota-cli/README.md index 447f6a3..5cc48a4 100644 --- a/packages/ota-cli/README.md +++ b/packages/ota-cli/README.md @@ -2,8 +2,8 @@ CLI (`ota-ns`) for Ed25519 key generation, per-platform NativeScript runtime compatibility fingerprinting (including Android V8 snapshot & `codeCache` checks), Webpack 5 and `@nativescript/vite` bundle packaging, offline CI verification, and local fault-injection testing. -- Documentation: https://ota-ns.getcortexlabs.com/guide/cli -- Fingerprinting guide: https://ota-ns.getcortexlabs.com/guide/fingerprinting +- Documentation: https://otto.getcortexlabs.com/docs/guide/cli +- Fingerprinting guide: https://otto.getcortexlabs.com/docs/guide/fingerprinting - Repository: https://github.com/getcortexlabs/ota-nativescript ## Install diff --git a/packages/ota-cli/package.json b/packages/ota-cli/package.json index bac8da1..2598d39 100644 --- a/packages/ota-cli/package.json +++ b/packages/ota-cli/package.json @@ -4,7 +4,7 @@ "description": "Packaging, signing, runtime fingerprinting, and local fixture server CLI for ota-nativescript.", "license": "MIT", "author": "Rafael Augusto ", - "homepage": "https://ota-ns.getcortexlabs.com/guide/cli", + "homepage": "https://otto.getcortexlabs.com/docs/guide/cli", "repository": { "type": "git", "url": "git+https://github.com/getcortexlabs/ota-nativescript.git", diff --git a/packages/ota-nativescript/README.md b/packages/ota-nativescript/README.md index 6ff2da8..65b7317 100644 --- a/packages/ota-nativescript/README.md +++ b/packages/ota-nativescript/README.md @@ -2,9 +2,9 @@ Signed over-the-air (OTA) JavaScript and asset updates for NativeScript 9.1+ release builds (Webpack 5 and `@nativescript/vite`) — native pre-boot bundle selection before V8 starts, Ed25519 + streaming SHA-256 verification (Apple `CryptoKit` / Google Tink), content-addressed local asset reuse across releases, per-platform runtime compatibility contracts, and offline crash rollback. -- Documentation: https://ota-ns.getcortexlabs.com/guide/ -- Integration guide: https://ota-ns.getcortexlabs.com/guide/integration-guide -- Support matrix: https://ota-ns.getcortexlabs.com/guide/support-matrix +- Documentation: https://otto.getcortexlabs.com/docs/guide/ +- Integration guide: https://otto.getcortexlabs.com/docs/guide/integration-guide +- Support matrix: https://otto.getcortexlabs.com/docs/guide/support-matrix - Repository: https://github.com/getcortexlabs/ota-nativescript ## Install @@ -25,6 +25,10 @@ export function onFirstUsableScreen() { } ``` +## Observed installations + +To connect lifecycle reports to an installation in Otto Console, use `createOtaUpdates({ installId })` with a persistent random app-scoped UUID. Never use an email or advertising/hardware identifier. See the [operations guide](https://otto.getcortexlabs.com/docs/guide/otto#observed-installations) for the persistence example and observation limits. + ## License MIT diff --git a/packages/ota-nativescript/package.json b/packages/ota-nativescript/package.json index 356f567..93f3457 100644 --- a/packages/ota-nativescript/package.json +++ b/packages/ota-nativescript/package.json @@ -4,7 +4,7 @@ "description": "Over-the-air (OTA) update SDK for NativeScript with signed bundles, runtime compatibility checks, and offline startup rollback.", "license": "MIT", "author": "Rafael Augusto ", - "homepage": "https://ota-ns.getcortexlabs.com/", + "homepage": "https://otto.getcortexlabs.com/docs/", "repository": { "type": "git", "url": "git+https://github.com/getcortexlabs/ota-nativescript.git", diff --git a/packages/ota-nativescript/src/client.ts b/packages/ota-nativescript/src/client.ts index 7022944..c55275e 100644 --- a/packages/ota-nativescript/src/client.ts +++ b/packages/ota-nativescript/src/client.ts @@ -67,6 +67,7 @@ export interface OtaUpdatesOptions { getBootInfo(): NativeBootInfo | null; markReady(): boolean; }; + /** Persist an app-scoped random ID across launches. Never use an email or advertising ID. */ installId?: string; timeoutMs?: number; maxBundleBytes?: number; @@ -94,7 +95,7 @@ export function createOtaUpdates(options: OtaUpdatesOptions = {}): OtaUpdatesApi markReady: nativeMarkReady, }; const listeners = new Set(); - const now = options.now ?? (() => new Date().toISOString().replace(/\.\d{3}Z$/, 'Z')); + const now = options.now ?? (() => new Date().toISOString()); let resolvedConfig: EmbeddedOtaConfig | null = options.config ? validateEmbeddedOtaConfig(options.config) @@ -199,6 +200,7 @@ export function createOtaUpdates(options: OtaUpdatesOptions = {}): OtaUpdatesApi targetBuild: string; runtimeContract: string; channel: string; + installId?: string; } { const cfg = (resolvedConfig ??= nativeGetEmbeddedConfig()); return { @@ -210,6 +212,7 @@ export function createOtaUpdates(options: OtaUpdatesOptions = {}): OtaUpdatesApi targetBuild: bootInfo.targetBuild, runtimeContract: bootInfo.runtimeContract, channel: cfg?.channel ?? 'unknown', + ...(options.installId ? { installId: options.installId } : {}), }; } @@ -240,6 +243,7 @@ export function createOtaUpdates(options: OtaUpdatesOptions = {}): OtaUpdatesApi recoveredTo: before.lastRecovery.recoveredTo, recoveredReleaseId: before.lastRecovery.recoveredReleaseId, attempts: before.lastRecovery.attempts, + recoveredAt: before.lastRecovery.recoveredAt, }); } @@ -273,6 +277,9 @@ export function createOtaUpdates(options: OtaUpdatesOptions = {}): OtaUpdatesApi channel: cfg.channel, currentReleaseId: bootInfo.releaseId, currentDirectiveSeq: state.lastDirectiveSeq, + timestamp: now(), + confirmedReleaseId: state.confirmedReleaseId, + stagedReleaseId: state.stagedReleaseId, ...(options.installId ? { installId: options.installId } : {}), }); diff --git a/packages/ota-nativescript/test/staging-and-client.test.ts b/packages/ota-nativescript/test/staging-and-client.test.ts index fb14cfb..8240b5b 100644 --- a/packages/ota-nativescript/test/staging-and-client.test.ts +++ b/packages/ota-nativescript/test/staging-and-client.test.ts @@ -228,11 +228,14 @@ describe('staging manager, HttpUpdateClient, GC and public SDK API (#8, #10)', ( } }); - it('sends a cold-launch receipt even when markReady precedes the first check', async () => { - const fetchMock = vi.fn(async () => new Response(null, { status: 204 })); + it('sends an identified cold-launch receipt even when markReady precedes the first check', async () => { + const fetchMock = vi.fn( + async (_url: unknown, _init?: RequestInit) => new Response(null, { status: 204 }), + ); vi.stubGlobal('fetch', fetchMock); const sdk = createOtaUpdates({ platform: 'ios', + installId: 'app-scoped-random-reference', config: { appId: 'com.example.desk', endpoint: 'https://updates.example.com/check', @@ -263,6 +266,10 @@ describe('staging manager, HttpUpdateClient, GC and public SDK API (#8, #10)', ( expect.objectContaining({ body: expect.stringContaining('startup_confirmed') }), ), ); + expect(JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body))).toMatchObject({ + type: 'startup_confirmed', + installId: 'app-scoped-random-reference', + }); }); it('downloads, verifies, atomically stages a signed release, emits events and collects garbage', async () => { @@ -278,6 +285,12 @@ describe('staging manager, HttpUpdateClient, GC and public SDK API (#8, #10)', ( const mockFetch = createMockFetch((url, init) => { if (url === `${baseUrl}/check` && init?.method === 'POST') { + expect(JSON.parse(String(init.body))).toMatchObject({ + installId: 'persistent-sdk-test', + currentReleaseId: 'ota-103', + confirmedReleaseId: 'ota-103', + stagedReleaseId: null, + }); const directive: UpdateDirective = { protocolVersion: 1, directiveId: 'dir-5', @@ -353,6 +366,7 @@ describe('staging manager, HttpUpdateClient, GC and public SDK API (#8, #10)', ( const sdk = createOtaUpdates({ platform: 'ios', + installId: 'persistent-sdk-test', config: { appId: 'com.getcortexlabs.example', endpoint: `${baseUrl}/check`, @@ -633,6 +647,7 @@ describe('staging manager, HttpUpdateClient, GC and public SDK API (#8, #10)', ( expect(sdk.markReady()).toBe(true); expect(sdk.getCurrentRelease()).toBe('ota-104'); expect(events.map((e) => e.type)).toEqual(['recovered_fallback', 'startup_confirmed']); + expect(events[0]).toMatchObject({ recoveredAt: '2026-12-03T00:04:00Z' }); // Repeated markReady() does not emit a duplicate recovered_fallback event. expect(sdk.markReady()).toBe(true); diff --git a/packages/protocol/README.md b/packages/protocol/README.md index 2f61ba9..2ca4a45 100644 --- a/packages/protocol/README.md +++ b/packages/protocol/README.md @@ -2,7 +2,7 @@ Signed manifest schemas, update-check HTTP contract, RFC 8785 JCS canonicalization, boot-state transitions, path safety validators, and error codes for `ota-nativescript`. -- Documentation: https://ota-ns.getcortexlabs.com/guide/protocol +- Documentation: https://otto.getcortexlabs.com/docs/guide/protocol - Repository: https://github.com/getcortexlabs/ota-nativescript ## Install diff --git a/packages/protocol/package.json b/packages/protocol/package.json index 0e1c69f..580e77f 100644 --- a/packages/protocol/package.json +++ b/packages/protocol/package.json @@ -4,7 +4,7 @@ "description": "Signed manifest schema, update check contract, canonical serialization, and error codes for ota-nativescript.", "license": "MIT", "author": "Rafael Augusto ", - "homepage": "https://ota-ns.getcortexlabs.com/guide/protocol", + "homepage": "https://otto.getcortexlabs.com/docs/guide/protocol", "repository": { "type": "git", "url": "git+https://github.com/getcortexlabs/ota-nativescript.git", diff --git a/packages/protocol/src/types.ts b/packages/protocol/src/types.ts index 7dc8bcc..1cfe8d3 100644 --- a/packages/protocol/src/types.ts +++ b/packages/protocol/src/types.ts @@ -48,6 +48,10 @@ export interface UpdateCheckRequest { currentReleaseId: string | null; currentDirectiveSeq?: number; installId?: string; + /** Client observation time; optional for older clients. */ + timestamp?: string; + confirmedReleaseId?: string | null; + stagedReleaseId?: string | null; } export interface BaseDirective { @@ -143,6 +147,8 @@ export type OtaLifecycleEventType = | 'recovered_fallback'; interface BaseLifecycleEvent { + /** App-scoped pseudonymous installation ID, supplied by the integrator. */ + installId?: string; protocolVersion: ProtocolVersion; timestamp: string; appId: string; @@ -185,6 +191,7 @@ export interface StartupConfirmedEvent extends BaseLifecycleEvent { } export interface RecoveredFallbackEvent extends BaseLifecycleEvent { + recoveredAt?: string; type: 'recovered_fallback'; failedReleaseId: string; recoveredTo: BootSource; diff --git a/packages/protocol/src/validation.ts b/packages/protocol/src/validation.ts index f456b69..4ca0fde 100644 --- a/packages/protocol/src/validation.ts +++ b/packages/protocol/src/validation.ts @@ -427,6 +427,19 @@ export function validateUpdateCheckRequest(input: unknown): UpdateCheckRequest { ); } + if (obj.timestamp !== undefined) + result.timestamp = assertIsoUtcTimestamp( + obj.timestamp, + OTA_ERROR_CODES.CHECK_REQUEST_INVALID, + 'timestamp', + ); + for (const key of ['confirmedReleaseId', 'stagedReleaseId'] as const) { + if (obj[key] !== undefined) + result[key] = + obj[key] === null + ? null + : assertReleaseId(obj[key], OTA_ERROR_CODES.CHECK_REQUEST_INVALID, key); + } return result; } @@ -741,6 +754,15 @@ export function validateLifecycleEvent(input: unknown): OtaLifecycleEvent { 'runtimeContract', ), channel: assertNonEmptyString(obj.channel, OTA_ERROR_CODES.EVENT_INVALID, 'channel'), + ...(obj.installId === undefined + ? {} + : { + installId: assertNonEmptyString( + obj.installId, + OTA_ERROR_CODES.EVENT_INVALID, + 'installId', + ), + }), }; switch (obj.type) { @@ -851,6 +873,15 @@ export function validateLifecycleEvent(input: unknown): OtaLifecycleEvent { return { ...base, type: 'recovered_fallback', + ...(obj.recoveredAt === undefined + ? {} + : { + recoveredAt: assertIsoUtcTimestamp( + obj.recoveredAt, + OTA_ERROR_CODES.EVENT_INVALID, + 'recoveredAt', + ), + }), failedReleaseId: assertReleaseId( obj.failedReleaseId, OTA_ERROR_CODES.EVENT_INVALID, diff --git a/packages/protocol/test/validation.test.ts b/packages/protocol/test/validation.test.ts index 44cb4f5..881330a 100644 --- a/packages/protocol/test/validation.test.ts +++ b/packages/protocol/test/validation.test.ts @@ -343,3 +343,60 @@ describe('boot state and lifecycle events', () => { ); }); }); + +describe('optional installation observation fields', () => { + const request = { + protocolVersion: 1, + appId: 'com.example.app', + platform: 'ios', + binaryVersion: '1', + targetBuild: '42', + runtimeContract: 'ios-v1', + channel: 'beta', + currentReleaseId: null, + currentDirectiveSeq: 0, + }; + it('preserves legacy payloads without inventing observation data', () => { + expect(validateUpdateCheckRequest(request)).toEqual(request); + }); + it('retains identity, precise timestamps and nullable boot references', () => { + const observed = { + ...request, + installId: 'random-local-id', + timestamp: '2026-12-03T00:00:00.123Z', + confirmedReleaseId: 'good', + stagedReleaseId: null, + }; + expect(validateUpdateCheckRequest(observed)).toEqual(observed); + const event = { + ...request, + type: 'recovered_fallback', + timestamp: '2026-12-03T00:01:00Z', + recoveredAt: observed.timestamp, + installId: observed.installId, + failedReleaseId: 'bad', + recoveredTo: 'embedded', + recoveredReleaseId: null, + attempts: 1, + }; + expect(validateLifecycleEvent(event)).toMatchObject({ + installId: observed.installId, + recoveredAt: observed.timestamp, + }); + }); + it('rejects malformed timestamps and release references', () => { + expect(() => validateUpdateCheckRequest({ ...request, timestamp: 'yesterday' })).toThrow(); + expect(() => validateUpdateCheckRequest({ ...request, stagedReleaseId: '../bad' })).toThrow(); + expect(() => + validateLifecycleEvent({ + ...request, + type: 'startup_confirmed', + releaseId: null, + source: 'embedded', + attempts: 0, + timestamp: '2026-12-03T00:00:00Z', + installId: '', + }), + ).toThrow(); + }); +});