diff --git a/.github/workflows/repository-hygiene.yml b/.github/workflows/repository-hygiene.yml index d34f47e3e..27b1dbc9d 100644 --- a/.github/workflows/repository-hygiene.yml +++ b/.github/workflows/repository-hygiene.yml @@ -370,7 +370,6 @@ jobs: env: PIIK_BUILD_VERSION: ${{ steps.release.outputs.version }} PIIK_BUILD_REVISION: ${{ github.sha }} - VITE_PIIK_VERSION: ${{ steps.release.outputs.version }} VITE_PIIK_REVISION: ${{ github.sha }} release-server: diff --git a/cmd/piik-app/README.md b/cmd/piik-app/README.md index 75ecc9a04..227d4fae1 100644 --- a/cmd/piik-app/README.md +++ b/cmd/piik-app/README.md @@ -148,9 +148,8 @@ explains backup scope and restore behavior. ## Upgrading -Use the next matching package supplied for this 3.0 test, including its Web UI. -A public 2.x release is not an update for the test App. When versions are -incompatible, update the domain's Server and connected Apps together, then refresh its pages. +Use the next package supplied for this 3.0 test, including its bundled Web UI. +If prompted to update, follow the [version troubleshooting guide](../../docs/guide/troubleshooting.md#app-and-page-versions-are-incompatible). 1. Save needed backups, finish transfers and stop personal activities. 2. Stop App normally. Extract the full desktop update into a new directory, diff --git a/cmd/piik-app/README.zh-CN.md b/cmd/piik-app/README.zh-CN.md index f692a540a..f31e64ec7 100644 --- a/cmd/piik-app/README.zh-CN.md +++ b/cmd/piik-app/README.zh-CN.md @@ -112,8 +112,8 @@ Browser 托管房间使用该浏览器的站点存储,清除它可能删除房 ## 升级 -使用这次 3.0 测试后续提供的匹配程序包,包括其中的网页界面。 -公开的 2.x Release 不是测试 App 的更新。出现版本不兼容时,域需同步更新 Server 和连接的 App,再刷新网页。 +使用本次 3.0 内测提供的新版程序包,保留内附的网页界面。 +如果提示更新,请参阅[版本排障指南](../../docs/guide/troubleshooting.zh-CN.md#app-与页面版本不兼容)。 1. 保存需要的备份,结束传输和个人活动。 2. 正常关闭 App。电脑上把完整新版解压到新目录;Android 使用同一测试渠道的新版覆盖安装。 diff --git a/docs/adr/0017-contracts-fixed-before-release.md b/docs/adr/0017-contracts-fixed-before-release.md index bdfb38d25..b19c5b3fa 100644 --- a/docs/adr/0017-contracts-fixed-before-release.md +++ b/docs/adr/0017-contracts-fixed-before-release.md @@ -26,8 +26,6 @@ requires one exact identifier, and its capability object has grown to fifteen entries, one per feature, which its promise to older peers keeps. The private 3.0 implementation currently has these boundaries: -- Channel joins and local App discovery still require their private wire - identifiers. The public product-version handshake remains to be installed. - Domain and signed room replies identify their waiting operation separately from observer notifications. Unknown outcomes end that operation without confirming success. Wire objects accept ordinary extensions; typed store @@ -41,50 +39,13 @@ The private 3.0 implementation currently has these boundaries: ### Settled before the first public release -1. **Compatibility.** Two parties work together when the first numbers of - their versions are equal; when they differ, each tells its person which - side to update. Four rules make any two second numbers work together. - None of them is a flag for one feature or a path for one older peer. - - *A party states its two numbers once,* where it is already described: a - session when it joins, the Domain in its welcome or in the refusal that - takes its place, the App in its discovery. The Domain publishes a session's numbers beside its key, so - the numbers of a room's writer are those of its host's session. They - decide what a client offers to its person. No result depends on them. - - *An unknown kind gets an answer where one is waited for.* A request of a - kind its receiver does not know is refused as unsupported in that - request's reply. A reply of a kind its requester does not know ends that - request as an unknown outcome and never as success. A notification of an - unknown kind is ignored. A new action an older receiver must decline - uses a distinct request. Changes to state older observers already display - retain their baseline update semantics. - - *An unknown field is ignored by its final recipient at every depth.* - Relays forward enclosed signed payloads unchanged. Known bounds, types, - required fields and kind values keep their defined contracts. A writer stores - the fields it knows, and its confirmation carries the message as stored, - so a sender sees what was kept. A new constraint whose omission would - widen authority, lifetime, recipients or the target uses a distinct - request; baseline requests retain all their defined constraints. A writer - keeps nothing it cannot read, because deleting a message, clearing media - and copying a room are promises about everything stored. What is written - to last is the exception to ignoring, since nobody is there to be told: - a store or an archive that holds what its reader does not know is - refused before anything is installed. - - *A party gets a new form by asking for it.* A request names the optional - parts and forms it wants. One that names none gets what the first - release gave. A part that was not asked for, or that the answering party - does not know, is absent, and absent never means empty or deleted. - - What the four cannot express, which is changing or removing something - that exists, waits for the next first number. That number also removes - every branch written for an older peer, so such branches live for one - first number at most. The first release exercises the rules at each - independently implemented wire boundary, including a real mixed-version - path. Tests cover unknown fields, requests, replies and notifications and - a peer with a higher second number; shared decoders share boundary tests. - An extension mechanism that is not used stops working - ([RFC 9170](https://www.rfc-editor.org/rfc/rfc9170.html)). Until the first - release the one private number keeps its present job of telling apart - builds that were not made for each other. +1. **Compatibility.** A single product major/minor serves both Domain joins + and local App discovery. The room writer may run on an older participant's + device, so compatible additions must work with older readers and writers + in either role. [Versioning](../standards/versioning.md#extending-interfaces) + owns the rules for extensions and their mixed-version acceptance. + Extensions must be exercised to stay usable + ([RFC 9170](https://www.rfc-editor.org/rfc/rfc9170.html)). 2. **Replies.** A request ends in an explicit terminal outcome that tells rejected from unknown, and a copy sent to an observer is separate from the requester's reply. Idempotency is scoped by operation: chat already has @@ -156,7 +117,7 @@ their meaning, and a new form reaches only a party that asked for it. under the present rule for private experiments. - A feature added after release is a new kind, a new field or a new part to ask for, and raises the second number. No matrix of pairs is kept, because - every pair that shares a first number works by the same four rules. + same-major peers use the shared extension rules. - Refusing unknown fields goes from the wire. Stores and archives keep refusing what they do not know. One wire field per feature is not added again. The descriptions a join already carries of what a party's runtime @@ -166,9 +127,8 @@ their meaning, and a new form reaches only a party that asked for it. that newer clients could use them through an older host, was weighed and left out: no feature in sight needs it, and it can be added later as one more addition under these rules. -- [Versioning](../standards/versioning.md#extending-interfaces) states the - rule for 3.0, whose direction the owner confirmed. The distance of the - private code from it is release work. +- Acceptance requires exercising the first public contract with mixed-version + artifacts. [TODO](../todo.md) tracks that work. ## References diff --git a/docs/adr/0020-one-vocabulary-for-extension.md b/docs/adr/0020-one-vocabulary-for-extension.md index 5e1cd4ca3..39fc7f37f 100644 --- a/docs/adr/0020-one-vocabulary-for-extension.md +++ b/docs/adr/0020-one-vocabulary-for-extension.md @@ -54,9 +54,8 @@ fixed. the message as stored, so its sender sees what was kept. What a writer has to act on arrives as a request of its own, which an older writer refuses as unsupported in that request's reply - ([ADR-0017](./0017-contracts-fixed-before-release.md), decision 1). No - capability is announced per feature: a client reads the writer's two - numbers to decide what to offer. + ([versioning](../standards/versioning.md#extending-interfaces)). A client + can use the writer's minor version to decide what to offer. - *A program is a participant* (decision 5). It joins and acts through the wire a person's client uses, so no second interface has to keep step with the first, and joining never comes to depend on something only diff --git a/docs/guide/troubleshooting.md b/docs/guide/troubleshooting.md index 74e1e544f..54336c838 100644 --- a/docs/guide/troubleshooting.md +++ b/docs/guide/troubleshooting.md @@ -221,8 +221,8 @@ its public rooms. Use the same browser profile to retain your existing identity; private/incognito profiles have separate saved credentials. -If Piik asks you to update, use matching 3.0 App, Web and Server versions, then -reload. A 2.x App or site is not a replacement for the test endpoint. +If Piik asks you to refresh, reload the page. If it asks you to update the +site, contact the administrator who runs its Piik App or Server. ### The page opens but the site will not connect @@ -247,8 +247,13 @@ does not open the approval page, allow popups for this site and try again. ### App and page versions are incompatible -Ask the site administrator for the 3.0 test package that matches this site. -Install it, restart Piik App and reload the page. Then select **App** again. +If Piik asks you to update the App, install the latest package supplied for +your 3.0 test and restart it. If it asks you to refresh, reload the page. If +the page still needs an update, contact the site administrator. Then select +**App** again. + +If you are using an earlier beta with the old handshake, ask +the site administrator for the App package from that candidate. ## Chat and files @@ -326,7 +331,7 @@ The source picker distinguishes these outcomes: | Message | Next step | | --- | --- | | Cannot connect to Piik App | Confirm the App is running and this site is approved. Close idle pages using the App if it reports a busy request, then retry. | -| App and page versions are incompatible | [Update Piik App and reload the page](#app-and-page-versions-are-incompatible). | +| App and page versions are incompatible | [Follow the update prompt](#app-and-page-versions-are-incompatible). | | Piik App capture is currently unavailable | Check the App diagnostics for capture or encoder availability. Review your encoding setting or use browser capture. | | Piik App timed out | Wait a moment, then select **Refresh sharing sources** in the source picker. | | Could not read the screen and window list | Refresh to retry. If it keeps failing, collect both the App and browser reports. | diff --git a/docs/guide/troubleshooting.zh-CN.md b/docs/guide/troubleshooting.zh-CN.md index 8ff8002d7..ab22d58c0 100644 --- a/docs/guide/troubleshooting.zh-CN.md +++ b/docs/guide/troubleshooting.zh-CN.md @@ -178,8 +178,7 @@ Piik App 的本地网络邀请使用临时自签名 HTTPS 证书,浏览器可 房间邀请被拒绝不会妨碍你继续使用站点或进入公开房间。 使用原浏览器配置可保留已有身份;隐私模式或另一浏览器配置使用各自保存的凭据。 -提示需要更新时,使用匹配的 3.0 App、网页和 Server,再刷新页面。 -2.x App 或站点不能替代当前测试端。 +如果 Piik 提示刷新,请重新加载页面。如果提示更新站点,请联系站点管理员更新托管站点的 App 或 Server。 ### 网页能打开但站点连接不上 @@ -199,7 +198,10 @@ Piik App 的本地网络邀请使用临时自签名 HTTPS 证书,浏览器可 ### App 与页面版本不兼容 -向站点管理员获取与此站点匹配的 3.0 内测包。安装后重启 Piik App 并刷新页面,再点击 **App**。 +如果 Piik 提示更新 App,请安装本次 3.0 内测提供的最新版并重启 App。如果提示刷新,请重新加载页面。 +如果页面仍提示需要更新,请联系站点管理员。完成后再次点击 **App**。 + +如果还在使用采用旧握手的内测站点,请向站点管理员索取同一内测批次的 App。 ## 聊天与文件 @@ -264,7 +266,7 @@ App 来源缺失则按下节操作。 | 提示 | 处理方法 | | --- | --- | | 未能连接 Piik App | 确认 App 正在运行,且当前站点已获得授权。若提示 App 忙碌,可关闭未使用的 Piik 页面后重试。 | -| App 与页面版本不兼容 | [更新 Piik App 并刷新页面](#app-与页面版本不兼容)。 | +| App 与页面版本不兼容 | [按提示更新](#app-与页面版本不兼容)。 | | Piik App 采集功能当前不可用 | 查看 App 诊断信息中的采集和编码能力,检查编码设置,或使用浏览器采集。 | | Piik App 响应超时 | 稍等片刻,然后在选源器中点击 **刷新分享来源**。 | | 未能读取 App 的窗口和屏幕列表 | 刷新重试;若持续失败,请导出同一次尝试的 App 和网页诊断报告。 | diff --git a/docs/standards/versioning.md b/docs/standards/versioning.md index f8cb76596..dd82d2b39 100644 --- a/docs/standards/versioning.md +++ b/docs/standards/versioning.md @@ -1,9 +1,8 @@ # Versions And Compatibility -Reviewed 2026-11-09. `v1.0.0` is the declared published compatibility baseline. -App, Server and the embedded Web build share one product version, plus the full -Git SHA for source provenance. [Status](../status.md) owns the current publication -state; automatic publication follows the product-change boundary below. +A release assigns one product version to its App, Server and bundled Web +build and records the full source SHA. See the [publication status](../status.md) +and the [published 2.x contract](#published-2x). ## Give Each Identifier One Job @@ -13,8 +12,7 @@ state; automatic publication follows the product-change boundary below. | Full Git SHA / `REVISION` | Exact source revision | Changes with the source commit; never use SHA inequality as release ordering or compatibility proof | | Artifact SHA-256 | Exact packaged bytes in the release descriptor | Each artifact; one source SHA can produce different platform/toolchain binaries | | Platform application version fields | Generated package metadata | Product version in the platform's numeric format; source SHA stays separate. XML/desktop-format versions remain specification values | -| Browser/Server signaling identifier | Owning wire types: Core `wire.rs`/Browser channel protocol for 3.0; published 2.x [Browser wire](https://github.com/TNTcraftHIM/Piik/blob/f2f9d27db66565f9234c16d46ddd10f4d143cc16/src/shared/protocol.ts) and [protocol constants](https://github.com/TNTcraftHIM/Piik/tree/f2f9d27db66565f9234c16d46ddd10f4d143cc16/internal/server/protocol) stay on the maintenance line | Change for an incompatible wire contract, not UI edits or every release | -| Browser/App control identifier | Current App discovery/approval: Browser `channel/app-link.ts` and Server `app.rs`; published 2.x: [matched App control wire](https://github.com/TNTcraftHIM/Piik/blob/f2f9d27db66565f9234c16d46ddd10f4d143cc16/src/client/native/wire.ts) on the maintenance line | Independent compatibility boundary; installed App and Site can update separately | +| Product major and minor on 3.0 connections | Derived from the product build version for Domain joins and App discovery | The major controls compatibility. The minor guides which features a client offers. See [Extending Interfaces](#extending-interfaces) | | Capture probe and encoded-frame envelope | Rust Native capture/media owners; retained standalone helpers own their matched private formats | Internal matched bundle; change only the affected format | | SQLite schema, App config format, Browser storage-key format | Their storage/parser owners | Change with the actual stored representation; preserve accepted authority across a compatible upgrade | | Portable backup format | Core backup metadata and the archive adapters | Change when the exported archive representation changes; a new backup format does not imply resetting an unchanged live database | @@ -22,17 +20,13 @@ state; automatic publication follows the product-change boundary below. | Room policy and grants | Persisted room authority | Preserve accepted authority across compatible upgrades | | Share/route/publication/media generations, connection IDs and flow leases | Current resource owners | Follow the lifetime of the resource independently of releases | -Current numeric values are in source and [status](../status.md#accepted-release-contract). -Keep those internal values at the first public release: resetting schema or -authorization counters for visual consistency can invalidate data or stale-work -fences. The two 3.0 wire identifiers are the exception: the first 3.0 release -puts the product's first two numbers in their place -([Extending Interfaces](#extending-interfaces)). A room number is a user-facing address, not a software version. +Keep storage and authorization counters at the first public release to +preserve data and stale-work fences. The private tooling-only npm package carries no independent product version. Local test candidates may explicitly set `PIIK_BUILD_VERSION=v3.0.0-beta.4`. This prerelease build identity does not declare a public release: stable-tag -selection and publication remain stable-only. Keep the full prerelease string -and source SHA in product/build metadata; wire and storage generations are unchanged. +selection and publication remain stable-only. The handshake uses the major and +minor from the build version. Build metadata keeps the full tag and source SHA. Android versionCode and macOS numeric bundle fields use the major/minor/patch base. Successive candidates with the same base therefore share an Android code and require explicit local replacement (for example, `adb install -r`); keep @@ -58,13 +52,11 @@ scheduling, resource cleanup, code organization and presentation alone do not require new wire or storage identities. Review the actual message and data contracts, including nested payloads. Extend an existing operation before introducing an incompatible representation. -Protocol identifiers reject mismatched private builds; they do not require -compatibility bridges. An incompatible change needs a concrete requirement that -the existing contract cannot express. Update matched App, Web, Server, previews -and guides together. Change storage identity only when its representation changes, -and explain a required data reset instead of maintaining a private legacy format. -The public promises below apply to published releases, including the separate 2.x -maintenance line. +An incompatible change needs a concrete requirement that the existing contract +cannot express. Update affected runtimes, previews and guides together. Change +storage identity when its representation changes and explain any required reset. +The product-version handshake replaces the old private wire shape. Testers on +older betas use packages from the same candidate when keeping an earlier build. ## Public Compatibility Promise @@ -107,20 +99,19 @@ avoid a major justifies mislabeling an incompatible release. ## Extending Interfaces -### From the first 3.0 release +### 3.0 [ADR-0017](../adr/0017-contracts-fixed-before-release.md), decision 1, records the reasons and the sources. The rule: - **Two numbers.** A party states the first two numbers of its product version - once, where it is already described: a session in its join, the Domain in - its welcome or, when the first numbers differ, in its refusal, the App in - its discovery. The Domain publishes a session's - numbers with its other facts, so the numbers of a room's writer are those of - its host's session. Parties with equal first numbers work together. When the - first numbers differ the connection is refused and each side says which one - to update. The second number decides only what a client offers to its - person. No result depends on it. + in its existing handshake. The session states them in its join, the Domain + in its welcome or refusal for an incompatible major, and the App in local + discovery. The Domain publishes the numbers with the session's other facts, + including those of the room writer's host session. Equal majors pass the + version check. A major mismatch blocks the connection and prompts the user + to update the older side. The minor guides which features a client offers; + operation outcomes do not depend on it. - **Unknown kinds.** A request of a kind its receiver does not know is refused as unsupported in that request's reply. A reply of a kind its requester does not know ends that request as an unknown outcome, never as success. A @@ -177,39 +168,17 @@ Native discovery distinguishes an incompatible Piik App from an absent App. The offers update/refresh guidance and Browser operation. Do not reload, reinstall or interrupt an active share just because an unrelated product/build label changed. -### The private 3.0 code today - -On the Domain's wire a terminal `reply` carries its request ID and, for a room -operation, its room ID. Notifications carry no request ID. On the room's signed wire, -`command` is a request, `record` is its requester's outcome, and `notice` is an -observer update. The authenticated address and role are read before the kind. -Unknown outcomes end only their matching request as unconfirmed; a notice does -not settle a request. A history page states which optional parts it supplies; -omitted parts do not clear a reader's existing data. -Joins and App discovery each require one exact private identifier. Domain and -App senders use the fields defined for each command, and most command variants -reject unknown keys. A few parameterless commands, including Domain `leave` -and App `targets`, ignore extra keys and execute the ordinary operation. -Native accepts extra Domain-event fields. Browser generally strips them and -passes room-host payloads through to Core. Nested schemas retain their own -checks. The [Core wire types](../../prototype/channel-core/src/wire.rs) and -[Browser decoder](../../src/client/channel/protocol.ts) own these -distinctions. Closing the distance to the rule above is release work in -[TODO](../todo.md). +Domain results use `reply`; the signed room carriers `command`, `record` and +`notice` mean request, requester reply and observer notification respectively. +The [Core wire types](../../prototype/channel-core/src/wire.rs), +[Browser decoder](../../src/client/channel/protocol.ts) and +[App discovery](../../src/client/channel/app-link.ts) own exact fields. +[TODO](../todo.md) tracks the remaining public baseline checks. ### Published 2.x -Published 2.x command/event contracts reject unknown keys, with an explicit -[receive-side exception](https://github.com/TNTcraftHIM/Piik/blob/main/docs/standards/rooms-access.md#room-interactions) for the bounded -display-only reaction identifier. A 2.x addition advertises an optional -capability and is exchanged only with sessions that selected it. Those rules -stay with the [maintenance line's standard](https://github.com/TNTcraftHIM/Piik/blob/main/docs/standards/versioning.md#extending-interfaces). - -In the 2.0 contract, numeric media descriptions and retry progress -are independent of current implementation limits and retry policy. Extending -those policies does not require another count-specific capability flag. -Representation acceptance still requires local operation/resource admission; -it is not a promise that every same-major peer can produce a new media format. +The 2.x maintenance line owns its published compatibility baseline, wire +identifiers and extension rules. See [2.x versioning](https://github.com/TNTcraftHIM/Piik/blob/main/docs/standards/versioning.md). ## Release And Recovery @@ -513,10 +482,9 @@ establish cross-origin fetch support. ## Public Release Baseline -The declared `v1.0.0` release starts the compatibility promise above. Its packages, -reviewed notes and descriptors are immutable. Subsequent releases preserve this -baseline through compatible upgrades; the remaining physical device/network -limits stay in [verification status](../verification-status.md). +The first public 3.0 release establishes the baseline for this major. Its +packages, reviewed notes and descriptors are immutable. See +[verification status](../verification-status.md) for device and network limits. ## References diff --git a/docs/status.md b/docs/status.md index 7c791402d..c5271c339 100644 --- a/docs/status.md +++ b/docs/status.md @@ -35,9 +35,9 @@ The [Server/App reference](../prototype/channel-server/README.md), Published 2.x compatibility is owned by the [maintenance contract](https://github.com/TNTcraftHIM/Piik/blob/main/docs/status.md#accepted-release-contract) and its [versioning rules](https://github.com/TNTcraftHIM/Piik/blob/main/docs/standards/versioning.md). -Internal 3.0 uses matching artifacts under this tree's -[versioning rules](./standards/versioning.md) and -[saved-data formats](../prototype/channel-server/README.md#saved-data-and-files). +The 3.0 candidate uses the product-version handshake. The first public baseline +and Browser/App mixed-version artifact acceptance remain open. +[3.0 versioning](./standards/versioning.md) ## Accepted Interaction Phase diff --git a/docs/todo.md b/docs/todo.md index ff1c052d1..6f40cd8c9 100644 --- a/docs/todo.md +++ b/docs/todo.md @@ -72,17 +72,19 @@ the feedback period; they do not delay that delivery. [ADR-0017](./adr/0017-contracts-fixed-before-release.md) against actual readers, writers and release storage fixtures. The [rule for extending interfaces](./standards/versioning.md#extending-interfaces) - is set: trace it through each connection, bring the private code to it and - exercise it in tests, then install the product-version handshake and verify - mixed-version artifacts before publication. Check compatibility before - redeeming a one-use local launch ticket. Do not add exact-version steps, - closed wire boundaries or individual feature flags meanwhile. + is set. Complete Browser/App mixed-version artifact acceptance before + publication alongside the SDK/Server controls. Confirm the [module and connection-pool owners](./standards/engineering.md#architecture-baseline) and [public compatibility boundary](./standards/versioning.md#public-compatibility-promise). Verify unknown request outcomes cannot confirm work in the selected Native, Browser and SDK readers. Keep API/Bot capabilities within existing actions and authority. [Adopted architecture](./adr/0016-shared-rust-core.md) · [Design review](./research/clean-room-design-review.md) +- [ ] **Peer control outcomes.** Give File and Watch controls explicit request, + reply and notice roles. Answer unknown requests without reading a source, + settle unknown replies only for the matching supplier, key and request, and + preserve other file ranges and Watch relay error codes. Verify the complete + Browser/WASM and Native paths under the same interface extension rule. - [ ] **Remaining ownership reductions.** Preserve platform queue retirement semantics and the destination writer's validation when sharing their owners. Review SQLite single-row storage and a diff --git a/docs/verification-status.md b/docs/verification-status.md index e38837db3..2c6c8137b 100644 --- a/docs/verification-status.md +++ b/docs/verification-status.md @@ -9,6 +9,14 @@ have separate records. [3.0 status](./status.md#isolated-30-prototype) · ## Current Evidence +Same-source SDK and Linux Server artifacts with product versions 3.0 and 3.1 +completed both pairing directions. Their compiled versions appeared in the real +Join and Welcome. Each pair created a private room, confirmed signed chat, +retained it after the sender left and served it to another admitted reader. +All four sessions received Leave confirmation. The standalone Server control +also rejected a different major before consuming the launch ticket, then +admitted a compatible client with that ticket exactly once. + An isolated Windows runner at `56092074` exercised the actual WebView2 window lifecycle and local stop shortcut. It verified candidate retirement, window and browser-process exit, profile cleanup, and all four combinations of extra Shift diff --git a/prototype/channel-android/Cargo.lock b/prototype/channel-android/Cargo.lock index ec52634f8..d68ffd87f 100644 --- a/prototype/channel-android/Cargo.lock +++ b/prototype/channel-android/Cargo.lock @@ -3912,6 +3912,7 @@ dependencies = [ "ed25519-dalek", "hmac 0.12.1", "rusqlite", + "semver", "serde", "serde_ignored", "serde_json", diff --git a/prototype/channel-browser/Cargo.lock b/prototype/channel-browser/Cargo.lock index 9bebd9db1..e7c246d9c 100644 --- a/prototype/channel-browser/Cargo.lock +++ b/prototype/channel-browser/Cargo.lock @@ -420,6 +420,7 @@ dependencies = [ "base64ct", "ed25519-dalek", "hmac", + "semver", "serde", "serde_ignored", "serde_json", diff --git a/prototype/channel-browser/node/text-participant.ts b/prototype/channel-browser/node/text-participant.ts index 095704ac9..d4db7b237 100644 --- a/prototype/channel-browser/node/text-participant.ts +++ b/prototype/channel-browser/node/text-participant.ts @@ -5,9 +5,11 @@ import { randomBytes, randomUUID } from 'node:crypto'; import WebSocket from 'ws'; import { z } from 'zod'; import type { MessageReactionSnapshot, ProfileUpdate, ReactionEvent, ReactionTarget } from '../../../src/client/channel/protocol'; -import init, { SessionSigner, verify_conversation } from '../pkg/piik_channel_browser.js'; -import { CHANNEL_PROTOCOL, HISTORY_INLINE_IMAGES, CHANNEL_EVENT_BYTES, CHANNEL_SESSION_LIMIT, CHANNEL_ROOM_LIMIT, channelWelcomeSchema, eventSchema, requireConversationDelivery, roomSchema, createRoomCommand, snapshotSchema, type ChannelCommand, type ChannelEvent, type ReceivedConversation, type ConversationReply, type ChannelMessage, type ChatOptions, type RoomSettings, type RoomSummary, type StoredMessage } from '../../../src/client/channel/protocol'; +import init, { SessionSigner, channel_wire_limits, verify_conversation } from '../pkg/piik_channel_browser.js'; +import { checkDomainVersion, HISTORY_INLINE_IMAGES, CHANNEL_EVENT_BYTES, CHANNEL_SESSION_LIMIT, CHANNEL_ROOM_LIMIT, channelWelcomeSchema, eventSchema, requireConversationDelivery, roomSchema, createRoomCommand, snapshotSchema, type ChannelCommand, type ChannelEvent, type ReceivedConversation, type ConversationReply, type ChannelMessage, type ChatOptions, type RoomSettings, type RoomSummary, type StoredMessage } from '../../../src/client/channel/protocol'; +import { productVersionSchema } from '../../../src/client/channel/product-version'; await init({ module_or_path: readFileSync(new URL('../pkg/piik_channel_browser_bg.wasm', import.meta.url)) }); +const productVersion = productVersionSchema.parse(JSON.parse(channel_wire_limits())); type ConversationCommand = Extract; @@ -27,21 +29,20 @@ const conversationRoomSchema = roomSchema.pick({ id: true, authorized: true, ava const conversationStateSchema = z.object({ channel: snapshotSchema.shape.channel.pick({ hostingMode: true }) .extend({ rooms: z.array(conversationRoomSchema).max(CHANNEL_ROOM_LIMIT) }), - sessions: z.array(snapshotSchema.shape.sessions.element.pick({ id: true, signingKey: true })).max(CHANNEL_SESSION_LIMIT), + sessions: z.array(snapshotSchema.shape.sessions.element.pick({ id: true, signingKey: true, major: true, minor: true })).max(CHANNEL_SESSION_LIMIT), }); const textWelcomeSchema = channelWelcomeSchema.extend({ state: conversationStateSchema, selfProfile: channelWelcomeSchema.shape.selfProfile.pick({ id: true }) }); const textStateSchema = z.object({ type: z.literal('state'), state: conversationStateSchema }); -const eventHeaderSchema = z.object({ type: z.string(), protocol: z.unknown().optional() }); +const eventHeaderSchema = z.object({ type: z.string() }); type TextEvent = ChannelEvent | z.infer | z.infer; function decodeTextEvent(raw: unknown, wireBytes: number): TextEvent | undefined { if (wireBytes > CHANNEL_EVENT_BYTES) throw new Error('Channel event exceeds frame limit'); - const header = eventHeaderSchema.parse(raw); - switch (header.type) { - case 'welcome': - if (header.protocol !== CHANNEL_PROTOCOL) throw new Error('incompatible_protocol'); - return textWelcomeSchema.parse(raw); + const { type } = eventHeaderSchema.parse(raw); + checkDomainVersion(raw, productVersion); + switch (type) { + case 'welcome': return textWelcomeSchema.parse(raw); case 'state': return textStateSchema.parse(raw); case 'conversation': case 'reply': case 'error': return eventSchema.parse(raw); // This participant neither installs media nor hosts rooms. @@ -125,7 +126,7 @@ export class TextParticipant extends EventEmitter { }; const join = () => { try { - this.write({ type: 'join', protocol: CHANNEL_PROTOCOL, snapshotForm: 'conversation', canUsePeerTransport: false, name: this.options.name ?? '', credential: this.credential, + this.write({ type: 'join', ...productVersion, snapshotForm: 'conversation', canUsePeerTransport: false, name: this.options.name ?? '', credential: this.credential, sessionId: this.sessionId, signingKey: Array.from(this.signer.signing_key()) }); } catch (error) { diff --git a/prototype/channel-browser/src/lib.rs b/prototype/channel-browser/src/lib.rs index b27ac8999..9982780d2 100644 --- a/prototype/channel-browser/src/lib.rs +++ b/prototype/channel-browser/src/lib.rs @@ -419,9 +419,10 @@ pub fn attachment_media_type(bytes: &[u8]) -> String { /// Static Browser and Node schemas are constructed before the WASM runtime starts. #[wasm_bindgen] pub fn channel_wire_limits() -> Result { - use piik_channel_core::{wire, MAX_ROOMS, MAX_SESSIONS, PROFILE_PAGE_SIZE}; + use piik_channel_core::{wire, MAX_ROOMS, MAX_SESSIONS, PRODUCT_VERSION, PROFILE_PAGE_SIZE}; encode(&serde_json::json!({ - "protocol": wire::CHANNEL_PROTOCOL, + "major": PRODUCT_VERSION.major, + "minor": PRODUCT_VERSION.minor, "sessions": MAX_SESSIONS, "rooms": MAX_ROOMS, "profilePage": PROFILE_PAGE_SIZE, diff --git a/prototype/channel-core/Cargo.lock b/prototype/channel-core/Cargo.lock index f9b27685f..f293995d3 100644 --- a/prototype/channel-core/Cargo.lock +++ b/prototype/channel-core/Cargo.lock @@ -432,6 +432,7 @@ dependencies = [ "ed25519-dalek", "hmac", "rusqlite", + "semver", "serde", "serde_ignored", "serde_json", diff --git a/prototype/channel-core/Cargo.toml b/prototype/channel-core/Cargo.toml index 3e268eeca..8689cc13c 100644 --- a/prototype/channel-core/Cargo.toml +++ b/prototype/channel-core/Cargo.toml @@ -9,6 +9,10 @@ publish = false default = [] sqlite = ["dep:rusqlite"] +[build-dependencies] +semver = "1" +serde_json = "1" + [dependencies] rusqlite = { version = "0.41", features = ["bundled", "backup", "fallible_uint"], optional = true } serde = { version = "1", features = ["derive"] } diff --git a/prototype/channel-core/build.rs b/prototype/channel-core/build.rs new file mode 100644 index 000000000..84d596902 --- /dev/null +++ b/prototype/channel-core/build.rs @@ -0,0 +1,36 @@ +use std::{env, fs, path::PathBuf}; + +fn main() { + println!("cargo:rerun-if-env-changed=PIIK_BUILD_VERSION"); + println!("cargo:rerun-if-changed=development-version.json"); + let version = env::var("PIIK_BUILD_VERSION").unwrap_or_else(|_| "development".into()); + let (major, minor) = if version == "development" { + let target: serde_json::Value = + serde_json::from_str(include_str!("development-version.json")) + .expect("Invalid development version"); + ( + target["major"].as_u64().unwrap(), + target["minor"].as_u64().unwrap(), + ) + } else { + let parsed = semver::Version::parse( + version + .strip_prefix('v') + .expect("Build version must start with v"), + ) + .expect("Invalid build version"); + assert!( + parsed.build.is_empty(), + "Build version cannot contain build metadata" + ); + (parsed.major, parsed.minor) + }; + let major = u32::try_from(major).expect("Product major exceeds u32"); + let minor = u32::try_from(minor).expect("Product minor exceeds u32"); + let output = PathBuf::from(env::var_os("OUT_DIR").unwrap()).join("product_version.rs"); + fs::write( + output, + format!("ProductVersion {{ major: {major}, minor: {minor} }}"), + ) + .unwrap(); +} diff --git a/prototype/channel-core/development-version.json b/prototype/channel-core/development-version.json new file mode 100644 index 000000000..85c3132be --- /dev/null +++ b/prototype/channel-core/development-version.json @@ -0,0 +1 @@ +{"major":3,"minor":0} diff --git a/prototype/channel-core/src/channel.rs b/prototype/channel-core/src/channel.rs index 1cd3a3c38..9f809cc61 100644 --- a/prototype/channel-core/src/channel.rs +++ b/prototype/channel-core/src/channel.rs @@ -2300,6 +2300,7 @@ impl Channel { sessions: self.identity.sessions.values().map(|session| SigningSession { id: session.id, signing_key: session.signing_key, + version: session.version, }).collect(), } } @@ -2428,6 +2429,7 @@ impl Channel { user_id: session.user_id, online: session.connection.is_some(), signing_key: session.signing_key, + version: session.version, }) .collect(), publications, diff --git a/prototype/channel-core/src/channel/discovery.rs b/prototype/channel-core/src/channel/discovery.rs index df4a7a922..83e336c17 100644 --- a/prototype/channel-core/src/channel/discovery.rs +++ b/prototype/channel-core/src/channel/discovery.rs @@ -823,6 +823,7 @@ mod tests { identity .admit( Admission { + version: crate::PRODUCT_VERSION, snapshot_form: Default::default(), name, signing_key: [0; 32], diff --git a/prototype/channel-core/src/channel_tests.rs b/prototype/channel-core/src/channel_tests.rs index 6271bbd79..dd2c625b3 100644 --- a/prototype/channel-core/src/channel_tests.rs +++ b/prototype/channel-core/src/channel_tests.rs @@ -106,6 +106,7 @@ fn image_directory_and_active_host_output_fit_the_domain_socket_budget() { channel .join( Admission { + version: crate::PRODUCT_VERSION, snapshot_form: Default::default(), capabilities: PeerCapabilities { can_use_peer_transport: true, @@ -429,6 +430,7 @@ fn text_limits_match_browser_utf16_and_room_history() { let owner = channel .join( Admission { + version: crate::PRODUCT_VERSION, snapshot_form: Default::default(), capabilities: PeerCapabilities { can_use_peer_transport: true, @@ -527,6 +529,7 @@ fn consecutive_profile_and_domain_patches_merge_before_projection() { let owner = channel .join( Admission { + version: crate::PRODUCT_VERSION, snapshot_form: Default::default(), capabilities: PeerCapabilities { can_use_peer_transport: true, diff --git a/prototype/channel-core/src/identity.rs b/prototype/channel-core/src/identity.rs index ffad287c0..7a617efec 100644 --- a/prototype/channel-core/src/identity.rs +++ b/prototype/channel-core/src/identity.rs @@ -99,6 +99,7 @@ pub struct Session { pub user_id: Uuid, pub connection: Option, pub snapshot_form: SnapshotForm, + pub version: crate::ProductVersion, pub disconnected_at: Option, pub signing_key: [u8; 32], pub capabilities: PeerCapabilities, @@ -114,6 +115,7 @@ pub struct Identity { pub struct Admission<'a> { pub snapshot_form: SnapshotForm, + pub version: crate::ProductVersion, pub signing_key: [u8; 32], pub capabilities: PeerCapabilities, pub credential: Option<&'a str>, @@ -338,9 +340,11 @@ impl Identity { snapshot_form: input.snapshot_form, disconnected_at: None, signing_key: input.signing_key, + version: input.version, capabilities: input.capabilities, }); session.signing_key = input.signing_key; + session.version = input.version; let peer_transport_withdrawn = session.capabilities.can_use_peer_transport && !input.capabilities.can_use_peer_transport; session.capabilities = input.capabilities; @@ -464,6 +468,7 @@ mod tests { resume: Option<&'a str>, ) -> Admission<'a> { Admission { + version: crate::PRODUCT_VERSION, snapshot_form: Default::default(), signing_key: [1; 32], capabilities: PeerCapabilities { diff --git a/prototype/channel-core/src/lib.rs b/prototype/channel-core/src/lib.rs index c29887464..865d8bf4f 100644 --- a/prototype/channel-core/src/lib.rs +++ b/prototype/channel-core/src/lib.rs @@ -18,6 +18,7 @@ pub mod history; pub mod host; mod identity; pub mod input; +mod product_version; mod publication; mod remote; mod room; @@ -38,6 +39,7 @@ pub use access::{ }; pub use attachment::{AttachmentDescriptor, AttachmentLimits, ATTACHMENT_LIMITS}; pub use channel::{DomainStateHeader, DurableState, MAX_ROOMS}; +pub use product_version::{ProductVersion, PRODUCT_VERSION}; pub use identity::{Endpoint, Member, User, MAX_SESSIONS, PROFILE_PAGE_SIZE, RECOVERY_MS}; pub use room::{RoomRecipient, RoomRuntime, RoomSnapshot}; #[cfg(feature = "sqlite")] @@ -48,7 +50,7 @@ use host::{RequestContext, RoomReply, RoomResult}; use identity::{Admission, PeerCapabilities}; use serde_json::Value; use uuid::Uuid; -use wire::{Command, Event, ProfileId, ReplyResult, Request, SnapshotForm, CHANNEL_PROTOCOL}; +use wire::{Command, Event, ProfileId, ReplyResult, Request, SnapshotForm}; /// Events are addressed to physical connections, not reusable endpoint sessions. /// Deliver events before closing the listed connections so leave can acknowledge. @@ -618,14 +620,8 @@ impl Authority { } fn join(&mut self, connection: Uuid, request: Request, now: u64, effects: &mut Effects) { - if matches!(&request.command, Command::Join { protocol, .. } if *protocol != CHANNEL_PROTOCOL) - { - Self::error(connection, None, "incompatible_protocol", effects); - effects.close.push(connection); - return; - } let Command::Join { - protocol: _, + version, snapshot_form, name, credential, @@ -647,8 +643,14 @@ impl Authority { effects.close.push(connection); return; }; + if !version.is_compatible() { + effects.events.push((connection, Event::IncompatibleVersion { version: PRODUCT_VERSION })); + effects.close.push(connection); + return; + } match self.channel.join( Admission { + version, snapshot_form, name: &name, credential: credential.as_deref(), @@ -675,7 +677,7 @@ impl Authority { let user_id = self.channel.identity.sessions[&session_id].user_id; let welcome = match snapshot_form { SnapshotForm::Full => Event::Welcome { - protocol: CHANNEL_PROTOCOL, + version: PRODUCT_VERSION, self_profile: self.channel.identity.users[&user_id].profile(), credential: admitted.credential, session_id, @@ -684,7 +686,7 @@ impl Authority { invitation_origin: None, }, SnapshotForm::Conversation => Event::ConversationWelcome { - protocol: CHANNEL_PROTOCOL, + version: PRODUCT_VERSION, self_profile: ProfileId { id: user_id }, credential: admitted.credential, session_id, diff --git a/prototype/channel-core/src/product_version.rs b/prototype/channel-core/src/product_version.rs new file mode 100644 index 000000000..02907c052 --- /dev/null +++ b/prototype/channel-core/src/product_version.rs @@ -0,0 +1,16 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] +pub struct ProductVersion { + pub major: u32, + pub minor: u32, +} + +impl ProductVersion { + pub fn is_compatible(self) -> bool { + self.major == PRODUCT_VERSION.major + } +} + +pub const PRODUCT_VERSION: ProductVersion = + include!(concat!(env!("OUT_DIR"), "/product_version.rs")); diff --git a/prototype/channel-core/src/transport.rs b/prototype/channel-core/src/transport.rs index 43cde2492..704fd397d 100644 --- a/prototype/channel-core/src/transport.rs +++ b/prototype/channel-core/src/transport.rs @@ -883,6 +883,7 @@ mod tests { identity.sessions.insert( id, crate::identity::Session { + version: crate::PRODUCT_VERSION, id, user_id: id, connection: Some(socket), @@ -1352,6 +1353,7 @@ mod tests { identity.sessions.insert( id, crate::identity::Session { + version: crate::PRODUCT_VERSION, id, user_id: id, connection: Some(socket), diff --git a/prototype/channel-core/src/wire.rs b/prototype/channel-core/src/wire.rs index bd2dbd4e6..cd1414080 100644 --- a/prototype/channel-core/src/wire.rs +++ b/prototype/channel-core/src/wire.rs @@ -4,7 +4,8 @@ use serde_json::Value; use std::collections::BTreeMap; use uuid::Uuid; -pub const CHANNEL_PROTOCOL: u8 = 55; +use crate::{ProductVersion, PRODUCT_VERSION}; + pub const CHANNEL_MESSAGE_BYTES: usize = 4 * 1024 * 1024; #[derive(Clone, Deserialize, Serialize)] @@ -17,8 +18,8 @@ pub enum Command { Join { #[serde(default, skip_serializing_if = "SnapshotForm::is_full")] snapshot_form: SnapshotForm, - #[serde(default)] - protocol: u8, + #[serde(flatten)] + version: ProductVersion, name: String, credential: Option, owner_key: Option, @@ -285,7 +286,25 @@ pub struct Request { impl Request { pub fn parse(text: &str) -> Result, &'static str)> { - let mut input: Value = serde_json::from_str(text).map_err(|_| (None, "invalid_request"))?; + let input = serde_json::from_str(text).map_err(|_| (None, "invalid_request"))?; + Self::from_value(input) + } + + /// Check the Join header before decoding fields owned by its major version. + pub fn parse_first(text: &str) -> Result> { + fn error((id, code): (Option, &'static str)) -> Box { + Box::new(Event::completion(id, None, ReplyResult::Error { code: code.into() })) + } + let input: Value = serde_json::from_str(text).map_err(|_| error((None, "invalid_request")))?; + if input["type"] == "join" + && ProductVersion::deserialize(&input).is_ok_and(|version| !version.is_compatible()) + { + return Err(Box::new(Event::IncompatibleVersion { version: PRODUCT_VERSION })); + } + Self::from_value(input).map_err(error) + } + + fn from_value(mut input: Value) -> Result, &'static str)> { let object = input.as_object_mut().ok_or((None, "invalid_request"))?; let request_id = match object.remove("requestId") { Some(Value::String(id)) if valid_id(&id) => Some(id), @@ -967,6 +986,8 @@ pub struct SessionInfo { pub user_id: Uuid, pub online: bool, pub signing_key: [u8; 32], + #[serde(flatten)] + pub version: ProductVersion, } #[derive(Clone, Deserialize, Serialize)] @@ -1104,6 +1125,8 @@ pub struct ConversationRoomInfo { pub struct SigningSession { pub id: Uuid, pub signing_key: [u8; 32], + #[serde(flatten)] + pub version: ProductVersion, } #[derive(Clone, Serialize)] @@ -1161,8 +1184,13 @@ pub enum Event { room_id: String, input: crate::host::HostInput, }, + IncompatibleVersion { + #[serde(flatten)] + version: ProductVersion, + }, Welcome { - protocol: u8, + #[serde(flatten)] + version: ProductVersion, credential: String, self_profile: UserInfo, session_id: Uuid, @@ -1176,7 +1204,8 @@ pub enum Event { }, #[serde(rename(serialize = "welcome"), skip_deserializing)] ConversationWelcome { - protocol: u8, + #[serde(flatten)] + version: ProductVersion, credential: String, self_profile: ProfileId, session_id: Uuid, diff --git a/prototype/channel-core/src/wire_images.rs b/prototype/channel-core/src/wire_images.rs index 167fef520..5467a4753 100644 --- a/prototype/channel-core/src/wire_images.rs +++ b/prototype/channel-core/src/wire_images.rs @@ -1,5 +1,6 @@ //! Physical WebSocket image transfer. Domain state remains a complete Snapshot. use crate::wire::{Event, Snapshot, CHANNEL_MESSAGE_BYTES}; +use serde::Deserialize; use serde_json::{Map, Value}; use std::collections::BTreeMap; use uuid::Uuid; @@ -145,8 +146,10 @@ impl StateImageDecoder { let mut value: Value = serde_json::from_str(text).map_err(|_| "invalid_channel_event")?; match value.get("type").and_then(Value::as_str) { Some("welcome") => { - if value["protocol"] != crate::wire::CHANNEL_PROTOCOL { - return Err("incompatible_protocol"); + let version = crate::ProductVersion::deserialize(&value) + .map_err(|_| "invalid_channel_event")?; + if !version.is_compatible() { + return Ok(Event::IncompatibleVersion { version }); } Images::default().transform(&mut value["state"], true)?; } @@ -174,14 +177,14 @@ impl StateImageDecoder { mod tests { use super::*; use crate::{ - wire::{Request, CHANNEL_PROTOCOL}, + wire::Request, PRODUCT_VERSION, Authority, }; use serde_json::json; fn welcome() -> Event { let mut core = Authority::new("owner".into(), vec![]).unwrap(); - core.handle(Uuid::new_v4(), Request::parse(&json!({"type":"join","protocol":CHANNEL_PROTOCOL,"canUsePeerTransport":false,"name":"Owner","ownerKey":"owner","signingKey":vec![1;32]}).to_string()).unwrap(), 0) + core.handle(Uuid::new_v4(), Request::parse(&json!({"type":"join","major":PRODUCT_VERSION.major,"minor":PRODUCT_VERSION.minor,"canUsePeerTransport":false,"name":"Owner","ownerKey":"owner","signingKey":vec![1;32]}).to_string()).unwrap(), 0) .events.into_iter().find_map(|(_, event)| matches!(event, Event::Welcome { .. }).then_some(event)).unwrap() } @@ -189,18 +192,19 @@ mod tests { fn incompatible_welcome_is_rejected_before_reading_its_state() { let full = serde_json::to_value(welcome()).unwrap(); let mut previous = full.clone(); - previous["protocol"] = json!(CHANNEL_PROTOCOL - 1); + previous["major"] = json!(PRODUCT_VERSION.major ^ 1); + previous.as_object_mut().unwrap().remove("state"); let mut missing = full; - missing.as_object_mut().unwrap().remove("protocol"); + missing.as_object_mut().unwrap().remove("minor"); missing.as_object_mut().unwrap().remove("state"); - for value in [previous, missing] { - assert_eq!( - StateImageDecoder::default() - .decode(&value.to_string()) - .err(), - Some("incompatible_protocol") - ); - } + assert!(matches!( + StateImageDecoder::default().decode(&previous.to_string()), + Ok(Event::IncompatibleVersion { version }) if version.major == (PRODUCT_VERSION.major ^ 1) + )); + assert_eq!( + StateImageDecoder::default().decode(&missing.to_string()).err(), + Some("invalid_channel_event") + ); } #[test] @@ -332,7 +336,8 @@ mod tests { decoder.decode(&encoder.encode(&greeting).unwrap()).unwrap(); let mut invalid_welcome: Value = serde_json::from_str(&compact).unwrap(); invalid_welcome["type"] = json!("welcome"); - invalid_welcome["protocol"] = json!(CHANNEL_PROTOCOL); + invalid_welcome["major"] = json!(PRODUCT_VERSION.major); + invalid_welcome["minor"] = json!(PRODUCT_VERSION.minor); assert_eq!( decoder.decode(&invalid_welcome.to_string()).err(), Some("missing_identity_image") diff --git a/prototype/channel-core/tests/authority.rs b/prototype/channel-core/tests/authority.rs index ba9c95a3b..ea60e2152 100644 --- a/prototype/channel-core/tests/authority.rs +++ b/prototype/channel-core/tests/authority.rs @@ -8,8 +8,9 @@ use uuid::Uuid; fn apply(core: &mut Authority, connection: Uuid, mut command: Value, now: u64) -> Effects { if command["type"] == "join" { - if command.get("protocol").is_none() { - command["protocol"] = json!(piik_channel_core::wire::CHANNEL_PROTOCOL); + if command.get("major").is_none() { + command["major"] = json!(piik_channel_core::PRODUCT_VERSION.major); + command["minor"] = json!(piik_channel_core::PRODUCT_VERSION.minor); } command["signingKey"] = json!(piik_channel_core::conversation::SessionSigner::from_seed([1; 32]).signing_key()); @@ -323,43 +324,44 @@ fn retained_profiles_are_read_in_bounded_pages_without_consuming_live_identity_c } #[test] -fn domain_protocol_rejects_old_clients_before_admission() { +fn join_version_is_checked_before_admission_and_tracks_the_resumed_signer() { + use piik_channel_core::PRODUCT_VERSION; + let mut core = Authority::new("owner".into(), vec![]).unwrap(); - let before = serde_json::to_value(core.export_backup()).unwrap(); - for protocol in [ - None, - Some(0), - Some(1), - Some(2), - Some(3), - Some(4), - Some(5), - Some(6), - Some(piik_channel_core::wire::CHANNEL_PROTOCOL - 1), - ] { - let connection = Uuid::new_v4(); - let mut join = json!({"type":"join","name":"Old","requestId":"join", - "signingKey":piik_channel_core::conversation::SessionSigner::from_seed([1; 32]).signing_key()}); - if let Some(protocol) = protocol { - join["protocol"] = json!(protocol); - } - let effects = core.handle(connection, Request::parse(&join.to_string()).unwrap(), 0); - assert!(effects.close.contains(&connection)); - assert!(effects.events.iter().any(|(_, event)| matches!(event, Event::Error { code, .. } | Event::Reply { result: ReplyResult::Error { code }, .. } if code == "incompatible_protocol"))); - assert!(!effects - .events - .iter() - .any(|(_, event)| matches!(event, Event::Welcome { .. } | Event::HostInput { .. }))); - assert_eq!(serde_json::to_value(core.export_backup()).unwrap(), before); - } let connection = Uuid::new_v4(); - let effects = apply( - &mut core, - connection, - json!({"type":"join","name":"Current"}), - 0, - ); - assert!(effects.events.iter().any(|(_, event)| matches!(event, Event::Welcome { protocol, .. } if *protocol == piik_channel_core::wire::CHANNEL_PROTOCOL))); + let incompatible = PRODUCT_VERSION.major ^ 1; + let refusal = json!({"type":"incompatible_version","major":PRODUCT_VERSION.major,"minor":PRODUCT_VERSION.minor}); + let mut command = json!({"type":"join","major":incompatible,"minor":0,"name":false}); + let event = Request::parse_first(&command.to_string()).err().unwrap(); + assert_eq!(serde_json::to_value(event).unwrap(), refusal); + + command["major"] = json!(PRODUCT_VERSION.major); + command["requestId"] = json!("join"); + let invalid = Request::parse_first(&command.to_string()).err().unwrap(); + assert!(matches!(*invalid, Event::Reply { request_id, result: ReplyResult::Error { code }, .. } if request_id == "join" && code == "invalid_request")); + let effects = apply(&mut core, connection, json!({"type":"join","major":incompatible,"minor":0,"name":"Friend"}), 0); + assert_eq!(effects.close, [connection]); + assert_eq!(effects.events.len(), 1); + assert_eq!(serde_json::to_value(&effects.events[0].1).unwrap(), refusal); + + let minor = PRODUCT_VERSION.minor ^ 1; + let join = json!({"type":"join","name":"Friend","major":PRODUCT_VERSION.major,"minor":minor}); + let effects = apply(&mut core, connection, join, 0); + let Event::Welcome { version, state, session_id, credential, .. } = &effects.events[0].1 else { panic!("expected welcome") }; + assert_eq!(*version, PRODUCT_VERSION); + assert_eq!(state.sessions.len(), 1); + assert_eq!(state.sessions[0].version.minor, minor); + let resume = json!({"type":"join","major":PRODUCT_VERSION.major,"minor":PRODUCT_VERSION.minor, + "snapshotForm":"conversation","name":"Friend","sessionId":session_id,"credential":credential, + "signingKey":vec![2; 32]}); + let resumed = core.handle(Uuid::new_v4(), Request::parse_first(&resume.to_string()).ok().unwrap(), 1); + assert_eq!(resumed.close, [connection]); + let Event::ConversationWelcome { version, state, .. } = &resumed.events[0].1 else { panic!("expected resumed welcome") }; + assert_eq!(*version, PRODUCT_VERSION); + assert_eq!(state.sessions.len(), 1); + assert_eq!(state.sessions[0].id, *session_id); + assert_eq!(state.sessions[0].version, PRODUCT_VERSION); + assert_eq!(state.sessions[0].signing_key, [2; 32]); } #[test] diff --git a/prototype/channel-core/tests/base_routes.rs b/prototype/channel-core/tests/base_routes.rs index cb18f416b..43f6e2807 100644 --- a/prototype/channel-core/tests/base_routes.rs +++ b/prototype/channel-core/tests/base_routes.rs @@ -3958,7 +3958,7 @@ fn confirmed_business_pairs_follow_room_scope_sockets_and_flow_leases() { ); let resumed = Uuid::new_v4(); let effects = network.authority.handle(resumed, Request::parse(&json!({ - "type":"join", "canUsePeerTransport":true,"protocol":piik_channel_core::wire::CHANNEL_PROTOCOL, + "type":"join", "canUsePeerTransport":true,"major":piik_channel_core::PRODUCT_VERSION.major,"minor":piik_channel_core::PRODUCT_VERSION.minor, "name":"Returning viewer","credential":credential,"sessionId":b, "signingKey":piik_channel_core::conversation::SessionSigner::from_seed([1;32]).signing_key() }).to_string()).unwrap(), 101); @@ -5727,7 +5727,7 @@ fn resuming_without_peer_transport_retires_media_and_file_routes_but_keeps_room_ let old_output = net.host_turn(&room, input); assert!(old_output.projection.relay_session_ids.contains(&participant)); let sync = net.authority.handle(resumed, request(json!({"type":"join","name":"Same reader", - "credential":credential,"protocol":piik_channel_core::wire::CHANNEL_PROTOCOL,"sessionId":participant, + "credential":credential,"major":piik_channel_core::PRODUCT_VERSION.major,"minor":piik_channel_core::PRODUCT_VERSION.minor,"sessionId":participant, "signingKey":piik_channel_core::conversation::SessionSigner::from_seed([1;32]).signing_key()})), 101); let pending = net.authority.handle(owner, request(json!({"type":"host_output","roomId":room,"output":old_output})), 101); assert!(!pending.events.iter().any(|(_, event)| matches!(event, Event::Error { .. } | Event::Reply { result: ReplyResult::Error { .. }, .. } | Event::Reply { room_id: Some(_), .. }))); diff --git a/prototype/channel-core/tests/host_review.rs b/prototype/channel-core/tests/host_review.rs index f860b3d7f..2e8a32340 100644 --- a/prototype/channel-core/tests/host_review.rs +++ b/prototype/channel-core/tests/host_review.rs @@ -143,7 +143,7 @@ fn review_admit(core: &mut piik_channel_core::Authority, connection: Uuid, key: core.handle( connection, piik_channel_core::wire::Request::parse( - &serde_json::json!({"type":"join","canUsePeerTransport":true,"protocol":piik_channel_core::wire::CHANNEL_PROTOCOL,"signingKey":piik_channel_core::conversation::SessionSigner::from_seed([1; 32]).signing_key(),"name":"Review","ownerKey":(key=="owner").then_some(key)}).to_string(), + &serde_json::json!({"type":"join","canUsePeerTransport":true,"major":piik_channel_core::PRODUCT_VERSION.major,"minor":piik_channel_core::PRODUCT_VERSION.minor,"signingKey":piik_channel_core::conversation::SessionSigner::from_seed([1; 32]).signing_key(),"name":"Review","ownerKey":(key=="owner").then_some(key)}).to_string(), ) .unwrap(), 0, @@ -279,7 +279,7 @@ fn pending_room_request_finishes_when_its_host_binding_retires() { let reader = Uuid::new_v4(); review_admit(&mut core, owner, "owner"); let joined = core.handle(reader, Request::parse(&serde_json::json!({ - "type":"join","canUsePeerTransport":true,"protocol":piik_channel_core::wire::CHANNEL_PROTOCOL, "name":"Reader", "signingKey":piik_channel_core::conversation::SessionSigner::from_seed([2; 32]).signing_key() + "type":"join","canUsePeerTransport":true,"major":piik_channel_core::PRODUCT_VERSION.major,"minor":piik_channel_core::PRODUCT_VERSION.minor, "name":"Reader", "signingKey":piik_channel_core::conversation::SessionSigner::from_seed([2; 32]).signing_key() }).to_string()).unwrap(), 0); let (reader_session, credential) = joined .events @@ -393,7 +393,7 @@ fn pending_room_request_finishes_when_its_host_binding_retires() { let replacement = Uuid::new_v4(); if case == "requester-replaced" { core.handle(replacement, Request::parse(&serde_json::json!({ - "type":"join","canUsePeerTransport":true,"protocol":piik_channel_core::wire::CHANNEL_PROTOCOL, "name":"Reader", "credential":credential, "sessionId":reader_session, + "type":"join","canUsePeerTransport":true,"major":piik_channel_core::PRODUCT_VERSION.major,"minor":piik_channel_core::PRODUCT_VERSION.minor, "name":"Reader", "credential":credential, "sessionId":reader_session, "signingKey":piik_channel_core::conversation::SessionSigner::from_seed([2; 32]).signing_key() }).to_string()).unwrap(), 2); } @@ -1664,7 +1664,7 @@ fn host_output_requires_current_pairs_for_new_media_and_scopes_screen_helpers() let effects = core.handle( socket, Request::parse( - &json!({"type":"join","canUsePeerTransport":true,"protocol":piik_channel_core::wire::CHANNEL_PROTOCOL, + &json!({"type":"join","canUsePeerTransport":true,"major":piik_channel_core::PRODUCT_VERSION.major,"minor":piik_channel_core::PRODUCT_VERSION.minor, "name":"Viewer","signingKey":signer,"credential":credential,"sessionId":resume}) .to_string(), ) diff --git a/prototype/channel-core/tests/room_access.rs b/prototype/channel-core/tests/room_access.rs index d3d7cf991..9d52b7d88 100644 --- a/prototype/channel-core/tests/room_access.rs +++ b/prototype/channel-core/tests/room_access.rs @@ -1690,7 +1690,7 @@ fn conversation_snapshot_follows_current_connection_and_room_authority() { fields }).collect::>()}, "sessions":state.sessions.iter().map(|session| json!({ - "id":session.id,"signingKey":session.signing_key + "id":session.id,"signingKey":session.signing_key,"major":session.version.major,"minor":session.version.minor })).collect::>(), }); let effects = command(&mut network, text, reopen("conversation")); diff --git a/prototype/channel-core/tests/support/mod.rs b/prototype/channel-core/tests/support/mod.rs index 6564850fc..f122cdce4 100644 --- a/prototype/channel-core/tests/support/mod.rs +++ b/prototype/channel-core/tests/support/mod.rs @@ -39,8 +39,9 @@ impl RoomNetwork { } pub fn command_at(&mut self, connection: Uuid, mut value: Value, now: u64) -> Effects { - if value["type"] == "join" && value.get("protocol").is_none() { - value["protocol"] = json!(piik_channel_core::wire::CHANNEL_PROTOCOL); + if value["type"] == "join" && value.get("major").is_none() { + value["major"] = json!(piik_channel_core::PRODUCT_VERSION.major); + value["minor"] = json!(piik_channel_core::PRODUCT_VERSION.minor); value.as_object_mut().unwrap().entry("canUsePeerTransport").or_insert(json!(true)); } if value["type"] == "join" && value.get("signingKey").is_none() { diff --git a/prototype/channel-native/Cargo.lock b/prototype/channel-native/Cargo.lock index a4aa3b17a..0d4eea317 100644 --- a/prototype/channel-native/Cargo.lock +++ b/prototype/channel-native/Cargo.lock @@ -2832,6 +2832,7 @@ dependencies = [ "ed25519-dalek", "hmac 0.12.1", "rusqlite", + "semver", "serde", "serde_ignored", "serde_json", diff --git a/prototype/channel-native/src/backup.rs b/prototype/channel-native/src/backup.rs index 8834a873d..4312e4462 100644 --- a/prototype/channel-native/src/backup.rs +++ b/prototype/channel-native/src/backup.rs @@ -634,7 +634,7 @@ mod tests { #[test] fn domain_archive_contains_only_its_own_authority() -> Result<()> { use base64::Engine; - use piik_channel_core::wire::{Event, Request, CHANNEL_PROTOCOL}; + use piik_channel_core::{wire::{Event, Request}, PRODUCT_VERSION}; let mut authority = Authority::new("owner".into(), vec![]).unwrap(); let mut png = base64::engine::general_purpose::STANDARD.decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4z8DwHwAFgAI/ScLbtAAAAABJRU5ErkJggg==")?; png.resize( @@ -650,7 +650,7 @@ mod tests { let mut identities = Vec::new(); for index in 0..200 { let connection = Uuid::new_v4(); - let request = serde_json::json!({"type":"join","protocol":CHANNEL_PROTOCOL,"canUsePeerTransport":false,"name":format!("Friend {index}"),"ownerKey":(index==0).then_some("owner"),"signingKey":vec![1;32]}); + let request = serde_json::json!({"type":"join","major":PRODUCT_VERSION.major,"minor":PRODUCT_VERSION.minor,"canUsePeerTransport":false,"name":format!("Friend {index}"),"ownerKey":(index==0).then_some("owner"),"signingKey":vec![1;32]}); let effects = authority.handle(connection, Request::parse(&request.to_string()).unwrap(), 0); let (credential, _) = effects diff --git a/prototype/channel-native/src/peer/input.rs b/prototype/channel-native/src/peer/input.rs index ec2531458..03fa53832 100644 --- a/prototype/channel-native/src/peer/input.rs +++ b/prototype/channel-native/src/peer/input.rs @@ -382,6 +382,7 @@ pub(super) mod tests { user_id: id(3), online: true, signing_key: [0; 32], + version: piik_channel_core::PRODUCT_VERSION, }], publications: vec![PublicationInfo { screen: Some(piik_channel_core::wire::ScreenInfo { diff --git a/prototype/channel-native/src/peer/tests.rs b/prototype/channel-native/src/peer/tests.rs index 40804243f..6d2830b15 100644 --- a/prototype/channel-native/src/peer/tests.rs +++ b/prototype/channel-native/src/peer/tests.rs @@ -212,7 +212,8 @@ async fn capture_scope_survives_host_signaling_recovery_but_not_retired_authorit fn send(core: &mut Authority, connection: Uuid, mut command: Value, now: u64) -> Effects { if command["type"] == "join" { - command["protocol"] = json!(piik_channel_core::wire::CHANNEL_PROTOCOL); + command["major"] = json!(piik_channel_core::PRODUCT_VERSION.major); + command["minor"] = json!(piik_channel_core::PRODUCT_VERSION.minor); command["signingKey"] = json!( piik_channel_core::conversation::SessionSigner::from_seed([1; 32]).signing_key() ); diff --git a/prototype/channel-native/src/session.rs b/prototype/channel-native/src/session.rs index 3525e8ffc..4ae0f48ff 100644 --- a/prototype/channel-native/src/session.rs +++ b/prototype/channel-native/src/session.rs @@ -21,7 +21,7 @@ use piik_channel_core::{ Command, Event, Kind, PublicationInput, ReplyResult, Room, RoomAccess, RoomDelivery, Snapshot, VideoSettings, }, - RoomState, RECOVERY_MS, + RoomState, PRODUCT_VERSION, RECOVERY_MS, }; use std::sync::{ atomic::{AtomicBool, Ordering}, @@ -1047,7 +1047,7 @@ impl Session { if let Ok(Ok((mut socket, _))) = connection { let join = Command::Join { snapshot_form: Default::default(), - protocol: piik_channel_core::wire::CHANNEL_PROTOCOL, + version: PRODUCT_VERSION, can_use_peer_transport: true, can_prepare_udp: self.config.server_udp.is_none(), can_receive_video_layers: true, @@ -1277,12 +1277,25 @@ impl Session { match message { Some(Incoming { text, _budget }) => { let event = images.decode(&text).map_err(anyhow::Error::msg)?; - if matches!(event, Event::Welcome { .. }) { - admitted = true; - self.recovery = None; - } - if let Event::Error { code, .. } = &event { - if !admitted { bail!("admission failed: {code}"); } + match &event { + Event::Welcome { .. } => { + admitted = true; + self.recovery = None; + } + Event::IncompatibleVersion { version } => { + let (code, update) = if version.major > PRODUCT_VERSION.major { + ("app-update", "Update the App") + } else { + ("domain_update_required", "Update the Site's Server") + }; + return Err(anyhow!("{update} (App {}.{}, Server {}.{})", + PRODUCT_VERSION.major, PRODUCT_VERSION.minor, version.major, version.minor) + .context(code)); + } + Event::Error { code, .. } if !admitted => { + bail!("admission failed: {code}"); + } + _ => {} } pending = Some((event, _budget)); }, diff --git a/prototype/channel-native/src/session/composition_tests.rs b/prototype/channel-native/src/session/composition_tests.rs index 0e307f154..1c20aa79f 100644 --- a/prototype/channel-native/src/session/composition_tests.rs +++ b/prototype/channel-native/src/session/composition_tests.rs @@ -453,7 +453,7 @@ async fn stored_room_commit_precedes_reply_and_stop_discards_queued_work() -> Re }); let join = Command::Join { snapshot_form: Default::default(), - protocol: piik_channel_core::wire::CHANNEL_PROTOCOL, + version: piik_channel_core::PRODUCT_VERSION, name: "Owned".into(), credential: None, owner_key: None, diff --git a/prototype/channel-native/src/session/connection_tests.rs b/prototype/channel-native/src/session/connection_tests.rs index a1e020ea8..a8cece200 100644 --- a/prototype/channel-native/src/session/connection_tests.rs +++ b/prototype/channel-native/src/session/connection_tests.rs @@ -3,12 +3,29 @@ use super::*; #[tokio::test] async fn reader_preserves_rejection_and_malformed_frame_before_close() { use tokio_tungstenite::tungstenite::protocol::Role; - for (text, expected) in [ + let (major, minor) = (PRODUCT_VERSION.major, PRODUCT_VERSION.minor); + for (text, expected, direction) in [ ( - r#"{"type":"error","code":"forbidden"}"#, + r#"{"type":"error","code":"forbidden"}"#.to_owned(), "admission failed: forbidden", + None, ), - ("not-json", "invalid_channel_event"), + ( + serde_json::json!({"type":"incompatible_version","major":major+1,"minor":minor}).to_string(), + "Update the App", + Some("app-update"), + ), + ( + serde_json::json!({"type":"incompatible_version","major":major-1,"minor":minor}).to_string(), + "Update the Site's Server", + Some("domain_update_required"), + ), + ( + serde_json::json!({"type":"welcome","major":major+1,"minor":minor}).to_string(), + "Update the App", + Some("app-update"), + ), + ("not-json".to_owned(), "invalid_channel_event", None), ] { let (local, remote) = tokio::io::duplex(4096); let mut socket = WebSocketStream::from_raw_socket(local, Role::Client, None).await; @@ -16,7 +33,7 @@ async fn reader_preserves_rejection_and_malformed_frame_before_close() { let mut session = connection_session("ws://memory.invalid".into()); let join = Command::Join { snapshot_form: Default::default(), - protocol: piik_channel_core::wire::CHANNEL_PROTOCOL, + version: piik_channel_core::PRODUCT_VERSION, name: "Memory client".into(), credential: None, owner_key: None, @@ -33,7 +50,10 @@ async fn reader_preserves_rejection_and_malformed_frame_before_close() { .connected(&mut socket, join, &mut stop) .await .unwrap_err(); - assert!(error.to_string().contains(expected), "{error:#}"); + assert!(format!("{error:#}").contains(expected), "{error:#}"); + if let Some(code) = direction { + assert_eq!(error.to_string(), code); + } } } @@ -90,7 +110,7 @@ async fn reader_keeps_invalid_utf8_on_carrier_recovery_path() { let mut session = connection_session("ws://memory.invalid".into()); let join = Command::Join { snapshot_form: Default::default(), - protocol: piik_channel_core::wire::CHANNEL_PROTOCOL, + version: piik_channel_core::PRODUCT_VERSION, name: "Memory client".into(), credential: None, owner_key: None, diff --git a/prototype/channel-native/src/session/core_burst.rs b/prototype/channel-native/src/session/core_burst.rs index 35ab656b4..3e68fd208 100644 --- a/prototype/channel-native/src/session/core_burst.rs +++ b/prototype/channel-native/src/session/core_burst.rs @@ -2,8 +2,8 @@ use crate::hosted_room::HostedRoom; use anyhow::{anyhow, ensure, Result}; use piik_channel_core::{ - wire::{Command, Event, ReplyResult, Request, RoomAccess, CHANNEL_PROTOCOL}, - Authority, Effects, RoomState, + wire::{Command, Event, ReplyResult, Request, RoomAccess}, + Authority, Effects, RoomState, PRODUCT_VERSION, }; use std::{ collections::{BTreeMap, VecDeque}, @@ -70,7 +70,7 @@ impl CoreBurst { request_id: None, command: Command::Join { snapshot_form: Default::default(), - protocol: CHANNEL_PROTOCOL, + version: PRODUCT_VERSION, name: format!("Owned participant {i}"), credential: None, owner_key: None, @@ -277,7 +277,7 @@ impl CoreBurst { fn join(credential: Option, session_id: Option, owner: bool) -> Command { Command::Join { snapshot_form: Default::default(), - protocol: CHANNEL_PROTOCOL, + version: PRODUCT_VERSION, name: "Owned Native host".into(), credential, owner_key: owner.then(|| "owned-composition-owner".into()), diff --git a/prototype/channel-native/src/session/tests.rs b/prototype/channel-native/src/session/tests.rs index 9867f417c..c853fb801 100644 --- a/prototype/channel-native/src/session/tests.rs +++ b/prototype/channel-native/src/session/tests.rs @@ -111,7 +111,7 @@ async fn welcome_restores_stored_rooms_for_the_admitted_creator_or_hosted_servic .event( Event::Welcome { connection_id: Uuid::new_v4(), - protocol: piik_channel_core::wire::CHANNEL_PROTOCOL, + version: piik_channel_core::PRODUCT_VERSION, self_profile: self_profile(&state, session_id), credential: "fixture".into(), session_id, @@ -306,7 +306,7 @@ async fn resumed_endpoint_retires_its_missing_host_after_a_deleted_output_cannot .event( Event::Welcome { connection_id: Uuid::new_v4(), - protocol: piik_channel_core::wire::CHANNEL_PROTOCOL, + version: piik_channel_core::PRODUCT_VERSION, self_profile: self_profile(&state, native), credential: "fixture".into(), session_id: native, @@ -638,7 +638,7 @@ async fn hosted_private_backup_checks_creator_and_policy_before_replacing_bound_ }); session.event(Event::Welcome { connection_id: Uuid::new_v4(), - protocol: piik_channel_core::wire::CHANNEL_PROTOCOL, + version: piik_channel_core::PRODUCT_VERSION, self_profile: self_profile(&state, native), credential: "fixture".into(), session_id: native, @@ -776,7 +776,7 @@ async fn committed_restore_registration_completes_each_coalesced_reply_with_its_ std::fs::write(&path, &original).unwrap(); session.event(Event::Welcome { connection_id: Uuid::new_v4(), - protocol: piik_channel_core::wire::CHANNEL_PROTOCOL, + version: piik_channel_core::PRODUCT_VERSION, self_profile: self_profile(&state, native), credential: "fixture".into(), session_id: native, @@ -1042,7 +1042,7 @@ async fn capture_projection_session() -> (Session, Socket, WebSocketStream Result<()> id: "pending".into(), name: "New room".into(), bootstrap: false, }); session.event(Event::Welcome { - connection_id: Uuid::new_v4(), protocol: piik_channel_core::wire::CHANNEL_PROTOCOL, + connection_id: Uuid::new_v4(), version: piik_channel_core::PRODUCT_VERSION, self_profile: profile, credential: "fixture".into(), session_id, state, invitation_origin: None, }, &mut socket).await?; @@ -1801,7 +1801,7 @@ async fn check_hosting_description_file_failures(hosted_service: bool) -> Result state.channel.rooms[1].creator_id = profile.id; std::fs::write(directory.path().join("unreadable.sqlite"), b"invalid database")?; session.event(Event::Welcome { - connection_id: Uuid::new_v4(), protocol: piik_channel_core::wire::CHANNEL_PROTOCOL, + connection_id: Uuid::new_v4(), version: piik_channel_core::PRODUCT_VERSION, self_profile: profile, credential: "fixture".into(), session_id, state: state.clone(), invitation_origin: None, }, &mut socket).await?; diff --git a/prototype/channel-server/Cargo.lock b/prototype/channel-server/Cargo.lock index 6549feed3..e1aabd971 100644 --- a/prototype/channel-server/Cargo.lock +++ b/prototype/channel-server/Cargo.lock @@ -3898,6 +3898,7 @@ dependencies = [ "ed25519-dalek", "hmac 0.12.1", "rusqlite", + "semver", "serde", "serde_ignored", "serde_json", diff --git a/prototype/channel-server/README.md b/prototype/channel-server/README.md index 70160b631..a1ad1af7e 100644 --- a/prototype/channel-server/README.md +++ b/prototype/channel-server/README.md @@ -277,11 +277,8 @@ the separate App management/discovery listener is not a site-forwarding endpoint Changing the port retains App-hosted rooms but changes the web origin. Browser identity, preferences and cached files remain associated with the old address. -Build the App, bundled Web files and domain server from the same source for -internal testing. Incompatible control or signaling protocols are -rejected at entry. App discovery advertises both protocol identifiers so the Web -page checks native control and domain participation before approval. The storage -format and reset boundary are documented below. +Build the App with its bundled Web files. The page checks local App +compatibility at discovery, before approval. See [versioning](../../docs/standards/versioning.md#extending-interfaces). Build the frontend and start it: @@ -380,12 +377,8 @@ current hosting runtime. Existing Browser rooms remain in their pages and are not migrated; a remembered App preference cannot prevent Browser hosting when the App is absent. -After updating the 3.0 test App, refresh the Web page you use. An incompatible -App Link shows the existing update prompt; [versioning](../../docs/standards/versioning.md) -owns interface compatibility. - -A reachable App with an incompatible control protocol is distinct from an absent -App. Without a selected port, discovery keeps looking for a compatible process +An incompatible App Link prompts the user to update the older App or site. +Without a selected port, discovery keeps looking for a compatible process before it reports the mismatch, and Browser capture stays available. Discovery has one bounded deadline, which starts once the Browser's local-network consent is no longer pending; a failed fetch alone does not establish that consent was @@ -633,8 +626,8 @@ picture/sound settings belong to that share's card; changing the room selection or focused picture never retargets those settings to another publication. In the accepted model, reading and writing conversation require the domain -connection and current room host, independently of ICE. Domain Join/Welcome check -one protocol version and reject older incompatible endpoints explicitly. +connection and current room host, independently of ICE. Domain Join/Welcome +apply the [versioning rules](../../docs/standards/versioning.md#extending-interfaces). Each speaker, screen publication, file and forwarded webpage activity selects paths on confirmed connections within its authorized room graph. An eligible participant can forward voice without joining or hearing the call. diff --git a/prototype/channel-server/browser-directory-acceptance.mjs b/prototype/channel-server/browser-directory-acceptance.mjs index cb8c723e7..6624df8ba 100644 --- a/prototype/channel-server/browser-directory-acceptance.mjs +++ b/prototype/channel-server/browser-directory-acceptance.mjs @@ -48,7 +48,7 @@ try { const initialCount = await sample(`${gate}.snapshot().state.channel.userCount`); const expectedCount = initialCount + 75; const identities = await sample(`(async () => { - const { CHANNEL_PROTOCOL } = await import('/src/client/channel/protocol.ts'); + const { PRODUCT_VERSION } = await import('/src/client/channel/product-version.ts'); const self = window.__channelGate.snapshot().self.id; const room = window.__channelGate.snapshot().state.channel.rooms[0]; const credential = localStorage.getItem('piik.channel.prototype.credential'); @@ -65,7 +65,7 @@ try { const timer = setTimeout(() => { socket.removeEventListener('message', receive); reject(new Error(command.type)); }, 5000); function receive({ data }) { const event = JSON.parse(data); - if (joining ? !['welcome', 'error'].includes(event.type) + if (joining ? !['welcome', 'error', 'incompatible_version'].includes(event.type) : event.type !== 'reply' || event.requestId !== requestId) return; clearTimeout(timer); socket.removeEventListener('message', receive); const result = joining ? event : event.result; @@ -78,7 +78,7 @@ try { }); } const signingKey = Array.from(new Uint8Array(await crypto.subtle.exportKey('raw', (await crypto.subtle.generateKey('Ed25519', true, ['sign', 'verify'])).publicKey))); - const welcome = await request({ type: 'join', canUsePeerTransport: false, name, credential, signingKey, protocol: CHANNEL_PROTOCOL }, 'welcome'); + const welcome = await request({ type: 'join', canUsePeerTransport: false, name, credential, signingKey, ...PRODUCT_VERSION }, 'welcome'); return { socket, request, welcome }; } const offline = []; diff --git a/prototype/channel-server/browser-native-acceptance.mjs b/prototype/channel-server/browser-native-acceptance.mjs index fc6292e0f..685d299b1 100644 --- a/prototype/channel-server/browser-native-acceptance.mjs +++ b/prototype/channel-server/browser-native-acceptance.mjs @@ -12,8 +12,7 @@ import { acceptanceServerExecutable } from "./acceptance-server-executable.mjs"; import { freeUdpPort } from "./acceptance-udp-port.mjs"; import { nativePreviews } from "./browser-preview-acceptance.mjs"; -const { CHANNEL_PROTOCOL } = await tsImport("../../src/client/channel/protocol.ts", import.meta.url); -const { APP_PROTOCOL } = await tsImport("../../src/client/channel/app-link.ts", import.meta.url); +const { PRODUCT_VERSION } = await tsImport("../../src/client/channel/product-version.ts", import.meta.url); // App hosting and Browser participation share a user, not an endpoint or lifetime. export async function appRoom({ initial, serverRoom, browser, action, view, evaluate, until, sample, @@ -84,7 +83,7 @@ export async function appRoom({ initial, serverRoom, browser, action, view, eval const browserRoom = await action(1, "createRoom({name:'Browser-owned room',icon:'couch',access:'public',hidden:false})"); start(); await ready(); const discovery = await fetch(`${local}/connect-discovery`).then(response => response.json()); - assert.deepEqual(discovery, { service: "piik-channel-app", protocol: APP_PROTOCOL, domainProtocol: CHANNEL_PROTOCOL, port, windowNavigation: false, connectURL: `${local}/client` }); + assert.deepEqual(discovery, { service: "piik-channel-app", ...PRODUCT_VERSION, port, windowNavigation: false, connectURL: `${local}/client` }); assert.equal((await health(origin)).status, 403, "discovery does not approve its caller"); await approve(origin); const token = (await (await health(origin)).json()).token; diff --git a/prototype/channel-server/check.mjs b/prototype/channel-server/check.mjs index 69880d156..9ac6bdcf9 100644 --- a/prototype/channel-server/check.mjs +++ b/prototype/channel-server/check.mjs @@ -3,12 +3,14 @@ import { once } from "node:events"; import { generateKeyPairSync, randomUUID } from "node:crypto"; import { test } from "node:test"; import WebSocket from "ws"; -import { CHANNEL_PROTOCOL, ChannelEventDecoder, eventSchema } from "../../src/client/channel/protocol.ts"; +import { ChannelEventDecoder, eventSchema } from "../../src/client/channel/protocol.ts"; +import { productVersion } from "../../scripts/release-version.mjs"; const endpoint = process.env.CHANNEL_WS_URL ?? "ws://127.0.0.1:8791/prototype/channel"; const origin = process.env.CHANNEL_UI_ORIGIN ?? "http://127.0.0.1:8790"; assert(["127.0.0.1", "localhost"].includes(new URL(endpoint).hostname), "Checks only target loopback"); const ownerKey = process.env.PIIK_CHANNEL_OWNER_KEY; +const version = productVersion(process.env.PIIK_BUILD_VERSION); assert(ownerKey, "Set PIIK_CHANNEL_OWNER_KEY to the local server's owner bootstrap key"); // The protocol-only sources explicitly declare the accepted 720p30 ceiling. const videoSettings = { ceiling: { resolution: { width: 1280, height: 720 }, maxFramerate: 30, maxBitrate: 3_000_000 }, degradationPreference: 'balanced' }; @@ -66,8 +68,8 @@ async function connect(t, join = {}) { }, }; const signingKey = [...Buffer.from(generateKeyPairSync("ed25519").publicKey.export({ format: "jwk" }).x, "base64url")]; - socket.send(JSON.stringify({ type: "join", canUsePeerTransport: true, protocol: CHANNEL_PROTOCOL, name: "Protocol check", signingKey, ...join })); - client.welcome = await wait(event => ["welcome", "error"].includes(event.type), "join result"); + socket.send(JSON.stringify({ type: "join", canUsePeerTransport: true, ...version, name: "Protocol check", signingKey, ...join })); + client.welcome = await wait(event => ["welcome", "error", "incompatible_version"].includes(event.type), "join result"); return client; } @@ -111,8 +113,8 @@ test("the frontend accepts real cross-room publications and subscriptions", { ti }); test("authenticated users, signed conversation and selective source ownership", { timeout: 30_000 }, async t => { - const previous = await connect(t, { protocol: CHANNEL_PROTOCOL - 1 }); - assert.equal(previous.welcome.code, "incompatible_protocol"); + const incompatible = await connect(t, { major: (version.major ^ 1) >>> 0 }); + assert.deepEqual(incompatible.welcome, { type: "incompatible_version", ...version }); const owner = await connect(t, { ownerKey, name: "Owner check" }); const friend = await connect(t, { name: "Friend check" }); const other = await connect(t, { name: "Other check" }); @@ -254,7 +256,8 @@ test("Server-owned private invitations admit new users, conceal content and revo test("a lightweight room cancellation round-trips on the current channel protocol", { timeout: 30_000 }, async t => { const owner = await connect(t, { ownerKey }); assert.equal(owner.welcome.type, "welcome"); - assert.equal(owner.welcome.protocol, CHANNEL_PROTOCOL); + assert.equal(owner.welcome.major, version.major); + assert.equal(owner.welcome.minor, version.minor); const existing = owner.welcome.state.channel.rooms.find(room => room.available) ?? (await owner.wait(event => event.type === "state" && event.state.channel.rooms.some(room => room.available), "registered fixture room")).state.channel.rooms.find(room => room.available); diff --git a/prototype/channel-server/examples/network_lab.rs b/prototype/channel-server/examples/network_lab.rs index 4b6247d57..f9edbe458 100644 --- a/prototype/channel-server/examples/network_lab.rs +++ b/prototype/channel-server/examples/network_lab.rs @@ -114,7 +114,7 @@ async fn participant() -> Result<()> { &mut socket, Command::Join { snapshot_form: Default::default(), - protocol: piik_channel_core::wire::CHANNEL_PROTOCOL, + version: piik_channel_core::PRODUCT_VERSION, name: "Kernel Native reader".into(), credential: None, owner_key: None, diff --git a/prototype/channel-server/src/app.rs b/prototype/channel-server/src/app.rs index 4c5686b05..6bf728d64 100644 --- a/prototype/channel-server/src/app.rs +++ b/prototype/channel-server/src/app.rs @@ -42,6 +42,7 @@ use futures_util::{ FutureExt, SinkExt, StreamExt, }; use piik_channel_core::host::NewRoom; +use piik_channel_core::PRODUCT_VERSION; use piik_channel_native::{ capture::{CaptureOptions, EncodingExecution, Settings, Target, VideoCodec, VideoCodecMode}, input::{Desktop, Mode, SourceView}, @@ -69,7 +70,6 @@ use uuid::Uuid; const IO_TIMEOUT: Duration = Duration::from_secs(5); const MAX_REQUEST_BYTES: usize = 256 * 1024; const SERVICE: &str = "piik-channel-app"; -const PROTOCOL: u8 = 28; const BUILD_VERSION: &str = match option_env!("PIIK_BUILD_VERSION") { Some(value) => value, None => "development", @@ -407,7 +407,7 @@ fn host_task(task: JoinHandle>) -> HostTask { async move { match task.await { Ok(Ok(())) => {} - Ok(Err(error)) => eprintln!("App hosting ended: {error}"), + Ok(Err(error)) => eprintln!("App hosting ended: {error:#}"), Err(error) => eprintln!("App hosting task ended: {error}"), } }.boxed().shared() @@ -822,12 +822,12 @@ async fn access( } async fn discovery(State(app): State>) -> Json { Json( - json!({"service":SERVICE,"protocol":PROTOCOL,"domainProtocol":piik_channel_core::wire::CHANNEL_PROTOCOL,"port":app.port, + json!({"service":SERVICE,"major":PRODUCT_VERSION.major,"minor":PRODUCT_VERSION.minor,"port":app.port, "windowNavigation":app.config.window_navigation.is_some(),"connectURL":format!("http://127.0.0.1:{}/client",app.port)}), ) } async fn health(State(app): State>) -> Json { - let mut state = json!({"service":SERVICE,"protocol":PROTOCOL,"domainProtocol":piik_channel_core::wire::CHANNEL_PROTOCOL,"port":app.port,"token":app.token, + let mut state = json!({"service":SERVICE,"major":PRODUCT_VERSION.major,"minor":PRODUCT_VERSION.minor,"port":app.port,"token":app.token, "version":BUILD_VERSION,"revision":BUILD_REVISION,"packageTarget":PACKAGE_TARGET, "windowNavigation":app.config.window_navigation.is_some(),"updateSupported":app.update.supported()}); if app.config.page_player.is_some() { @@ -3849,6 +3849,10 @@ mod lifecycle_tests { assert_eq!(discovery.status(), StatusCode::OK); let discovery: Value = serde_json::from_slice(&discovery.bytes().await.unwrap()).unwrap(); assert_eq!(discovery["connectURL"], format!("{origin}/client")); + assert_eq!(discovery["major"], PRODUCT_VERSION.major); + assert_eq!(discovery["minor"], PRODUCT_VERSION.minor); + assert!(discovery.get("protocol").is_none()); + assert!(discovery.get("domainProtocol").is_none()); let bookmarks = "/api/client-launcher/bookmarks"; let allowed = stale(bookmarks) diff --git a/prototype/channel-server/src/app_domain.rs b/prototype/channel-server/src/app_domain.rs index 7c95d2e6f..754a165d5 100644 --- a/prototype/channel-server/src/app_domain.rs +++ b/prototype/channel-server/src/app_domain.rs @@ -592,7 +592,7 @@ mod tests { socket .send(Message::Text( json!({ - "type":"join", "protocol":piik_channel_core::wire::CHANNEL_PROTOCOL, + "type":"join", "major":piik_channel_core::PRODUCT_VERSION.major,"minor":piik_channel_core::PRODUCT_VERSION.minor, "name":"Owner", "ownerKey":owner_key, "signingKey":vec![1u8; 32], }) .to_string() diff --git a/prototype/channel-server/src/domain.rs b/prototype/channel-server/src/domain.rs index 84c017b87..07d911b2d 100644 --- a/prototype/channel-server/src/domain.rs +++ b/prototype/channel-server/src/domain.rs @@ -19,6 +19,8 @@ use piik_channel_core::{ wire::{Command, Event, HostingMode, ReplyResult, Request, RoomCreationPolicy}, Authority, Effects, }; +#[cfg(test)] +use piik_channel_core::PRODUCT_VERSION; use std::{ collections::BTreeMap, future::Future, @@ -482,15 +484,10 @@ async fn session(mut socket: WebSocket, state: Domain, local_entry: bool) { Ok(Some(Ok(Message::Text(text)))) => text, _ => return, }; - let mut request = match Request::parse(&text) { + let mut request = match Request::parse_first(&text) { Ok(request) => request, - Err((request_id, code)) => { - send( - &mut socket, - &Event::completion(request_id, None, ReplyResult::Error { code: code.into() }), - &mut images, - ) - .await; + Err(event) => { + send(&mut socket, &event, &mut images).await; return; } }; @@ -906,7 +903,7 @@ mod tests { assert_eq!(domain.owner_key(), owner_key); let redeem = |ticket: &str| { let mut join = Request::parse(&json!({"type":"join","name":"Operator","ownerKey":ticket, - "protocol":piik_channel_core::wire::CHANNEL_PROTOCOL,"signingKey":vec![0;32]}).to_string()).unwrap(); + "major":PRODUCT_VERSION.major,"minor":PRODUCT_VERSION.minor,"signingKey":vec![0;32]}).to_string()).unwrap(); let mut hub = domain.hub.lock().unwrap(); hub.redeem_launch(&mut join); let Command::Join { owner_key, .. } = join.command else { unreachable!() }; @@ -927,7 +924,7 @@ mod tests { let (credential, mut backup) = { let mut hub = domain.hub.lock().unwrap(); let join = Request::parse(&json!({"type":"join","name":"Operator","ownerKey":owner_key, - "protocol":piik_channel_core::wire::CHANNEL_PROTOCOL,"signingKey":vec![0;32]}).to_string()).unwrap(); + "major":PRODUCT_VERSION.major,"minor":PRODUCT_VERSION.minor,"signingKey":vec![0;32]}).to_string()).unwrap(); let effects = hub.authority.handle(Uuid::new_v4(), join, 0); let credential = effects.events.into_iter().find_map(|(_, event)| match event { Event::Welcome { credential, .. } => Some(credential), _ => None, @@ -973,7 +970,8 @@ mod tests { }; let request = |mut value: serde_json::Value| { if value["type"] == "join" { - value["protocol"] = serde_json::json!(piik_channel_core::wire::CHANNEL_PROTOCOL); + value["major"] = serde_json::json!(PRODUCT_VERSION.major); + value["minor"] = serde_json::json!(PRODUCT_VERSION.minor); } Request::parse(&value.to_string()).unwrap() }; diff --git a/prototype/channel-server/src/runtime_tests.rs b/prototype/channel-server/src/runtime_tests.rs index 07355ced2..5c6751708 100644 --- a/prototype/channel-server/src/runtime_tests.rs +++ b/prototype/channel-server/src/runtime_tests.rs @@ -53,7 +53,8 @@ impl Endpoint { fn request(&self, hub: &mut Hub, mut command: Value) { if command["type"] == "join" { command["canUsePeerTransport"] = json!(true); - command["protocol"] = json!(piik_channel_core::wire::CHANNEL_PROTOCOL); + command["major"] = json!(PRODUCT_VERSION.major); + command["minor"] = json!(PRODUCT_VERSION.minor); command["signingKey"] = json!( piik_channel_core::conversation::SessionSigner::from_seed([1; 32]).signing_key() ); @@ -328,7 +329,7 @@ fn domain_metadata_requires_owner_and_commits_before_broadcast_then_reopens() { assert_eq!(saved["icon"], icon); assert!(saved.get("access").is_none()); assert!(saved.get("passwordHash").is_none()); - let join=Request::parse(&json!({"type":"join","canUsePeerTransport":true,"protocol":piik_channel_core::wire::CHANNEL_PROTOCOL, + let join=Request::parse(&json!({"type":"join","canUsePeerTransport":true,"major":PRODUCT_VERSION.major,"minor":PRODUCT_VERSION.minor, "name":"Visitor","signingKey":piik_channel_core::conversation::SessionSigner::from_seed([1;32]).signing_key()}).to_string()).unwrap(); assert!(restored .handle(Uuid::new_v4(), join, 1) @@ -1002,7 +1003,8 @@ async fn state_when(socket: &mut Socket, predicate: impl Fn(&Snapshot) -> bool) async fn send_request(socket: &mut Socket, mut value: Value) { if value["type"] == "join" { value["canUsePeerTransport"] = json!(true); - value["protocol"] = json!(piik_channel_core::wire::CHANNEL_PROTOCOL); + value["major"] = json!(PRODUCT_VERSION.major); + value["minor"] = json!(PRODUCT_VERSION.minor); value["signingKey"] = json!(piik_channel_core::conversation::SessionSigner::from_seed([1; 32]).signing_key()); } else if value.get("requestId").is_none() { @@ -1323,6 +1325,61 @@ async fn http_and_https_share_a_domain_and_release_both_listeners_on_stop() { std::fs::remove_dir_all(folder).unwrap(); } +#[tokio::test] +async fn incompatible_major_leaves_launch_ticket_for_one_compatible_join() { + let directory = tempfile::tempdir().unwrap(); + let origin = "http://localhost"; + let domain = Domain::open(directory.path(), None, origin.into(), None, vec![]).unwrap(); + let ticket = domain.launch_ticket().unwrap(); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let (stop, stopped) = oneshot::channel(); + let task = tokio::spawn(domain.serve(listener, Router::new(), async { + let _ = stopped.await; + })); + + let join = |version: piik_channel_core::ProductVersion| { + let ticket = ticket.clone(); + async move { + let mut request = format!("ws://{address}/prototype/channel") + .into_client_request().unwrap(); + request.headers_mut().insert("Origin", origin.parse().unwrap()); + let (mut socket, _) = connect_async(request).await.unwrap(); + socket.send(Message::Text(json!({ + "type": "join", + "major": version.major, + "minor": version.minor, + "name": "Owner", + "ownerKey": ticket, + "signingKey": piik_channel_core::conversation::SessionSigner::from_seed([1; 32]).signing_key(), + }).to_string().into())).await.unwrap(); + tokio::time::timeout(Duration::from_secs(5), event(&mut socket)).await.unwrap() + } + }; + let newer_major = piik_channel_core::ProductVersion { + major: PRODUCT_VERSION.major + 1, + minor: 0, + }; + assert!(matches!(join(newer_major).await, Event::IncompatibleVersion { version } if version == PRODUCT_VERSION)); + + let mixed_minor = piik_channel_core::ProductVersion { + major: PRODUCT_VERSION.major, + minor: PRODUCT_VERSION.minor + 1, + }; + let Event::Welcome { version, state, session_id, self_profile, .. } = join(mixed_minor).await else { + panic!("a matching major must redeem the original launch ticket"); + }; + assert_eq!(version, PRODUCT_VERSION); + assert_eq!(state.channel.owner_id, Some(self_profile.id)); + assert_eq!( + state.sessions.iter().find(|session| session.id == session_id).unwrap().version, + mixed_minor, + ); + assert!(matches!(join(PRODUCT_VERSION).await, Event::Error { code, .. } if code == "invalid_owner_key")); + stop.send(()).unwrap(); + task.await.unwrap().unwrap(); +} + #[tokio::test] async fn invitation_origin_is_only_a_second_exact_http_entry() { let folder = std::env::temp_dir().join(format!("piik-domain-origins-{}", Uuid::new_v4())); diff --git a/prototype/channel-server/tests/native_session.rs b/prototype/channel-server/tests/native_session.rs index 83be9f474..1a2076122 100644 --- a/prototype/channel-server/tests/native_session.rs +++ b/prototype/channel-server/tests/native_session.rs @@ -217,7 +217,7 @@ async fn committed_domain_restore_reports_native_restart_failure_without_rolling replacement.handle( Uuid::new_v4(), Request::parse( - &json!({"type":"join","canUsePeerTransport":true,"protocol":piik_channel_core::wire::CHANNEL_PROTOCOL, + &json!({"type":"join","canUsePeerTransport":true,"major":piik_channel_core::PRODUCT_VERSION.major,"minor":piik_channel_core::PRODUCT_VERSION.minor, "name":"Restored owner","ownerKey":"restored-owner","signingKey":vec![7u8;32]}) .to_string(), ) @@ -252,7 +252,7 @@ async fn committed_domain_restore_reports_native_restart_failure_without_rolling .headers_mut() .insert("Origin", origin.parse().unwrap()); let (mut page, _) = tokio_tungstenite::connect_async(upgrade).await.unwrap(); - page.send(Message::Text(json!({"type":"join","canUsePeerTransport":true,"protocol":piik_channel_core::wire::CHANNEL_PROTOCOL,"name":"Owner","ownerKey":"old-owner","signingKey":vec![7u8;32]}).to_string().into())).await.unwrap(); + page.send(Message::Text(json!({"type":"join","canUsePeerTransport":true,"major":piik_channel_core::PRODUCT_VERSION.major,"minor":piik_channel_core::PRODUCT_VERSION.minor,"name":"Owner","ownerKey":"old-owner","signingKey":vec![7u8;32]}).to_string().into())).await.unwrap(); let credential = tokio::time::timeout(Duration::from_secs(10), async { let mut credential = None; loop { @@ -684,7 +684,7 @@ async fn real_session_resumes_bindings_and_restarts_from_committed_room_files() let guest = Uuid::new_v4(); let signer = piik_channel_core::conversation::SessionSigner::from_seed([9; 32]); domain.command(guest, json!({ - "type":"join","canUsePeerTransport":true,"protocol":piik_channel_core::wire::CHANNEL_PROTOCOL, "name": "Observer", "signingKey": signer.signing_key() + "type":"join","canUsePeerTransport":true,"major":piik_channel_core::PRODUCT_VERSION.major,"minor":piik_channel_core::PRODUCT_VERSION.minor, "name": "Observer", "signingKey": signer.signing_key() })).await; domain .command(guest, json!({"type":"browse","roomId":"one","active":true})) @@ -1024,7 +1024,7 @@ async fn app_host_outlives_its_page_and_restores_rooms_only_after_real_admission let mut authority = Authority::new("owner".into(), vec![]).unwrap(); let (channel, user) = authority.identity(); let browser = Uuid::new_v4(); - let admitted = authority.handle(browser, Request::parse(&json!({"type":"join","canUsePeerTransport":true,"protocol":piik_channel_core::wire::CHANNEL_PROTOCOL,"ownerKey":"owner","name":"Owner", "signingKey":SessionSigner::from_seed([1;32]).signing_key()}).to_string()).unwrap(), 100); + let admitted = authority.handle(browser, Request::parse(&json!({"type":"join","canUsePeerTransport":true,"major":piik_channel_core::PRODUCT_VERSION.major,"minor":piik_channel_core::PRODUCT_VERSION.minor,"ownerKey":"owner","name":"Owner", "signingKey":SessionSigner::from_seed([1;32]).signing_key()}).to_string()).unwrap(), 100); let (credential, browser_session) = admitted .events .into_iter() @@ -1037,7 +1037,7 @@ async fn app_host_outlives_its_page_and_restores_rooms_only_after_real_admission _ => None, }) .unwrap(); - let guest = authority.handle(Uuid::new_v4(), Request::parse(&json!({"type":"join","canUsePeerTransport":true,"protocol":piik_channel_core::wire::CHANNEL_PROTOCOL,"name":"Guest", "signingKey":SessionSigner::from_seed([2;32]).signing_key()}).to_string()).unwrap(), 100); + let guest = authority.handle(Uuid::new_v4(), Request::parse(&json!({"type":"join","canUsePeerTransport":true,"major":piik_channel_core::PRODUCT_VERSION.major,"minor":piik_channel_core::PRODUCT_VERSION.minor,"name":"Guest", "signingKey":SessionSigner::from_seed([2;32]).signing_key()}).to_string()).unwrap(), 100); let guest_credential = guest .events .into_iter() @@ -1080,11 +1080,11 @@ async fn app_host_outlives_its_page_and_restores_rooms_only_after_real_admission let (status, discovery) = app_http(address, "GET", "/connect-discovery", None, None).await; assert_eq!(status, 200); assert_eq!(discovery["service"], "piik-channel-app"); - assert_eq!(discovery["protocol"], 28); - assert_eq!( - discovery["domainProtocol"], - piik_channel_core::wire::CHANNEL_PROTOCOL - ); + let version = piik_channel_core::PRODUCT_VERSION; + assert_eq!(discovery["major"], version.major); + assert_eq!(discovery["minor"], version.minor); + assert!(discovery.get("protocol").is_none()); + assert!(discovery.get("domainProtocol").is_none()); assert!( discovery.get("token").is_none(), "discovery grants no authority" @@ -1123,13 +1123,15 @@ async fn app_host_outlives_its_page_and_restores_rooms_only_after_real_admission let (status, health) = app_http(address, "GET", "/health", Some(&origin), None).await; assert_eq!(status, 200); assert_eq!(health["service"], discovery["service"]); - assert_eq!(health["protocol"], discovery["protocol"]); + assert_eq!(health["major"], discovery["major"]); + assert_eq!(health["minor"], discovery["minor"]); + assert!(health.get("protocol").is_none()); + assert!(health.get("domainProtocol").is_none()); assert_eq!( health.get("externalScreenInputAvailable"), piik_channel_native::peer::supports_external_input() .then_some(&Value::Bool(true)) ); - assert_eq!(health["domainProtocol"], discovery["domainProtocol"]); assert_eq!(health["port"], address.port()); let (status, launcher) = app_http( address, @@ -2019,7 +2021,7 @@ async fn app_launch_retries_owns_one_domain_and_preserves_its_origin() { let (mut guest, _) = connect_async(upgrade).await.unwrap(); guest .send(Message::Text( - json!({"type":"join","canUsePeerTransport":true,"protocol":piik_channel_core::wire::CHANNEL_PROTOCOL,"name":"LAN guest", + json!({"type":"join","canUsePeerTransport":true,"major":piik_channel_core::PRODUCT_VERSION.major,"minor":piik_channel_core::PRODUCT_VERSION.minor,"name":"LAN guest", "signingKey":SessionSigner::from_seed([31;32]).signing_key()}) .to_string() .into(), @@ -2121,7 +2123,7 @@ async fn app_launch_retries_owns_one_domain_and_preserves_its_origin() { .headers_mut() .insert("Origin", origin.parse().unwrap()); let (mut admin, _) = connect_async(request).await.unwrap(); - admin.send(Message::Text(json!({"type":"join","canUsePeerTransport":true,"protocol":piik_channel_core::wire::CHANNEL_PROTOCOL,"ownerKey":ticket,"name":"Owner", "signingKey":SessionSigner::from_seed([32;32]).signing_key()}).to_string().into())).await.unwrap(); + admin.send(Message::Text(json!({"type":"join","canUsePeerTransport":true,"major":piik_channel_core::PRODUCT_VERSION.major,"minor":piik_channel_core::PRODUCT_VERSION.minor,"ownerKey":ticket,"name":"Owner", "signingKey":SessionSigner::from_seed([32;32]).signing_key()}).to_string().into())).await.unwrap(); let admitted: Value = serde_json::from_str(&admin.next().await.unwrap().unwrap().into_text().unwrap()) .unwrap(); @@ -2451,7 +2453,7 @@ async fn app_external_origin_is_exact_and_owned_startup_restores_it() { .headers_mut() .insert("Origin", public.parse().unwrap()); let (mut viewer, _) = connect_async(request).await.unwrap(); - viewer.send(Message::Text(json!({"type":"join","canUsePeerTransport":true,"protocol":piik_channel_core::wire::CHANNEL_PROTOCOL,"name":"External viewer","signingKey":SessionSigner::from_seed([54;32]).signing_key()}).to_string().into())).await.unwrap(); + viewer.send(Message::Text(json!({"type":"join","canUsePeerTransport":true,"major":piik_channel_core::PRODUCT_VERSION.major,"minor":piik_channel_core::PRODUCT_VERSION.minor,"name":"External viewer","signingKey":SessionSigner::from_seed([54;32]).signing_key()}).to_string().into())).await.unwrap(); let welcome: Value = serde_json::from_str(&viewer.next().await.unwrap().unwrap().into_text().unwrap()) .unwrap(); @@ -2539,7 +2541,7 @@ async fn app_relay_capacity_confirms_the_native_endpoint_without_changing_the_br let mut authority = Authority::new("owner".into(), vec![]).unwrap(); let (channel, user) = authority.identity(); let browser = Uuid::new_v4(); - let admitted=authority.handle(browser,Request::parse(&json!({"type":"join","canUsePeerTransport":true,"protocol":piik_channel_core::wire::CHANNEL_PROTOCOL,"ownerKey":"owner","name":"Owner","signingKey":SessionSigner::from_seed([1;32]).signing_key()}).to_string()).unwrap(),100); + let admitted=authority.handle(browser,Request::parse(&json!({"type":"join","canUsePeerTransport":true,"major":piik_channel_core::PRODUCT_VERSION.major,"minor":piik_channel_core::PRODUCT_VERSION.minor,"ownerKey":"owner","name":"Owner","signingKey":SessionSigner::from_seed([1;32]).signing_key()}).to_string()).unwrap(),100); let (credential, browser_session) = admitted .events .into_iter() diff --git a/prototype/channel-server/tests/room_creation_policy.rs b/prototype/channel-server/tests/room_creation_policy.rs index 4931c8369..77235857f 100644 --- a/prototype/channel-server/tests/room_creation_policy.rs +++ b/prototype/channel-server/tests/room_creation_policy.rs @@ -1,5 +1,5 @@ use futures_util::{SinkExt, StreamExt}; -use piik_channel_core::{conversation::SessionSigner, wire::CHANNEL_PROTOCOL}; +use piik_channel_core::{conversation::SessionSigner, PRODUCT_VERSION}; use piik_channel_prototype::domain::Domain; use serde_json::{json, Value}; use std::{net::UdpSocket, path::Path, process::Stdio, time::Duration}; @@ -99,7 +99,8 @@ async fn join(origin: &str, owner: bool) -> (Socket, Value) { .unwrap(); let mut join = json!({ "type": "join", - "protocol": CHANNEL_PROTOCOL, + "major": PRODUCT_VERSION.major, + "minor": PRODUCT_VERSION.minor, "canUsePeerTransport": false, "name": "Room policy check", "signingKey": SessionSigner::from_seed([if owner { 1 } else { 2 }; 32]).signing_key() diff --git a/scripts/build-channel-web.mjs b/scripts/build-channel-web.mjs index 8cbb80fb8..b4fbe587a 100644 --- a/scripts/build-channel-web.mjs +++ b/scripts/build-channel-web.mjs @@ -23,7 +23,7 @@ export function buildChannelWeb(root, { version, revision, cargoTarget }) { } const env = { ...process.env, RUSTUP_TOOLCHAIN: '1.91.0', PIIK_BUILD_VERSION: version, PIIK_BUILD_REVISION: revision, - VITE_PIIK_VERSION: version, VITE_PIIK_REVISION: revision, + VITE_PIIK_REVISION: revision, ...(cargoTarget ? { CARGO_TARGET_DIR: cargoTarget } : {}) }; writeChannelWebLicenseNotices(root, join(root, 'public', 'third-party-licenses.txt')); for (const args of [ diff --git a/scripts/check-container.mjs b/scripts/check-container.mjs index e00e31f97..41e650ebb 100644 --- a/scripts/check-container.mjs +++ b/scripts/check-container.mjs @@ -8,16 +8,15 @@ import { dirname, join, resolve } from "node:path"; import { setTimeout as delay } from "node:timers/promises"; import { fileURLToPath } from "node:url"; import WebSocket from "ws"; -import { tsImport } from "tsx/esm/api"; import { resetBuildWorkspace } from "./build-workspace.mjs"; import { checkWebSourceIdentity } from "./container-web-identity.mjs"; +import { productVersion } from "./release-version.mjs"; const [image, revision] = process.argv.slice(2); if (process.argv.length !== 4 || !image || !/^[0-9a-f]{40}$/.test(revision ?? "")) { throw new Error("Usage: node scripts/check-container.mjs "); } const root = resolve(dirname(fileURLToPath(import.meta.url)), ".."); -const { CHANNEL_PROTOCOL } = await tsImport("../src/client/channel/protocol.ts", import.meta.url); const project = `piik-check-${randomUUID()}`; const workspace = resetBuildWorkspace(root, "container-check", project); const origin = "https://share.example.com"; @@ -48,7 +47,7 @@ async function request(path) { assert.ok(response.ok, `${path}: HTTP ${response.status}`); return response; } -async function rooms() { +async function rooms(version) { const socket = new WebSocket("ws://127.0.0.1:8787/prototype/channel", { origin }); let timer; try { @@ -57,14 +56,18 @@ async function rooms() { socket.once("error", reject); socket.once("open", () => { const publicKey = generateKeyPairSync("ed25519").publicKey.export({ format: "jwk" }); - socket.send(JSON.stringify({ type: "join", protocol: CHANNEL_PROTOCOL, canUsePeerTransport: false, name: "Container check", ownerKey, + socket.send(JSON.stringify({ type: "join", ...version, canUsePeerTransport: false, name: "Container check", ownerKey, signingKey: [...Buffer.from(publicKey.x, "base64url")] })); }); socket.on("message", bytes => { try { const event = JSON.parse(bytes.toString()); assert.notEqual(event.type, "error", event.code); - if (event.type === "welcome") credential = event.credential; + assert.notEqual(event.type, "incompatible_version", "Server major must match the image label"); + if (event.type === "welcome") { + assert.deepEqual({ major: event.major, minor: event.minor }, version); + credential = event.credential; + } if (!["welcome", "state"].includes(event.type)) return; const { channel } = event.state; if (channel.rooms.length === 3 && channel.rooms.every(room => room.available)) { @@ -85,6 +88,9 @@ try { const metadata = JSON.parse(docker("image", "inspect", image))[0]; assert.equal(metadata.Config.User, "65532:65532"); assert.equal(metadata.Config.Labels["org.opencontainers.image.revision"], revision); + const label = metadata.Config.Labels["org.opencontainers.image.version"]; + assert.equal(typeof label, "string"); + const version = productVersion(label); assert.equal(metadata.Os, "linux"); assert.equal(metadata.Architecture, process.arch === "x64" ? "amd64" : process.arch); assert.ok(["amd64", "arm64"].includes(metadata.Architecture)); @@ -93,7 +99,7 @@ try { await until(async () => assert.equal(await (await request("/healthz")).text(), "piik-channel-prototype"), "ready"); const html = await (await request("/")).text(); await checkWebSourceIdentity(html, revision, async asset => (await request(asset)).text()); - const initial = await rooms(); + const initial = await rooms(version); const backupURL = "http://127.0.0.1:8787/prototype/channel/rooms/living/backup"; const headers = { Origin: origin, Authorization: `Bearer ${credential}` }; const backup = await fetch(backupURL, { headers, signal: AbortSignal.timeout(10_000) }); @@ -107,7 +113,7 @@ try { const invalid = await fetch(restoreURL, { method: "PUT", headers: { ...headers, "Content-Type": "application/zip" }, body: "invalid owned archive", signal: AbortSignal.timeout(10_000) }); assert.equal(invalid.status, 400, "invalid archives fail without replacing the room"); await invalid.body?.cancel(); - assert.deepEqual(await rooms(), initial); + assert.deepEqual(await rooms(version), initial); const container = JSON.parse(docker("inspect", compose("ps", "-q", "piik")))[0]; assert.equal(container.HostConfig.ReadonlyRootfs, true); assert.ok(container.HostConfig.CapDrop.includes("ALL")); @@ -115,7 +121,7 @@ try { compose("up", "-d", "--force-recreate", "--pull", "never"); await until(async () => assert.equal(await (await request("/healthz")).text(), "piik-channel-prototype"), "restart"); - assert.deepEqual(await rooms(), initial, "Recreated Server must reopen its persistent rooms"); + assert.deepEqual(await rooms(version), initial, "Recreated Server must reopen its persistent rooms"); compose("stop"); const stopped = JSON.parse(docker("inspect", compose("ps", "-aq", "piik")))[0]; assert.equal(stopped.State.ExitCode, 0, "SIGTERM must shut down cleanly"); diff --git a/scripts/release-version.mjs b/scripts/release-version.mjs index afaa57810..4f6582220 100644 --- a/scripts/release-version.mjs +++ b/scripts/release-version.mjs @@ -2,6 +2,7 @@ import { execFileSync } from "node:child_process"; import { appendFileSync } from "node:fs"; import { pathToFileURL } from "node:url"; import semver from "semver"; +import developmentVersion from "../prototype/channel-core/development-version.json" with { type: "json" }; const git = (root, ...args) => execFileSync("git", args, { cwd: root, encoding: "utf8" }).trim(); export const isReleaseVersion = (value) => typeof value === "string" && @@ -52,12 +53,26 @@ export function releaseCommits(root, revision, previous) { return commits; } +export function productVersion(version = "development") { + if (version === "development") return developmentVersion; + const parsed = semver.parse(version); + if (!parsed || version !== `v${parsed.version}`) + throw new Error("Build version must be vMAJOR.MINOR.PATCH with an optional prerelease suffix, or development"); + const { major, minor } = parsed; + if (major > 0xffffffff || minor > 0xffffffff) throw new Error("Product major/minor exceeds u32"); + return { major, minor }; +} + +export const productVersionDefine = (version = "development") => ({ + "import.meta.env.VITE_PIIK_VERSION": JSON.stringify(version), + __PIIK_PRODUCT_VERSION__: JSON.stringify(productVersion(version)), +}); + // Prerelease candidates are explicit build inputs, never inferred stable releases. export function buildVersion(root, revision, requested = process.env.PIIK_BUILD_VERSION) { const version = requested || stableTags(root, "--points-at", revision)[0] || "development"; if (version === "development") return version; - if (!version.startsWith("v") || semver.valid(version) !== version.slice(1)) - throw new Error("Build version must be vMAJOR.MINOR.PATCH with an optional prerelease suffix, or development"); + productVersion(version); if (git(root, "tag", "--list", version) && git(root, "rev-parse", `${version}^{commit}`) !== revision) { throw new Error("A release version cannot identify two source revisions"); diff --git a/src/client/channel/app-link.ts b/src/client/channel/app-link.ts index becfc3250..d4767b821 100644 --- a/src/client/channel/app-link.ts +++ b/src/client/channel/app-link.ts @@ -1,5 +1,6 @@ import type { NativeCaptureSelection } from "../native/capture-selection"; -import { CHANNEL_PROTOCOL, isIncompatibleProtocol, MAX_RELAY_CAPACITY, roomSummarySchema, watchByteSourceSchema, type WatchByteSource, type RoomSettings, type RoomSummary } from "./protocol"; +import { MAX_RELAY_CAPACITY, roomSummarySchema, watchByteSourceSchema, type WatchByteSource, type RoomSettings, type RoomSummary } from "./protocol"; +import { PRODUCT_VERSION, productVersionSchema } from "./product-version"; import { unsupportedVideoFormatSchema, type UnsupportedVideoFormat, nativePageEventSchema, nativePageStateSchema, nativePageMediaChoiceSchema, nativePageIndexedCandidateSchema, nativePageMetadataReadSchema, nativePageMetadataResultSchema, nativePageIndexedSelectionSchema, nativePageResourceReadSchema, nativePageResourceResultSchema, @@ -9,7 +10,7 @@ import { unsupportedVideoFormatSchema, type UnsupportedVideoFormat, nativePageEv import type { AppPagePort, WatchMediaEvent, WatchMediaPatch, WatchMediaState } from "./watch-media"; import type { WatchByteResult } from "./watch-resource"; import { z } from "zod"; -import { discoverLocalApp, type AppDiscovery, type AppDiscoveryOptions } from "../native/discovery"; +import { discoverLocalApp, type AppCompatibilityIssue, type AppDiscovery, type AppDiscoveryOptions } from "../native/discovery"; import { nativeCaptureTargetSchema, nativeVideoCodecSchema, remoteControlStateSchema, remoteStopShortcutSchema, type NativeCaptureTarget, type EncodingExecution } from "../native/wire"; import { remoteShortcutKeySchema, type RemoteControlMode } from "../remote-control/protocol"; import type { QualityProfile } from "../media/quality"; @@ -27,12 +28,13 @@ const openRoomResultSchema = z.discriminatedUnion("type", [ z.object({ type: z.literal("settings_rejected"), reason: z.string().min(1) }), ]); -export const APP_PROTOCOL = 28; const APP_REQUEST_BYTES = 256 * 1024; const SOURCE_LIST_TIMEOUT_MS = 8_000; const SHORTCUT_ACTION_MAX_AGE_MS = 1_000; -const identitySchema = z.object({ service: z.literal("piik-channel-app"), protocol: z.number().int().positive(), domainProtocol: z.number().int().positive().optional(), port: z.number().int().min(1).max(65535) }); -const healthSchema = identitySchema.extend({ protocol: z.literal(APP_PROTOCOL), domainProtocol: z.literal(CHANNEL_PROTOCOL), token: z.string().min(1).max(256).regex(/^[A-Za-z0-9_-]+$/), +const endpointSchema = z.object({ service: z.enum(["piik-channel-app", "piik-client"]), port: z.number().int().min(1).max(65535) }); +const identitySchema = endpointSchema.extend({ service: z.literal("piik-channel-app"), ...productVersionSchema.shape }); +const legacyIdentitySchema = z.object({ protocol: z.number().int().positive() }); +const healthSchema = identitySchema.extend({ token: z.string().min(1).max(256).regex(/^[A-Za-z0-9_-]+$/), version: z.string().optional(), revision: z.string().optional(), packageTarget: z.string().optional(), updateSupported: z.boolean().optional(), pagePlayer: z.boolean().optional(), externalScreenInputAvailable: z.boolean().optional(), backgroundVoiceShortcuts: z.boolean().optional() }); type AppHealth = z.infer; @@ -111,8 +113,13 @@ const stopShortcutSchema = remoteStopShortcutSchema.extend({ stopShortcutLabel: export type ChannelStopShortcut = z.infer; export type ChannelRemoteControlState = z.infer; const inputStateSchema = z.object({ type: z.literal("input_state"), publicationId: z.uuid(), state: inputControlStateSchema }); -function isIncompatible(error: unknown): boolean { - return error instanceof Error && isIncompatibleProtocol(error.message); +function compatibilityIssue(error: unknown): AppCompatibilityIssue | null { + const code = error instanceof Error ? error.message : null; + return code === "app-update" || code === "site-update" || code === "domain_update_required" ? code : null; +} + +function checkAppVersion(major: number): void { + if (major !== PRODUCT_VERSION.major) throw new Error(major < PRODUCT_VERSION.major ? "app-update" : "site-update"); } type AppCommand = { type: string; publicationId?: string; roomId?: string; [key: string]: unknown }; @@ -278,17 +285,20 @@ export class AppPage implements AppPagePort { } function identity(body: unknown, port: number): void { - const value = identitySchema.extend({ service: z.enum(["piik-channel-app", "piik-client"]) }).parse(body); - if (value.port !== port) throw new Error("invalid_app_response"); - if (value.service !== "piik-channel-app" || value.protocol !== APP_PROTOCOL || value.domainProtocol !== CHANNEL_PROTOCOL) - throw new Error("incompatible_protocol"); + const endpoint = endpointSchema.parse(body); + if (endpoint.port !== port) throw new Error("invalid_app_response"); + if (endpoint.service === "piik-client") { + legacyIdentitySchema.parse(body); + throw new Error("app-update"); + } + checkAppVersion(productVersionSchema.parse(body).major); } export function discoverChannelAppHealth(options: AppDiscoveryOptions = {}): Promise<(AppHealth & { managementURL?: string }) | null> { return discoverLocalApp("health", (body, port) => { identity(body, port); return { ...healthSchema.parse(body), managementURL: `http://127.0.0.1:${port}/client` }; - }, options, isIncompatible); + }, options, compatibilityIssue); } const launcherAddressSchema = z.object({ connectURL: z.string().max(256) }); @@ -310,13 +320,13 @@ export const channelAppDiscovery: AppDiscovery = { const url = readLauncherAddress(body, port); const { windowNavigation } = windowNavigationSchema.parse(body); return { url: url.href, windowNavigation }; - }, { signal }, isIncompatible), + }, { signal }, compatibilityIssue), connect: (options = {}) => discoverLocalApp("connect-discovery", (body, port) => { const url = readLauncherAddress(body, port); url.searchParams.set("site", window.location.origin); return url.href; - }, options, isIncompatible), - isIncompatible, + }, options, compatibilityIssue), + compatibilityIssue, }; export interface BackgroundVoiceShortcuts { @@ -386,6 +396,8 @@ export class ChannelApp { private readonly onCaptureControlsChanged: (publicationId: string) => void = () => {}, onExternalInput: (event: NativeExternalInputState) => void = () => {}, canReceiveVoiceShortcut: () => boolean = () => false) { + const identity = identitySchema.parse(verifiedHealth); + checkAppVersion(identity.major); const health = healthSchema.parse(verifiedHealth); this.port = health.port; this.pagePlayer = health.pagePlayer === true; diff --git a/src/client/channel/product-version.ts b/src/client/channel/product-version.ts new file mode 100644 index 000000000..e51e1ea3c --- /dev/null +++ b/src/client/channel/product-version.ts @@ -0,0 +1,9 @@ +import { z } from "zod"; +import developmentVersion from "../../../prototype/channel-core/development-version.json" with { type: "json" }; + +export const productVersionSchema = z.object({ major: z.uint32(), minor: z.uint32() }); +export type ProductVersion = z.infer; + +declare const __PIIK_PRODUCT_VERSION__: ProductVersion; +export const PRODUCT_VERSION: ProductVersion = + typeof __PIIK_PRODUCT_VERSION__ === "undefined" ? developmentVersion : __PIIK_PRODUCT_VERSION__; diff --git a/src/client/channel/protocol.ts b/src/client/channel/protocol.ts index 31512d296..b3bad02ea 100644 --- a/src/client/channel/protocol.ts +++ b/src/client/channel/protocol.ts @@ -1,4 +1,5 @@ import { z } from "zod"; +import { productVersionSchema, type ProductVersion } from "./product-version"; import { watchFormatSchema } from "../../shared/watch-format"; export type { WatchFormat } from "../../shared/watch-format"; import { MAX_AUDIO_SEND_BITRATE, MIN_AUDIO_BITRATE, videoSettingsSchema, type VideoSettings } from "../../shared/protocol"; @@ -17,10 +18,6 @@ export const identityImageSchema = z.string().max(IDENTITY_IMAGE_URL_BYTES) export const roomIconSchema = z.string().regex(/^[A-Za-z0-9_-]{1,64}$/); export const identityIconSchema = z.union([roomIconSchema, identityImageSchema]); const signingKey = z.array(z.number().int().min(0).max(255)).length(32); -export const CHANNEL_PROTOCOL = 55; -export function isIncompatibleProtocol(code: string): boolean { - return code === "incompatible_protocol" || code.endsWith(": incompatible_protocol"); -} export const CHANNEL_SESSION_LIMIT = 128; export const CHANNEL_ROOM_LIMIT = 64; export const roomCreationPolicySchema = z.enum(["ordinary", "invite_only", "owner_only"]); @@ -122,7 +119,7 @@ export const snapshotSchema = z.object({ managedRoomIds: z.array(id).max(CHANNEL_ROOM_LIMIT), }), users: z.array(userSummarySchema), - sessions: z.array(z.object({ id, userId: id, online: z.boolean(), signingKey })).max(CHANNEL_SESSION_LIMIT), + sessions: z.array(z.object({ id, userId: id, online: z.boolean(), signingKey, ...productVersionSchema.shape })).max(CHANNEL_SESSION_LIMIT), publications: z.array(publicationSchema), voice: z.array(z.object({ sessionId: id, roomId: id, muted: z.boolean(), deafened: z.boolean() })), subscriptions: z.array(id), @@ -162,9 +159,24 @@ export const channelTopologySchema = z.object({ })) }).nullable(), }); export type ChannelTopology = z.infer; -export const channelWelcomeSchema = z.object({ type: z.literal("welcome"), protocol: z.literal(CHANNEL_PROTOCOL), credential: id, selfProfile: userSchema, sessionId: id, state: snapshotSchema, invitationOrigin: z.string().url().optional() }); +export const channelWelcomeSchema = z.object({ type: z.literal("welcome"), ...productVersionSchema.shape, credential: id, selfProfile: userSchema, sessionId: id, state: snapshotSchema, invitationOrigin: z.string().url().optional() }); const typeHeaderSchema = z.object({ type: z.string() }); + +export class DomainVersionMismatch extends Error { + constructor(readonly update: "participant" | "domain") { + super(update === "participant" ? "Update this Piik client." : "Update the Piik App or Server that hosts this site."); + } +} + +// Check the handshake header before reading the body owned by its major version. +export function checkDomainVersion(raw: unknown, localVersion: ProductVersion): void { + if (!record(raw) || (raw.type !== "welcome" && raw.type !== "incompatible_version")) return; + const { major } = productVersionSchema.parse(raw); + if (major !== localVersion.major) + throw new DomainVersionMismatch(major > localVersion.major ? "participant" : "domain"); + if (raw.type === "incompatible_version") throw new Error("invalid_response"); +} const replyResultSchema = z.discriminatedUnion("type", [ z.object({ type: z.literal("done") }), z.object({ type: z.literal("error"), code: z.string() }), @@ -324,7 +336,7 @@ export type ChannelCommand = | { type: "join_watch"; roomId: string; id: string; mode: WatchMode | null } | { type: "set_watch_byte_source"; roomId: string; id: string; byteSource: WatchByteSource | null } | { type: "stop_watch"; successorScreenId?: string; roomId: string; id: string } - | { type: "join"; protocol: typeof CHANNEL_PROTOCOL; snapshotForm?: "conversation"; canUsePeerTransport?: boolean; name: string; signingKey: number[]; credential?: string; ownerKey?: string; sessionId?: string } + | (ProductVersion & { type: "join"; snapshotForm?: "conversation"; canUsePeerTransport?: boolean; name: string; signingKey: number[]; credential?: string; ownerKey?: string; sessionId?: string }) | { type: "conversation"; packet: SignedConversationPacket } | { type: "set_profile"; name?: string; avatar?: string | null } | ({ type: "update_domain" } & Partial) diff --git a/src/client/channel/session.ts b/src/client/channel/session.ts index 740eb4e7b..e186a43a5 100644 --- a/src/client/channel/session.ts +++ b/src/client/channel/session.ts @@ -15,6 +15,7 @@ import { WatchPlayer } from "./watch-playback"; import { Stage, type SourceSelection, type ScreenShare } from "./stage"; import { HTMLVideoMedia, AppPageMedia, createResourceWatchMedia, waitForWatchMedia, type WatchMedia } from "./watch-media"; import { watchSourceSchema, type WatchPlayback, type WatchSource, type WatchMode, type WatchByteSource, type WatchFormat } from "./protocol"; +import { PRODUCT_VERSION } from "./product-version"; import { ChannelMedia } from "./media"; import { ChannelInput } from "./input"; import { ChannelConversation } from "./conversation"; @@ -23,7 +24,7 @@ import { RoomReadMarkers } from "./read-markers"; import { historyProfileIds } from "./message-history"; import { RoomHistory, type CompletedPage, type HistoryRefresh } from "./room-history"; import { userProfile } from "./presentation"; -import { HISTORY_INLINE_IMAGES, CHANNEL_PROTOCOL, CHANNEL_EVENT_BYTES, PROFILE_PAGE_SIZE, ChannelEventDecoder, createRoomCommand, roomSummarySchema, userSchema, type ChannelUser, type ProfilePage, type ProfileUpdate, type ChannelCommand, type ChannelEvent, type ChannelMessage, type ChannelReply, type ChannelSnapshot, type ChannelTopology, type ConversationReply, type ReceivedRecord, type DomainSettings, type MessageReactionSnapshot, type RoomInvitationState, type RoomSettings, type RoomSummary, type ScreenSource } from "./protocol"; +import { HISTORY_INLINE_IMAGES, CHANNEL_EVENT_BYTES, PROFILE_PAGE_SIZE, ChannelEventDecoder, DomainVersionMismatch, checkDomainVersion, createRoomCommand, roomSummarySchema, userSchema, type ChannelUser, type ProfilePage, type ProfileUpdate, type ChannelCommand, type ChannelEvent, type ChannelMessage, type ChannelReply, type ChannelSnapshot, type ChannelTopology, type ConversationReply, type ReceivedRecord, type DomainSettings, type MessageReactionSnapshot, type RoomInvitationState, type RoomSettings, type RoomSummary, type ScreenSource } from "./protocol"; import { requestBrowserRoomPersistence } from "./browser-room-persistence"; import { ChannelAttachments, type DraftFile, type PreparedFile } from "./attachments"; import { messageRemoved, type ChannelActions, type HostMediaTarget, type ReportError, type ChannelView, type ChatAttachmentPreparation, type ChatOptions, type SourceMicrophoneConfiguration, type SourceMicrophoneSettings } from "./types"; @@ -506,7 +507,7 @@ export class ChannelSession { const signingKey = await this.conversation.initialize(); if (this.socket !== socket || this.closed) return; sentBootstrap = newIdentity ? undefined : this.ownerBootstrap; - this.write({ type: "join", protocol: CHANNEL_PROTOCOL, canUsePeerTransport: typeof RTCPeerConnection === "function", signingKey, name: stored(nameKey) ?? "", credential, ownerKey: sentBootstrap?.key, sessionId: this.view.sessionId ?? undefined }); + this.write({ type: "join", ...PRODUCT_VERSION, canUsePeerTransport: typeof RTCPeerConnection === "function", signingKey, name: stored(nameKey) ?? "", credential, ownerKey: sentBootstrap?.key, sessionId: this.view.sessionId ?? undefined }); } catch (error) { if (this.socket === socket && !this.closed) { this.closeConnection(); @@ -520,9 +521,7 @@ export class ChannelSession { const text = String(data), wireBytes = new TextEncoder().encode(text).byteLength; if (wireBytes > CHANNEL_EVENT_BYTES) throw new Error("Channel event exceeds frame limit"); const raw = JSON.parse(text); - if (raw.type === "welcome" && raw.protocol !== CHANNEL_PROTOCOL) { - this.closeConnection(); this.patch({ error: "incompatible_protocol" }); return; - } + checkDomainVersion(raw, PRODUCT_VERSION); const event = decoder.decode(raw, wireBytes); if (!event) return; if (event.type === "welcome") { @@ -532,7 +531,12 @@ export class ChannelSession { sentBootstrap = undefined; this.receive(event, skipRoom, bootstrap); } else this.receive(event); - } catch { + } catch (error) { + if (error instanceof DomainVersionMismatch) { + this.closeConnection(); + this.patch({ error: error.update === "participant" ? "page_update_required" : "domain_update_required" }); + return; + } this.patch({ error: "invalid_response" }); // Later frames may omit pictures; recovery must start with a complete Welcome. socket.close(); @@ -651,7 +655,7 @@ export class ChannelSession { if (event.payload !== null) this.media.signal(event.pairId, event.payload); } else if (event.type === "error") { if (event.roomId !== undefined && event.roomId !== this.roomId) return; - if (!this.view.sessionId || event.code === "incompatible_protocol" || event.code === "invalid_credential") { + if (!this.view.sessionId || event.code === "invalid_credential") { this.closeConnection(); } this.patch({ error: event.code }); diff --git a/src/client/components/error-presentation.ts b/src/client/components/error-presentation.ts index 2c7045da6..f33e26a41 100644 --- a/src/client/components/error-presentation.ts +++ b/src/client/components/error-presentation.ts @@ -1,6 +1,5 @@ import type { CopyKey } from "../locales"; import type { UnsupportedVideoFormat } from "../native/wire"; -import { isIncompatibleProtocol } from "../channel/protocol"; import { diagnoseChannelFact } from "../ui/diagnosis"; export interface ChannelErrorPresentation { @@ -33,8 +32,7 @@ export function channelErrorPresentation(error: string | null, t: (key: CopyKey, return display("channel.error.webassemblyUnavailable"); if (error === "room_runtime_unavailable") return display("channel.error.roomRuntimeUnavailable"); - if (isIncompatibleProtocol(error)) - return display("channel.error.incompatibleProtocol"); + if (error === "page_update_required") return display("channel.error.pageUpdateRequired"); if (error === "channel_full") return display("channel.error.channelFull"); if (error === "directory_storage_failed") diff --git a/src/client/components/living/AppConnectionButton.tsx b/src/client/components/living/AppConnectionButton.tsx index df98a77df..18b852ffd 100644 --- a/src/client/components/living/AppConnectionButton.tsx +++ b/src/client/components/living/AppConnectionButton.tsx @@ -16,7 +16,7 @@ import { channelAppDiscovery } from "../../channel/app-link"; import { OpenInClient, type AppNavigationIssue } from "./OpenInClient"; import { currentTheme, subscribeTheme } from "../../ui/theme"; import type {} from "../../ui/native-window"; -import { diagnoseChannelFact, type AppConnectionState } from "../../ui/diagnosis"; +import { diagnoseChannelFact, isAppConnectionIssue, type AppConnectionState } from "../../ui/diagnosis"; import { ChannelDiagnosisHelp } from "../ChannelDiagnosisHelp"; interface AppConnectionProps { @@ -162,7 +162,8 @@ export function AppConnectionButton({ onConnected, discovery = channelAppDiscove if (!approval || approving || signal.aborted) return; approving = true; const health = await native?.health({ signal, waitForPermission: Boolean(attempt.popup), port: Number(approval.port) }).catch(error => { - if (!signal.aborted && native?.isIncompatible(error)) finish("incompatible"); + const issue = native?.compatibilityIssue(error); + if (!signal.aborted && issue) finish(issue); return null; }); if (signal.aborted) return; @@ -170,7 +171,7 @@ export function AppConnectionButton({ onConnected, discovery = channelAppDiscove if (health) { rememberBuild(health); try { await activate(health); } - catch (error) { if (!signal.aborted) finish(native?.isIncompatible(error) ? "incompatible" : "unavailable"); } + catch (error) { if (!signal.aborted) finish(native?.compatibilityIssue(error) ?? "unavailable"); } } else if (reported) finish("unavailable"); else if (attempt.popup?.closed) finish("idle"); }; @@ -190,7 +191,7 @@ export function AppConnectionButton({ onConnected, discovery = channelAppDiscove if (pending.current === attempt) { pending.current = null; automaticFailed.current = result !== "ready"; - const failed = result === "unavailable" || result === "incompatible"; + const failed = isAppConnectionIssue(result); setAutomaticHint(false); setState(attempt.automatic && failed ? "idle" : result); if (!attempt.automatic && failed) showHelp(); @@ -236,7 +237,7 @@ export function AppConnectionButton({ onConnected, discovery = channelAppDiscove if (!url) { finish("unavailable"); return; } // A compatible App was found; health may only see an older, approved App. const health = await native.health({ signal, waitForPermission: !attempt.automatic }).catch(error => { - if (native?.isIncompatible(error)) return null; + if (native?.compatibilityIssue(error)) return null; throw error; }); if (signal.aborted) return; @@ -259,7 +260,7 @@ export function AppConnectionButton({ onConnected, discovery = channelAppDiscove setAutomaticHint(attempt.automatic); setState("approval"); } catch (error) { - if (!signal.aborted) finish(native?.isIncompatible(error) ? "incompatible" : "unavailable"); + if (!signal.aborted) finish(native?.compatibilityIssue(error) ?? "unavailable"); } }; if (wake && wakeURL) { @@ -280,9 +281,9 @@ export function AppConnectionButton({ onConnected, discovery = channelAppDiscove useEffect(() => { if (!ready) return; // Confirmed App readiness supersedes earlier discovery failures. - setNavigationIssue(issue => issue === "unavailable" || issue === "incompatible" ? null : issue); + setNavigationIssue(issue => isAppConnectionIssue(issue) ? null : issue); }, [ready]); - const failed = state === "unavailable" || state === "incompatible"; + const failed = isAppConnectionIssue(state); const diagnosis = diagnoseChannelFact({ area: "app", state }); const label = t(state === "approval" || failed ? diagnosis!.message : ({ idle: "client.connect.action", @@ -291,15 +292,16 @@ export function AppConnectionButton({ onConnected, discovery = channelAppDiscove approving: "client.connect.approving", ready: connected === false ? "client.connect.action" : "client.connect.manage", } as const)[state]); - const navigationDiagnosis = navigationIssue === "unavailable" || navigationIssue === "incompatible" + const navigationDiagnosis = isAppConnectionIssue(navigationIssue) ? diagnoseChannelFact({ area: "app", state: navigationIssue }) : null; const navigationMessage = navigationIssue === "unsupported" ? "client.connect.navigationUnsupported" : navigationIssue === "popup-blocked" ? "client.connect.navigationPopupBlocked" : navigationDiagnosis?.message; - const helpDiagnosis = state === "incompatible" ? diagnosis : navigationDiagnosis ?? diagnosis; + const incompatible = diagnosis?.topic === "appVersion"; + const helpDiagnosis = incompatible ? diagnosis : navigationDiagnosis ?? diagnosis; const update = ready ? release : null; const availableUpdate = update?.kind === "update-available" || update?.kind === "major-update"; const title = availableUpdate ? t("client.connect.update", { current: build!.version, version: update.version }) : label; - return <> @@ -333,7 +335,7 @@ export function AppConnectionButton({ onConnected, discovery = channelAppDiscove
{state === "busy" ? : } + )}
}