From 2e75ba3c9e4a0c4cc11dbabf4a03796728e35052 Mon Sep 17 00:00:00 2001 From: egdev6 Date: Sat, 21 Nov 2026 15:21:18 +0100 Subject: [PATCH 1/9] test(catalog): add shared v4 corpus and catalog v4 task plan --- crates/nexo-catalog/fixtures/parity-v4.json | 398 ++++++++++++++++++++ crates/nexo-catalog/fixtures/v4.json | 72 ++++ odd/tasks/catalog-v4.md | 36 ++ 3 files changed, 506 insertions(+) create mode 100644 crates/nexo-catalog/fixtures/parity-v4.json create mode 100644 crates/nexo-catalog/fixtures/v4.json create mode 100644 odd/tasks/catalog-v4.md diff --git a/crates/nexo-catalog/fixtures/parity-v4.json b/crates/nexo-catalog/fixtures/parity-v4.json new file mode 100644 index 0000000..9944d02 --- /dev/null +++ b/crates/nexo-catalog/fixtures/parity-v4.json @@ -0,0 +1,398 @@ +{ + "description": "Shared Rust/TypeScript v4 corpus. Each case patches v4.json (ops: set, add, remove, duplicate as in parity.json). projections: expected flat catalog (schemaVersion 4) for v4.json resolved for each platform key; apps without an entry are dropped and windows detection is wrapped as {windows: ...}.", + "cases": [ + { + "name": "v4 full", + "valid": true + }, + { + "name": "v4 linux only app", + "valid": true, + "patches": [ + { + "op": "set", + "path": "/apps/1/platforms", + "value": { + "linux-x86_64": { + "installerUrl": "https://github.com/egdev6/winonly/releases/download/v0.4.0/winonly_0.4.0_x64-setup.exe", + "latestJsonUrl": "https://github.com/egdev6/winonly/releases/download/v0.4.0/latest.json", + "version": "0.4.0", + "releasedAt": "2025-03-04T05:06:07Z" + } + } + } + ] + }, + { + "name": "v4 entry without key", + "valid": true, + "patches": [ + { + "op": "remove", + "path": "/apps/0/platforms/darwin-aarch64/updaterPublicKey" + } + ] + }, + { + "name": "v4 missing platforms", + "valid": false, + "patches": [ + { + "op": "remove", + "path": "/apps/0/platforms" + } + ] + }, + { + "name": "v4 empty platforms", + "valid": false, + "patches": [ + { + "op": "set", + "path": "/apps/0/platforms", + "value": {} + } + ] + }, + { + "name": "v4 unknown platform key", + "valid": false, + "patches": [ + { + "op": "add", + "path": "/apps/0/platforms/macos-aarch64", + "value": { + "installerUrl": "https://github.com/egdev6/example/releases/download/v1.2.3/example_aarch64.dmg", + "latestJsonUrl": "https://github.com/egdev6/example/releases/download/v1.2.3/latest.json", + "version": "1.2.2", + "releasedAt": "2025-01-01T00:00:00Z", + "updaterPublicKey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDQ2RkFBNEZCQjUwNTQxMDAKUldRQVFRVzErNlQ2UnJmZTl1MVpMWk9sUE82Skx0ZFRDZHFoNDRjTWlwU0NNYkJ2UzhwT1Z4YWQK" + } + } + ] + }, + { + "name": "v4 unknown arch", + "valid": false, + "patches": [ + { + "op": "add", + "path": "/apps/0/platforms/linux-riscv64", + "value": { + "installerUrl": "https://github.com/egdev6/example/releases/download/v1.2.3/example_aarch64.dmg", + "latestJsonUrl": "https://github.com/egdev6/example/releases/download/v1.2.3/latest.json", + "version": "1.2.2", + "releasedAt": "2025-01-01T00:00:00Z", + "updaterPublicKey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDQ2RkFBNEZCQjUwNTQxMDAKUldRQVFRVzErNlQ2UnJmZTl1MVpMWk9sUE82Skx0ZFRDZHFoNDRjTWlwU0NNYkJ2UzhwT1Z4YWQK" + } + } + ] + }, + { + "name": "v4 detection on darwin", + "valid": false, + "patches": [ + { + "op": "add", + "path": "/apps/0/platforms/darwin-aarch64/detection", + "value": { + "displayName": "Example App", + "publisher": "Example", + "executableRelativePath": "example.exe" + } + } + ] + }, + { + "name": "v4 detection on linux", + "valid": false, + "patches": [ + { + "op": "add", + "path": "/apps/0/platforms/linux-x86_64", + "value": { + "installerUrl": "https://github.com/egdev6/example/releases/download/v1.2.3/example_aarch64.dmg", + "latestJsonUrl": "https://github.com/egdev6/example/releases/download/v1.2.3/latest.json", + "version": "1.2.2", + "releasedAt": "2025-01-01T00:00:00Z", + "updaterPublicKey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDQ2RkFBNEZCQjUwNTQxMDAKUldRQVFRVzErNlQ2UnJmZTl1MVpMWk9sUE82Skx0ZFRDZHFoNDRjTWlwU0NNYkJ2UzhwT1Z4YWQK", + "detection": { + "displayName": "Example App", + "publisher": "Example", + "executableRelativePath": "example.exe" + } + } + } + ] + }, + { + "name": "v4 nested windows detection", + "valid": false, + "patches": [ + { + "op": "set", + "path": "/apps/0/platforms/windows-x86_64/detection", + "value": { + "windows": { + "displayName": "Example App", + "publisher": "Example", + "executableRelativePath": "example.exe" + } + } + } + ] + }, + { + "name": "v4 missing version", + "valid": false, + "patches": [ + { + "op": "remove", + "path": "/apps/0/platforms/darwin-aarch64/version" + } + ] + }, + { + "name": "v4 missing releasedAt", + "valid": false, + "patches": [ + { + "op": "remove", + "path": "/apps/0/platforms/darwin-aarch64/releasedAt" + } + ] + }, + { + "name": "v4 invalid semver", + "valid": false, + "patches": [ + { + "op": "set", + "path": "/apps/0/platforms/darwin-aarch64/version", + "value": "1.2" + } + ] + }, + { + "name": "v4 invalid date", + "valid": false, + "patches": [ + { + "op": "set", + "path": "/apps/0/platforms/darwin-aarch64/releasedAt", + "value": "2025-02-29T00:00:00Z" + } + ] + }, + { + "name": "v4 installer not a release asset", + "valid": false, + "patches": [ + { + "op": "set", + "path": "/apps/0/platforms/darwin-aarch64/installerUrl", + "value": "https://example.com/example.dmg" + } + ] + }, + { + "name": "v4 latest not a release asset", + "valid": false, + "patches": [ + { + "op": "set", + "path": "/apps/0/platforms/windows-x86_64/latestJsonUrl", + "value": "https://github.com/egdev6/example/latest.json" + } + ] + }, + { + "name": "v4 deceptive owner", + "valid": false, + "patches": [ + { + "op": "set", + "path": "/apps/0/platforms/windows-x86_64/installerUrl", + "value": "https://github.com/egdev6x/example/releases/download/v1/setup.exe" + } + ] + }, + { + "name": "v4 invalid updater key", + "valid": false, + "patches": [ + { + "op": "set", + "path": "/apps/0/platforms/windows-x86_64/updaterPublicKey", + "value": "dGVzdA==" + } + ] + }, + { + "name": "v4 unknown entry field", + "valid": false, + "patches": [ + { + "op": "add", + "path": "/apps/0/platforms/windows-x86_64/sha256", + "value": "x" + } + ] + }, + { + "name": "v4 flat installer at app level", + "valid": false, + "patches": [ + { + "op": "add", + "path": "/apps/0/installerUrl", + "value": "https://github.com/egdev6/example/releases/download/v1.2.3/example_1.2.3_x64-setup.exe" + } + ] + }, + { + "name": "v4 flat version at app level", + "valid": false, + "patches": [ + { + "op": "add", + "path": "/apps/0/version", + "value": "1.2.3" + } + ] + }, + { + "name": "v4 app without icon or art", + "valid": false, + "patches": [ + { + "op": "remove", + "path": "/apps/1/iconUrl" + } + ] + }, + { + "name": "v4 duplicate app", + "valid": false, + "patches": [ + { + "op": "duplicate", + "path": "/apps" + } + ] + }, + { + "name": "v4 bad app id", + "valid": false, + "patches": [ + { + "op": "set", + "path": "/apps/0/id", + "value": "Bad_id" + } + ] + } + ], + "projections": { + "windows-x86_64": { + "schemaVersion": 4, + "apps": [ + { + "id": "example-app", + "name": "Example App", + "tagline": "An example for testing", + "description": "A fictional catalog entry.", + "tags": [ + "Example", + "Desktop" + ], + "iconUrl": "https://example.com/icon.png", + "artUrl": "https://example.com/art.png", + "integrationLevel": "full", + "featured": true, + "links": { + "github": "https://github.com/example/example", + "youtube": "https://youtube.com/@example" + }, + "news": [ + { + "id": "release", + "title": "Example release", + "text": "A fictional release announcement.", + "publishedAt": "2025-01-02T03:04:05Z", + "kind": "new" + } + ], + "installerUrl": "https://github.com/egdev6/example/releases/download/v1.2.3/example_1.2.3_x64-setup.exe", + "latestJsonUrl": "https://github.com/egdev6/example/releases/download/v1.2.3/latest.json", + "version": "1.2.3", + "releasedAt": "2025-01-02T03:04:05Z", + "updaterPublicKey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDQ2RkFBNEZCQjUwNTQxMDAKUldRQVFRVzErNlQ2UnJmZTl1MVpMWk9sUE82Skx0ZFRDZHFoNDRjTWlwU0NNYkJ2UzhwT1Z4YWQK", + "detection": { + "windows": { + "displayName": "Example App", + "publisher": "Example", + "executableRelativePath": "example.exe" + } + } + }, + { + "id": "windows-only", + "name": "Windows Only", + "tagline": "Only on Windows", + "description": "A Windows-only entry.", + "tags": [], + "iconUrl": "https://example.com/w.png", + "integrationLevel": "update", + "featured": false, + "news": [], + "installerUrl": "https://github.com/egdev6/winonly/releases/download/v0.4.0/winonly_0.4.0_x64-setup.exe", + "latestJsonUrl": "https://github.com/egdev6/winonly/releases/download/v0.4.0/latest.json", + "version": "0.4.0", + "releasedAt": "2025-03-04T05:06:07Z" + } + ] + }, + "darwin-aarch64": { + "schemaVersion": 4, + "apps": [ + { + "id": "example-app", + "name": "Example App", + "tagline": "An example for testing", + "description": "A fictional catalog entry.", + "tags": [ + "Example", + "Desktop" + ], + "iconUrl": "https://example.com/icon.png", + "artUrl": "https://example.com/art.png", + "integrationLevel": "full", + "featured": true, + "links": { + "github": "https://github.com/example/example", + "youtube": "https://youtube.com/@example" + }, + "news": [ + { + "id": "release", + "title": "Example release", + "text": "A fictional release announcement.", + "publishedAt": "2025-01-02T03:04:05Z", + "kind": "new" + } + ], + "installerUrl": "https://github.com/egdev6/example/releases/download/v1.2.3/example_aarch64.dmg", + "latestJsonUrl": "https://github.com/egdev6/example/releases/download/v1.2.3/latest.json", + "version": "1.2.2", + "releasedAt": "2025-01-01T00:00:00Z", + "updaterPublicKey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDQ2RkFBNEZCQjUwNTQxMDAKUldRQVFRVzErNlQ2UnJmZTl1MVpMWk9sUE82Skx0ZFRDZHFoNDRjTWlwU0NNYkJ2UzhwT1Z4YWQK" + } + ] + }, + "linux-x86_64": { + "schemaVersion": 4, + "apps": [] + } + } +} diff --git a/crates/nexo-catalog/fixtures/v4.json b/crates/nexo-catalog/fixtures/v4.json new file mode 100644 index 0000000..5bd94ba --- /dev/null +++ b/crates/nexo-catalog/fixtures/v4.json @@ -0,0 +1,72 @@ +{ + "schemaVersion": 4, + "apps": [ + { + "id": "example-app", + "name": "Example App", + "tagline": "An example for testing", + "description": "A fictional catalog entry.", + "tags": [ + "Example", + "Desktop" + ], + "iconUrl": "https://example.com/icon.png", + "artUrl": "https://example.com/art.png", + "integrationLevel": "full", + "featured": true, + "links": { + "github": "https://github.com/example/example", + "youtube": "https://youtube.com/@example" + }, + "news": [ + { + "id": "release", + "title": "Example release", + "text": "A fictional release announcement.", + "publishedAt": "2025-01-02T03:04:05Z", + "kind": "new" + } + ], + "platforms": { + "windows-x86_64": { + "installerUrl": "https://github.com/egdev6/example/releases/download/v1.2.3/example_1.2.3_x64-setup.exe", + "latestJsonUrl": "https://github.com/egdev6/example/releases/download/v1.2.3/latest.json", + "version": "1.2.3", + "releasedAt": "2025-01-02T03:04:05Z", + "updaterPublicKey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDQ2RkFBNEZCQjUwNTQxMDAKUldRQVFRVzErNlQ2UnJmZTl1MVpMWk9sUE82Skx0ZFRDZHFoNDRjTWlwU0NNYkJ2UzhwT1Z4YWQK", + "detection": { + "displayName": "Example App", + "publisher": "Example", + "executableRelativePath": "example.exe" + } + }, + "darwin-aarch64": { + "installerUrl": "https://github.com/egdev6/example/releases/download/v1.2.3/example_aarch64.dmg", + "latestJsonUrl": "https://github.com/egdev6/example/releases/download/v1.2.3/latest.json", + "version": "1.2.2", + "releasedAt": "2025-01-01T00:00:00Z", + "updaterPublicKey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDQ2RkFBNEZCQjUwNTQxMDAKUldRQVFRVzErNlQ2UnJmZTl1MVpMWk9sUE82Skx0ZFRDZHFoNDRjTWlwU0NNYkJ2UzhwT1Z4YWQK" + } + } + }, + { + "id": "windows-only", + "name": "Windows Only", + "tagline": "Only on Windows", + "description": "A Windows-only entry.", + "tags": [], + "iconUrl": "https://example.com/w.png", + "integrationLevel": "update", + "featured": false, + "news": [], + "platforms": { + "windows-x86_64": { + "installerUrl": "https://github.com/egdev6/winonly/releases/download/v0.4.0/winonly_0.4.0_x64-setup.exe", + "latestJsonUrl": "https://github.com/egdev6/winonly/releases/download/v0.4.0/latest.json", + "version": "0.4.0", + "releasedAt": "2025-03-04T05:06:07Z" + } + } + } + ] +} diff --git a/odd/tasks/catalog-v4.md b/odd/tasks/catalog-v4.md new file mode 100644 index 0000000..da9139e --- /dev/null +++ b/odd/tasks/catalog-v4.md @@ -0,0 +1,36 @@ +# Catalog v4: apps, versions and news per operating system +> Objective: Nexo 0.2.0 (draft release, launch Monday 2026-11-23) reads a v4 catalog where each app declares per-platform installers, and shows only the apps, news and updates of the platform it runs on. Issue #83. Branches: feat/catalog-v4 in egdev6/nexo-catalog and egdev6/nexo. Runner: catalog validate.yml (jsonschema), Vitest, cargo test/clippy (Linux + native Windows). + +## Specs + +- S1: "Cada sistema operativo debería de coordnar sólo las nuevas versiones de su sistema operativo ligado al instalador de cada una no? en windows, windows. en macOS macOS. en linux linux. [...] cuando digo versiones, también me refiero a las apps del catálogo. Por ej: antena está sólo en windows, asi que en nexo MacOS no debería mostrarse." +- S2: "la 0.2.0 ya está publicada. Podríamos hacer esa implementación para la salida?" / "miento, tengo la 0.2.0 en borrador. Podríamos completarla con eso?" / "yo me arriesgaría tenemos 2 dias" — the v4 support ships in 0.2.0. +- S3 (design accepted from #83): v4 app = common fields (`id`, `name`, `tagline`, `description`, `tags`, `iconUrl`/`artUrl`, `integrationLevel`, `featured`, `links`, `news`) + `platforms`: an object with at least one entry, keyed by Tauri updater targets `^(windows|darwin|linux)-(x86_64|aarch64|i686|armv7)$` (e.g. `windows-x86_64`, `darwin-aarch64`, `darwin-x86_64`, `linux-x86_64`). Each platform entry: `installerUrl` and `latestJsonUrl` (egdev6 GitHub release assets, as v3), `version` (semver), `releasedAt` (timestamp), optional `updaterPublicKey`, and optional `detection` — `detection` uses the existing Windows hint shape (`displayName`, `publisher`, `executableRelativePath`) and is allowed only on `windows-*` keys. A keyed `windows-x86_64` entry must point to a per-user NSIS `_x64-setup.exe` (same rule as v3). +- S4: The hub resolves its own platform key at runtime (Rust: target OS + arch mapped to the same keys) and only shows apps with an entry for that key; their news, install, update and detection use that entry. Apps without an entry for the current platform are hidden everywhere (catalog, Mis apps catalog matching, Novedades, update checks). +- S5: The catalog keeps publishing `catalog.json`, `v2/` and `v3/` unchanged for installed Nexo 0.1.x; v4 lives at `v4/catalog.json` (`https://egdev6.github.io/nexo-catalog/v4/catalog.json`). Nexo 0.2.0 reads only v4. +- S6: Today every app is Windows-only: Antena and Quorb get a single `windows-x86_64` entry carrying their current v3 values. +- S7 (parent contract, decided 2026-11-21, shared by T2a and T2b): + - v4 is a wire format only. Both Rust (`crates/nexo-catalog`) and TypeScript (`apps/hub/src/catalog/format.ts`) validate a v4 document and then **project** it for one platform key into the existing flat catalog shape: `schemaVersion: 4`, apps without an entry for that key dropped, the entry's `installerUrl`, `latestJsonUrl`, `version`, `releasedAt`, `updaterPublicKey` copied to app level, and the entry's flat `detection` wrapped as `detection: { windows: ... }`. Every existing consumer keeps reading the flat shape; checks that today mean "v3 release-asset catalog" (`schemaVersion === 3` / `== 3`) now mean v4. + - v4 domain rules = schema v4 (copied from egdev6/nexo-catalog `catalog.schema.json`, PR #11) + existing domain checks applied per entry: release-asset URLs as v3, updater key decoding as v3, dates, semver, unique app and news ids, detection rules as v2/v3 hints. Platform key regex `^(windows|darwin|linux)-(x86_64|aarch64|i686|armv7)$`; `detection` only on `windows-*`. + - Shared corpus: `crates/nexo-catalog/fixtures/v4.json` + `fixtures/parity-v4.json` (cases with patches; `projections` = expected flat catalog per platform key). Both test suites must pass it unchanged; do not edit these two files. + - Runtime platform key: Rust helper mapping `std::env::consts::OS` (`windows`, `macos`→`darwin`, `linux`) and `ARCH` (`x86_64`, `aarch64`, `x86`→`i686`, `arm`→`armv7`) to the key; unsupported → no key, every app hidden. Exposed to the frontend by Tauri command `platform_key` → `string | null`. + - Endpoint `https://egdev6.github.io/nexo-catalog/v4/catalog.json` is the only one 0.2.0 fetches (Rust install feed and TS loader). Cache: one v4 cache file read by command `read_catalog_v4_cache` → `string | null` (raw v4 text); `write_catalog_cache` accepts only a valid v4 document. Commands `read_catalog_cache`, `read_catalog_v2_cache`, `read_catalog_v3_cache` and the v1/v2/v3 fallback chain are removed; old cache files are ignored. + - The flat (v1–v3) parser stays in the crate as the internal projected model and for existing fixtures; the hub never fetches or caches v1–v3. + +## Tasks + +| ID | Specs | Route | Status | Commit | +| --- | --- | --- | --- | --- | +| T1 | S3, S5, S6 | parent (nexo-catalog: schema v4, v4/catalog.json, validate.yml, README) | done: 4 files valid, 6 invalid cases rejected, darwin-only app accepted; rebased on Antena 0.18.0 (#10) and v4 resynced | nexo-catalog PR #11 | +| T2a | S3, S4, S5, S7 | worker: Rust (crates/nexo-catalog v4 + projection + schema copy, src-tauri platform key, install feed v4, v4 cache + commands, docs/catalog.md) | pending | | +| T2b | S3, S4, S5, S7 | worker: TypeScript (format.ts v4 + projection, loader v4 only, platform_key invoke, schemaVersion checks, i18n `install.v3Required`, tests) | pending | | +| T3 | S2 | parent: release notes, rebuild 0.2.0 (maintainer deletes draft and reruns Release) | pending | | +| T4 | all | verify | pending | | + +## Log + +- L1 (2026-11-21, user): S1 question → issue #83 created as proposal (roadmap v1.12). +- L2 (2026-11-21, user): S2. Parent recommended shipping 0.2.0 as is (self-update lets v4 arrive in 0.3.0); maintainer chose to include it: "yo me arriesgaría tenemos 2 dias". +- L4 (2026-11-21, user): "pr de T1" → nexo-catalog PR #11 opened after rebasing on #10 (Antena 0.18.0) and resyncing v4. +- L5 (2026-11-21, user): "si" → start T2. Parent fixed contract S7 and wrote the shared v4 corpus; the corpus exposed a schema bug in PR #11 (darwin/linux entries matched patternProperties and skipped platformEntry), fixed in nexo-catalog 9ee8a98. +- L3 (state): 0.2.0 is a draft (built from 3e17ef8, signed, valid signature with key B9313A349CF8A2BD). Releases "latest" is still v0.1.4 because drafts cannot be latest. From 4e62aac24a6817f5e76807294a717c22722b11b8 Mon Sep 17 00:00:00 2001 From: egdev6 Date: Sat, 21 Nov 2026 15:58:24 +0100 Subject: [PATCH 2/9] feat(catalog): validate catalog v4 and project it for one platform --- crates/nexo-catalog/catalog.schema.json | 39 +++- crates/nexo-catalog/src/lib.rs | 258 +++++++++++++++++++----- crates/nexo-catalog/tests/parity_v4.rs | 89 ++++++++ 3 files changed, 328 insertions(+), 58 deletions(-) create mode 100644 crates/nexo-catalog/tests/parity_v4.rs diff --git a/crates/nexo-catalog/catalog.schema.json b/crates/nexo-catalog/catalog.schema.json index ad25ec4..e76cc0d 100644 --- a/crates/nexo-catalog/catalog.schema.json +++ b/crates/nexo-catalog/catalog.schema.json @@ -1,19 +1,20 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://example.com/nexo/catalog-v1-v2-v3.schema.json", - "title": "Nexo official catalog, versions 1, 2 and 3", + "$id": "https://example.com/nexo/catalog-v1-v4.schema.json", + "title": "Nexo official catalog, versions 1 to 4", "description": "Shape validation must be followed by domain validation (including uniqueness by id). The $id is illustrative, not a publication URL.", "type": "object", "required": ["schemaVersion", "apps"], "additionalProperties": false, "properties": { - "schemaVersion": { "enum": [1, 2, 3] }, + "schemaVersion": { "enum": [1, 2, 3, 4] }, "apps": { "type": "array" } }, "oneOf": [ { "properties": { "schemaVersion": { "const": 1 }, "apps": { "items": { "$ref": "#/$defs/appV1" } } } }, { "properties": { "schemaVersion": { "const": 2 }, "apps": { "items": { "$ref": "#/$defs/appV2" } } } }, - { "properties": { "schemaVersion": { "const": 3 }, "apps": { "items": { "$ref": "#/$defs/appV3" } } } } + { "properties": { "schemaVersion": { "const": 3 }, "apps": { "items": { "$ref": "#/$defs/appV3" } } } }, + { "properties": { "schemaVersion": { "const": 4 }, "apps": { "items": { "$ref": "#/$defs/appV4" } } } } ], "$defs": { "id": { "type": "string", "pattern": "^[a-z0-9-]+$", "not": { "pattern": "[^a-z0-9-]" } }, @@ -59,6 +60,36 @@ "allOf": [{ "$ref": "#/$defs/app" }], "unevaluatedProperties": false, "properties": { "detection": { "$ref": "#/$defs/detection" } } }, + "platformEntry": { + "type": "object", "additionalProperties": false, + "required": ["installerUrl", "latestJsonUrl", "version", "releasedAt"], + "properties": { + "installerUrl": { "$ref": "#/$defs/releaseAsset" }, "latestJsonUrl": { "$ref": "#/$defs/releaseAsset" }, + "version": { "$ref": "#/$defs/semver" }, "releasedAt": { "$ref": "#/$defs/timestamp" }, + "updaterPublicKey": { "$ref": "#/$defs/updaterPublicKey" }, + "detection": { "$ref": "#/$defs/windowsDetection" } + } + }, + "appV4": { + "type": "object", "additionalProperties": false, + "required": ["id", "name", "tagline", "description", "tags", "integrationLevel", "featured", "news", "platforms"], + "anyOf": [{ "required": ["iconUrl"] }, { "required": ["artUrl"] }], + "properties": { + "id": { "$ref": "#/$defs/id" }, "name": { "$ref": "#/$defs/text" }, "tagline": { "$ref": "#/$defs/text" }, + "description": { "$ref": "#/$defs/text" }, "tags": { "type": "array", "items": { "$ref": "#/$defs/text" } }, + "iconUrl": { "$ref": "#/$defs/https" }, "artUrl": { "$ref": "#/$defs/https" }, + "integrationLevel": { "enum": ["full", "update", "launch"] }, "featured": { "type": "boolean" }, + "links": { "$ref": "#/$defs/links" }, "news": { "type": "array", "items": { "$ref": "#/$defs/news" } }, + "platforms": { + "type": "object", "minProperties": 1, + "propertyNames": { "pattern": "^(windows|darwin|linux)-(x86_64|aarch64|i686|armv7)$" }, + "additionalProperties": { "$ref": "#/$defs/platformEntry" }, + "patternProperties": { + "^(darwin|linux)-": { "allOf": [{ "$ref": "#/$defs/platformEntry" }, { "not": { "required": ["detection"] } }] } + } + } + } + }, "appV3": { "allOf": [{ "$ref": "#/$defs/app" }], "unevaluatedProperties": false, "properties": { diff --git a/crates/nexo-catalog/src/lib.rs b/crates/nexo-catalog/src/lib.rs index 713d5f6..380ddf7 100644 --- a/crates/nexo-catalog/src/lib.rs +++ b/crates/nexo-catalog/src/lib.rs @@ -1,11 +1,13 @@ -//! Versions 1, 2 and 3 of the public, maintainer-curated catalog. -//! Parse untrusted input with [`parse_catalog`] rather than deserializing it directly. +//! Public, maintainer-curated catalog formats. +//! +//! Validate v4 wire documents with [`parse_catalog_v4`], then project them with +//! [`project_catalog_v4`]. [`parse_catalog`] retains the flat v1–v3 formats. use base64::{Engine, engine::general_purpose::STANDARD}; use chrono::DateTime; use semver::Version; use serde::{Deserialize, Deserializer, Serialize}; -use std::collections::HashSet; +use std::collections::{BTreeMap, HashSet}; use thiserror::Error; use url::Url; @@ -68,6 +70,91 @@ pub struct CatalogApp { pub news: Vec, } +/// The v4 wire document, before selecting a platform. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct CatalogV4 { + pub schema_version: u64, + pub apps: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct CatalogAppV4 { + pub id: String, + pub name: String, + pub tagline: String, + pub description: String, + pub tags: Vec, + #[serde( + default, + deserialize_with = "optional_non_null", + skip_serializing_if = "Option::is_none" + )] + pub icon_url: Option, + #[serde( + default, + deserialize_with = "optional_non_null", + skip_serializing_if = "Option::is_none" + )] + pub art_url: Option, + pub integration_level: IntegrationLevel, + pub featured: bool, + #[serde( + default, + deserialize_with = "optional_non_null", + skip_serializing_if = "Option::is_none" + )] + pub links: Option, + pub news: Vec, + pub platforms: BTreeMap, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct PlatformEntry { + pub installer_url: String, + pub latest_json_url: String, + pub version: String, + pub released_at: String, + #[serde( + default, + deserialize_with = "optional_non_null", + skip_serializing_if = "Option::is_none" + )] + pub updater_public_key: Option, + #[serde( + default, + deserialize_with = "optional_non_null", + skip_serializing_if = "Option::is_none" + )] + pub detection: Option, +} + +impl CatalogAppV4 { + fn project(&self, entry: &PlatformEntry) -> CatalogApp { + CatalogApp { + id: self.id.clone(), + name: self.name.clone(), + tagline: self.tagline.clone(), + description: self.description.clone(), + tags: self.tags.clone(), + icon_url: self.icon_url.clone(), + art_url: self.art_url.clone(), + installer_url: entry.installer_url.clone(), + latest_json_url: entry.latest_json_url.clone(), + updater_public_key: entry.updater_public_key.clone(), + integration_level: self.integration_level, + released_at: entry.released_at.clone(), + featured: self.featured, + version: Some(entry.version.clone()), + links: self.links.clone(), + detection: entry.detection.clone().map(|windows| Detection { windows }), + news: self.news.clone(), + } + } +} + #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct Detection { @@ -389,68 +476,131 @@ pub fn parse_catalog(input: &str) -> Result { } let mut app_ids = HashSet::new(); for app in &catalog.apps { - if catalog.schema_version == 3 { - check_release_asset_url(&app.installer_url)?; - check_release_asset_url(&app.latest_json_url)?; - if let Some(key) = &app.updater_public_key { - check_updater_key(key)?; - } + validate_app(app, catalog.schema_version, Some(&mut app_ids))?; + } + Ok(catalog) +} + +fn validate_app<'a>( + app: &'a CatalogApp, + schema_version: u64, + app_ids: Option<&mut HashSet<&'a String>>, +) -> Result<(), CatalogError> { + if schema_version >= 3 { + check_release_asset_url(&app.installer_url)?; + check_release_asset_url(&app.latest_json_url)?; + if let Some(key) = &app.updater_public_key { + check_updater_key(key)?; } - if let Some(detection) = &app.detection { - check_text(&detection.windows.display_name)?; - check_text(&detection.windows.publisher)?; - check_executable_path(&detection.windows.executable_relative_path)?; + } + if let Some(detection) = &app.detection { + check_text(&detection.windows.display_name)?; + check_text(&detection.windows.publisher)?; + check_executable_path(&detection.windows.executable_relative_path)?; + } + if !valid_id(&app.id) { + return Err(CatalogError::BadId); + } + if let Some(ids) = app_ids + && !ids.insert(&app.id) + { + return Err(CatalogError::DuplicateId); + } + for text in [&app.name, &app.tagline, &app.description] + .into_iter() + .chain(app.tags.iter()) + { + check_text(text)?; + } + if app.icon_url.is_none() && app.art_url.is_none() { + return Err(CatalogError::MissingArtwork); + } + for url in [ + app.icon_url.as_deref(), + app.art_url.as_deref(), + Some(&app.installer_url), + Some(&app.latest_json_url), + ] + .into_iter() + .flatten() + { + check_url(url)?; + } + if let Some(links) = &app.links { + for url in [links.github.as_deref(), links.youtube.as_deref()] + .into_iter() + .flatten() + { + check_url(url)?; } - if !valid_id(&app.id) { + } + if let Some(version) = &app.version { + Version::parse(version).map_err(|_| CatalogError::BadVersion)?; + } + check_date(&app.released_at)?; + let mut news_ids = HashSet::new(); + for item in &app.news { + if !valid_id(&item.id) { return Err(CatalogError::BadId); } - if !app_ids.insert(&app.id) { - return Err(CatalogError::DuplicateId); + if !news_ids.insert(&item.id) { + return Err(CatalogError::DuplicateNewsId); } - for text in [&app.name, &app.tagline, &app.description] - .into_iter() - .chain(app.tags.iter()) - { - check_text(text)?; + check_text(&item.title)?; + check_text(&item.text)?; + check_date(&item.published_at)?; + } + Ok(()) +} + +/// Decode and validate every platform entry of a v4 wire document. +pub fn parse_catalog_v4(input: &str) -> Result { + let mut value: serde_json::Value = + serde_json::from_str(input).map_err(|_| CatalogError::Document)?; + if let Some(version) = value.get_mut("schemaVersion") + && version.is_number() + { + if version.as_f64() != Some(4.0) { + return Err(CatalogError::SchemaVersion); } - if app.icon_url.is_none() && app.art_url.is_none() { - return Err(CatalogError::MissingArtwork); + *version = serde_json::Value::from(4); + } + let catalog: CatalogV4 = serde_json::from_value(value).map_err(|_| CatalogError::Document)?; + if catalog.schema_version != 4 { + return Err(CatalogError::SchemaVersion); + } + let mut app_ids = HashSet::new(); + for app in &catalog.apps { + if app.platforms.is_empty() { + return Err(CatalogError::Document); } - for url in [ - app.icon_url.as_deref(), - app.art_url.as_deref(), - Some(&app.installer_url), - Some(&app.latest_json_url), - ] - .into_iter() - .flatten() - { - check_url(url)?; + if !app_ids.insert(&app.id) { + return Err(CatalogError::DuplicateId); } - if let Some(links) = &app.links { - for url in [links.github.as_deref(), links.youtube.as_deref()] - .into_iter() - .flatten() + for (key, entry) in &app.platforms { + let Some((os, arch)) = key.split_once('-') else { + return Err(CatalogError::Document); + }; + if !matches!(os, "windows" | "darwin" | "linux") + || !matches!(arch, "x86_64" | "aarch64" | "i686" | "armv7") + || (os != "windows" && entry.detection.is_some()) { - check_url(url)?; + return Err(CatalogError::Document); } - } - if let Some(version) = &app.version { - Version::parse(version).map_err(|_| CatalogError::BadVersion)?; - } - check_date(&app.released_at)?; - let mut news_ids = HashSet::new(); - for item in &app.news { - if !valid_id(&item.id) { - return Err(CatalogError::BadId); - } - if !news_ids.insert(&item.id) { - return Err(CatalogError::DuplicateNewsId); - } - check_text(&item.title)?; - check_text(&item.text)?; - check_date(&item.published_at)?; + validate_app(&app.project(entry), 4, None)?; } } Ok(catalog) } + +/// Project a validated v4 document into the existing flat model for one platform. +pub fn project_catalog_v4(catalog: &CatalogV4, platform: &str) -> Catalog { + Catalog { + schema_version: 4, + apps: catalog + .apps + .iter() + .filter_map(|app| app.platforms.get(platform).map(|entry| app.project(entry))) + .collect(), + } +} diff --git a/crates/nexo-catalog/tests/parity_v4.rs b/crates/nexo-catalog/tests/parity_v4.rs new file mode 100644 index 0000000..74a7822 --- /dev/null +++ b/crates/nexo-catalog/tests/parity_v4.rs @@ -0,0 +1,89 @@ +use nexo_catalog::{parse_catalog_v4, project_catalog_v4}; +use serde_json::{Value, json}; + +fn patched_document(case: &Value) -> Value { + let mut document: Value = serde_json::from_str(include_str!("../fixtures/v4.json")).unwrap(); + for patch in case["patches"].as_array().into_iter().flatten() { + let path = patch["path"].as_str().unwrap(); + match patch["op"].as_str().unwrap() { + "set" => *document.pointer_mut(path).unwrap() = patch["value"].clone(), + "remove" | "add" => { + let (parent, key) = path.rsplit_once('/').unwrap(); + let object = document + .pointer_mut(parent) + .unwrap() + .as_object_mut() + .unwrap(); + if patch["op"] == "remove" { + object.remove(key).unwrap(); + } else { + object.insert(key.to_owned(), patch["value"].clone()); + } + } + "duplicate" => { + let items = document.pointer_mut(path).unwrap().as_array_mut().unwrap(); + items.push(items[0].clone()); + } + _ => panic!("unknown patch"), + } + } + document +} + +#[test] +fn shared_v4_corpus_pins_validation_and_platform_projections() { + let corpus: Value = serde_json::from_str(include_str!("../fixtures/parity-v4.json")).unwrap(); + for case in corpus["cases"].as_array().unwrap() { + let parsed = parse_catalog_v4(&patched_document(case).to_string()); + assert_eq!( + parsed.is_ok(), + case["valid"].as_bool().unwrap(), + "{}", + case["name"] + ); + } + let catalog = parse_catalog_v4(include_str!("../fixtures/v4.json")).unwrap(); + for (platform, expected) in corpus["projections"].as_object().unwrap() { + assert_eq!( + serde_json::to_value(project_catalog_v4(&catalog, platform)).unwrap(), + *expected, + "{platform}" + ); + } + assert!(project_catalog_v4(&catalog, "unsupported").apps.is_empty()); +} + +#[test] +fn v4_requires_valid_data_on_every_platform_even_when_not_projected() { + let mut document: Value = serde_json::from_str(include_str!("../fixtures/v4.json")).unwrap(); + document["apps"][0]["platforms"]["darwin-aarch64"]["version"] = json!("invalid"); + assert!(parse_catalog_v4(&document.to_string()).is_err()); +} + +#[test] +fn v4_rejects_null_optional_fields_and_duplicate_news_but_accepts_integral_version_number() { + let mut document: Value = serde_json::from_str(include_str!("../fixtures/v4.json")).unwrap(); + document["schemaVersion"] = json!(4.0); + assert!(parse_catalog_v4(&document.to_string()).is_ok()); + document["apps"][0]["platforms"]["darwin-aarch64"]["updaterPublicKey"] = Value::Null; + assert!(parse_catalog_v4(&document.to_string()).is_err()); + document["apps"][0]["platforms"]["darwin-aarch64"] + .as_object_mut() + .unwrap() + .remove("updaterPublicKey"); + let news = document["apps"][0]["news"][0].clone(); + document["apps"][0]["news"] + .as_array_mut() + .unwrap() + .push(news); + assert!(parse_catalog_v4(&document.to_string()).is_err()); +} + +#[test] +fn leaves_the_nsis_installer_rule_to_native_selection() { + let mut document: serde_json::Value = + serde_json::from_str(include_str!("../fixtures/v4.json")).unwrap(); + document["apps"][0]["platforms"]["windows-x86_64"]["installerUrl"] = + serde_json::json!("https://github.com/egdev6/example/releases/download/v1.2.3/example.msi"); + assert!(nexo_catalog::parse_catalog_v4(&document.to_string()).is_ok()); +} From de007af085decfdab373273e8ed17a966fd64959 Mon Sep 17 00:00:00 2001 From: egdev6 Date: Sat, 21 Nov 2026 15:58:24 +0100 Subject: [PATCH 3/9] feat(hub): read only catalog v4 natively and expose the platform key --- apps/hub/src-tauri/src/apps.rs | 53 +++++-- apps/hub/src-tauri/src/catalog_cache.rs | 105 ++++--------- apps/hub/src-tauri/src/install_feed.rs | 31 ++-- apps/hub/src-tauri/src/install_feed_tests.rs | 140 +++++++++++++----- .../src-tauri/src/install_service_tests.rs | 43 +++--- apps/hub/src-tauri/src/lib.rs | 11 +- apps/hub/src-tauri/src/platform.rs | 60 ++++++++ .../hub/src-tauri/src/update_service_tests.rs | 28 +--- apps/hub/src-tauri/src/vp_install_tests.rs | 33 ++--- 9 files changed, 314 insertions(+), 190 deletions(-) create mode 100644 apps/hub/src-tauri/src/platform.rs diff --git a/apps/hub/src-tauri/src/apps.rs b/apps/hub/src-tauri/src/apps.rs index 51141ee..ae270c4 100644 --- a/apps/hub/src-tauri/src/apps.rs +++ b/apps/hub/src-tauri/src/apps.rs @@ -66,15 +66,14 @@ pub(crate) fn activate_connected_menu_item( #[cfg(windows)] fn official_catalog(app: tauri::AppHandle) -> Result { - let text = match crate::catalog_cache::read_catalog_v3_cache(app.clone())? { - Some(text) => text, - None => match crate::catalog_cache::read_catalog_v2_cache(app.clone())? { - Some(text) => text, - None => crate::catalog_cache::read_catalog_cache(app)? - .ok_or_else(|| "nexo.appNoCatalog".to_string())?, - }, - }; - nexo_catalog::parse_catalog(&text).map_err(|error| error.to_string()) + let text = crate::catalog_cache::read_catalog_v4_cache(app)? + .ok_or_else(|| "nexo.appNoCatalog".to_string())?; + let document = nexo_catalog::parse_catalog_v4(&text).map_err(|error| error.to_string())?; + let platform = crate::platform::platform_key(); + Ok(nexo_catalog::project_catalog_v4( + &document, + platform.as_deref().unwrap_or(""), + )) } #[cfg(windows)] @@ -1069,6 +1068,42 @@ mod tests { assert!(launcher.launched.borrow().is_empty()); } + #[test] + fn apps_without_a_platform_entry_cannot_be_matched_opened_or_detected() { + let document = nexo_catalog::parse_catalog_v4(include_str!( + "../../../../crates/nexo-catalog/fixtures/v4.json" + )) + .unwrap(); + let darwin = nexo_catalog::project_catalog_v4(&document, "darwin-aarch64"); + let windows = nexo_catalog::project_catalog_v4(&document, "windows-x86_64"); + let hidden = windows + .apps + .iter() + .find(|app| app.id == "windows-only") + .unwrap(); + let registry = fake(Ok(vec![entry("physical-a")])); + let launcher = FakeLauncher::default(); + assert!( + observe(&darwin, ®istry) + .iter() + .all(|item| item.id != hidden.id) + ); + assert!( + official_duplicates(&darwin, ®istry, &launcher) + .iter() + .all(|item| item.id != hidden.id) + ); + assert_eq!( + open_official(&darwin, ®istry, &launcher, &hidden.id), + Err("nexo.appNotOfficial".into()) + ); + assert_eq!( + install_detection(&darwin, hidden, ®istry), + crate::install_service::Detection::Unknown + ); + assert!(launcher.launched.borrow().is_empty()); + } + #[test] fn official_open_still_refuses_a_local_executable_path_as_an_id() { let registry = fake(Ok(vec![entry("physical-a")])); diff --git a/apps/hub/src-tauri/src/catalog_cache.rs b/apps/hub/src-tauri/src/catalog_cache.rs index bece50c..11108f4 100644 --- a/apps/hub/src-tauri/src/catalog_cache.rs +++ b/apps/hub/src-tauri/src/catalog_cache.rs @@ -4,24 +4,11 @@ use std::sync::atomic::{AtomicU64, Ordering}; use tauri::{AppHandle, Manager}; static NEXT_TEMP: AtomicU64 = AtomicU64::new(0); +const CACHE_NAME: &str = "catalog-v4.json"; -fn cache_name(version: u64) -> Result<&'static str, String> { - match version { - 1 => Ok("catalog.json"), - 2 => Ok("catalog-v2.json"), - 3 => Ok("catalog-v3.json"), - _ => Err("Unsupported catalog cache version".into()), - } -} - -fn read_version(directory: &Path, version: u64) -> Result, String> { - match std::fs::read_to_string(directory.join(cache_name(version)?)) { - Ok(text) - if nexo_catalog::parse_catalog(&text) - .is_ok_and(|catalog| catalog.schema_version == version) => - { - Ok(Some(text)) - } +fn read_cache(directory: &Path) -> Result, String> { + match std::fs::read_to_string(directory.join(CACHE_NAME)) { + Ok(text) if nexo_catalog::parse_catalog_v4(&text).is_ok() => Ok(Some(text)), Ok(_) => Ok(None), Err(error) if matches!(error.kind(), ErrorKind::NotFound | ErrorKind::InvalidData) => { Ok(None) @@ -30,15 +17,8 @@ fn read_version(directory: &Path, version: u64) -> Result, String } } -fn read_cache(directory: &Path) -> Result, String> { - read_version(directory, 1) -} - fn write_cache(directory: &Path, input: &str) -> Result<(), String> { - let version = nexo_catalog::parse_catalog(input) - .map_err(|error| error.to_string())? - .schema_version; - let target = cache_name(version)?; + nexo_catalog::parse_catalog_v4(input).map_err(|error| error.to_string())?; std::fs::create_dir_all(directory).map_err(|error| error.to_string())?; let name = format!( ".catalog-{}-{}.tmp", @@ -56,7 +36,7 @@ fn write_cache(directory: &Path, input: &str) -> Result<(), String> { file.write_all(input.as_bytes())?; file.sync_all()?; drop(file); - std::fs::rename(&temporary, directory.join(target)) + std::fs::rename(&temporary, directory.join(CACHE_NAME)) })(); if result.is_err() && created { let _ = std::fs::remove_file(&temporary); @@ -65,7 +45,7 @@ fn write_cache(directory: &Path, input: &str) -> Result<(), String> { } #[tauri::command] -pub(crate) fn read_catalog_cache(app: AppHandle) -> Result, String> { +pub(crate) fn read_catalog_v4_cache(app: AppHandle) -> Result, String> { let directory = app .path() .app_data_dir() @@ -73,24 +53,6 @@ pub(crate) fn read_catalog_cache(app: AppHandle) -> Result, Strin read_cache(&directory) } -#[tauri::command] -pub(crate) fn read_catalog_v2_cache(app: AppHandle) -> Result, String> { - let directory = app - .path() - .app_data_dir() - .map_err(|error| error.to_string())?; - read_version(&directory, 2) -} - -#[tauri::command] -pub(crate) fn read_catalog_v3_cache(app: AppHandle) -> Result, String> { - let directory = app - .path() - .app_data_dir() - .map_err(|error| error.to_string())?; - read_version(&directory, 3) -} - #[tauri::command] pub(crate) fn write_catalog_cache(app: AppHandle, input: String) -> Result<(), String> { let directory = app @@ -106,8 +68,8 @@ mod tests { use std::sync::atomic::{AtomicU64, Ordering}; static NEXT: AtomicU64 = AtomicU64::new(0); - const VALID: &str = include_str!("../../../../crates/nexo-catalog/fixtures/full.json"); - const EMPTY: &str = "{\"schemaVersion\":1,\"apps\":[]}"; + const VALID: &str = include_str!("../../../../crates/nexo-catalog/fixtures/v4.json"); + const EMPTY: &str = "{\"schemaVersion\":4,\"apps\":[]}"; struct Scratch(std::path::PathBuf); impl Scratch { @@ -138,45 +100,34 @@ mod tests { } #[test] - fn rejected_document_never_replaces_valid_cache() { + fn v4_cache_rejects_v3_and_invalid_documents_without_replacing_valid_data() { let dir = Scratch::new(); write_cache(&dir.0, VALID).unwrap(); - for invalid in ["{", "{\"schemaVersion\":4,\"apps\":[]}"] { + assert_eq!(read_cache(&dir.0).unwrap().as_deref(), Some(VALID)); + for invalid in [ + "{", + "{\"schemaVersion\":1,\"apps\":[]}", + "{\"schemaVersion\":2,\"apps\":[]}", + "{\"schemaVersion\":3,\"apps\":[]}", + "{\"schemaVersion\":4,\"apps\":[{}]}", + ] { assert!(write_cache(&dir.0, invalid).is_err()); assert_eq!(read_cache(&dir.0).unwrap().as_deref(), Some(VALID)); + assert_eq!( + std::fs::read_to_string(dir.0.join(CACHE_NAME)).unwrap(), + VALID + ); } } #[test] - fn v2_write_does_not_replace_the_v1_cache() { - let dir = Scratch::new(); - write_cache(&dir.0, VALID).unwrap(); - let v2 = "{\"schemaVersion\":2,\"apps\":[]}"; - write_cache(&dir.0, v2).unwrap(); - assert_eq!(read_cache(&dir.0).unwrap().as_deref(), Some(VALID)); - assert_eq!(read_version(&dir.0, 2).unwrap().as_deref(), Some(v2)); - assert!(write_cache(&dir.0, "{\"schemaVersion\":4,\"apps\":[]}").is_err()); - assert_eq!(read_version(&dir.0, 2).unwrap().as_deref(), Some(v2)); - } - - #[test] - fn v3_cache_is_separate_and_invalid_writes_preserve_all_versions() { + fn old_cache_files_are_ignored_and_corrupt_v4_recovers() { let dir = Scratch::new(); - let v2 = "{\"schemaVersion\":2,\"apps\":[]}"; - let v3 = "{\"schemaVersion\":3,\"apps\":[]}"; - write_cache(&dir.0, VALID).unwrap(); - write_cache(&dir.0, v2).unwrap(); - write_cache(&dir.0, v3).unwrap(); - assert!(write_cache(&dir.0, "{\"schemaVersion\":3,\"apps\":[{}]}").is_err()); - assert_eq!(read_cache(&dir.0).unwrap().as_deref(), Some(VALID)); - assert_eq!(read_version(&dir.0, 2).unwrap().as_deref(), Some(v2)); - assert_eq!(read_version(&dir.0, 3).unwrap().as_deref(), Some(v3)); - } - - #[test] - fn corrupt_cache_is_ignored_and_a_later_valid_write_recovers() { - let dir = Scratch::new(); - std::fs::write(dir.0.join("catalog.json"), "{broken").unwrap(); + for name in ["catalog.json", "catalog-v2.json", "catalog-v3.json"] { + std::fs::write(dir.0.join(name), "{\"schemaVersion\":3,\"apps\":[]}").unwrap(); + } + assert_eq!(read_cache(&dir.0).unwrap(), None); + std::fs::write(dir.0.join(CACHE_NAME), "{broken").unwrap(); assert_eq!(read_cache(&dir.0).unwrap(), None); write_cache(&dir.0, EMPTY).unwrap(); assert_eq!(read_cache(&dir.0).unwrap().as_deref(), Some(EMPTY)); diff --git a/apps/hub/src-tauri/src/install_feed.rs b/apps/hub/src-tauri/src/install_feed.rs index b9b105b..0e3b5f5 100644 --- a/apps/hub/src-tauri/src/install_feed.rs +++ b/apps/hub/src-tauri/src/install_feed.rs @@ -1,4 +1,4 @@ -//! Native v3 catalog source for installation authorization. +//! Native v4 catalog source for installation authorization. //! //! This is not an authorization by itself. A transaction must obtain a new catalog at //! the action boundary and another immediately before spawning, then revalidate its @@ -8,7 +8,7 @@ use crate::install_download::{Body, Network, ResponseKind}; use nexo_catalog::{Catalog, CatalogApp}; use std::time::Duration; -pub const OFFICIAL_V3_FEED: &str = "https://egdev6.github.io/nexo-catalog/v3/catalog.json"; +pub const OFFICIAL_V4_FEED: &str = "https://egdev6.github.io/nexo-catalog/v4/catalog.json"; pub const FEED_LIMIT: u64 = 2 * 1024 * 1024; pub const FEED_TIMEOUT: Duration = Duration::from_secs(8); @@ -57,7 +57,7 @@ impl FreshCatalog { &self.catalog } - /// Select by official ID only. Validated v3 entries without keys remain display-only. + /// Select by official ID only. Validated v4 entries without keys remain display-only. pub fn select(&self, id: &str) -> Result { let app = self .catalog @@ -104,11 +104,23 @@ pub trait CatalogFeed: Sync { pub struct NativeFeed { network: N, + platform: Option, } impl NativeFeed { pub fn new(network: N) -> Self { - Self { network } + Self { + network, + platform: crate::platform::platform_key(), + } + } + + #[cfg(test)] + pub(crate) fn for_platform(network: N, platform: Option<&str>) -> Self { + Self { + network, + platform: platform.map(str::to_owned), + } } } @@ -117,10 +129,10 @@ impl CatalogFeed for NativeFeed { let fetch = async { let response = self .network - .get(OFFICIAL_V3_FEED) + .get(OFFICIAL_V4_FEED) .await .map_err(|_| FeedError::Network)?; - if response.effective_url != OFFICIAL_V3_FEED { + if response.effective_url != OFFICIAL_V4_FEED { return Err(FeedError::InvalidResponse); } let ResponseKind::Ok { length, mut body } = response.kind else { @@ -149,11 +161,10 @@ impl CatalogFeed for NativeFeed { return Err(FeedError::LengthMismatch); } let text = std::str::from_utf8(&bytes).map_err(|_| FeedError::InvalidCatalog)?; + let document = + nexo_catalog::parse_catalog_v4(text).map_err(|_| FeedError::InvalidCatalog)?; let catalog = - nexo_catalog::parse_catalog(text).map_err(|_| FeedError::InvalidCatalog)?; - if catalog.schema_version != 3 { - return Err(FeedError::InvalidCatalog); - } + nexo_catalog::project_catalog_v4(&document, self.platform.as_deref().unwrap_or("")); Ok(FreshCatalog { catalog }) }; tokio::time::timeout(FEED_TIMEOUT, fetch) diff --git a/apps/hub/src-tauri/src/install_feed_tests.rs b/apps/hub/src-tauri/src/install_feed_tests.rs index 065af99..5834e46 100644 --- a/apps/hub/src-tauri/src/install_feed_tests.rs +++ b/apps/hub/src-tauri/src/install_feed_tests.rs @@ -10,7 +10,7 @@ const OTHER_URL: &str = const KEY: &str = include_str!("../tests/fixtures/tauri-test.pub"); const OTHER_KEY: &str = include_str!("../tests/fixtures/minisign-test.pub"); -fn catalog_value() -> Value { +fn legacy_catalog_value() -> Value { let mut value: Value = serde_json::from_str(include_str!( "../../../../crates/nexo-catalog/fixtures/minimal.json" )) @@ -27,12 +27,39 @@ fn catalog_value() -> Value { value } +fn catalog_value() -> Value { + let mut value = legacy_catalog_value(); + value["schemaVersion"] = json!(4); + let app = value["apps"][0].as_object_mut().unwrap(); + let mut entry = serde_json::Map::new(); + for field in [ + "installerUrl", + "latestJsonUrl", + "version", + "releasedAt", + "updaterPublicKey", + ] { + entry.insert(field.into(), app.remove(field).unwrap()); + } + entry.insert( + "detection".into(), + app.remove("detection").unwrap()["windows"].clone(), + ); + app.insert("platforms".into(), json!({"windows-x86_64": entry})); + value +} + fn fresh(value: &Value) -> FreshCatalog { + let document = nexo_catalog::parse_catalog_v4(&value.to_string()).unwrap(); FreshCatalog { - catalog: nexo_catalog::parse_catalog(&value.to_string()).unwrap(), + catalog: nexo_catalog::project_catalog_v4(&document, "windows-x86_64"), } } +fn test_feed(network: FakeNetwork) -> NativeFeed { + NativeFeed::for_platform(network, Some("windows-x86_64")) +} + enum Reply { Ok { length: Option, @@ -127,9 +154,9 @@ impl Network for FakeNetwork { } #[tokio::test] -async fn fetches_and_validates_only_the_fixed_native_v3_source() { +async fn fetches_and_validates_only_the_fixed_native_v4_source() { let text = catalog_value().to_string(); - let feed = NativeFeed::new(FakeNetwork::new(vec![body(text.as_bytes())])); + let feed = test_feed(FakeNetwork::new(vec![body(text.as_bytes())])); let catalog = feed.fetch().await.unwrap(); let selected = catalog.select("minimal").unwrap(); assert_eq!(selected.app().installer_url, URL); @@ -137,13 +164,13 @@ async fn fetches_and_validates_only_the_fixed_native_v3_source() { selected.app().updater_public_key.as_deref(), Some(STANDARD.encode(KEY).as_str()) ); - assert_eq!(feed.network.requests(), [OFFICIAL_V3_FEED]); + assert_eq!(feed.network.requests(), [OFFICIAL_V4_FEED]); } #[tokio::test] async fn each_fetch_is_fresh_and_failure_never_falls_back_to_previous_data() { let text = catalog_value().to_string(); - let feed = NativeFeed::new(FakeNetwork::new(vec![ + let feed = test_feed(FakeNetwork::new(vec![ body(text.as_bytes()), Reply::Network, ])); @@ -160,16 +187,16 @@ async fn each_fetch_is_fresh_and_failure_never_falls_back_to_previous_data() { assert_eq!(feed.fetch().await.unwrap_err(), FeedError::Network); assert_eq!( feed.network.requests(), - [OFFICIAL_V3_FEED, OFFICIAL_V3_FEED] + [OFFICIAL_V4_FEED, OFFICIAL_V4_FEED] ); } #[tokio::test] async fn rejects_redirects_changed_effective_urls_and_failed_responses() { for reply in [Reply::Redirect, Reply::WrongUrl, Reply::Failed] { - let feed = NativeFeed::new(FakeNetwork::new(vec![reply])); + let feed = test_feed(FakeNetwork::new(vec![reply])); assert_eq!(feed.fetch().await.unwrap_err(), FeedError::InvalidResponse); - assert_eq!(feed.network.requests(), [OFFICIAL_V3_FEED]); + assert_eq!(feed.network.requests(), [OFFICIAL_V4_FEED]); } } @@ -177,32 +204,75 @@ async fn rejects_redirects_changed_effective_urls_and_failed_responses() { async fn rejects_old_malformed_or_policy_invalid_catalogs() { let valid = catalog_value(); let mut documents = vec![b"{".to_vec(), vec![0xff]]; - for version in [1, 2] { - let mut old = valid.clone(); - old["schemaVersion"] = json!(version); - old["apps"][0] - .as_object_mut() - .unwrap() - .remove("updaterPublicKey"); - if version == 1 { - old["apps"][0].as_object_mut().unwrap().remove("detection"); - } - documents.push(old.to_string().into_bytes()); + for version in [1, 2, 3] { + documents.push( + json!({"schemaVersion": version, "apps": []}) + .to_string() + .into_bytes(), + ); } let mut invalid_url = valid.clone(); - invalid_url["apps"][0]["installerUrl"] = + invalid_url["apps"][0]["platforms"]["windows-x86_64"]["installerUrl"] = json!("https://github.com.evil/egdev6/example/releases/download/v1/a.exe"); documents.push(invalid_url.to_string().into_bytes()); let mut invalid_key = valid; - invalid_key["apps"][0]["updaterPublicKey"] = json!("not-a-key"); + invalid_key["apps"][0]["platforms"]["windows-x86_64"]["updaterPublicKey"] = json!("not-a-key"); documents.push(invalid_key.to_string().into_bytes()); for document in documents { - let feed = NativeFeed::new(FakeNetwork::new(vec![body(&document)])); + let feed = test_feed(FakeNetwork::new(vec![body(&document)])); assert_eq!(feed.fetch().await.unwrap_err(), FeedError::InvalidCatalog); - assert_eq!(feed.network.requests(), [OFFICIAL_V3_FEED]); + assert_eq!(feed.network.requests(), [OFFICIAL_V4_FEED]); } } +#[tokio::test] +async fn native_feed_rejects_a_valid_v3_document() { + let text = legacy_catalog_value().to_string(); + let feed = test_feed(FakeNetwork::new(vec![body(text.as_bytes())])); + assert_eq!(feed.fetch().await.unwrap_err(), FeedError::InvalidCatalog); + assert_eq!(feed.network.requests(), [OFFICIAL_V4_FEED]); +} + +#[tokio::test] +async fn fetch_projects_the_requested_platform_and_hides_every_app_when_unknown() { + let text = include_str!("../../../../crates/nexo-catalog/fixtures/v4.json"); + for (platform, expected_ids) in [ + (Some("windows-x86_64"), vec!["example-app", "windows-only"]), + (Some("darwin-aarch64"), vec!["example-app"]), + (Some("linux-x86_64"), vec![]), + (None, vec![]), + ] { + let feed = + NativeFeed::for_platform(FakeNetwork::new(vec![body(text.as_bytes())]), platform); + let catalog = feed.fetch().await.unwrap(); + assert_eq!( + catalog + .catalog() + .apps + .iter() + .map(|app| app.id.as_str()) + .collect::>(), + expected_ids + ); + if platform != Some("windows-x86_64") { + assert_eq!( + catalog.select("windows-only"), + Err(SelectionError::NotOfficial) + ); + } + } + let feed = NativeFeed::new(FakeNetwork::new(vec![body(text.as_bytes())])); + let actual = feed.fetch().await.unwrap(); + let document = nexo_catalog::parse_catalog_v4(text).unwrap(); + assert_eq!( + actual.catalog(), + &nexo_catalog::project_catalog_v4( + &document, + crate::platform::platform_key().as_deref().unwrap_or("") + ) + ); +} + #[tokio::test] async fn bounds_feed_bytes_and_rejects_length_mismatches_without_fallback() { for (reply, expected) in [ @@ -235,18 +305,18 @@ async fn bounds_feed_bytes_and_rejects_length_mismatches_without_fallback() { FeedError::LengthMismatch, ), ] { - let feed = NativeFeed::new(FakeNetwork::new(vec![reply])); + let feed = test_feed(FakeNetwork::new(vec![reply])); assert_eq!(feed.fetch().await.unwrap_err(), expected); - assert_eq!(feed.network.requests(), [OFFICIAL_V3_FEED]); + assert_eq!(feed.network.requests(), [OFFICIAL_V4_FEED]); } } #[tokio::test(start_paused = true)] async fn bounds_both_connection_and_stream_time() { for reply in [Reply::PendingConnection, Reply::PendingBody] { - let feed = NativeFeed::new(FakeNetwork::new(vec![reply])); + let feed = test_feed(FakeNetwork::new(vec![reply])); assert_eq!(feed.fetch().await.unwrap_err(), FeedError::Timeout); - assert_eq!(feed.network.requests(), [OFFICIAL_V3_FEED]); + assert_eq!(feed.network.requests(), [OFFICIAL_V4_FEED]); } } @@ -256,7 +326,7 @@ fn selecting_requires_an_official_id_and_a_public_key() { let catalog = fresh(&value); assert_eq!(catalog.select("unknown"), Err(SelectionError::NotOfficial)); assert_eq!(catalog.select("minimal").unwrap().app().id, "minimal"); - value["apps"][0] + value["apps"][0]["platforms"]["windows-x86_64"] .as_object_mut() .unwrap() .remove("updaterPublicKey"); @@ -276,7 +346,7 @@ fn keyed_selection_refuses_assets_without_the_x64_nsis_suffix() { "example_x64-setup.exe.txt", ] { let mut value = catalog_value(); - value["apps"][0]["installerUrl"] = json!(format!( + value["apps"][0]["platforms"]["windows-x86_64"]["installerUrl"] = json!(format!( "https://github.com/egdev6/example/releases/download/v1/{asset}" )); assert_eq!( @@ -297,7 +367,7 @@ fn revalidation_rejects_removal_or_change_of_release_key_and_detection_identity( removed["apps"] = json!([]); cases.push(removed); let mut missing_key = original.clone(); - missing_key["apps"][0] + missing_key["apps"][0]["platforms"]["windows-x86_64"] .as_object_mut() .unwrap() .remove("updaterPublicKey"); @@ -309,11 +379,15 @@ fn revalidation_rejects_removal_or_change_of_release_key_and_detection_identity( ("version", json!("2.0.0")), ( "detection", - json!({"windows": {"displayName": "Other", "publisher": "Example", "executableRelativePath": "Minimal.exe"}}), + json!({"displayName": "Other", "publisher": "Example", "executableRelativePath": "Minimal.exe"}), ), ] { let mut changed = original.clone(); - changed["apps"][0][field] = new_value; + if field == "id" { + changed["apps"][0][field] = new_value; + } else { + changed["apps"][0]["platforms"]["windows-x86_64"][field] = new_value; + } cases.push(changed); } for changed in cases { diff --git a/apps/hub/src-tauri/src/install_service_tests.rs b/apps/hub/src-tauri/src/install_service_tests.rs index adceef9..e250c6f 100644 --- a/apps/hub/src-tauri/src/install_service_tests.rs +++ b/apps/hub/src-tauri/src/install_service_tests.rs @@ -24,20 +24,23 @@ use std::{ }; use tokio::sync::Semaphore; -fn document() -> Value { +pub(super) fn document() -> Value { let mut value: Value = serde_json::from_str(include_str!( "../../../../crates/nexo-catalog/fixtures/minimal.json" )) .unwrap(); - value["schemaVersion"] = json!(3); - value["apps"][0]["installerUrl"] = - json!("https://github.com/egdev6/example/releases/download/v1/example_x64-setup.exe"); - value["apps"][0]["latestJsonUrl"] = - json!("https://github.com/egdev6/example/releases/download/v1/latest.json"); - value["apps"][0]["updaterPublicKey"] = - json!(STANDARD.encode(include_str!("../tests/fixtures/tauri-test.pub"))); - value["apps"][0]["version"] = json!("1.0.0"); - value["apps"][0]["detection"] = json!({"windows": {"displayName": "Minimal", "publisher": "Example", "executableRelativePath": "Minimal.exe"}}); + value["schemaVersion"] = json!(4); + let app = value["apps"][0].as_object_mut().unwrap(); + for field in ["installerUrl", "latestJsonUrl", "releasedAt"] { + app.remove(field).unwrap(); + } + app.insert("platforms".into(), json!({"windows-x86_64": { + "installerUrl": "https://github.com/egdev6/example/releases/download/v1/example_x64-setup.exe", + "latestJsonUrl": "https://github.com/egdev6/example/releases/download/v1/latest.json", + "updaterPublicKey": STANDARD.encode(include_str!("../tests/fixtures/tauri-test.pub")), + "version": "1.0.0", "releasedAt": "2025-01-01T00:00:00Z", + "detection": {"displayName": "Minimal", "publisher": "Example", "executableRelativePath": "Minimal.exe"} + }})); value } @@ -150,7 +153,9 @@ impl CatalogFeed for Feed { .unwrap() .pop_front() .unwrap_or_else(|| Ok(document()))?; - NativeFeed::new(DocumentNetwork(doc)).fetch().await + NativeFeed::for_platform(DocumentNetwork(doc), Some("windows-x86_64")) + .fetch() + .await } } struct FakeNetwork(Arc); @@ -693,7 +698,10 @@ async fn initial_installed_detection_still_blocks_before_approval() { fn without_detection_hint(state: &State) { let mut doc = document(); - doc["apps"][0].as_object_mut().unwrap().remove("detection"); + doc["apps"][0]["platforms"]["windows-x86_64"] + .as_object_mut() + .unwrap() + .remove("detection"); *state.documents.lock().unwrap() = [Ok(doc.clone()), Ok(doc)].into(); } @@ -833,7 +841,7 @@ async fn unknown_prespawn_requires_warning_approval_and_revalidates_before_launc let state = State::new(1, 1); let mut changed = document(); - changed["apps"][0]["version"] = json!("2.0.0"); + changed["apps"][0]["platforms"]["windows-x86_64"]["version"] = json!("2.0.0"); *state.documents.lock().unwrap() = [Ok(document()), Ok(document()), Ok(changed)].into(); state.observe(vec![Detection::NotInstalled, Detection::Unknown]); assert_eq!( @@ -1007,15 +1015,16 @@ async fn denied_or_dismissed_native_approval_never_downloads() { #[tokio::test] async fn changed_release_key_detection_or_removed_entry_aborts_and_cleans() { let mut changed_url = document(); - changed_url["apps"][0]["installerUrl"] = + changed_url["apps"][0]["platforms"]["windows-x86_64"]["installerUrl"] = json!("https://github.com/egdev6/example/releases/download/v2/example_x64-setup.exe"); let mut changed_version = document(); - changed_version["apps"][0]["version"] = json!("2.0.0"); + changed_version["apps"][0]["platforms"]["windows-x86_64"]["version"] = json!("2.0.0"); let mut changed_key = document(); - changed_key["apps"][0]["updaterPublicKey"] = + changed_key["apps"][0]["platforms"]["windows-x86_64"]["updaterPublicKey"] = json!(STANDARD.encode(include_str!("../tests/fixtures/minisign-test.pub"))); let mut changed_detection = document(); - changed_detection["apps"][0]["detection"]["windows"]["publisher"] = json!("Other"); + changed_detection["apps"][0]["platforms"]["windows-x86_64"]["detection"]["publisher"] = + json!("Other"); let mut removed = document(); removed["apps"] = json!([]); for changed in [ diff --git a/apps/hub/src-tauri/src/lib.rs b/apps/hub/src-tauri/src/lib.rs index f33abcd..b91cc56 100644 --- a/apps/hub/src-tauri/src/lib.rs +++ b/apps/hub/src-tauri/src/lib.rs @@ -29,6 +29,7 @@ mod ipc; mod local_apps; #[cfg(any(windows, test))] mod open_external; +mod platform; mod position; #[cfg(any(windows, test))] mod registry_presentation; @@ -738,9 +739,8 @@ pub fn run() { get_flyout_motion, get_flyout_state, hide_flyout, - catalog_cache::read_catalog_cache, - catalog_cache::read_catalog_v2_cache, - catalog_cache::read_catalog_v3_cache, + platform::platform_key, + catalog_cache::read_catalog_v4_cache, catalog_cache::write_catalog_cache, config::get_settings, config::save_settings, @@ -781,9 +781,8 @@ pub fn run() { get_flyout_motion, get_flyout_state, hide_flyout, - catalog_cache::read_catalog_cache, - catalog_cache::read_catalog_v2_cache, - catalog_cache::read_catalog_v3_cache, + platform::platform_key, + catalog_cache::read_catalog_v4_cache, catalog_cache::write_catalog_cache, config::get_settings, config::save_settings, diff --git a/apps/hub/src-tauri/src/platform.rs b/apps/hub/src-tauri/src/platform.rs new file mode 100644 index 0000000..f953559 --- /dev/null +++ b/apps/hub/src-tauri/src/platform.rs @@ -0,0 +1,60 @@ +/// Map Rust target identifiers to Tauri updater platform keys. +pub(crate) fn key_for(os: &str, arch: &str) -> Option { + let os = match os { + "windows" => "windows", + "macos" => "darwin", + "linux" => "linux", + _ => return None, + }; + let arch = match arch { + "x86_64" => "x86_64", + "aarch64" => "aarch64", + "x86" => "i686", + "arm" => "armv7", + _ => return None, + }; + Some(format!("{os}-{arch}")) +} + +#[tauri::command] +pub(crate) fn platform_key() -> Option { + key_for(std::env::consts::OS, std::env::consts::ARCH) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn maps_every_supported_os_and_architecture_and_rejects_unknown_targets() { + for (os, target_os) in [ + ("windows", "windows"), + ("macos", "darwin"), + ("linux", "linux"), + ] { + for (arch, target_arch) in [ + ("x86_64", "x86_64"), + ("aarch64", "aarch64"), + ("x86", "i686"), + ("arm", "armv7"), + ] { + assert_eq!( + key_for(os, arch), + Some(format!("{target_os}-{target_arch}")) + ); + } + } + for (os, arch) in [ + ("freebsd", "x86_64"), + ("darwin", "x86_64"), + ("linux", "riscv64"), + ("", ""), + ] { + assert_eq!(key_for(os, arch), None); + } + assert_eq!( + platform_key(), + key_for(std::env::consts::OS, std::env::consts::ARCH) + ); + } +} diff --git a/apps/hub/src-tauri/src/update_service_tests.rs b/apps/hub/src-tauri/src/update_service_tests.rs index 64782e6..05b6a10 100644 --- a/apps/hub/src-tauri/src/update_service_tests.rs +++ b/apps/hub/src-tauri/src/update_service_tests.rs @@ -7,9 +7,9 @@ use crate::install_service::{ InstallResult, InstallService, InstallWorkspace, Installer, Monitor, Operation, ProgressReporter, ProgressSink, UpdateCloser, UpdateDetection, }; +use crate::install_service_tests::document; use crate::install_workspace::PrepareError; use crate::update_close::{CloseOutcome, ProbeError}; -use base64::{Engine, engine::general_purpose::STANDARD}; use nexo_catalog::CatalogApp; use serde_json::{Value, json}; use std::{ @@ -22,22 +22,6 @@ use std::{ }; use tokio::sync::Semaphore; -fn document() -> Value { - let mut value: Value = serde_json::from_str(include_str!( - "../../../../crates/nexo-catalog/fixtures/minimal.json" - )) - .unwrap(); - value["schemaVersion"] = json!(3); - value["apps"][0]["installerUrl"] = - json!("https://github.com/egdev6/example/releases/download/v1/example_x64-setup.exe"); - value["apps"][0]["latestJsonUrl"] = - json!("https://github.com/egdev6/example/releases/download/v1/latest.json"); - value["apps"][0]["updaterPublicKey"] = - json!(STANDARD.encode(include_str!("../tests/fixtures/tauri-test.pub"))); - value["apps"][0]["version"] = json!("1.0.0"); - value["apps"][0]["detection"] = json!({"windows":{"displayName":"Minimal","publisher":"Example","executableRelativePath":"Minimal.exe"}}); - value -} fn installed(version: &str) -> UpdateDetection { UpdateDetection::Installed { version: Some(version.into()), @@ -137,7 +121,9 @@ impl CatalogFeed for Feed { .unwrap() .pop_front() .unwrap_or_else(|| Ok(document()))?; - NativeFeed::new(DocumentNetwork(document)).fetch().await + NativeFeed::for_platform(DocumentNetwork(document), Some("windows-x86_64")) + .fetch() + .await } } struct NoNetwork; @@ -395,7 +381,7 @@ async fn update_still_refuses_unknown_installation_before_approval() { async fn absent_key_bad_feed_and_denied_approval_never_download_or_launch() { let state = State::new(); let mut missing = document(); - missing["apps"][0] + missing["apps"][0]["platforms"]["windows-x86_64"] .as_object_mut() .unwrap() .remove("updaterPublicKey"); @@ -427,7 +413,7 @@ async fn absent_key_bad_feed_and_denied_approval_never_download_or_launch() { #[tokio::test] async fn changed_release_or_observation_aborts_after_download_and_cleans() { let mut changed = document(); - changed["apps"][0]["version"] = json!("1.1.0"); + changed["apps"][0]["platforms"]["windows-x86_64"]["version"] = json!("1.1.0"); let state = State::new(); *state.documents.lock().unwrap() = [Ok(document()), Ok(changed)].into(); assert_eq!(update(&state).await, json!({"status":"releaseChanged"})); @@ -480,7 +466,7 @@ async fn failed_close_or_final_process_probe_never_spawns_and_cleans() { #[tokio::test] async fn metadata_and_identity_are_rechecked_after_close_before_spawn() { let mut changed = document(); - changed["apps"][0]["version"] = json!("1.1.0"); + changed["apps"][0]["platforms"]["windows-x86_64"]["version"] = json!("1.1.0"); let state = State::new(); *state.documents.lock().unwrap() = [Ok(document()), Ok(document()), Ok(changed)].into(); assert_eq!(update(&state).await, json!({"status":"releaseChanged"})); diff --git a/apps/hub/src-tauri/src/vp_install_tests.rs b/apps/hub/src-tauri/src/vp_install_tests.rs index eb430e0..0d11338 100644 --- a/apps/hub/src-tauri/src/vp_install_tests.rs +++ b/apps/hub/src-tauri/src/vp_install_tests.rs @@ -50,21 +50,20 @@ fn official_parser_still_accepts_full_integration_and_projects_news() { } #[test] -fn vp_official_catalogs_validate_v3_keys_and_reject_them_in_v2() { - use base64::{Engine, engine::general_purpose::STANDARD}; - let mut raw = [0_u8; 42]; - raw[..2].copy_from_slice(b"Ed"); - let key = STANDARD.encode(format!("untrusted comment: k\n{}\n", STANDARD.encode(raw))); - let doc = |version: u8, key: Option<&str>| { - let mut app = serde_json::json!({"id": "antena", "name": "Antena", "tagline": "t", "description": "d", - "tags": [], "iconUrl": "https://example.com/i.png", "installerUrl": INITIAL, - "latestJsonUrl": "https://github.com/egdev6/antena/releases/download/v1/latest.json", - "integrationLevel": "launch", "releasedAt": "2026-01-01T00:00:00Z", "featured": false, "news": []}); - if let Some(key) = key { - app["updaterPublicKey"] = key.into(); - } - serde_json::json!({"schemaVersion": version, "apps": [app]}).to_string() - }; - assert!(nexo_catalog::parse_catalog(&doc(3, Some(&key))).is_ok()); - assert!(nexo_catalog::parse_catalog(&doc(2, Some(&key))).is_err()); +fn vp_official_v4_catalogs_validate_platform_keys_and_reject_old_versions() { + let mut value: serde_json::Value = serde_json::from_str(include_str!( + "../../../../crates/nexo-catalog/fixtures/v4.json" + )) + .unwrap(); + assert!(nexo_catalog::parse_catalog_v4(&value.to_string()).is_ok()); + value["apps"][0]["platforms"]["windows-x86_64"]["updaterPublicKey"] = "bad".into(); + assert!(nexo_catalog::parse_catalog_v4(&value.to_string()).is_err()); + for version in [1, 2, 3] { + assert!( + nexo_catalog::parse_catalog_v4( + &serde_json::json!({"schemaVersion": version, "apps": []}).to_string() + ) + .is_err() + ); + } } From 8394e02755f94663d16a2ba138547577be114f62 Mon Sep 17 00:00:00 2001 From: egdev6 Date: Sat, 21 Nov 2026 15:58:24 +0100 Subject: [PATCH 4/9] feat(hub): load catalog v4 and show only apps for the current platform --- apps/hub/src/App.test.tsx | 39 ++-- apps/hub/src/App.tsx | 8 +- apps/hub/src/catalog-refresh.test.tsx | 52 ++++- apps/hub/src/catalog/endpoints.test.ts | 8 +- apps/hub/src/catalog/format.test.ts | 40 +++- apps/hub/src/catalog/format.ts | 53 ++++- apps/hub/src/catalog/index.test.tsx | 8 +- apps/hub/src/catalog/index.tsx | 2 +- apps/hub/src/catalog/install/ui.test.tsx | 9 +- .../src/catalog/install/update-ui.test.tsx | 18 +- apps/hub/src/catalog/loader.test.ts | 189 ++++++------------ apps/hub/src/catalog/loader.ts | 44 +--- apps/hub/src/catalog/update.ts | 2 +- apps/hub/src/i18n/messages.json | 4 +- apps/hub/src/local-apps/isolation.test.tsx | 27 ++- apps/hub/src/mis-apps.test.tsx | 2 +- apps/hub/src/news/real-data.test.tsx | 26 ++- apps/hub/src/test-helpers/catalog-v4.ts | 24 +++ 18 files changed, 302 insertions(+), 253 deletions(-) create mode 100644 apps/hub/src/test-helpers/catalog-v4.ts diff --git a/apps/hub/src/App.test.tsx b/apps/hub/src/App.test.tsx index 6b2151b..4d25d79 100644 --- a/apps/hub/src/App.test.tsx +++ b/apps/hub/src/App.test.tsx @@ -13,6 +13,7 @@ import { defaultSettings } from './sample'; import fullCatalog from '../../../crates/nexo-catalog/fixtures/full.json'; import * as catalogLoader from './catalog/loader'; import { parseCatalog } from './catalog/format'; +import { windowsCatalog } from './test-helpers/catalog-v4'; // Test the shell's public wiring independently of the other area writers. vi.mock('./local-apps/view', () => ({ LocalAppsView: () => null })); @@ -25,8 +26,6 @@ vi.mock('@tauri-apps/api/core', () => ({ vi.mock('./catalog/loader', async importOriginal => ({ ...(await importOriginal()), OFFICIAL_CATALOG_URL: undefined, - OFFICIAL_CATALOG_V2_URL: undefined, - OFFICIAL_CATALOG_V3_URL: undefined, })); vi.mock('@tauri-apps/api/event', () => ({ listen: vi.fn().mockResolvedValue(() => {}) })); vi.mock('./catalog', () => ({ @@ -110,18 +109,19 @@ it('loads the native catalog without treating samples or unknown installation as expect(screen.queryByRole('dialog', { name: 'Novedades' })).toBeNull(); fireEvent.click(screen.getByRole('button', { name: 'Ver catálogo' })); await waitFor(() => expect(screen.getByText('Estado catálogo: error')).toBeTruthy()); - expect(invoke).toHaveBeenCalledWith('read_catalog_cache'); + expect(invoke).toHaveBeenCalledWith('read_catalog_v4_cache'); }); it('shows actual installed and absent observations with a registry version and unknown running state', async () => { vi.mocked(isTauri).mockReturnValue(true); const first = { ...fullCatalog.apps[0], detection: { windows: { displayName: 'Example App', publisher: 'Example Publisher', executableRelativePath: 'Example.exe' } } }; const second = { ...first, id: 'other-app', name: 'Other App' }; - const catalog = JSON.stringify({ schemaVersion: 2, apps: [first, second] }); + const catalog = JSON.stringify(windowsCatalog([first, second])); vi.mocked(invoke).mockImplementation(((command: string) => { if (command === 'get_settings') return Promise.resolve({ state: 'ready', settings: { ...defaultSettings, firstRunComplete: true, showNewsOnOpen: false, sources: [] } }); if (command === 'plugin:autostart|is_enabled') return Promise.resolve(false); - if (command === 'read_catalog_v2_cache') return Promise.resolve(catalog); + if (command === 'platform_key') return Promise.resolve('windows-x86_64'); + if (command === 'read_catalog_v4_cache') return Promise.resolve(catalog); if (command === 'installed_apps') return Promise.resolve([ { id: 'example-app', state: 'installed', version: '9.1.0', reason: 'Instalación detectada' }, { id: 'other-app', state: 'notInstalled', version: null, reason: 'Sin coincidencias' }, @@ -146,12 +146,13 @@ it('shows actual installed and absent observations with a registry version and u it('projects a native process observation into the official row and refreshes after close', async () => { vi.mocked(isTauri).mockReturnValue(true); const app = { ...fullCatalog.apps[0], detection: { windows: { displayName: 'Example App', publisher: 'Example Publisher', executableRelativePath: 'Example.exe' } } }; - vi.spyOn(catalogLoader, 'loadVersionedCatalog').mockResolvedValue({ status: 'ready', catalog: parseCatalog({ schemaVersion: 2, apps: [app] }) }); + vi.spyOn(catalogLoader, 'loadCatalog').mockResolvedValue({ status: 'ready', catalog: { ...parseCatalog({ schemaVersion: 2, apps: [app] }), schemaVersion: 4 } }); let running = true; vi.mocked(invoke).mockImplementation(((command: string) => { if (command === 'get_settings') return Promise.resolve({ state: 'ready', settings: { ...defaultSettings, firstRunComplete: true, showNewsOnOpen: false, sources: [] } }); if (command === 'plugin:autostart|is_enabled') return Promise.resolve(false); - if (command === 'read_catalog_v2_cache') return Promise.resolve(JSON.stringify({ schemaVersion: 2, apps: [app] })); + if (command === 'platform_key') return Promise.resolve('windows-x86_64'); + if (command === 'read_catalog_v4_cache') return Promise.resolve(JSON.stringify(windowsCatalog([app]))); if (command === 'installed_apps') return Promise.resolve([{ id: 'example-app', state: 'installed', runningState: running ? 'running' : 'notRunning', version: '9.1.0', reason: 'Instalación detectada', canOpen: true }]); if (command === 'close_official_app') { running = false; return Promise.resolve({ status: 'closed', message: 'Example App se ha cerrado.' }); } return Promise.resolve(null); @@ -173,7 +174,8 @@ it('ignores an older installation scan that resolves after a newer refresh', asy vi.mocked(invoke).mockImplementation(((command: string) => { if (command === 'get_settings') return Promise.resolve({ state: 'ready', settings: { ...defaultSettings, firstRunComplete: true, showNewsOnOpen: false, sources: [] } }); if (command === 'plugin:autostart|is_enabled') return Promise.resolve(false); - if (command === 'read_catalog_v2_cache') return Promise.resolve(JSON.stringify({ schemaVersion: 2, apps: [app] })); + if (command === 'platform_key') return Promise.resolve('windows-x86_64'); + if (command === 'read_catalog_v4_cache') return Promise.resolve(JSON.stringify(windowsCatalog([app]))); if (command === 'installed_apps') { if (++scans === 1) return new Promise(resolve => { finishFirst = resolve; }); return Promise.resolve([{ id: 'example-app', state: 'installed', version: '9.1.0', reason: 'Instalación detectada' }]); @@ -198,7 +200,8 @@ it('routes a connected plugin close through IPC, reports refusal, and refreshes vi.mocked(invoke).mockImplementation(((command: string) => { if (command === 'get_settings') return Promise.resolve({ state: 'ready', settings: { ...defaultSettings, firstRunComplete: true, showNewsOnOpen: false, sources: [] } }); if (command === 'plugin:autostart|is_enabled') return Promise.resolve(false); - if (command === 'read_catalog_v2_cache') return Promise.resolve(JSON.stringify({ schemaVersion: 2, apps: [app] })); + if (command === 'platform_key') return Promise.resolve('windows-x86_64'); + if (command === 'read_catalog_v4_cache') return Promise.resolve(JSON.stringify(windowsCatalog([app]))); if (command === 'installed_apps') return Promise.resolve([{ id: 'example-app', state: 'installed', version: '9.1.0', reason: 'Instalación detectada' }]); if (command === 'close_connected_app') return Promise.reject('Cambios sin guardar'); return Promise.resolve(null); @@ -246,7 +249,8 @@ it('keeps installation unknown on scan failure instead of claiming absence', asy vi.mocked(invoke).mockImplementation(((command: string) => { if (command === 'get_settings') return Promise.resolve({ state: 'ready', settings: { ...defaultSettings, firstRunComplete: true, showNewsOnOpen: false, sources: [] } }); if (command === 'plugin:autostart|is_enabled') return Promise.resolve(false); - if (command === 'read_catalog_v2_cache') return Promise.resolve(JSON.stringify({ schemaVersion: 2, apps: [app] })); + if (command === 'platform_key') return Promise.resolve('windows-x86_64'); + if (command === 'read_catalog_v4_cache') return Promise.resolve(JSON.stringify(windowsCatalog([app]))); if (command === 'installed_apps') return Promise.reject('denied'); return Promise.resolve(null); }) as typeof invoke); @@ -266,7 +270,8 @@ it('disables plugin show without capability and sends only an ID when supported' vi.mocked(invoke).mockImplementation(((command: string) => { if (command === 'get_settings') return Promise.resolve({ state: 'ready', settings: { ...defaultSettings, firstRunComplete: true, showNewsOnOpen: false, sources: [] } }); if (command === 'plugin:autostart|is_enabled') return Promise.resolve(false); - if (command === 'read_catalog_v2_cache') return Promise.resolve(JSON.stringify({ schemaVersion: 2, apps: [app] })); + if (command === 'platform_key') return Promise.resolve('windows-x86_64'); + if (command === 'read_catalog_v4_cache') return Promise.resolve(JSON.stringify(windowsCatalog([app]))); if (command === 'installed_apps') return Promise.resolve([{ id: 'example-app', state: 'installed', version: '9.1.0', reason: 'Instalación detectada' }]); if (command === 'open_official_app') return Promise.resolve('Solicitud enviada; no hay confirmación de la ventana'); return Promise.resolve(null); @@ -293,7 +298,8 @@ it('keeps settings, live IPC and late-arriving catalog news together', async () vi.mocked(invoke).mockImplementation(((command: string, args?: { patch?: Partial }) => { if (command === 'get_settings') return Promise.resolve({ state: 'ready', settings: saved }); if (command === 'plugin:autostart|is_enabled') return Promise.resolve(false); - if (command === 'read_catalog_cache') return cache; + if (command === 'platform_key') return Promise.resolve('windows-x86_64'); + if (command === 'read_catalog_v4_cache') return cache; if (command === 'get_flyout_state') return Promise.resolve({ visible: true, sequence: 1, cycle: 1, at: Date.now() }); if (command === 'save_settings') { saved = { ...saved, ...args?.patch }; return Promise.resolve(saved); } return Promise.resolve(null); @@ -305,7 +311,7 @@ it('keeps settings, live IPC and late-arriving catalog news together', async () expect(screen.getByRole('main').style.getPropertyValue('--hub-accent')).toBe('#123456'); expect(screen.queryByRole('dialog', { name: 'Novedades' })).toBeNull(); const now = new Date().toISOString(); - await act(async () => { resolveCache(JSON.stringify({ schemaVersion: 1, apps: [{ id: 'minimal', name: 'Minimal', tagline: 'Prueba', description: 'Una app', tags: [], iconUrl: 'https://example.com/icon.png', installerUrl: 'https://example.com/app.exe', latestJsonUrl: 'https://example.com/latest.json', integrationLevel: 'launch', releasedAt: now, featured: false, news: [{ id: 'release', title: 'Novedad de catálogo', text: 'Disponible', publishedAt: now, kind: 'new' }] }] })); }); + await act(async () => { resolveCache(JSON.stringify(windowsCatalog([{ id: 'minimal', name: 'Minimal', tagline: 'Prueba', description: 'Una app', tags: [], iconUrl: 'https://example.com/icon.png', installerUrl: 'https://example.com/app.exe', latestJsonUrl: 'https://example.com/latest.json', integrationLevel: 'launch', releasedAt: now, featured: false, news: [{ id: 'release', title: 'Novedad de catálogo', text: 'Disponible', publishedAt: now, kind: 'new' }] }]))); }); expect(await screen.findByRole('dialog', { name: 'Novedades' })).toBeTruthy(); expect(screen.getByText('Novedad de catálogo')).toBeTruthy(); closeNews(); @@ -355,7 +361,7 @@ it('does not exit only the hub while a pending settings save fails', async () => vi.mocked(invoke).mockImplementation(((command: string, args?: { patch?: Partial }) => { if (command === 'get_settings') return Promise.resolve({ state: 'ready', settings: saved }); if (command === 'plugin:autostart|is_enabled') return Promise.resolve(false); - if (command === 'read_catalog_cache') return Promise.resolve(null); + if (command === 'read_catalog_v4_cache') return Promise.resolve(null); if (command === 'save_settings') { if (failSave) return Promise.reject(new Error('disco lleno')); saved = { ...saved, ...args?.patch }; return Promise.resolve(saved); @@ -536,9 +542,10 @@ it('keeps live registry updates and unknown installation state through catalog e const catalog = screen.getByRole('tab', { name: 'Catálogo' }); fireEvent.mouseDown(catalog, { button: 0 }); fireEvent.click(catalog); await waitFor(() => expect(screen.getByText('Estado catálogo: error')).toBeTruthy()); - expect(vi.mocked(invoke).mock.calls.filter(([command]) => command === 'read_catalog_cache')).toHaveLength(1); + expect(vi.mocked(invoke).mock.calls.filter(([command]) => command === 'read_catalog_v4_cache')).toHaveLength(1); fireEvent.click(screen.getByRole('button', { name: 'Reintentar catálogo' })); - await waitFor(() => expect(vi.mocked(invoke).mock.calls.filter(([command]) => command === 'read_catalog_cache')).toHaveLength(2)); + await waitFor(() => expect(vi.mocked(invoke).mock.calls.filter(([command]) => command === 'read_catalog_v4_cache')).toHaveLength(2)); + expect(vi.mocked(invoke).mock.calls.filter(([command]) => command === 'platform_key')).toHaveLength(1); const apps = screen.getByRole('tab', { name: 'Mis apps' }); fireEvent.mouseDown(apps, { button: 0 }); fireEvent.click(apps); expect(screen.getByText('App conectada')).toBeTruthy(); diff --git a/apps/hub/src/App.tsx b/apps/hub/src/App.tsx index cf45485..69b856a 100644 --- a/apps/hub/src/App.tsx +++ b/apps/hub/src/App.tsx @@ -2,13 +2,13 @@ import { useEffect, useLayoutEffect, useRef, useState } from 'react'; import type { CSSProperties, ReactNode } from 'react'; import { AppIcon, Button, Cluster, Collapsible, CollapsibleContent, CollapsibleHeader, CollapsibleTrigger, Icon, IconButton, Notice, PageHeader, StatusDot, Tabs, Text } from '@egdev/ui'; import { AppDetails } from './apps/details'; -import { isTauri } from '@tauri-apps/api/core'; +import { invoke, isTauri } from '@tauri-apps/api/core'; import { activateConnectedMenuItem, closeConnectedApp, closeOfficialApp, localizeAppReason, openOfficialApp, scanInstallations, type InstallationObservation } from './apps'; import { CatalogView } from './catalog'; import { useCatalogInstalls, type CatalogInstalls } from './catalog/install/use-installs'; import { InstallAction } from './catalog/install/action'; import { availableUpdate } from './catalog/update'; -import { diskCache, diskCacheV2, diskCacheV3, loadVersionedCatalog, OFFICIAL_CATALOG_URL, OFFICIAL_CATALOG_V2_URL, OFFICIAL_CATALOG_V3_URL, webFetcher, type CatalogState } from './catalog/loader'; +import { diskCache, loadCatalog, OFFICIAL_CATALOG_URL, webFetcher, type CatalogState } from './catalog/loader'; import { projectCatalog } from './catalog/mapping'; import { FirstRun } from './first-run'; import { formatNumber, intlLocale, t } from './i18n'; @@ -406,6 +406,7 @@ export default function App(props: FlyoutProps) { const [catalogState, setCatalogState] = useState({ status: 'loading' }); const [installations, setInstallations] = useState(null); const requestId = useRef(0); + const platformKey = useRef | null>(null); const catalogInFlight = useRef(false); const catalogActive = useRef(false); const lastCatalogSuccess = useRef(null); @@ -427,7 +428,8 @@ export default function App(props: FlyoutProps) { catalogInFlight.current = true; const id = ++requestId.current; setCatalogState(current => current.catalog ? current : { ...current, status: 'loading' }); - void loadVersionedCatalog(OFFICIAL_CATALOG_V2_URL, OFFICIAL_CATALOG_URL, diskCacheV2, diskCache, webFetcher, OFFICIAL_CATALOG_V3_URL, diskCacheV3).then(result => { + platformKey.current ??= invoke('platform_key').catch(() => null); + void platformKey.current.then(key => loadCatalog(OFFICIAL_CATALOG_URL, diskCache, webFetcher, key)).then(result => { if (!catalogActive.current || id !== requestId.current) return; if ((result.status === 'ready' || result.status === 'empty') && result.catalog) lastCatalogSuccess.current = Date.now(); setCatalogState(current => (result.status === 'error' || result.status === 'offline') && current.catalog ? diff --git a/apps/hub/src/catalog-refresh.test.tsx b/apps/hub/src/catalog-refresh.test.tsx index 81d37a4..ceb8ebc 100644 --- a/apps/hub/src/catalog-refresh.test.tsx +++ b/apps/hub/src/catalog-refresh.test.tsx @@ -4,6 +4,7 @@ import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testi import { afterEach, beforeEach, expect, it, vi } from 'vitest'; import App from './App'; import { defaultSettings } from './sample'; +import v4 from '../../../crates/nexo-catalog/fixtures/v4.json'; const bridge = vi.hoisted(() => ({ invoke: vi.fn(), @@ -25,11 +26,11 @@ let cycle: number; let stored: string | null; const fiveMinutes = 5 * 60 * 1000; function catalog(version: string) { - return JSON.stringify({ schemaVersion: 3, apps: [{ + return JSON.stringify({ schemaVersion: 4, apps: [{ id: 'example-app', name: 'Example App', tagline: 'Example', description: 'Example application', tags: [], - iconUrl: 'https://example.com/icon.png', installerUrl: 'https://github.com/egdev6/example-app/releases/download/v1.0.0/setup.exe', - latestJsonUrl: 'https://github.com/egdev6/example-app/releases/download/v1.0.0/latest.json', - integrationLevel: 'launch', releasedAt: '2025-01-02T03:04:05Z', featured: false, version, news: [], + iconUrl: 'https://example.com/icon.png', integrationLevel: 'launch', featured: false, news: [], + platforms: { 'windows-x86_64': { installerUrl: 'https://github.com/egdev6/example-app/releases/download/v1.0.0/example-app_x64-setup.exe', + latestJsonUrl: 'https://github.com/egdev6/example-app/releases/download/v1.0.0/latest.json', releasedAt: '2025-01-02T03:04:05Z', version } }, }] }); } function response(url: string, version: string) { @@ -70,8 +71,8 @@ beforeEach(() => { if (command === 'get_settings') return { state: 'ready', settings }; if (command === 'save_settings') { settings = { ...settings, ...args?.patch }; return settings; } if (command === 'get_flyout_state') return { visible: false, sequence: 0, cycle: 0, at: now }; - if (command === 'read_catalog_v3_cache') return stored; - if (command === 'read_catalog_v2_cache' || command === 'read_catalog_cache') return null; + if (command === 'platform_key') return 'windows-x86_64'; + if (command === 'read_catalog_v4_cache') return stored; if (command === 'write_catalog_cache') { stored = args?.input ?? null; return null; } if (command === 'installed_apps') return [{ id: 'example-app', state: 'notInstalled', reason: 'No está instalada', version: null }]; if (command === 'plugin:autostart|is_enabled') return false; @@ -80,6 +81,43 @@ beforeEach(() => { }); afterEach(() => { cleanup(); vi.restoreAllMocks(); vi.unstubAllGlobals(); }); +it('hides a Windows-only app and its news on Darwin throughout the live UI', async () => { + const doc = structuredClone(v4); + const timestamp = new Date(now).toISOString(); + doc.apps[0].news[0] = { id: 'darwin-news', title: 'Darwin news', text: 'Available', publishedAt: timestamp, kind: 'new' }; + doc.apps[0].platforms['darwin-aarch64']!.releasedAt = timestamp; + doc.apps[1].platforms['windows-x86_64'].releasedAt = timestamp; + (doc.apps[1].news as { id: string; title: string; text: string; publishedAt: string; kind: string }[]).push({ id: 'windows-news', title: 'Windows news', text: 'Windows only', publishedAt: timestamp, kind: 'new' }); + const text = JSON.stringify(doc); + bridge.fetch.mockImplementation(async (url: string) => ({ ok: true, redirected: false, url, text: async () => text })); + const original = bridge.invoke.getMockImplementation()!; + bridge.invoke.mockImplementation(async (command: string, args?: unknown) => { + if (command === 'platform_key') return 'darwin-aarch64'; + if (command === 'get_settings') return { state: 'ready', settings: { ...defaultSettings, firstRunComplete: true, showNewsOnOpen: true } }; + if (command === 'installed_apps') return [{ id: 'windows-only', state: 'installed', version: '0.1.0' }, { id: 'example-app', state: 'notInstalled', version: null }]; + return original(command, args); + }); + render(); + await screen.findByText('Instaladas'); + await waitFor(() => expect(stored).toBe(text)); + await waitFor(() => expect(bridge.events.has('flyout-visibility')).toBe(true)); + expect(screen.queryByText('Windows Only')).toBeNull(); + expect(screen.queryByRole('button', { name: /Actualizar a v/ })).toBeNull(); + visibility(true); + const dialog = await screen.findByRole('dialog', { name: 'Novedades' }); + expect(within(dialog).getByText('Darwin news')).toBeTruthy(); + expect(within(dialog).queryByText('Windows news')).toBeNull(); + fireEvent.click(within(dialog).getByRole('button', { name: 'Cerrar novedades' })); + selectTab('Catálogo'); + expect(await screen.findByRole('article', { name: 'Example App' })).toBeTruthy(); + expect(screen.queryByRole('article', { name: 'Windows Only' })).toBeNull(); + selectTab('Mis apps'); + fireEvent.click(screen.getByRole('button', { name: 'Actualizar apps' })); + await waitFor(() => expect(bridge.fetch).toHaveBeenCalledTimes(2)); + expect(bridge.invoke.mock.calls.filter(([command]) => command === 'platform_key')).toHaveLength(1); + expect(bridge.fetch.mock.calls.every(([url]) => url === 'https://egdev6.github.io/nexo-catalog/v4/catalog.json')).toBe(true); +}); + it('fetches once on first open, throttles through five minutes, then refreshes in the background', async () => { await start(); expect(bridge.fetch).toHaveBeenCalledTimes(1); @@ -143,7 +181,7 @@ it('retains the visible catalog if a failed refresh cannot read any cache', asyn bridge.fetch.mockRejectedValue(new Error('offline')); visibility(false); now += fiveMinutes + 1; visibility(true); await screen.findByText(/Sin conexión con el catálogo/); - expect(bridge.fetch).toHaveBeenCalledTimes(4); + expect(bridge.fetch).toHaveBeenCalledTimes(2); expect(version()).toContain('1.0.0'); expect(stored).toBeNull(); expect(screen.queryByText('Cargando catálogo…')).toBeNull(); diff --git a/apps/hub/src/catalog/endpoints.test.ts b/apps/hub/src/catalog/endpoints.test.ts index dbde187..2fa5286 100644 --- a/apps/hub/src/catalog/endpoints.test.ts +++ b/apps/hub/src/catalog/endpoints.test.ts @@ -1,15 +1,15 @@ import { describe, expect, it } from 'vitest'; import tauriConfig from '../../src-tauri/tauri.conf.json?raw'; import * as loader from './loader'; -const { OFFICIAL_CATALOG_URL, OFFICIAL_CATALOG_V2_URL } = loader; +const { OFFICIAL_CATALOG_URL } = loader; const ORIGIN = 'https://egdev6.github.io'; describe('official catalog endpoints', () => { it('points at the public catalog published on GitHub Pages', () => { - expect((loader as unknown as Record).OFFICIAL_CATALOG_V3_URL).toBe(`${ORIGIN}/nexo-catalog/v3/catalog.json`); - expect(OFFICIAL_CATALOG_V2_URL).toBe(`${ORIGIN}/nexo-catalog/v2/catalog.json`); - expect(OFFICIAL_CATALOG_URL).toBe(`${ORIGIN}/nexo-catalog/catalog.json`); + expect(OFFICIAL_CATALOG_URL).toBe(`${ORIGIN}/nexo-catalog/v4/catalog.json`); + expect(loader).not.toHaveProperty('OFFICIAL_CATALOG_V2_URL'); + expect(loader).not.toHaveProperty('OFFICIAL_CATALOG_V3_URL'); }); it('limits the webview to the catalog origin for fetches and images', () => { diff --git a/apps/hub/src/catalog/format.test.ts b/apps/hub/src/catalog/format.test.ts index 5bd7231..871fcca 100644 --- a/apps/hub/src/catalog/format.test.ts +++ b/apps/hub/src/catalog/format.test.ts @@ -2,7 +2,9 @@ import { describe, expect, it } from 'vitest'; import full from '../../../../crates/nexo-catalog/fixtures/full.json'; import minimal from '../../../../crates/nexo-catalog/fixtures/minimal.json'; import parity from '../../../../crates/nexo-catalog/fixtures/parity.json'; -import { parseCatalog } from './format'; +import v4 from '../../../../crates/nexo-catalog/fixtures/v4.json'; +import parityV4 from '../../../../crates/nexo-catalog/fixtures/parity-v4.json'; +import { parseCatalog, parseCatalogV4, projectCatalogV4 } from './format'; import { projectCatalog } from './mapping'; const copy = () => structuredClone(full); @@ -63,8 +65,8 @@ describe('catalog format v1', () => { }); type ParityCase = { name: string; base: string; valid: boolean; patches?: { op: string; path: string; value?: unknown }[] }; -function parityDocument(test: ParityCase): unknown { - const document: Record = structuredClone(test.base === 'full' ? full : test.base === 'minimal' ? minimal : { schemaVersion: 1, apps: [] }); +function parityDocument(test: ParityCase, base?: unknown): unknown { + const document = structuredClone(base ?? (test.base === 'full' ? full : test.base === 'minimal' ? minimal : { schemaVersion: 1, apps: [] })) as Record; for (const patch of test.patches ?? []) { const keys = patch.path.split('/').slice(1); const parent = keys.slice(0, -1).reduce((value, key) => (value as Record)[key], document as unknown) as Record; @@ -84,6 +86,32 @@ it.each(parity.cases as ParityCase[])('matches shared Rust validation and catalo else expect(() => parseCatalog(document)).toThrow(); }); +it.each(parityV4.cases)('v4 shared validation: $name', test => { + const document = parityDocument({ ...test, base: 'v4' }, v4); + if (test.valid) expect(parseCatalogV4(document)).toEqual(document); + else expect(() => parseCatalogV4(document)).toThrow('Invalid catalog'); +}); + +it.each(Object.entries(parityV4.projections))('v4 shared projection for %s', (platform, expected) => { + expect(projectCatalogV4(parseCatalogV4(v4), platform)).toEqual(expected); +}); + +it('v4 shared projection hides all apps for an unsupported platform', () => { + expect(projectCatalogV4(parseCatalogV4(v4), null)).toEqual({ schemaVersion: 4, apps: [] }); +}); + +it('v4 applies common and detection validation to every platform', () => { + for (const patch of [ + { op: 'add', path: '/unknown', value: true }, + { op: 'add', path: '/apps/0/detection', value: {} }, + { op: 'add', path: '/apps/0/platforms/windows-x86_64/detection/extra', value: true }, + { op: 'set', path: '/apps/0/platforms/windows-x86_64/detection/executableRelativePath', value: '../escape.exe' }, + { op: 'duplicate', path: '/apps/0/news' }, + { op: 'set', path: '/apps/0/news/0/publishedAt', value: '2025-02-29T00:00:00Z' }, + { op: 'add', path: '/apps/0/platforms/windows-x86_64\n', value: v4.apps[0].platforms['windows-x86_64'] }, + ]) expect(() => parseCatalogV4(parityDocument({ name: patch.path, base: 'v4', valid: false, patches: [patch] }, v4)), patch.path).toThrow('Invalid catalog'); +}); + it('accepts only Tauri-encoded minisign public keys in v3', () => { const doc = copy(); doc.schemaVersion = 3; doc.apps[0].installerUrl = 'https://github.com/egdev6/example/releases/download/v1/setup.exe'; @@ -120,3 +148,9 @@ it('uses only observed installation data and maps installed capabilities indepen const inherited = copy(); inherited.apps[0].id = 'constructor'; expect(projectCatalog(parseCatalog(inherited)).apps[0].statusKnown).toBe(false); }); + +it('leaves the NSIS installer rule to native selection, like Rust, so one entry cannot reject the whole v4 catalog', () => { + const doc = structuredClone(v4) as typeof v4; + doc.apps[0].platforms['windows-x86_64'].installerUrl = 'https://github.com/egdev6/example/releases/download/v1.2.3/example.msi'; + expect(projectCatalogV4(parseCatalogV4(doc), 'windows-x86_64').apps[0].installerUrl).toMatch(/example\.msi$/); +}); diff --git a/apps/hub/src/catalog/format.ts b/apps/hub/src/catalog/format.ts index 2d94bc4..28e6482 100644 --- a/apps/hub/src/catalog/format.ts +++ b/apps/hub/src/catalog/format.ts @@ -29,7 +29,20 @@ export interface CatalogApp { news: CatalogNews[]; } -export interface Catalog { schemaVersion: 1 | 2 | 3; apps: CatalogApp[] } +export interface Catalog { schemaVersion: 1 | 2 | 3 | 4; apps: CatalogApp[] } + +export interface CatalogPlatform { + installerUrl: string; + latestJsonUrl: string; + version: string; + releasedAt: string; + updaterPublicKey?: string; + detection?: NonNullable['windows']; +} +export interface CatalogV4 { + schemaVersion: 4; + apps: (Omit & { platforms: Record })[]; +} function fail(): never { throw new Error('Invalid catalog'); } function record(value: unknown, required: string[], optional: string[] = []): Record { @@ -168,3 +181,41 @@ export function parseCatalog(value: unknown): Catalog { } return value as Catalog; } + +/** Validate every v4 platform before projecting or caching the wire document. */ +export function parseCatalogV4(value: unknown): CatalogV4 { + const root = record(value, ['schemaVersion', 'apps']); + if (root.schemaVersion !== 4 || !Array.isArray(root.apps)) return fail(); + const ids = new Set(); + for (const entry of root.apps) { + const app = record(entry, ['id', 'name', 'tagline', 'description', 'tags', 'integrationLevel', 'featured', 'news', 'platforms'], ['iconUrl', 'artUrl', 'links']); + if (ids.has(app.id as string)) fail(); + ids.add(app.id as string); + const { platforms, ...common } = app; + if (typeof platforms !== 'object' || platforms === null || Array.isArray(platforms)) return fail(); + const entries = Object.entries(platforms); + if (!entries.length) fail(); + for (const [key, value] of entries) { + const match = /^(windows|darwin|linux)-(x86_64|aarch64|i686|armv7)$/.exec(key); + if (!match || match[0] !== key) fail(); + const platform = record(value, ['installerUrl', 'latestJsonUrl', 'version', 'releasedAt'], ['updaterPublicKey', 'detection']); + if (Object.hasOwn(platform, 'detection') && !key.startsWith('windows-')) fail(); + const { detection, ...fields } = platform; + const flat = { ...common, ...fields, ...(Object.hasOwn(platform, 'detection') ? { detection: { windows: detection } } : {}) }; + // Reuse the existing release-asset, key, timestamp, detection and common-field rules. + parseCatalog({ schemaVersion: 3, apps: [flat] }); + } + } + return value as CatalogV4; +} + +/** Project only the selected platform into the flat catalog consumed by the hub. */ +export function projectCatalogV4(catalog: CatalogV4, platformKey: string | null): Catalog { + const apps: CatalogApp[] = []; + if (platformKey !== null) for (const { platforms, ...common } of catalog.apps) { + if (!Object.hasOwn(platforms, platformKey)) continue; + const { detection, ...fields } = platforms[platformKey]; + apps.push({ ...common, ...fields, ...(detection === undefined ? {} : { detection: { windows: detection } }) }); + } + return { schemaVersion: 4, apps }; +} diff --git a/apps/hub/src/catalog/index.test.tsx b/apps/hub/src/catalog/index.test.tsx index 7ae8b15..486bcda 100644 --- a/apps/hub/src/catalog/index.test.tsx +++ b/apps/hub/src/catalog/index.test.tsx @@ -197,7 +197,7 @@ it('shows an error without pretending an uncached catalog is empty', () => { it.each([ ['es', 'Instalar Pizarra', 'No se puede comprobar si ya está instalada'], ['en', 'Install Pizarra', 'Cannot check whether it is already installed.'], -] as const)('explains unknown installation in %s and still requires an official v3 catalog', (locale, label, reason) => { +] as const)('explains unknown installation in %s and still requires an up-to-date official catalog', (locale, label, reason) => { native.locale = locale; render(); const card = screen.getByRole('article', { name: 'Pizarra' }); @@ -205,15 +205,15 @@ it.each([ expect(button.disabled).toBe(true); const warning = within(card).getByText(reason); expect(button.getAttribute('aria-describedby')?.split(/\s+/)).toContain(warning.id); - expect(within(card).getByText(locale === 'es' ? 'La instalación requiere un catálogo oficial v3.' : 'Installation requires an official v3 catalog.')).toBeTruthy(); + expect(within(card).getByText(locale === 'es' ? 'Actualiza el catálogo oficial antes de instalar.' : 'Refresh the official catalog before installing.')).toBeTruthy(); fireEvent.click(button); expect(native.invoke).not.toHaveBeenCalled(); }); -it('does not enable official installation without a validated v3 catalog', () => { +it('does not enable official installation without a validated v4 catalog', () => { render(); expect((screen.getByRole('button', { name: 'Instalar Pizarra' }) as HTMLButtonElement).disabled).toBe(true); - expect(screen.getByText('La instalación requiere un catálogo oficial v3.')).toBeTruthy(); + expect(screen.getByText('Actualiza el catálogo oficial antes de instalar.')).toBeTruthy(); }); it('preserves the disabled official install action alongside discovery links', () => { diff --git a/apps/hub/src/catalog/index.tsx b/apps/hub/src/catalog/index.tsx index e1d3ef4..e6b6297 100644 --- a/apps/hub/src/catalog/index.tsx +++ b/apps/hub/src/catalog/index.tsx @@ -49,7 +49,7 @@ function CatalogCard({ app, focused = false, reason, installs }: { app: HubApp; function disabledReason(app: HubApp, state: Props['state'], stale: boolean, catalog?: Catalog, installs?: CatalogInstalls): MessageKey | undefined { if (app.installed || app.installationState === 'installed') return 'install.alreadyInstalled'; if (stale || state !== 'ready') return 'install.offline'; - if (catalog?.schemaVersion !== 3) return 'install.v3Required'; + if (catalog?.schemaVersion !== 4) return 'install.catalogUpdateRequired'; if (!catalog.apps.find(item => item.id === app.id)?.updaterPublicKey) return 'install.noKey'; if (!installs || installs.connection !== 'ready') return 'install.progressUnavailable'; return undefined; diff --git a/apps/hub/src/catalog/install/ui.test.tsx b/apps/hub/src/catalog/install/ui.test.tsx index 05cc485..9c6a046 100644 --- a/apps/hub/src/catalog/install/ui.test.tsx +++ b/apps/hub/src/catalog/install/ui.test.tsx @@ -11,7 +11,7 @@ import type { InstallProgress, InstallResult } from './index'; configure({ getElementError: message => new Error(message?.split('\n')[0] ?? 'Element not found') }); const native = vi.hoisted(() => ({ install: vi.fn(), cancel: vi.fn(), listen: vi.fn(), stop: vi.fn(), invoke: vi.fn(), load: vi.fn(), receive: undefined as undefined | ((progress: InstallProgress) => void), locale: 'es' as Language })); vi.mock('./index', () => ({ installApp: native.install, cancelInstall: native.cancel, onInstallProgress: native.listen })); -vi.mock('../loader', async importOriginal => ({ ...(await importOriginal()), loadVersionedCatalog: native.load })); +vi.mock('../loader', async importOriginal => ({ ...(await importOriginal()), loadCatalog: native.load })); vi.mock('@tauri-apps/api/core', () => ({ isTauri: () => true, invoke: native.invoke })); vi.mock('@tauri-apps/api/event', () => ({ listen: vi.fn().mockResolvedValue(() => {}) })); vi.mock('../../settings/use-settings', () => ({ useSettings: () => ({ settings: { ...defaultSettings, language: native.locale, firstRunComplete: true, showNewsOnOpen: false, sources: [] }, fileState: 'ready', languageDraft: null, autostart: {}, recordVisit: vi.fn(), getVisit: () => null }) })); @@ -21,7 +21,7 @@ vi.mock('../../window', () => ({ backdropAvailable: vi.fn().mockResolvedValue(fa vi.mock('../../local-apps/view', () => ({ LocalAppsView: () => null })); const base = { tagline: 'Test', description: 'Test', tags: [], installerUrl: 'https://github.com/egdev6/app/releases/download/v1/setup.exe', latestJsonUrl: 'https://github.com/egdev6/app/releases/download/v1/latest.json', integrationLevel: 'launch' as const, releasedAt: '2025-01-01T00:00:00Z', featured: false, news: [], version: '1.0.0', updaterPublicKey: 'validated-key' }; -const catalog: Catalog = { schemaVersion: 3, apps: [{ ...base, id: 'alfa', name: 'Alfa' }, { ...base, id: 'beta', name: 'Beta' }] }; +const catalog: Catalog = { schemaVersion: 4, apps: [{ ...base, id: 'alfa', name: 'Alfa' }, { ...base, id: 'beta', name: 'Beta' }] }; const app = (id: string, name: string): HubApp => ({ id, name, description: 'Test', installed: false, running: false, integration: 'catalog', source: 'official', statusKnown: true, installationState: 'notInstalled' }); const alfa = app('alfa', 'Alfa'); const beta = app('beta', 'Beta'); const deferred = () => { let resolve!: (value: T) => void; const promise = new Promise(done => { resolve = done; }); return { promise, resolve }; }; @@ -63,9 +63,12 @@ it('preserves the catalog and key gates for official entries, including unknown expect(card('Alfa').getByText('Actualiza el catálogo conectado antes de instalar.')).toBeTruthy(); expect((card('Alfa').getByRole('button', { name: 'Instalar Alfa' }) as HTMLButtonElement).disabled).toBe(true); rerender(); - expect(card('Alfa').getByText('La instalación requiere un catálogo oficial v3.')).toBeTruthy(); + expect(card('Alfa').getByText('Actualiza el catálogo oficial antes de instalar.')).toBeTruthy(); fireEvent.click(card('Alfa').getByRole('button', { name: 'Instalar Alfa' })); expect(native.install).not.toHaveBeenCalled(); + native.locale = 'en'; + rerender(); + expect(card('Alfa').getByText('Refresh the official catalog before installing.')).toBeTruthy(); }); it.each([ diff --git a/apps/hub/src/catalog/install/update-ui.test.tsx b/apps/hub/src/catalog/install/update-ui.test.tsx index 967a237..44e3ab3 100644 --- a/apps/hub/src/catalog/install/update-ui.test.tsx +++ b/apps/hub/src/catalog/install/update-ui.test.tsx @@ -10,7 +10,7 @@ import type { InstallProgress } from './index'; const native = vi.hoisted(() => ({ update: vi.fn(), install: vi.fn(), cancel: vi.fn(), listen: vi.fn(), invoke: vi.fn(), load: vi.fn(), receive: undefined as undefined | ((progress: InstallProgress) => void), publish: undefined as undefined | ((value: unknown) => void), locale: 'es' as Language })); vi.mock('./index', () => ({ updateApp: native.update, installApp: native.install, cancelInstall: native.cancel, onInstallProgress: native.listen })); -vi.mock('../loader', async original => ({ ...(await original()), loadVersionedCatalog: native.load })); +vi.mock('../loader', async original => ({ ...(await original()), loadCatalog: native.load })); vi.mock('@tauri-apps/api/core', () => ({ isTauri: () => true, invoke: native.invoke })); vi.mock('@tauri-apps/api/event', () => ({ listen: vi.fn().mockResolvedValue(() => {}) })); vi.mock('../../settings/use-settings', () => ({ useSettings: () => ({ settings: { ...defaultSettings, language: native.locale, firstRunComplete: true, showNewsOnOpen: false, sources: [] }, fileState: 'ready', languageDraft: null, autostart: {}, recordVisit: vi.fn(), getVisit: () => null }) })); @@ -20,14 +20,14 @@ vi.mock('../../window', () => ({ backdropAvailable: vi.fn().mockResolvedValue(fa vi.mock('../../local-apps/view', () => ({ LocalAppsView: () => null })); const key = btoa(`untrusted comment: key\n${btoa('Ed' + '\x00'.repeat(40))}\n`); -const catalog = (version = '2.0.0'): Catalog => parseCatalog({ schemaVersion: 3, apps: [{ id: 'antena', name: 'Antena', tagline: 'Test', description: 'Test', tags: [], iconUrl: 'https://example.com/icon.png', installerUrl: 'https://github.com/egdev6/antena/releases/download/v2/setup.exe', latestJsonUrl: 'https://github.com/egdev6/antena/releases/download/v2/latest.json', updaterPublicKey: key, integrationLevel: 'full', releasedAt: '2025-01-01T00:00:00Z', featured: false, version, news: [ +const catalog = (version = '2.0.0'): Catalog => ({ ...parseCatalog({ schemaVersion: 3, apps: [{ id: 'antena', name: 'Antena', tagline: 'Test', description: 'Test', tags: [], iconUrl: 'https://example.com/icon.png', installerUrl: 'https://github.com/egdev6/antena/releases/download/v2/setup.exe', latestJsonUrl: 'https://github.com/egdev6/antena/releases/download/v2/latest.json', updaterPublicKey: key, integrationLevel: 'full', releasedAt: '2025-01-01T00:00:00Z', featured: false, version, news: [ { id: 'newer', title: 'New notes', text: 'Plain text', publishedAt: '2025-01-01T10:00:00+01:00', kind: 'update' }, { id: 'older', title: 'Old notes', text: 'Old', publishedAt: '2025-01-01T08:30:00Z', kind: 'update' }, -] }] }); -const unkeyedCatalog = (schemaVersion: 1 | 2 | 3 = 3, version = '2.0.0'): Catalog => { +] }] }), schemaVersion: 4 }); +const unkeyedCatalog = (schemaVersion: 1 | 2 | 3 | 4 = 4, version = '2.0.0'): Catalog => { const result = catalog(version); delete result.apps[0].updaterPublicKey; - return parseCatalog({ ...result, schemaVersion }); + return { ...result, schemaVersion }; }; const installed = (version: string | undefined = '1.0.0'): HubApp => ({ id: 'antena', name: 'Antena', description: 'Test', installed: true, running: false, source: 'official', statusKnown: true, installationState: 'installed', integration: 'complete', version, canOpen: true }); const deferred = () => { let resolve!: (value: T) => void; const promise = new Promise(done => { resolve = done; }); return { promise, resolve }; }; @@ -53,7 +53,7 @@ beforeEach(() => { }); afterEach(cleanup); -it('shows the strictly newer v3 catalog version and latest news as plain text, reevaluating detection and catalog changes', async () => { +it('shows the strictly newer v4 catalog version and latest news as plain text, reevaluating detection and catalog changes', async () => { const { rerender, refresh } = await show(); expect(button()?.textContent).toBe('Actualizar a v2.0.0'); expect(screen.getByText('New notes')).toBeTruthy(); @@ -103,13 +103,13 @@ it('requires a known official installation and labels stale availability without it('distinguishes a verifiable update from newer unkeyed or legacy entries', () => { expect(availableUpdate(installed(), catalog())).toMatchObject({ status: 'available', version: '2.0.0' }); - for (const version of [1, 2, 3] as const) { + for (const version of [1, 2, 3, 4] as const) { expect(availableUpdate(installed(), unkeyedCatalog(version))).toMatchObject({ status: 'unverifiable', version: '2.0.0' }); } expect(availableUpdate(installed(), { ...catalog(), schemaVersion: 2 })).toMatchObject({ status: 'unverifiable', version: '2.0.0' }); }); -it.each([1, 2, 3] as const)('explains an unkeyed v%i version without offering an update in both languages', async schemaVersion => { +it.each([1, 2, 3, 4] as const)('explains an unkeyed v%i version without offering an update in both languages', async schemaVersion => { const fixture = unkeyedCatalog(schemaVersion); const { rerender, refresh } = await show(installed(), { status: 'ready', catalog: fixture }); expect(button()).toBeNull(); @@ -138,7 +138,7 @@ it('labels stale unkeyed updates and explains the missing key in both languages' it('does not show unkeyed updates for equal or older catalog versions', async () => { const { rerender, refresh } = await show(); - for (const schemaVersion of [1, 2, 3] as const) for (const version of ['2.0.0', '2.1.0']) { + for (const schemaVersion of [1, 2, 3, 4] as const) for (const version of ['2.0.0', '2.1.0']) { const fixture = unkeyedCatalog(schemaVersion); expect(availableUpdate(installed(version), fixture)).toBeUndefined(); rerender(); diff --git a/apps/hub/src/catalog/loader.test.ts b/apps/hub/src/catalog/loader.test.ts index cf3bc45..767981a 100644 --- a/apps/hub/src/catalog/loader.test.ts +++ b/apps/hub/src/catalog/loader.test.ts @@ -1,10 +1,12 @@ import { describe, expect, it, vi } from 'vitest'; -import full from '../../../../crates/nexo-catalog/fixtures/full.json'; -import { loadCatalog, loadVersionedCatalog, type CatalogFetcher } from './loader'; +import v4 from '../../../../crates/nexo-catalog/fixtures/v4.json'; +import parity from '../../../../crates/nexo-catalog/fixtures/parity-v4.json'; +import { loadCatalog, type CatalogFetcher } from './loader'; const endpoint = 'https://catalog.example.com/catalog.json'; -const valid = JSON.stringify(full); -const empty = JSON.stringify({ schemaVersion: 1, apps: [] }); +const valid = JSON.stringify(v4); +const empty = JSON.stringify({ schemaVersion: 4, apps: [] }); +const platform = 'windows-x86_64'; function cache(initial: string | null = null) { let stored = initial; return { read: vi.fn(async () => stored), write: vi.fn(async (text: string) => { stored = text; }), value: () => stored }; @@ -13,166 +15,89 @@ function fetchResponse(text: string, options: { ok?: boolean; url?: string; redi return vi.fn(async () => ({ ok: options.ok ?? true, url: options.url ?? endpoint, redirected: options.redirected ?? false, text: async () => text })); } -describe('catalog loader', () => { - it('fetches HTTPS, validates before caching and distinguishes ready from empty', async () => { +describe('v4 catalog loader', () => { + it('fetches once, caches raw v4 and returns the selected platform projection', async () => { const store = cache(); const fetcher = fetchResponse(valid); - expect((await loadCatalog(endpoint, store, fetcher)).status).toBe('ready'); - expect(fetcher).toHaveBeenCalledWith(endpoint, expect.objectContaining({ redirect: 'error', cache: 'no-cache', signal: expect.any(AbortSignal) })); + const result = await loadCatalog(endpoint, store, fetcher, platform); + expect(result).toEqual({ status: 'ready', catalog: parity.projections[platform] }); + expect(fetcher).toHaveBeenCalledExactlyOnceWith(endpoint, expect.objectContaining({ redirect: 'error', cache: 'no-cache', signal: expect.any(AbortSignal) })); + expect(store.write).toHaveBeenCalledExactlyOnceWith(valid); expect(store.value()).toBe(valid); - expect((await loadCatalog(endpoint, store, fetchResponse(empty))).status).toBe('empty'); + expect((await loadCatalog(endpoint, store, fetchResponse(empty), platform)).status).toBe('empty'); expect(store.value()).toBe(empty); }); - it('rejects non-HTTPS endpoints and redirects without replacing the cache', async () => { - const store = cache(valid); const fetcher = fetchResponse(empty); - expect((await loadCatalog('http://example.com/catalog.json', store, fetcher)).status).toBe('error'); - expect(fetcher).not.toHaveBeenCalled(); - for (const options of [{ redirected: true }, { url: 'http://example.com/catalog.json' }, { url: 'https://other.example.com/catalog.json' }]) { - const result = await loadCatalog(endpoint, store, fetchResponse(empty, options)); - expect(result.status).toBe('error'); expect(result.catalog?.apps).toHaveLength(1); expect(store.value()).toBe(valid); - } - }); - it('distinguishes offline from HTTP, malformed and invalid responses, preserving only a valid cache', async () => { - const store = cache(valid); const offline: CatalogFetcher = async () => { throw new Error('offline'); }; - expect((await loadCatalog(endpoint, store, offline)).status).toBe('offline'); - for (const fetcher of [fetchResponse('', { ok: false }), fetchResponse('{'), fetchResponse('{"schemaVersion":3,"apps":[]}')]) { - const result = await loadCatalog(endpoint, store, fetcher); - expect(result.status).toBe('error'); expect(result.catalog?.apps).toHaveLength(1); expect(store.value()).toBe(valid); - } - const corrupt = cache('{broken'); - const failed = await loadCatalog(endpoint, corrupt, offline); - expect(failed.status).toBe('offline'); expect(failed.catalog).toBeUndefined(); expect(corrupt.value()).toBe('{broken'); + it('projects the v4 cache when offline without changing it', async () => { + const store = cache(valid); + const offline: CatalogFetcher = async () => { throw new Error('offline'); }; + expect(await loadCatalog(endpoint, store, offline, 'darwin-aarch64')).toEqual({ status: 'offline', stale: true, catalog: parity.projections['darwin-aarch64'], reason: undefined }); + expect(store.write).not.toHaveBeenCalled(); expect(store.value()).toBe(valid); }); - it('recovers on retry and does not confuse a missing official endpoint with sample data', async () => { + it('returns an empty catalog for a null platform while caching the raw document', async () => { const store = cache(); - expect((await loadCatalog(undefined, store, fetchResponse(valid))).status).toBe('error'); - const offline: CatalogFetcher = async () => { throw new Error('offline'); }; - expect((await loadCatalog(endpoint, store, offline)).status).toBe('offline'); - expect((await loadCatalog(endpoint, store, fetchResponse(valid))).status).toBe('ready'); + expect(await loadCatalog(endpoint, store, fetchResponse(valid), null)).toEqual({ status: 'empty', catalog: { schemaVersion: 4, apps: [] } }); expect(store.value()).toBe(valid); }); - it('never replaces the v1 cache with a v2 feed', async () => { + it('rejects old and invalid responses without replacing the valid v4 cache', async () => { const store = cache(valid); - const result = await loadCatalog(endpoint, store, fetchResponse('{"schemaVersion":2,"apps":[]}')); - expect(result.status).toBe('error'); - expect(result.stale).toBe(true); - expect(result.catalog?.schemaVersion).toBe(1); - expect(store.value()).toBe(valid); + const invalid = structuredClone(v4); invalid.apps[0].platforms['darwin-aarch64']!.version = '1.2'; + for (const text of ['{', JSON.stringify(invalid), ...[1, 2, 3].map(schemaVersion => JSON.stringify({ schemaVersion, apps: [] }))]) { + const result = await loadCatalog(endpoint, store, fetchResponse(text), 'darwin-aarch64'); + expect(result).toEqual({ status: 'error', stale: true, reason: 'response', catalog: parity.projections['darwin-aarch64'] }); + expect(store.write).not.toHaveBeenCalled(); expect(store.value()).toBe(valid); + } }); - it('does not treat a misplaced v1 cache as a v2 cache', async () => { - const loadVersion = loadCatalog as typeof loadCatalog & ((endpoint: string, store: ReturnType, fetcher: CatalogFetcher, timeout: number, version: 1 | 2) => ReturnType); + it('never treats corrupt or old caches as v4', async () => { const offline: CatalogFetcher = async () => { throw new Error('offline'); }; - const result = await loadVersion(endpoint, cache(valid), offline, 100, 2); - expect(result.status).toBe('offline'); - expect(result.catalog).toBeUndefined(); - expect(result.stale).toBe(false); - }); - it('prefers the v2 feed without changing or fetching the v1 feed', async () => { - const v2 = '{"schemaVersion":2,"apps":[]}'; - const v2Store = cache(); const v1Store = cache(valid); - const fetcher = fetchResponse(v2); - const result = await loadVersionedCatalog(endpoint, 'https://v1.example.com/catalog.json', v2Store, v1Store, fetcher); - expect(result.status).toBe('empty'); - expect(result.catalog?.schemaVersion).toBe(2); - expect(fetcher).toHaveBeenCalledTimes(1); - expect(v2Store.value()).toBe(v2); - expect(v1Store.value()).toBe(valid); + for (const text of ['{broken', ...[1, 2, 3].map(schemaVersion => JSON.stringify({ schemaVersion, apps: [] }))]) { + const store = cache(text); + expect(await loadCatalog(endpoint, store, offline, platform)).toEqual({ status: 'offline', catalog: undefined, stale: false, reason: undefined }); + expect(store.write).not.toHaveBeenCalled(); expect(store.value()).toBe(text); + } }); - it('falls back to v1 when v2 has no valid cache and preserves both caches on an invalid response', async () => { - const v2Store = cache(); const v1Store = cache(valid); - const fetcher: CatalogFetcher = async url => ({ ok: true, url, redirected: false, text: async () => url === endpoint ? '{broken' : valid }); - const result = await loadVersionedCatalog(endpoint, 'https://v1.example.com/catalog.json', v2Store, v1Store, fetcher); - expect(result.status).toBe('ready'); - expect(result.catalog?.schemaVersion).toBe(1); - expect(v2Store.value()).toBeNull(); - expect(v1Store.value()).toBe(valid); + it('rejects non-HTTPS endpoints, HTTP errors and redirects without replacing the cache', async () => { + const store = cache(valid); const fetcher = fetchResponse(empty); + expect(await loadCatalog('http://example.com/catalog.json', store, fetcher, platform)).toMatchObject({ status: 'error', reason: 'unconfigured', stale: true }); + expect(fetcher).not.toHaveBeenCalled(); + for (const options of [{ ok: false }, { redirected: true }, { url: 'http://example.com/catalog.json' }, { url: 'https://other.example.com/catalog.json' }]) { + expect(await loadCatalog(endpoint, store, fetchResponse(empty, options), platform)).toMatchObject({ status: 'error', reason: 'response', stale: true, catalog: parity.projections[platform] }); + expect(store.write).not.toHaveBeenCalled(); expect(store.value()).toBe(valid); + } }); - it('marks a valid v2 cache stale on a failed v2 response', async () => { - const v2 = '{"schemaVersion":2,"apps":[]}'; - const v2Store = cache(v2); const v1Store = cache(valid); - const offline: CatalogFetcher = async () => { throw new Error('offline'); }; - const result = await loadVersionedCatalog(endpoint, 'https://v1.example.com/catalog.json', v2Store, v1Store, offline); - expect(result.status).toBe('offline'); expect(result.stale).toBe(true); - expect(result.catalog?.schemaVersion).toBe(2); expect(v2Store.value()).toBe(v2); expect(v1Store.value()).toBe(valid); + it('recovers on retry and reports a cache write failure', async () => { + const store = cache(); const offline: CatalogFetcher = async () => { throw new Error('offline'); }; + expect((await loadCatalog(undefined, store, fetchResponse(valid), platform)).status).toBe('error'); + expect((await loadCatalog(endpoint, store, offline, platform)).status).toBe('offline'); + expect((await loadCatalog(endpoint, store, fetchResponse(valid), platform)).status).toBe('ready'); + store.write.mockRejectedValueOnce(new Error('disk')); + expect(await loadCatalog(endpoint, store, fetchResponse(empty), platform)).toEqual({ status: 'error', reason: 'cache', catalog: { schemaVersion: 4, apps: [] } }); + expect(store.value()).toBe(valid); }); it('does not let an older overlapping response overwrite the newer valid cache', async () => { const store = cache(valid); let resolveFirst!: (response: Awaited>) => void; const firstFetcher: CatalogFetcher = () => new Promise(resolve => { resolveFirst = resolve; }); - const first = loadCatalog(endpoint, store, firstFetcher); + const first = loadCatalog(endpoint, store, firstFetcher, platform); await vi.waitFor(() => expect(resolveFirst).toBeTypeOf('function')); - expect((await loadCatalog(endpoint, store, fetchResponse(empty))).status).toBe('empty'); + expect((await loadCatalog(endpoint, store, fetchResponse(empty), platform)).status).toBe('empty'); resolveFirst({ ok: true, url: endpoint, redirected: false, text: async () => valid }); await first; expect(store.value()).toBe(empty); }); it('serializes overlapping writes that have already started', async () => { - let finishFirst!: () => void; - let stored: string | null = null; - let calls = 0; - const store = { - read: async () => stored, - write: async (text: string) => { - if (++calls === 1) await new Promise(resolve => { finishFirst = resolve; }); - stored = text; - }, - }; - const first = loadCatalog(endpoint, store, fetchResponse(valid)); + let finishFirst!: () => void; let stored: string | null = null; let calls = 0; + const store = { read: async () => stored, write: async (text: string) => { if (++calls === 1) await new Promise(resolve => { finishFirst = resolve; }); stored = text; } }; + const first = loadCatalog(endpoint, store, fetchResponse(valid), platform); await vi.waitFor(() => expect(finishFirst).toBeTypeOf('function')); - const second = loadCatalog(endpoint, store, fetchResponse(empty)); - finishFirst(); - await Promise.all([first, second]); + const second = loadCatalog(endpoint, store, fetchResponse(empty), platform); + finishFirst(); await Promise.all([first, second]); expect(stored).toBe(empty); }); - it('prevents an older v2 failure from starting a later v1 fallback', async () => { - const v2Store = cache(); const v1Store = cache(); - let resolveFirst!: (response: Awaited>) => void; - let requests = 0; - const v1 = 'https://v1.example.com/catalog.json'; - const fetcher: CatalogFetcher = url => { - requests++; - if (requests === 1) return new Promise(resolve => { resolveFirst = resolve; }); - return Promise.resolve({ ok: true, url, redirected: false, text: async () => url === endpoint ? '{broken' : empty }); - }; - const first = loadVersionedCatalog(endpoint, v1, v2Store, v1Store, fetcher); - await vi.waitFor(() => expect(resolveFirst).toBeTypeOf('function')); - expect((await loadVersionedCatalog(endpoint, v1, v2Store, v1Store, fetcher)).status).toBe('empty'); - resolveFirst({ ok: true, url: endpoint, redirected: false, text: async () => '{broken' }); - await first; - expect(requests).toBe(3); - expect(v1Store.value()).toBe(empty); - }); - it('prefers a v3 feed and preserves separate v2 and v1 caches', async () => { - const v3 = '{"schemaVersion":3,"apps":[]}'; - const v3Store = cache(); const v2Store = cache('{"schemaVersion":2,"apps":[]}'); const v1Store = cache(valid); - const loadV3 = loadVersionedCatalog as typeof loadVersionedCatalog & ((v2: string, v1: string, c2: ReturnType, c1: ReturnType, f: CatalogFetcher, v3: string, c3: ReturnType) => ReturnType); - const fetcher = fetchResponse(v3); - const result = await loadV3('https://v2.example.com/catalog.json', 'https://v1.example.com/catalog.json', v2Store, v1Store, fetcher, endpoint, v3Store); - expect(result.status).toBe('empty'); expect(result.catalog?.schemaVersion).toBe(3); - expect(v3Store.value()).toBe(v3); expect(v2Store.value()).toBe('{"schemaVersion":2,"apps":[]}'); expect(v1Store.value()).toBe(valid); - expect(fetcher).toHaveBeenCalledTimes(1); - }); - it('falls back from an invalid v3 response to v2 without replacing any cache', async () => { - const v2 = '{"schemaVersion":2,"apps":[]}'; - const v3Store = cache(); const v2Store = cache(v2); const v1Store = cache(valid); - const fetcher: CatalogFetcher = async url => ({ ok: true, url, redirected: false, text: async () => url === endpoint ? '{broken' : v2 }); - const result = await loadVersionedCatalog('https://v2.example.com/catalog.json', 'https://v1.example.com/catalog.json', v2Store, v1Store, fetcher, endpoint, v3Store); - expect(result.catalog?.schemaVersion).toBe(2); expect(v3Store.value()).toBeNull(); - expect(v2Store.value()).toBe(v2); expect(v1Store.value()).toBe(valid); - }); - it('keeps a stale v3 cache visible rather than silently replacing it with v2', async () => { - const v3 = '{"schemaVersion":3,"apps":[]}'; - const v3Store = cache(v3); const v2Store = cache('{"schemaVersion":2,"apps":[]}'); const v1Store = cache(valid); - const offline: CatalogFetcher = async () => { throw new Error('offline'); }; - const result = await loadVersionedCatalog('https://v2.example.com/catalog.json', 'https://v1.example.com/catalog.json', v2Store, v1Store, offline, endpoint, v3Store); - expect(result.status).toBe('offline'); expect(result.stale).toBe(true); expect(result.catalog?.schemaVersion).toBe(3); - expect(v3Store.value()).toBe(v3); expect(v2Store.value()).toBe('{"schemaVersion":2,"apps":[]}'); expect(v1Store.value()).toBe(valid); - }); it('bounds a fetcher that never resolves and signals its abort', async () => { vi.useFakeTimers(); try { let signal: AbortSignal | undefined; const fetcher: CatalogFetcher = async (_url, options) => { signal = options.signal; return new Promise(() => {}); }; - const pending = loadCatalog(endpoint, cache(), fetcher, 100); + const pending = loadCatalog(endpoint, cache(), fetcher, platform, 100); await vi.advanceTimersByTimeAsync(100); expect((await pending).status).toBe('offline'); expect(signal?.aborted).toBe(true); } finally { vi.useRealTimers(); } diff --git a/apps/hub/src/catalog/loader.ts b/apps/hub/src/catalog/loader.ts index 99b611a..3621ad2 100644 --- a/apps/hub/src/catalog/loader.ts +++ b/apps/hub/src/catalog/loader.ts @@ -1,10 +1,7 @@ import { invoke } from '@tauri-apps/api/core'; -import { isHttpsUrl, parseCatalog, type Catalog } from './format'; +import { isHttpsUrl, parseCatalogV4, projectCatalogV4, type Catalog } from './format'; -// T4: the maintainer sets the stable, reviewed public HTTPS URL after publication. -export const OFFICIAL_CATALOG_URL: string | undefined = 'https://egdev6.github.io/nexo-catalog/catalog.json'; -export const OFFICIAL_CATALOG_V2_URL: string | undefined = 'https://egdev6.github.io/nexo-catalog/v2/catalog.json'; -export const OFFICIAL_CATALOG_V3_URL: string | undefined = 'https://egdev6.github.io/nexo-catalog/v3/catalog.json'; +export const OFFICIAL_CATALOG_URL: string | undefined = 'https://egdev6.github.io/nexo-catalog/v4/catalog.json'; export const CATALOG_TIMEOUT_MS = 8000; export interface CatalogCache { read(): Promise; write(text: string): Promise } @@ -18,15 +15,7 @@ export interface CatalogState { } export const diskCache: CatalogCache = { - read: () => invoke('read_catalog_cache'), - write: text => invoke('write_catalog_cache', { input: text }), -}; -export const diskCacheV2: CatalogCache = { - read: () => invoke('read_catalog_v2_cache'), - write: text => invoke('write_catalog_cache', { input: text }), -}; -export const diskCacheV3: CatalogCache = { - read: () => invoke('read_catalog_v3_cache'), + read: () => invoke('read_catalog_v4_cache'), write: text => invoke('write_catalog_cache', { input: text }), }; export const webFetcher: CatalogFetcher = (url, options) => fetch(url, options); @@ -36,7 +25,6 @@ function endpointIsHttps(endpoint: string): boolean { return isHttpsUrl(endpoint type CacheTransaction = { generation: number; writes: Promise }; const cacheTransactions = new WeakMap(); -const versionedTransactions = new WeakMap(); function beginCacheTransaction(cache: CatalogCache): [CacheTransaction, number] { let transaction = cacheTransactions.get(cache); if (!transaction) { @@ -54,14 +42,13 @@ async function writeCurrent(cache: CatalogCache, transaction: CacheTransaction, } /** Startup/retry transaction. A failed response never replaces the last valid cache. */ -export async function loadCatalog(endpoint: string | undefined, cache: CatalogCache, fetcher: CatalogFetcher, timeoutMs = CATALOG_TIMEOUT_MS, version: 1 | 2 | 3 = 1): Promise { +export async function loadCatalog(endpoint: string | undefined, cache: CatalogCache, fetcher: CatalogFetcher, platformKey: string | null, timeoutMs = CATALOG_TIMEOUT_MS): Promise { const [transaction, generation] = beginCacheTransaction(cache); let previous: Catalog | undefined; try { const text = await cache.read(); if (text !== null) { - const parsed = parseCatalog(JSON.parse(text)); - if (parsed.schemaVersion === version) previous = parsed; + previous = projectCatalogV4(parseCatalogV4(JSON.parse(text)), platformKey); } } catch { /* Missing, corrupt or unavailable caches are not authoritative. */ } if (!endpoint || !endpointIsHttps(endpoint)) return { status: 'error', catalog: previous, stale: !!previous, reason: 'unconfigured' }; @@ -74,8 +61,7 @@ export async function loadCatalog(endpoint: string | undefined, cache: CatalogCa if (!response.ok || response.redirected || !endpointIsHttps(response.url) || new URL(response.url).origin !== new URL(endpoint).origin) throw new InvalidResponse(); const text = await response.text(); let catalog: Catalog; - try { catalog = parseCatalog(JSON.parse(text)); } catch { throw new InvalidResponse(); } - if (catalog.schemaVersion !== version) throw new InvalidResponse(); + try { catalog = projectCatalogV4(parseCatalogV4(JSON.parse(text)), platformKey); } catch { throw new InvalidResponse(); } return { text, catalog }; })(); const timeout = new Promise((_, reject) => { @@ -88,21 +74,3 @@ export async function loadCatalog(endpoint: string | undefined, cache: CatalogCa return { status: error instanceof InvalidResponse ? 'error' : 'offline', catalog: previous, stale: !!previous, reason: error instanceof InvalidResponse ? 'response' : undefined }; } finally { if (timer !== undefined) clearTimeout(timer); } } - -/** Prefer separately configured v3 and v2 feeds/caches; retain v1 for fallback. */ -export async function loadVersionedCatalog( - v2Endpoint: string | undefined, v1Endpoint: string | undefined, - v2Cache: CatalogCache, v1Cache: CatalogCache, fetcher: CatalogFetcher, - v3Endpoint?: string, v3Cache?: CatalogCache, -): Promise { - const generation = (versionedTransactions.get(v1Cache) ?? 0) + 1; - versionedTransactions.set(v1Cache, generation); - if (v3Cache) { - const v3 = await loadCatalog(v3Endpoint, v3Cache, fetcher, CATALOG_TIMEOUT_MS, 3); - if (v3.catalog || versionedTransactions.get(v1Cache) !== generation) return v3; - } - const v2 = await loadCatalog(v2Endpoint, v2Cache, fetcher, CATALOG_TIMEOUT_MS, 2); - if (v2.catalog || versionedTransactions.get(v1Cache) !== generation) return v2; - const v1 = await loadCatalog(v1Endpoint, v1Cache, fetcher); - return v1.catalog || v1Endpoint || !v2Endpoint ? v1 : v2; -} diff --git a/apps/hub/src/catalog/update.ts b/apps/hub/src/catalog/update.ts index e7b397a..4bdcd1a 100644 --- a/apps/hub/src/catalog/update.ts +++ b/apps/hub/src/catalog/update.ts @@ -7,6 +7,6 @@ export function availableUpdate(app: HubApp, catalog?: Catalog) { if (app.source !== 'official' || app.statusKnown !== true || !app.installed || app.installationState !== 'installed' || !catalog) return undefined; const item = catalog.apps.find(candidate => candidate.id === app.id); if (!item?.version || compareSemver(app.version, item.version) !== -1) return undefined; - const status = catalog.schemaVersion === 3 && item.updaterPublicKey ? 'available' as const : 'unverifiable' as const; + const status = catalog.schemaVersion === 4 && item.updaterPublicKey ? 'available' as const : 'unverifiable' as const; return { status, version: item.version, notes: latestCatalogNews(item.news) }; } diff --git a/apps/hub/src/i18n/messages.json b/apps/hub/src/i18n/messages.json index 06e0e2b..e948260 100644 --- a/apps/hub/src/i18n/messages.json +++ b/apps/hub/src/i18n/messages.json @@ -32,7 +32,7 @@ "install": { "confirm": { "title": "Confirmar instalación", "body": "¿Descargar e instalar {app}, versión {version}, desde {host}?", "unknownWarning": "Nexo no puede comprobar si la app ya está instalada." }, "installFor": "Instalar {name}", "retryFor": "Reintentar {name}", "cancel": "Cancelar", "cancelFor": "Cancelar {name}", "downloadFor": "Descarga de {name}", "percent": "{percent} %", - "alreadyInstalled": "La app ya está instalada.", "unknown": "No se puede comprobar si ya está instalada", "installedUnverified": "Instalada; Nexo no puede verificarlo", "offline": "Actualiza el catálogo conectado antes de instalar.", "v3Required": "La instalación requiere un catálogo oficial v3.", "noKey": "Falta la clave de verificación de esta app.", "progressUnavailable": "No se puede seguir el progreso de instalación. Reintenta la conexión.", "cancelUnavailable": "La instalación ya ha comenzado; no se puede cancelar.", + "alreadyInstalled": "La app ya está instalada.", "unknown": "No se puede comprobar si ya está instalada", "installedUnverified": "Instalada; Nexo no puede verificarlo", "offline": "Actualiza el catálogo conectado antes de instalar.", "catalogUpdateRequired": "Actualiza el catálogo oficial antes de instalar.", "noKey": "Falta la clave de verificación de esta app.", "progressUnavailable": "No se puede seguir el progreso de instalación. Reintenta la conexión.", "cancelUnavailable": "La instalación ya ha comenzado; no se puede cancelar.", "phase": { "fetching": "Consultando catálogo…", "awaitingApproval": "Esperando confirmación…", "downloading": "Descargando…", "verifying": "Verificando…", "closing": "Cerrando app…", "installing": "Instalando…", "detecting": "Comprobando instalación…" }, "error": { "urlNotAllowed": "La URL del instalador no está permitida. Actualiza el catálogo.", "hostNotAllowed": "La redirección de descarga no está permitida. Actualiza el catálogo.", "redirectLimit": "La descarga tuvo demasiadas redirecciones. Reintenta más tarde.", "networkFailed": "Falló la descarga. Comprueba la conexión y reintenta.", "connectTimedOut": "Se agotó el tiempo de conexión. Comprueba la conexión y reintenta.", "downloadTimedOut": "Se agotó el tiempo de descarga. Comprueba la conexión y reintenta.", "tooLarge": "El archivo de instalación supera el tamaño permitido. Actualiza el catálogo.", "lengthMismatch": "La descarga está incompleta o tiene un tamaño inesperado. Reintenta.", "storageFailed": "No se pudieron guardar o leer los archivos temporales. Comprueba el espacio y los permisos.", "keyMissing": "Falta la clave de verificación. Actualiza el catálogo.", "keyInvalid": "La clave de verificación no es válida. Actualiza el catálogo.", "signatureMalformed": "La firma del instalador no tiene un formato válido. Actualiza el catálogo.", "signatureUnsupported": "La firma del instalador usa un formato no admitido. Actualiza el catálogo.", "signatureInvalid": "No se pudo verificar la firma del instalador. No se ha ejecutado.", "assetNotAllowed": "Este instalador no es compatible. Actualiza el catálogo.", @@ -75,7 +75,7 @@ "install": { "confirm": { "title": "Confirm installation", "body": "Download and install {app} version {version} from {host}?", "unknownWarning": "Nexo cannot check whether the app is already installed." }, "installFor": "Install {name}", "retryFor": "Retry {name}", "cancel": "Cancel", "cancelFor": "Cancel {name}", "downloadFor": "Download of {name}", "percent": "{percent} %", - "alreadyInstalled": "The app is already installed.", "unknown": "Cannot check whether it is already installed.", "installedUnverified": "Installed; Nexo cannot verify it", "offline": "Refresh the online catalog before installing.", "v3Required": "Installation requires an official v3 catalog.", "noKey": "This app has no verification key.", "progressUnavailable": "Installation progress is unavailable. Retry the connection.", "cancelUnavailable": "Installation has started and cannot be cancelled.", + "alreadyInstalled": "The app is already installed.", "unknown": "Cannot check whether it is already installed.", "installedUnverified": "Installed; Nexo cannot verify it", "offline": "Refresh the online catalog before installing.", "catalogUpdateRequired": "Refresh the official catalog before installing.", "noKey": "This app has no verification key.", "progressUnavailable": "Installation progress is unavailable. Retry the connection.", "cancelUnavailable": "Installation has started and cannot be cancelled.", "phase": { "fetching": "Checking catalog…", "awaitingApproval": "Waiting for confirmation…", "downloading": "Downloading…", "verifying": "Verifying…", "closing": "Closing app…", "installing": "Installing…", "detecting": "Checking installation…" }, "error": { "urlNotAllowed": "The installer URL is not allowed. Refresh the catalog.", "hostNotAllowed": "The download redirect is not allowed. Refresh the catalog.", "redirectLimit": "The download had too many redirects. Retry later.", "networkFailed": "The download failed. Check the connection and retry.", "connectTimedOut": "The connection timed out. Check the connection and retry.", "downloadTimedOut": "The download timed out. Check the connection and retry.", "tooLarge": "The installation file exceeds the allowed size. Refresh the catalog.", "lengthMismatch": "The download is incomplete or has an unexpected size. Retry.", "storageFailed": "Could not save or read temporary files. Check disk space and permissions.", "keyMissing": "The verification key is missing. Refresh the catalog.", "keyInvalid": "The verification key is invalid. Refresh the catalog.", "signatureMalformed": "The installer signature has an invalid format. Refresh the catalog.", "signatureUnsupported": "The installer signature uses an unsupported format. Refresh the catalog.", "signatureInvalid": "The installer signature could not be verified. It was not run.", "assetNotAllowed": "This installer is not supported. Refresh the catalog.", diff --git a/apps/hub/src/local-apps/isolation.test.tsx b/apps/hub/src/local-apps/isolation.test.tsx index 692d8c5..00089d4 100644 --- a/apps/hub/src/local-apps/isolation.test.tsx +++ b/apps/hub/src/local-apps/isolation.test.tsx @@ -3,7 +3,8 @@ import { cleanup, render, waitFor } from '@testing-library/react'; import { afterEach, beforeEach, expect, it, vi } from 'vitest'; import full from '../../../../crates/nexo-catalog/fixtures/full.json'; import App from '../App'; -import { parseCatalog } from '../catalog/format'; +import { parseCatalogV4, projectCatalogV4 } from '../catalog/format'; +import { windowsCatalog } from '../test-helpers/catalog-v4'; import { projectCatalog } from '../catalog/mapping'; import { selectOfficialNews } from '../news/selection'; import { listLocalApps } from './index'; @@ -18,7 +19,8 @@ vi.mock('../news/selection', async importOriginal => { return { ...original, selectOfficialNews: vi.fn(original.selectOfficialNews) }; }); -const official = { ...full, schemaVersion: 2 as const }; +const official = windowsCatalog(full.apps); +const officialProjected = projectCatalogV4(parseCatalogV4(official), 'windows-x86_64'); const officialText = JSON.stringify(official); const secrets = ['PRIVATE_APP_NAME', 'C:\\Secret\\Work.exe', 'C:\\Secret\\private.json', 'icon-private.png', 'PRIVATE_NEWS_TITLE', 'https://private.example/icon.png']; const localDocument = { ...official, apps: [{ ...official.apps[0], name: secrets[0], iconUrl: secrets[5], news: [{ ...official.apps[0].news[0], title: secrets[4] }] }] }; @@ -37,7 +39,8 @@ beforeEach(() => { localApps: [{ id: 'manual', name: secrets[0], executable: secrets[1], icon: secrets[3] }], localBindings: [{ sourceId: 'private', appId: 'example-app', executable: secrets[1] }], } }; - if (command === 'read_catalog_cache' || command === 'read_catalog_v2_cache') return null; + if (command === 'platform_key') return 'windows-x86_64'; + if (command === 'read_catalog_v4_cache') return null; if (command === 'write_catalog_cache') { officialCache = args?.input ?? null; return; } if (command === 'installed_apps') return []; if (command === 'local_apps_list') return [ @@ -52,10 +55,10 @@ beforeEach(() => { afterEach(() => { cleanup(); document.documentElement.lang = previousLanguage; vi.unstubAllGlobals(); }); it('leaves the official projection byte-identical when there are no local rows', async () => { - const before = JSON.stringify(projectCatalog(parseCatalog(official))); + const before = JSON.stringify(projectCatalog(officialProjected)); bridge.invoke.mockResolvedValueOnce([]); expect(await listLocalApps()).toEqual([]); - expect(JSON.stringify(projectCatalog(parseCatalog(official)))).toBe(before); + expect(JSON.stringify(projectCatalog(officialProjected))).toBe(before); }); it('keeps manual records and legacy metadata out of News inputs, requests and official cache writes', async () => { @@ -67,23 +70,19 @@ it('keeps manual records and legacy metadata out of News inputs, requests and of await waitFor(() => expect(selectOfficialNews).toHaveBeenCalled()); for (const [input] of vi.mocked(selectOfficialNews).mock.calls) { - expect(input).toEqual(official); + expect(input).toEqual(officialProjected); expect(input).not.toEqual(localDocument); } - const projected = projectCatalog(parseCatalog(official)); + const projected = projectCatalog(officialProjected); expect(JSON.stringify(projected)).not.toContain(secrets[0]); - // The loader may try the v3 endpoint before falling back to v2; every request must - // target an official endpoint with redirects refused, and none may carry local data. - const officialEndpoints = [ - 'https://egdev6.github.io/nexo-catalog/v3/catalog.json', - 'https://egdev6.github.io/nexo-catalog/v2/catalog.json', - ]; + // Only the v4 endpoint is requested, with redirects refused and no local data. + const officialEndpoints = ['https://egdev6.github.io/nexo-catalog/v4/catalog.json']; expect(fetcher).toHaveBeenCalled(); for (const [url, options] of fetcher.mock.calls) { expect(officialEndpoints).toContain(url); expect(options).toMatchObject({ redirect: 'error' }); } - expect(fetcher.mock.calls.map(([url]) => url)).toContain(officialEndpoints[1]); + expect(fetcher.mock.calls.map(([url]) => url)).toEqual(officialEndpoints); expect(officialCache).toBe(officialText); const outbound = JSON.stringify({ requests: fetcher.mock.calls, ipc: bridge.invoke.mock.calls, newsInputs: vi.mocked(selectOfficialNews).mock.calls, cache: officialCache }); for (const secret of secrets) expect(outbound).not.toContain(JSON.stringify(secret).slice(1, -1)); diff --git a/apps/hub/src/mis-apps.test.tsx b/apps/hub/src/mis-apps.test.tsx index 51b6056..3d4a68a 100644 --- a/apps/hub/src/mis-apps.test.tsx +++ b/apps/hub/src/mis-apps.test.tsx @@ -25,7 +25,7 @@ vi.mock('./window', () => ({ backdropAvailable: vi.fn().mockResolvedValue(false) const official: HubApp = { id: 'official', name: 'Official', description: 'Official app', source: 'official', integration: 'complete', installed: true, running: false, statusKnown: true, installationState: 'installed', canOpen: true, version: '1.0.0', links: { github: 'https://github.com/egdev6/official', youtube: 'https://www.youtube.com/@egdev' } }; const connected: HubApp = { ...official, id: 'plugin', name: 'Plugin', links: { github: 'https://github.com/other/plugin' } }; -const catalog: Catalog = { schemaVersion: 3, apps: [official, connected].map(app => ({ id: app.id, name: app.name, tagline: '', description: '', tags: [], installerUrl: 'https://github.com/egdev6/official/setup.exe', latestJsonUrl: 'https://github.com/egdev6/official/latest.json', integrationLevel: 'full' as const, releasedAt: '2025-01-01T00:00:00Z', featured: false, news: [], version: '2.0.0', updaterPublicKey: 'key' })) }; +const catalog: Catalog = { schemaVersion: 4, apps: [official, connected].map(app => ({ id: app.id, name: app.name, tagline: '', description: '', tags: [], installerUrl: 'https://github.com/egdev6/official/setup.exe', latestJsonUrl: 'https://github.com/egdev6/official/latest.json', integrationLevel: 'full' as const, releasedAt: '2025-01-01T00:00:00Z', featured: false, news: [], version: '2.0.0', updaterPublicKey: 'key' })) }; const rows = [{ id: 'local:manual:1', source: 'local', name: 'Local One', state: 'missingExecutable', executable: 'C:\\Apps\\Local.exe', origin: { kind: 'manual', id: 'one' }, duplicateOf: 'official' }]; const absent: HubApp = { ...official, id: 'pizarra', name: 'Pizarra', installed: false, installationState: 'notInstalled' }; const card = (name: string) => within(screen.getByText(name).closest('.app-card') as HTMLElement); diff --git a/apps/hub/src/news/real-data.test.tsx b/apps/hub/src/news/real-data.test.tsx index 7546d64..a21a2f1 100644 --- a/apps/hub/src/news/real-data.test.tsx +++ b/apps/hub/src/news/real-data.test.tsx @@ -2,7 +2,8 @@ import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; import { afterEach, beforeAll, beforeEach, expect, it, vi } from 'vitest'; import App, { FlyoutPanel } from '../App'; -import { parseCatalog } from '../catalog/format'; +import { parseCatalogV4, projectCatalogV4 } from '../catalog/format'; +import { windowsCatalog } from '../test-helpers/catalog-v4'; import { selectOfficialNews } from './selection'; const bridge = vi.hoisted(() => ({ invoke: vi.fn(), listeners: new Map void>() })); @@ -15,8 +16,6 @@ vi.mock('@tauri-apps/api/event', () => ({ listen: vi.fn(async (name: string, cal vi.mock('../catalog/loader', async importOriginal => ({ ...(await importOriginal()), OFFICIAL_CATALOG_URL: undefined, - OFFICIAL_CATALOG_V2_URL: undefined, - OFFICIAL_CATALOG_V3_URL: undefined, })); vi.mock('@tauri-apps/api/window', () => ({ getCurrentWindow: () => ({ hide: vi.fn() }) })); vi.mock('../shell/registry', () => ({ subscribeRegistry: vi.fn().mockResolvedValue(() => {}), exitHubOnly: vi.fn() })); @@ -30,11 +29,10 @@ function app(id: string, releasedAt: string, featured = false, news: Entry[] = [ return { id, name: id, tagline: `Tag ${id}`, description: `Descripción ${id}`, tags: [], iconUrl: 'https://example.com/icon.png', installerUrl: 'https://example.com/setup.exe', latestJsonUrl: 'https://example.com/latest.json', integrationLevel: 'launch', releasedAt, featured, news }; } -function catalog(apps: ReturnType[]) { return JSON.stringify({ schemaVersion: 1, apps }); } +function catalog(apps: ReturnType[]) { return JSON.stringify(windowsCatalog(apps)); } const official = { id: 'official', label: 'Catálogo oficial egdev', kind: 'official' }; let stored: Record; let cache: string | null; -let cacheV3: string | null; let failSave: boolean; let sequence: number; let cycle: number; @@ -44,15 +42,15 @@ beforeEach(() => { vi.setSystemTime(new Date(today)); stored = { language: 'es', startWithWindows: false, showNewsOnOpen: true, accent: '#ff0036', compact: false, opacity: 85, blur: 24, firstRunComplete: true, sources: [official, { id: 'local', label: 'Local', kind: 'local' }] }; - cache = null; cacheV3 = null; failSave = false; sequence = 0; cycle = 0; bridge.listeners.clear(); bridge.invoke.mockReset(); + cache = null; failSave = false; sequence = 0; cycle = 0; bridge.listeners.clear(); bridge.invoke.mockReset(); bridge.invoke.mockImplementation(async (command: string, args?: { patch?: Record }) => { if (command === 'get_settings') return { state: 'ready', settings: structuredClone(stored) }; if (command === 'save_settings') { if (failSave) throw new Error('disco lleno'); stored = { ...stored, ...args?.patch }; return structuredClone(stored); } - if (command === 'read_catalog_cache') return cache; - if (command === 'read_catalog_v3_cache') return cacheV3; + if (command === 'platform_key') return 'windows-x86_64'; + if (command === 'read_catalog_v4_cache') return cache; if (command === 'get_flyout_state') return { visible: false, sequence: 0, cycle: 0 }; if (command === 'plugin:autostart|is_enabled' || command === 'backdrop_available') return false; if (command === 'local_apps_list') return []; @@ -63,7 +61,7 @@ afterEach(() => { cleanup(); vi.useRealTimers(); }); async function start() { render(); await screen.findByText('Instaladas'); - await waitFor(() => expect(bridge.invoke).toHaveBeenCalledWith('read_catalog_cache')); + await waitFor(() => expect(bridge.invoke).toHaveBeenCalledWith('read_catalog_v4_cache')); } function visibility(visible: boolean) { sequence++; if (visible) cycle++; @@ -73,7 +71,7 @@ async function open() { visibility(true); return screen.findByRole('dialog', { n function titles(dialog: HTMLElement) { return Array.from(dialog.querySelectorAll('.news-slide h3'), node => node.textContent); } function close() { fireEvent.click(screen.getByRole('button', { name: 'Cerrar novedades' })); } -it('opens the real-shaped v3 updates newest first and navigates both detected and unknown apps', async () => { +it('opens the real-shaped v4 updates newest first and navigates both detected and unknown apps', async () => { const timestamp = '2026-11-16T12:00:00Z'; vi.setSystemTime(new Date(timestamp)); const catalogApp = (id: string, name: string, version: string, date: string, featured: boolean) => ({ @@ -84,10 +82,10 @@ it('opens the real-shaped v3 updates newest first and navigates both detected an integrationLevel: 'update', releasedAt: date, featured, version, news: [{ id: `v${version.replaceAll('.', '-')}`, title: `${name} ${version}`, text: `A new ${name} release is available.`, publishedAt: date, kind: 'update' }], }); - cacheV3 = JSON.stringify({ schemaVersion: 3, apps: [ + cache = JSON.stringify(windowsCatalog([ { ...catalogApp('antena', 'Antena', '0.15.0', '2026-11-14T08:48:36Z', true), detection: { windows: { displayName: 'antena', publisher: 'EGDEV', executableRelativePath: 'antena.exe' } } }, catalogApp('quorb', 'Quorb', '0.8.0', '2026-10-28T14:55:56Z', false), - ] }); + ])); const invoke = bridge.invoke.getMockImplementation()!; bridge.invoke.mockImplementation(async (command: string, args?: unknown) => command === 'installed_apps' ? [ { id: 'antena', state: 'installed', version: '0.15.0', reason: 'Instalación detectada', canOpen: true }, @@ -221,7 +219,7 @@ it.each(['scrim', 'Escape', 'close', 'catalog'] as const)('clears background blu it('freezes the selected catalog news until the next show when the selection changes', async () => { const first = entry('first', '2026-05-31T11:00:00Z'); const second = app('two', '2026-05-30T00:00:00Z', false, [entry('second', '2026-05-30T00:00:00Z', 'update')]); - const select = (apps: ReturnType[]) => selectOfficialNews(parseCatalog(JSON.parse(catalog(apps))), Date.parse(today)).items; + const select = (apps: ReturnType[]) => selectOfficialNews(projectCatalogV4(parseCatalogV4(JSON.parse(catalog(apps))), 'windows-x86_64'), Date.parse(today)).items; const initial = select([app('one', '2026-05-30T00:00:00Z', false, [first]), second]); const changed = select([ app('one', '2026-05-30T00:00:00Z', false, [first, entry('replacement', '2026-05-31T11:30:00Z', 'update')]), @@ -318,7 +316,7 @@ it('opens late cached data only while visible and does not reopen after dismissa let resolve!: (value: string) => void; const deferred = new Promise(done => { resolve = done; }); const normal = bridge.invoke.getMockImplementation()!; - bridge.invoke.mockImplementation(async (command: string, args?: unknown) => command === 'read_catalog_cache' ? deferred : normal(command, args)); + bridge.invoke.mockImplementation(async (command: string, args?: unknown) => command === 'read_catalog_v4_cache' ? deferred : normal(command, args)); await start(); visibility(true); expect(screen.queryByRole('dialog')).toBeNull(); await act(async () => { resolve(catalog([app('late', today)])); }); await screen.findByRole('dialog', { name: 'Novedades' }); close(); diff --git a/apps/hub/src/test-helpers/catalog-v4.ts b/apps/hub/src/test-helpers/catalog-v4.ts new file mode 100644 index 0000000..3e3634f --- /dev/null +++ b/apps/hub/src/test-helpers/catalog-v4.ts @@ -0,0 +1,24 @@ +type FlatTestApp = { + id: string; + installerUrl: string; + latestJsonUrl: string; + releasedAt: string; + version?: string; + updaterPublicKey?: string; + detection?: { windows: { displayName: string; publisher: string; executableRelativePath: string } }; +}; + +/** Convert existing UI test data into a valid Windows v4 wire document. */ +export function windowsCatalog(apps: T[]) { + return { schemaVersion: 4 as const, apps: apps.map(app => { + const { installerUrl, latestJsonUrl, releasedAt, version, updaterPublicKey, detection, ...common } = app; + void installerUrl; void latestJsonUrl; + return { ...common, platforms: { 'windows-x86_64': { + installerUrl: `https://github.com/egdev6/${app.id}/releases/download/v1/${app.id}_x64-setup.exe`, + latestJsonUrl: `https://github.com/egdev6/${app.id}/releases/download/v1/latest.json`, + version: version ?? '1.0.0', releasedAt, + ...(updaterPublicKey === undefined ? {} : { updaterPublicKey }), + ...(detection === undefined ? {} : { detection: detection.windows }), + } } }; + }) }; +} From 2672ce08696147c5abbbe85b62ead710471317ed Mon Sep 17 00:00:00 2001 From: egdev6 Date: Sat, 21 Nov 2026 15:58:24 +0100 Subject: [PATCH 5/9] docs(catalog): document catalog v4 as the format Nexo 0.2.0 reads --- docs/catalog.md | 216 ++++++++++++++++++---------------------- odd/tasks/catalog-v4.md | 1 + 2 files changed, 100 insertions(+), 117 deletions(-) diff --git a/docs/catalog.md b/docs/catalog.md index 7c05f55..cab9405 100644 --- a/docs/catalog.md +++ b/docs/catalog.md @@ -1,136 +1,118 @@ -# Official catalog v1, v2 and v3 +# Official catalog v4 -The catalog is a maintainer-curated **allowlist**, not repository discovery: an app appears as an -official app only when the public catalog contains it. The maintainer reviews public status and -intended inclusion; schema validation cannot prove that a repository or asset is public. Do not -publish private URLs, tokens, private metadata or examples copied from this private repository. +The catalog is a maintainer-curated **allowlist**, not repository discovery. Schema validation +cannot prove that a repository or asset is public. Do not publish private URLs, tokens, private +metadata or examples copied from this repository. ## Format -The envelope is `{ "schemaVersion": 1, "apps": [...] }`, `{ "schemaVersion": 2, "apps": [...] }`, -or `{ "schemaVersion": 3, "apps": [...] }`. Readers accept all three versions; old versions -continue to reject fields introduced later. A fictional full example and a minimal -example are in `crates/nexo-catalog/fixtures/`; they are test/development fixtures, **not** the -live catalog. The structural schema is `crates/nexo-catalog/catalog.schema.json`; Rust -`nexo_catalog::parse_catalog` and TypeScript `parseCatalog` also perform domain validation. -A JSON Schema implementation alone cannot enforce uniqueness by an object's `id`, and `format` -checking varies by implementation: always run domain validation too. +Nexo 0.2.0 reads only `{ "schemaVersion": 4, "apps": [...] }`. The structural schema is +`crates/nexo-catalog/catalog.schema.json`; Rust `nexo_catalog::parse_catalog_v4` and the +TypeScript catalog parser also perform domain validation. JSON Schema alone cannot enforce uniqueness by +ID, and format checking varies by implementation. The fixtures under `crates/nexo-catalog/fixtures/` +are fictional test data, **not** the live catalog. -Each app has: +Each app has these common fields: | Field | Required | Meaning | | --- | --- | --- | -| `id` | yes | Stable app ID, also used by the IPC protocol. | +| `id` | yes | Stable, unique app ID; nonempty ASCII lowercase `[a-z0-9-]+`. | | `name`, `tagline`, `description` | yes | Nonblank display text; never HTML. | | `tags` | yes | Array of nonblank display strings; may be empty. | -| `iconUrl`, `artUrl` | at least one | HTTPS card icon or artwork; both may be present. | -| `installerUrl` | yes | Public HTTPS installer location; the catalog does not download or run it. | -| `latestJsonUrl` | yes | Public HTTPS endpoint maintained by the app for its updater. | -| `integrationLevel` | yes | `full`, `update`, or `launch`; capability, not source or installation state. | -| `releasedAt` | yes | RFC 3339 release timestamp. | +| `iconUrl`, `artUrl` | at least one | HTTPS card icon or artwork. | +| `integrationLevel` | yes | `full`, `update`, or `launch`; capability, not installation state. | | `featured` | yes | Boolean metadata for the news consumer. | -| `news` | yes | App-scoped news entries; may be empty. | -| `version` | no | SemVer metadata for the published app; not evidence of an installed version or update. | | `links` | no | Object with optional HTTPS `github` and `youtube` links. | -| `updaterPublicKey` | v3 only, optional | The Tauri updater's base64-encoded minisign public key, exactly as in `plugins.updater.pubkey`. Omit when not verified. | -| `detection` | v2/v3, optional | `{ "windows": { "displayName": "Example App", "publisher": "Example Publisher", "executableRelativePath": "bin\\\\Example.exe" } }`. All three fields are required nonblank strings. A hint is metadata, not proof of installation. | - -Each news entry has required `id`, nonblank `title` and `text`, `publishedAt`, and `kind` -(`new`, `featured`, `update`). IDs are unique within each app; the UI projects a globally -unambiguous `appId:newsId` identifier, badge, app ID and catalog CTA. Only the official catalog -supplies this projection. For Novedades, an app is eligible if its release is not in the future, -and either it is within the last 30 days or the app is featured. Each eligible app contributes at -most one entry: its latest news within the inclusive 30-day window, with equal timestamps resolved -by ascending news ID; if none qualifies, the app contributes a synthetic entry. Future news does -not hide an older in-window entry. Entries are ordered newest first, with equal timestamps resolved -by typed key, and the popup shows at most four. - -IDs are nonempty ASCII lowercase `[a-z0-9-]+` and app IDs are unique across the catalog. -Required fields and their JSON types are strict; unknown fields, null optional fields and unsupported -schema versions are rejected. URLs must be absolute lowercase-scheme `https://` URLs with a host, -no credentials, whitespace, controls or malformed percent escapes. Nonblank text excludes Unicode -whitespace and U+FEFF; URLs also reject U+FEFF and C0/C1 control characters. `version` follows SemVer 2, -with major/minor/patch bounded by unsigned 64-bit integers. Timestamps use the RFC 3339 profile -`YYYY-MM-DDTHH:MM:SS[.fraction](Z|±HH:MM)`, with real calendar values and explicit zone. -Future incompatible format changes require a new schema version; readers reject versions they do -not understand. Additive fields also require a new version while v1 rejects unknown fields. - -The Windows hint uses exact `DisplayName` and `Publisher` values from the current user's NSIS -uninstall entry, not the catalog display name. The executable path is relative to `InstallLocation`; +| `news` | yes | App-scoped news entries; may be empty. | +| `platforms` | yes | Nonempty object mapping platform keys to release entries. | + +Keys match `^(windows|darwin|linux)-(x86_64|aarch64|i686|armv7)$`, for example +`windows-x86_64`, `darwin-aarch64`, `darwin-x86_64`, and `linux-x86_64`. Every entry contains: + +| Field | Required | Meaning | +| --- | --- | --- | +| `installerUrl` | yes | egdev6 GitHub release-asset URL for this platform's installer. | +| `latestJsonUrl` | yes | egdev6 GitHub release-asset URL for this platform's updater manifest. | +| `version` | yes | SemVer 2 release version, not evidence of an installed version. | +| `releasedAt` | yes | RFC 3339 release timestamp. | +| `updaterPublicKey` | no | Tauri updater's base64-encoded minisign public key. Omit when not verified. | +| `detection` | Windows keys only, optional | Flat object with required nonblank `displayName`, `publisher`, and `executableRelativePath`. | + +The hub maps its own OS and architecture to a key (`macos` → `darwin`, `x86` → `i686`, +`arm` → `armv7`). It validates the whole wire document and projects only that entry to the +existing flat app shape, including wrapping the hint as `detection: { windows: ... }`. Apps +without that key are hidden from catalog, Mis apps matching, news, installation and update checks. +An unsupported OS or architecture has no key and hides all apps. News entries have required `id`, +nonblank `title` and `text`, `publishedAt`, and `kind` (`new`, `featured`, or `update`); IDs are +unique within their app. The UI projects globally unambiguous `appId:newsId` identifiers. An app +is eligible for Novedades if its release is not in the future and is within the last 30 days or +featured. Each eligible app contributes its latest in-window news (equal timestamps resolve by +ascending news ID), or a synthetic entry if none qualifies. Future news does not hide older +in-window news; entries are ordered newest first, with typed-key tie breaking, and the popup shows +at most four. + +Unknown fields, null optional fields, invalid platform keys and unsupported schema versions are +rejected. URLs must be absolute `https://` URLs without credentials, controls, whitespace or +malformed escapes. Nonblank text excludes Unicode whitespace and U+FEFF; URLs also reject U+FEFF +and C0/C1 controls. SemVer major/minor/patch components are bounded by unsigned 64-bit integers. +Installer and updater URLs must identify a release asset at +`https://github.com/egdev6//releases/download//`; the domain validator also +rejects non-default ports, query strings, fragments, normalized traversal and escaped separators. +Timestamps have real calendar values and explicit zones. The updater key must decode to a minisign +public-key file with an `untrusted comment:` line and a base64 `Ed` public-key record. This shape +check is not signature verification or publisher authentication. + +The Windows hint uses the exact `DisplayName` and `Publisher` from the current user's NSIS +uninstall entry, not the catalog display name. The executable path is relative to `InstallLocation`: only `.exe` paths are accepted, without absolute/UNC/drive paths, traversal, empty components, -Windows-forbidden characters, controls, or components ending in space or dot. A matching path and -publisher are not authentication: HKCU and same-user files can be spoofed. Confirm actual installer -metadata with app owners before publishing a hint. A v1 app or v2/v3 app without a hint has unknown -installation state; never infer it from catalog `version` or IPC. - -In v3, `installerUrl` and `latestJsonUrl` must identify a release asset at -`https://github.com/egdev6//releases/download//`. The domain validator -checks the parsed host, owner and path; rejects credentials, non-default ports, query strings, -fragments, normalized traversal and escaped separators; and permits no extra path components. -V1/v2 retain their original HTTPS policy. A v3 key must decode to a minisign public-key file -with an `untrusted comment:` line and a base64 `Ed` public-key record. This shape check is -not signature verification, proof of publisher control or authorization to execute anything. - -A v3 entry that publishes `updaterPublicKey` also asserts that its `installerUrl` is a per-user -Tauri NSIS installer (`bundle.windows.nsis.installMode: "currentUser"`) whose asset name ends in -`_x64-setup.exe`, signed by that key with a prehashed minisign signature at `.sig`. -The hub rejects any other asset (for example `.msi`) before downloading. App owners must confirm -the install mode of the release before adding or updating the key. At install time the hub verifies -the signature before running anything, runs the installer with `/S` and no elevation, and treats an -install that is not detected in the current user's uninstall registry as a failure. - -`latestJsonUrl` is owned by the app. Before any updater consumes it, the app owner must confirm -its actual Tauri updater manifest format and verification configuration; the catalog loader does -not fetch it. Installed versions come only from the current user's uninstall registry; the app's -IPC version is displayed separately. Detection failures, absent hints and ambiguous matches remain -unknown. Opening rechecks the matching entry and executable; connected plugins receive `show` and -can receive `quit` when supported. Other apps have unknown running state and must be closed from the -app itself. Accepted requests do not prove that a window opened or a process exited. An app's own -single-instance handler is responsible for handoff; duplicates are possible without one. Local apps -are owned by #9, and install/update execution by #7/#8. Catalog `version` is never the installed version. +Windows-forbidden characters, controls or components ending in space or dot. A matching path and +publisher are not authentication; HKCU and same-user files can be spoofed. Confirm actual installer +metadata with app owners before publishing a hint. Missing hints leave installation state unknown. + +A keyed `windows-x86_64` entry asserts that its installer is a per-user Tauri NSIS installer +(`bundle.windows.nsis.installMode: "currentUser"`), with an asset name ending in +`_x64-setup.exe` and a prehashed minisign signature at `.sig`. The hub rejects other +assets before download, verifies the signature, and runs the installer with `/S` and no elevation. +Owners must confirm the install mode before publishing a key. Installed versions come from the +current user's uninstall registry, not the catalog or IPC. + +`latestJsonUrl` is owned by the app; before any updater consumes it, the owner must confirm its +Tauri updater manifest format and verification configuration. Detection failures, absent hints and +ambiguous matches remain unknown. Opening rechecks the matching entry and executable; connected +plugins can receive `show` and, when supported, `quit`. Accepted requests do not prove that a +window opened or process exited. An app's single-instance handler is responsible for handoff. ## Loading, cache and trust -The native hub starts with fixed sources configured in `apps/hub/src/catalog/loader.ts`. -The official v1/v2 feeds are published from the public repository -[`egdev6/nexo-catalog`](https://github.com/egdev6/nexo-catalog) on GitHub Pages: -`https://egdev6.github.io/nexo-catalog/v2/catalog.json` and -`https://egdev6.github.io/nexo-catalog/catalog.json`. The new preferred v3 endpoint is -`https://egdev6.github.io/nexo-catalog/v3/catalog.json`; its publication requires separate -approval and coordination. Editing the catalog updates installs on their next start without a -Nexo release, as long as the content stays within a schema version the installed hub understands. -If all endpoints and caches fail, the hub displays an error with retry -rather than presenting a fixture as official. Browser-only design preview uses labeled sample data. The loader fetches on startup and explicit retry with an eight-second timeout, rejects -redirects, checks HTTPS, validates the whole response, and saves only valid data to the version-specific cache in Tauri's app-data directory: `catalog.json` for v1, -`catalog-v2.json` for v2, and `catalog-v3.json` for v3. A corrupt cache is ignored. On offline/HTTP/parse/ -validation failure a valid previous cache remains visible with a stale warning; without one the -error/offline state offers retry. A successful empty catalog shows the empty state. Cache write -failure is surfaced instead of claiming offline persistence. There is no TTL or ETag policy in v1. -New clients prefer the separately configured v3 endpoint and its cache, falling back to v2 and -then v1 when a newer version is unavailable and has no valid cache. Responses and caches of the wrong version are rejected. -Never replace a versioned endpoint in place with a newer schema. The webview performs the fetch: GitHub Pages answers -with `Access-Control-Allow-Origin: *` and `Cache-Control: max-age=600`, so changes reach clients within -about ten minutes. The webview CSP allows fetches and images only from `https://egdev6.github.io`; -catalog icons are served from the catalog repository for that reason. - -HTTPS and validation protect transport and shape, not publisher identity or installer integrity. -The catalog has no signature, mandatory installer hashes or key rotation/revocation mechanism. -The v3 key is metadata, not evidence that a download is trusted: the hub's installer fetches current -v3 data natively, asks for native confirmation, and verifies the detached signature with that key -before any execution. Third-party sources require a separate security design. Remote strings are -displayed as text; nothing is installed without the user's confirmation, and only signature-verified -installers are run. +The only feed Nexo 0.2.0 fetches, both in the webview and native installer, is +`https://egdev6.github.io/nexo-catalog/v4/catalog.json`. It validates the complete response and +stores only valid v4 documents in the single `catalog-v4.json` app-data cache; old cache files are +ignored. Offline or invalid responses may use the valid cache with a stale warning; without one the +hub offers retry. A corrupt cache is ignored and a write failure is surfaced. The native installer +always fetches fresh data and revalidates its selection before execution; it does not authorize +installation from cache. The loader uses an eight-second timeout, rejects redirects, and presents a +valid empty catalog as an empty state. Browser-only design preview uses labeled sample data. + +The public repository continues to publish `catalog.json`, `v2/catalog.json`, and +`v3/catalog.json` unchanged for installed Nexo 0.1.x clients. Do not replace a versioned endpoint +in place with a newer schema. Editing a catalog updates installs on their next start without a Nexo +release, provided the format stays compatible. GitHub Pages CORS allows the webview fetch and its +cache policy can delay changes. The webview CSP allows catalog fetches and images only from +`https://egdev6.github.io`. + +HTTPS and validation protect transport and shape, not publisher identity. The catalog has no +signature, mandatory installer hashes or key rotation/revocation mechanism. The updater key is +metadata; the installer verifies its detached signature before execution and asks for native user +confirmation. Third-party sources require a separate security design. Remote strings are displayed +as text; nothing is installed without confirmation. ## Publication and adding an app -1. The catalog lives in the **dedicated public repository** `egdev6/nexo-catalog`, served over HTTPS by - GitHub Pages; its `Validate catalog` workflow checks the published files against the schema. Do not make the - private Nexo repository public. -2. For each inclusion, a maintainer reviews the app and verifies that the repository, installer, - icon/art, updater endpoint and discovery destinations are intentionally public. Verify all URLs - anonymously and check CORS and stable hosting; HTTPS alone does not establish public status. -3. Add an entry to the public allowlist using the fields above, update the catalog under review, run - schema **and** domain validation and publish only with separate authorization. -4. Images and links must stay on origins the webview allows (`https://egdev6.github.io` for icons); - adding another origin requires a CSP change and a Nexo release. Verify anonymous access, redirects - and CORS after publishing. The example fixture URLs do not represent published apps or an existing release. +1. Publish from the dedicated public repository `egdev6/nexo-catalog`; its `Validate catalog` + workflow checks the published files. Do not make the private Nexo repository public. +2. Review each inclusion and verify anonymously that the repository, installer, icon/art, updater + endpoint and discovery destinations are intentionally public; verify platform and install mode. +3. Add an entry to the public allowlist, run schema **and** domain validation, and publish only + with separate authorization. +4. Images and links must stay on origins allowed by the webview; adding another origin requires a + CSP change and a Nexo release. Verify redirects and CORS after publishing. diff --git a/odd/tasks/catalog-v4.md b/odd/tasks/catalog-v4.md index da9139e..25f5cdc 100644 --- a/odd/tasks/catalog-v4.md +++ b/odd/tasks/catalog-v4.md @@ -33,4 +33,5 @@ - L2 (2026-11-21, user): S2. Parent recommended shipping 0.2.0 as is (self-update lets v4 arrive in 0.3.0); maintainer chose to include it: "yo me arriesgaría tenemos 2 dias". - L4 (2026-11-21, user): "pr de T1" → nexo-catalog PR #11 opened after rebasing on #10 (Antena 0.18.0) and resyncing v4. - L5 (2026-11-21, user): "si" → start T2. Parent fixed contract S7 and wrote the shared v4 corpus; the corpus exposed a schema bug in PR #11 (darwin/linux entries matched patternProperties and skipped platformEntry), fixed in nexo-catalog 9ee8a98. +- L6 (2026-11-21, evidence): T2a done (Rust; Windows MSVC clippy not runnable on this host: ring needs lib.exe). T2b first attempt blocked: worker ran pnpm in an npm project (package-lock.json, CI `npm ci`); parent restored with `npm ci`. Parent removed a TS-only NSIS check that rejected the whole v4 catalog for one non-NSIS windows-x86_64 entry (Rust and v3 enforce it at install selection); pinned in both languages. Native install stays Windows/NSIS-only (release builds Windows NSIS only), so darwin/linux entries are display-only. - L3 (state): 0.2.0 is a draft (built from 3e17ef8, signed, valid signature with key B9313A349CF8A2BD). Releases "latest" is still v0.1.4 because drafts cannot be latest. From a14d2fbd29a8a7650f2411d9c4c86b7cb319db13 Mon Sep 17 00:00:00 2001 From: egdev6 Date: Sat, 21 Nov 2026 15:58:35 +0100 Subject: [PATCH 6/9] docs(odd): record catalog v4 T2 evidence --- odd/tasks/catalog-v4.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/odd/tasks/catalog-v4.md b/odd/tasks/catalog-v4.md index 25f5cdc..4d6c806 100644 --- a/odd/tasks/catalog-v4.md +++ b/odd/tasks/catalog-v4.md @@ -22,8 +22,8 @@ | ID | Specs | Route | Status | Commit | | --- | --- | --- | --- | --- | | T1 | S3, S5, S6 | parent (nexo-catalog: schema v4, v4/catalog.json, validate.yml, README) | done: 4 files valid, 6 invalid cases rejected, darwin-only app accepted; rebased on Antena 0.18.0 (#10) and v4 resynced | nexo-catalog PR #11 | -| T2a | S3, S4, S5, S7 | worker: Rust (crates/nexo-catalog v4 + projection + schema copy, src-tauri platform key, install feed v4, v4 cache + commands, docs/catalog.md) | pending | | -| T2b | S3, S4, S5, S7 | worker: TypeScript (format.ts v4 + projection, loader v4 only, platform_key invoke, schemaVersion checks, i18n `install.v3Required`, tests) | pending | | +| T2a | S3, S4, S5, S7 | worker: Rust (crates/nexo-catalog v4 + projection + schema copy, src-tauri platform key, install feed v4, v4 cache + commands, docs/catalog.md) | done: cargo fmt/clippy/test green; Windows MSVC unverified locally | 4e62aac, de007af | +| T2b | S3, S4, S5, S7 | worker: TypeScript (format.ts v4 + projection, loader v4 only, platform_key invoke, schemaVersion checks, i18n `install.v3Required`, tests) | done: 612 vitest, tsc, build, ds:doctor green | 8394e02 (docs 2672ce0) | | T3 | S2 | parent: release notes, rebuild 0.2.0 (maintainer deletes draft and reruns Release) | pending | | | T4 | all | verify | pending | | @@ -34,4 +34,5 @@ - L4 (2026-11-21, user): "pr de T1" → nexo-catalog PR #11 opened after rebasing on #10 (Antena 0.18.0) and resyncing v4. - L5 (2026-11-21, user): "si" → start T2. Parent fixed contract S7 and wrote the shared v4 corpus; the corpus exposed a schema bug in PR #11 (darwin/linux entries matched patternProperties and skipped platformEntry), fixed in nexo-catalog 9ee8a98. - L6 (2026-11-21, evidence): T2a done (Rust; Windows MSVC clippy not runnable on this host: ring needs lib.exe). T2b first attempt blocked: worker ran pnpm in an npm project (package-lock.json, CI `npm ci`); parent restored with `npm ci`. Parent removed a TS-only NSIS check that rejected the whole v4 catalog for one non-NSIS windows-x86_64 entry (Rust and v3 enforce it at install selection); pinned in both languages. Native install stays Windows/NSIS-only (release builds Windows NSIS only), so darwin/linux entries are display-only. +- L7 (2026-11-21, evidence): T2 committed in 4 slices (~2.1k lines incl. tests and docs, past the ~400-line slice; delivery shape decided at publish: single PR or chained). - L3 (state): 0.2.0 is a draft (built from 3e17ef8, signed, valid signature with key B9313A349CF8A2BD). Releases "latest" is still v0.1.4 because drafts cannot be latest. From a088b2a3aa6643538cd5c1ea8b3d615a02a5bd99 Mon Sep 17 00:00:00 2001 From: egdev6 Date: Sat, 21 Nov 2026 16:05:54 +0100 Subject: [PATCH 7/9] docs(odd): record catalog v4 verification --- odd/tasks/catalog-v4.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/odd/tasks/catalog-v4.md b/odd/tasks/catalog-v4.md index 4d6c806..63fb444 100644 --- a/odd/tasks/catalog-v4.md +++ b/odd/tasks/catalog-v4.md @@ -25,7 +25,7 @@ | T2a | S3, S4, S5, S7 | worker: Rust (crates/nexo-catalog v4 + projection + schema copy, src-tauri platform key, install feed v4, v4 cache + commands, docs/catalog.md) | done: cargo fmt/clippy/test green; Windows MSVC unverified locally | 4e62aac, de007af | | T2b | S3, S4, S5, S7 | worker: TypeScript (format.ts v4 + projection, loader v4 only, platform_key invoke, schemaVersion checks, i18n `install.v3Required`, tests) | done: 612 vitest, tsc, build, ds:doctor green | 8394e02 (docs 2672ce0) | | T3 | S2 | parent: release notes, rebuild 0.2.0 (maintainer deletes draft and reruns Release) | pending | | -| T4 | all | verify | pending | | +| T4 | all | verify | pass S1, S3-S7 on Linux (336 cargo, 612 vitest, 161-case Rust/TS differential identical, published v4 projects Antena+Quorb only on windows-x86_64); cfg(windows) paths unproven until native Windows CI | — | ## Log From afe62daa314a01a895dde79db73c97e5241a6538 Mon Sep 17 00:00:00 2001 From: egdev6 Date: Sat, 21 Nov 2026 16:28:38 +0100 Subject: [PATCH 8/9] docs(release): note per-platform catalog in Nexo 0.2.0 --- odd/tasks/catalog-v4.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/odd/tasks/catalog-v4.md b/odd/tasks/catalog-v4.md index 63fb444..415b27c 100644 --- a/odd/tasks/catalog-v4.md +++ b/odd/tasks/catalog-v4.md @@ -24,7 +24,7 @@ | T1 | S3, S5, S6 | parent (nexo-catalog: schema v4, v4/catalog.json, validate.yml, README) | done: 4 files valid, 6 invalid cases rejected, darwin-only app accepted; rebased on Antena 0.18.0 (#10) and v4 resynced | nexo-catalog PR #11 | | T2a | S3, S4, S5, S7 | worker: Rust (crates/nexo-catalog v4 + projection + schema copy, src-tauri platform key, install feed v4, v4 cache + commands, docs/catalog.md) | done: cargo fmt/clippy/test green; Windows MSVC unverified locally | 4e62aac, de007af | | T2b | S3, S4, S5, S7 | worker: TypeScript (format.ts v4 + projection, loader v4 only, platform_key invoke, schemaVersion checks, i18n `install.v3Required`, tests) | done: 612 vitest, tsc, build, ds:doctor green | 8394e02 (docs 2672ce0) | -| T3 | S2 | parent: release notes, rebuild 0.2.0 (maintainer deletes draft and reruns Release) | pending | | +| T3 | S2 | parent: release notes, rebuild 0.2.0 (maintainer deletes draft and reruns Release) | notes done; rebuild waits for merge of nexo-catalog #11 and nexo #84 | see PR #84 | | T4 | all | verify | pass S1, S3-S7 on Linux (336 cargo, 612 vitest, 161-case Rust/TS differential identical, published v4 projects Antena+Quorb only on windows-x86_64); cfg(windows) paths unproven until native Windows CI | — | ## Log @@ -35,4 +35,5 @@ - L5 (2026-11-21, user): "si" → start T2. Parent fixed contract S7 and wrote the shared v4 corpus; the corpus exposed a schema bug in PR #11 (darwin/linux entries matched patternProperties and skipped platformEntry), fixed in nexo-catalog 9ee8a98. - L6 (2026-11-21, evidence): T2a done (Rust; Windows MSVC clippy not runnable on this host: ring needs lib.exe). T2b first attempt blocked: worker ran pnpm in an npm project (package-lock.json, CI `npm ci`); parent restored with `npm ci`. Parent removed a TS-only NSIS check that rejected the whole v4 catalog for one non-NSIS windows-x86_64 entry (Rust and v3 enforce it at install selection); pinned in both languages. Native install stays Windows/NSIS-only (release builds Windows NSIS only), so darwin/linux entries are display-only. - L7 (2026-11-21, evidence): T2 committed in 4 slices (~2.1k lines incl. tests and docs, past the ~400-line slice; delivery shape decided at publish: single PR or chained). +- L8 (2026-11-21, user): "si" → pushed feat/catalog-v4, opened nexo PR #84 (Closes #83); release notes for v0.2.0 updated. - L3 (state): 0.2.0 is a draft (built from 3e17ef8, signed, valid signature with key B9313A349CF8A2BD). Releases "latest" is still v0.1.4 because drafts cannot be latest. From 283683c23a47f6ec6f81ce3075706f70bd067a30 Mon Sep 17 00:00:00 2001 From: egdev6 Date: Sat, 21 Nov 2026 16:33:33 +0100 Subject: [PATCH 9/9] docs(odd): record native Windows CI evidence for catalog v4 --- docs/releases/v0.2.0.md | 2 ++ odd/tasks/catalog-v4.md | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/releases/v0.2.0.md b/docs/releases/v0.2.0.md index cf66254..3c75b57 100644 --- a/docs/releases/v0.2.0.md +++ b/docs/releases/v0.2.0.md @@ -7,6 +7,7 @@ Nexo 0.2.0: Nexo ya se actualiza solo. ## Mejorado +- **Catálogo según tu sistema.** Nexo solo muestra las apps, novedades y actualizaciones disponibles para el sistema operativo en el que lo usas. Si una app no existe para tu sistema, no aparece. - **Design system EGDEV actualizado.** Nexo usa la última versión de los componentes y estilos compartidos de la familia EGDEV. - **Pestañas con desplazamiento.** Si las pestañas no caben a lo ancho, ahora se pueden desplazar en lugar de recortarse. - **Controles nativos en modo oscuro.** Las barras de desplazamiento y los controles del sistema usan el tema oscuro. @@ -20,6 +21,7 @@ Nexo 0.2.0: Nexo ya se actualiza solo. - **Desde versiones anteriores a la 0.2.0** hay que instalar esta versión encima, una sola vez. A partir de aquí, Nexo se actualiza solo. - **Cerrar una app.** Las apps sin integración con Nexo (hoy, Quorb) pueden ocultarse en su propia bandeja en lugar de cerrarse. En ese caso, Nexo te avisa para que la cierres desde la propia app. +- **Primer arranque sin conexión.** Nexo 0.2.0 usa un catálogo nuevo. Si lo abres por primera vez sin conexión a internet, el catálogo aparecerá vacío hasta que Nexo pueda descargarlo. - **Solo Windows 10 y 11**, con un instalador por usuario. - **El instalador no tiene firma de código de Windows**, así que SmartScreen puede pedirte que confirmes que quieres ejecutarlo. diff --git a/odd/tasks/catalog-v4.md b/odd/tasks/catalog-v4.md index 415b27c..c259773 100644 --- a/odd/tasks/catalog-v4.md +++ b/odd/tasks/catalog-v4.md @@ -25,7 +25,7 @@ | T2a | S3, S4, S5, S7 | worker: Rust (crates/nexo-catalog v4 + projection + schema copy, src-tauri platform key, install feed v4, v4 cache + commands, docs/catalog.md) | done: cargo fmt/clippy/test green; Windows MSVC unverified locally | 4e62aac, de007af | | T2b | S3, S4, S5, S7 | worker: TypeScript (format.ts v4 + projection, loader v4 only, platform_key invoke, schemaVersion checks, i18n `install.v3Required`, tests) | done: 612 vitest, tsc, build, ds:doctor green | 8394e02 (docs 2672ce0) | | T3 | S2 | parent: release notes, rebuild 0.2.0 (maintainer deletes draft and reruns Release) | notes done; rebuild waits for merge of nexo-catalog #11 and nexo #84 | see PR #84 | -| T4 | all | verify | pass S1, S3-S7 on Linux (336 cargo, 612 vitest, 161-case Rust/TS differential identical, published v4 projects Antena+Quorb only on windows-x86_64); cfg(windows) paths unproven until native Windows CI | — | +| T4 | all | verify | pass S1, S3-S7 on Linux (336 cargo, 612 vitest, 161-case Rust/TS differential identical, published v4 projects Antena+Quorb only on windows-x86_64); cfg(windows) paths proven by PR #84 native Windows CI (afe62da: Rust tests and lint (Windows) pass) | — | ## Log