From 00faaa90ffefc232e167d64a35b485ee237575b7 Mon Sep 17 00:00:00 2001 From: AAA <35992542+TNTcraftHIM@users.noreply.github.com> Date: Mon, 9 Nov 2026 22:43:39 -0400 Subject: [PATCH] feat(app): show local certificate details in the shared launcher --- docs/guide/getting-started.md | 15 ++- docs/guide/getting-started.zh-CN.md | 10 +- docs/guide/room-tools.md | 17 +++ docs/guide/room-tools.zh-CN.md | 15 +++ docs/guide/troubleshooting.md | 13 ++- docs/guide/troubleshooting.zh-CN.md | 7 +- prototype/channel-server/src/app_domain.rs | 107 +++++++++++++++--- src/client/components/living/LauncherForm.tsx | 29 ++++- src/client/locales/en.ts | 4 + src/client/locales/zh.ts | 4 + src/client/pages/AppLauncherPage.tsx | 9 +- src/client/pages/ControlsPreview.tsx | 5 +- src/client/styles.css | 4 + tests/app-launcher-recovery.test.ts | 19 +++- 14 files changed, 219 insertions(+), 39 deletions(-) diff --git a/docs/guide/getting-started.md b/docs/guide/getting-started.md index 97bcacbd1..4866c8351 100644 --- a/docs/guide/getting-started.md +++ b/docs/guide/getting-started.md @@ -49,7 +49,8 @@ site, not the entry for this test version. open Piik. Keep the desktop package's files together. 2. The launcher opens in your system browser. Choose a mode below, then select **Open Piik**. The domain opens with its room list. -3. Select **Create room**, enter a name and choose **Public** for a first room +3. Open the room list (**Rooms** on a narrow screen), select **Create room**, + enter a name and choose **Public** for a first room everyone in the domain can enter. Check the hosting note, then select **Create room**. You are now in a usable room: send a message to try it. 4. [Invite your friends](#invite-friends), then select **Start sharing**. @@ -65,8 +66,10 @@ site, not the entry for this test version. - **Public invite:** for friends elsewhere. It creates a temporary Internet address while App is running. Send a new link if that address changes. -Local invitations use HTTPS. Before accepting the first certificate warning, -compare it with the fingerprint in the App terminal; see the +Local invitations use HTTPS. After starting **Local network**, return to the +App launcher and expand **Local connection details** below **Open Piik** to +read the address and certificate fingerprint. Compare it with the browser's +certificate before accepting its first warning; see the [certificate steps](./troubleshooting.md#local-https-certificate-warning). The domain owner can set **Public** or **Private** entry and an optional domain passphrase in **Domain settings → Domain**, beside the domain name. @@ -83,7 +86,8 @@ passphrase in **Domain settings → Domain**, beside the domain name. Send invitations only to people you want to admit. Domain entry and private-room entry are different: a domain invitation alone does not unlock every private room. -Use **Reset room invitation** only when you want a new link: the old link stops +To replace a link, expand **Reset room invitation**, then select +**Generate new invitation**. The old link stops working, while people who already have access keep it. If an older invitation cannot be recovered, the panel explains this before you generate a replacement. @@ -130,6 +134,9 @@ the native sources supported by your device. **App-hosted room** continues while App runs; a **Browser-hosted room** is unavailable while its hosting page is closed. Switching rooms or toggling **Compact interface** keeps your other room activities running. +- Closing the App launcher page leaves App running. Stopping App ends the + activities it runs and makes its hosted rooms unavailable across all its + connected sites. Reopen App to host those rooms again. - Confirmed chat history belongs to the room's host. Refreshing reloads history when that host is available; use **Earlier messages** for older pages. An unsent draft does not survive a page refresh. Captures and voice do not diff --git a/docs/guide/getting-started.zh-CN.md b/docs/guide/getting-started.zh-CN.md index 6a533ed6b..11c9fa149 100644 --- a/docs/guide/getting-started.zh-CN.md +++ b/docs/guide/getting-started.zh-CN.md @@ -44,7 +44,8 @@ Android 安装提供的 APK,再打开 Piik。桌面程序包内的文件应保持在一起。 2. 启动页会在系统浏览器中打开。按下方说明选择模式,再点击**进入 Piik**, 即可看到域及其房间列表。 -3. 点击**创建房间**,填写名称。第一个房间可选**公开**,让域内的人都能进入。 +3. 打开房间列表(窄屏先点**房间列表**),再点**创建房间**,填写名称。 + 第一个房间可选**公开**,让域内的人都能进入。 核对托管提示,再点击**创建房间**。现在房间已经可用,可以先发一条消息试试。 4. [邀请朋友](#邀请朋友)后,点击**开始分享**,选择**浏览器**、**摄像头**, 或 App 提供的窗口/屏幕来源。选定实际画面,需要且支持时开启来源声音。 @@ -58,7 +59,8 @@ - **公网邀请:** 适合其他网络的朋友。App 运行期间会提供临时公网地址, 地址变化后需发送新的链接。 -局域网邀请使用 HTTPS。首次接受证书提示前,请与 App 终端中的指纹核对, +局域网邀请使用 HTTPS。启动**局域网使用**后,返回 App 启动页,展开**进入 Piik**下方的 +**局域网连接详情**,查看网址与证书指纹。首次接受警告前,先与浏览器显示的证书核对, 操作见[证书确认说明](./troubleshooting.zh-CN.md#本地-https-证书提示)。 域主可在域名称旁的**域设置 → 域**中选择**公开**或**私密**入口,并设置可选的域口令。 @@ -70,7 +72,7 @@ 还没有邀请时,点击**生成新邀请**。该邀请可让接收者进入域及指定的私密房间。 请只把邀请发给你想接纳的人。进入域与进入私密房间是两回事:域邀请不会解锁所有私密房间。 -需要换新链接时才使用**重置房间邀请**:旧链接会失效,已获准的用户仍保留访问。 +需要换新链接时,展开**重置房间邀请**,再点**生成新邀请**:旧链接会失效,已获准的用户仍保留访问。 旧邀请无法取回时,面板会先说明,再由你决定是否生成新邀请。 ![邀请页面提供房间链接、复制、二维码和重置邀请操作。](../assets/guide/channel-invitation.zh-CN.png#gh-light-mode-only) @@ -107,6 +109,8 @@ - **停止分享**结束该分享,**停止观看**结束你的观看,**退出语音**结束你在该房间的通话。 - 关闭网页会结束它的个人分享、观看和语音。**App 托管房间**在 App 运行时继续服务; **网页托管房间**在托管网页关闭期间不可用。切换房间或开关**简洁界面**不会停止其他房间的活动。 +- 关闭 App 启动网页不会停止 App。停止 App 会结束由它运行的活动,并让它在各个已连接站点 + 托管的房间暂时不可用;重新打开 App 后可再次托管。 - 已确认的聊天记录由房间托管端保存。刷新后,托管端可用时会重新加载历史, 更早内容可点击**更早的消息**查看。未发送草稿不保留到刷新之后; 重新打开网页或 App 也不会自动恢复采集和语音。 diff --git a/docs/guide/room-tools.md b/docs/guide/room-tools.md index a30782288..18d660fdd 100644 --- a/docs/guide/room-tools.md +++ b/docs/guide/room-tools.md @@ -9,6 +9,23 @@ Once admitted to that room, you can chat, join voice, share a picture or watch someone else's share. Domain and room owners manage their respective settings; you do not need a separate participant role to use these activities. +## Manage a room + +Open the room list (**Rooms** on a narrow screen), then select the settings +button beside that room. This leaves your current conversation and activities +in place. The tabs show the tasks available to you: + +| Tab | Task | +| --- | --- | +| **Room** | Change the name, image or access, then **Save**. **Hide from users without access** hides a private room from people who have not been admitted. | +| **Invitation** | Copy the private-room invitation or open its QR code. Under **Users with access**, **Remove room access** ends that user's access and activities in this room; they need a new grant to return. | +| **My forwarding** | Choose how many people this device helps forward to in this room. | +| **Records and backups** | Export chat, or export a room backup when you manage its host. To restore, select **Restore backup**, choose the ZIP and read the replacement notice before **Confirm**. Restoration replaces this room's settings and messages. | + +Changing an invitation does not revoke people already admitted. To replace its +link, expand **Reset room invitation**, then select **Generate new invitation**. +Domain settings remain beside the domain name in the room list. + ## Chat and reactions 1. Select a room and send a message in its conversation. Use the attachment diff --git a/docs/guide/room-tools.zh-CN.md b/docs/guide/room-tools.zh-CN.md index 283aa57b4..99d4aebbc 100644 --- a/docs/guide/room-tools.zh-CN.md +++ b/docs/guide/room-tools.zh-CN.md @@ -8,6 +8,21 @@ 获准进入房间的人都可以聊天、加入语音、分享画面或观看别人的分享。 域主和房主分别管理域和房间设置,日常参与不需要额外的身份组。 +## 管理房间 + +打开房间列表(窄屏先点**房间列表**),再点对应房间旁的设置按钮。 +这不会切换当前聊天或停止活动。标签页按你的权限提供这些操作: + +| 标签页 | 操作 | +| --- | --- | +| **房间** | 修改名称、图片或访问方式,再点**保存**。**对未获准的用户隐藏房间**会让尚未获准的人看不到该私密房间。 | +| **邀请** | 复制私密房间邀请或打开二维码。在**已获准的用户**中,**移除房间资格**会结束该用户在此房间的访问和活动;再次进入需要重新获准。 | +| **我的转发** | 选择这台设备在本房间最多帮多少人转发。 | +| **记录与备份** | 导出聊天;管理房间托管端时还可导出房间备份。恢复时点**从备份恢复**,选择 ZIP,阅读替换提示后再点**确认**。恢复会替换此房间的设置和消息。 | + +更换邀请不会撤销已获准用户的资格。需要换新链接时,展开**重置房间邀请**,再点**生成新邀请**。 +域设置仍在房间列表的域名称旁。 + ## 聊天与表情 1. 选择房间,在聊天输入框中发送消息。点击附件按钮可添加图片或文件,也可以同时附上文字。 diff --git a/docs/guide/troubleshooting.md b/docs/guide/troubleshooting.md index 6f2ccc814..017cf3d62 100644 --- a/docs/guide/troubleshooting.md +++ b/docs/guide/troubleshooting.md @@ -158,10 +158,15 @@ Piik App's Local network invitation uses a temporary self-signed HTTPS certificate. The browser can show a certificate warning before opening it. 1. Check that the address is the one the Host intended to share. -2. Open the warning's certificate details and compare its **SHA-256 fingerprint** - with **Certificate SHA-256** in the App terminal. Ask the App owner over your usual - trusted chat if you are on another device. -3. If it matches, use the browser's **Advanced → Continue** option where available. +2. Ask the App owner to start **Local network**, return to the App launcher and + expand **Local connection details** below **Open Piik**. It shows the actual + HTTPS address and certificate **SHA-256 fingerprint**; **Copy verification + details** copies both. The App terminal's **Certificate SHA-256** is an + alternative on desktop. +3. Open the warning's certificate details and compare its **SHA-256 fingerprint** + with that value. If you are on another device, confirm it with the App owner + over your usual trusted chat. +4. If it matches, use the browser's **Advanced → Continue** option where available. Then allow microphone access or request remote control normally. The temporary certificate changes after an App restart. A different diff --git a/docs/guide/troubleshooting.zh-CN.md b/docs/guide/troubleshooting.zh-CN.md index 608aff9c2..10b977589 100644 --- a/docs/guide/troubleshooting.zh-CN.md +++ b/docs/guide/troubleshooting.zh-CN.md @@ -134,8 +134,11 @@ App 提示本地端口不可用时,先关闭占用它的旧 App 实例。 Piik App 的本地网络邀请使用临时自签名 HTTPS 证书,浏览器可能先显示证书警告。 1. 确认网址与房主准备分享的地址一致。 -2. 打开警告页的证书详情,将 **SHA-256 指纹** 与 App 终端中的 **Certificate SHA-256** 对照。异地使用时,可通过平时信任的聊天渠道向 App 使用者核对。 -3. 指纹一致后,使用浏览器提供的 **高级 → 继续访问**;进入页面后,再正常允许麦克风或申请远控。 +2. 请 App 使用者先启动**局域网使用**,返回 App 启动页,展开**进入 Piik**下方的**局域网连接详情**。 + 这里显示实际 HTTPS 网址和证书 **SHA-256 指纹**,**复制核对信息**可复制两者。 + 桌面端也可使用 App 终端中的 **Certificate SHA-256**。 +3. 打开警告页的证书详情,将 **SHA-256 指纹** 与上述值对照。在另一设备上使用时,通过平时信任的聊天渠道向 App 使用者核对。 +4. 指纹一致后,使用浏览器提供的 **高级 → 继续访问**;进入页面后,再正常允许麦克风或申请远控。 重启 App 会更换临时证书,新指纹需要重新确认。App 不保存证书文件,也不安装系统受信任证书。 不要全局关闭浏览器的安全检查。如果浏览器不允许接受例外,请改用该设备已信任证书的 HTTPS 站点; diff --git a/prototype/channel-server/src/app_domain.rs b/prototype/channel-server/src/app_domain.rs index dc7abb69b..716abe5ea 100644 --- a/prototype/channel-server/src/app_domain.rs +++ b/prototype/channel-server/src/app_domain.rs @@ -5,7 +5,7 @@ mod stun; use super::{console::Console, stop_hosts, tunnel, ApiResult, App, Permission}; use crate::{domain::Domain, web}; use axum::{extract::State, http::StatusCode, Json}; -use serde::Deserialize; +use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use std::{future::pending, net::Ipv4Addr, sync::Arc}; use tokio::{ @@ -36,9 +36,39 @@ impl Failure { #[derive(Clone)] enum Progress { Starting, - Ready(String), + Ready(Ready), Failed(Failure), } +#[derive(Clone, Serialize)] +#[serde(rename_all = "camelCase")] +struct Ready { + target: String, + #[serde(skip_serializing_if = "Option::is_none")] + local_certificate: Option, +} +#[derive(Clone, Serialize)] +#[serde(rename_all = "camelCase")] +struct LocalCertificate { + origin: String, + sha256_fingerprint: String, +} +impl Ready { + fn new(target: String, https: Option<&web::LanHttps>) -> Self { + Self { + target, + local_certificate: https.map(|https| LocalCertificate { + origin: https.origin().to_owned(), + sha256_fingerprint: https.fingerprint(), + }), + } + } + fn describe(&self, state: &mut Value) { + state["target"] = json!(self.target); + if let Some(certificate) = &self.local_certificate { + state["localCertificate"] = json!(certificate); + } + } +} pub(super) struct Launch { progress: watch::Receiver, stop: watch::Sender, @@ -77,7 +107,7 @@ pub(super) async fn describe(app: &App, state: &mut Value) -> anyhow::Result<()> if let Some(launch) = app.launch.lock().await.as_ref() { match &*launch.progress.borrow() { Progress::Starting => state["starting"] = json!(true), - Progress::Ready(target) => state["target"] = json!(target), + Progress::Ready(ready) => ready.describe(state), Progress::Failed(failure) => { state["reason"] = json!(failure.reason); state["detail"] = json!(failure.detail); @@ -124,7 +154,7 @@ pub(super) async fn launch(State(app): State>, Json(request): Json return Ok(Json(json!({ "target": target }))), + Progress::Ready(ready) => return Ok(Json(json!(ready))), Progress::Failed(failure) => return Err(failure.response()), Progress::Starting => {} } @@ -222,9 +252,17 @@ async fn run( )); } }; - if let Some(https) = &https { - eprintln!("Local invitation entry: {}", https.origin()); - eprintln!("Certificate SHA-256: {}", https.fingerprint()); + let mut ready = Ready::new( + format!( + "{origin}/?piik-client-port={}#owner={}&piik-client=1", + app.port, + domain.owner_key() + ), + https.as_ref(), + ); + if let Some(certificate) = &ready.local_certificate { + eprintln!("Local invitation entry: {}", certificate.origin); + eprintln!("Certificate SHA-256: {}", certificate.sha256_fingerprint); } let permission = Arc::new(Permission::new(identity.namespace)); app.registry.lock().await.local = Some((origin.clone(), permission.clone())); @@ -240,11 +278,7 @@ async fn run( }, )); console.ready(&invitation); - progress.send_replace(Progress::Ready(format!( - "{origin}/?piik-client-port={}#owner={}&piik-client=1", - app.port, - domain.owner_key() - ))); + progress.send_replace(Progress::Ready(ready.clone())); let (result, finished_service) = loop { tokio::select! { _ = stopped.changed() => break (Ok(()), None), @@ -287,9 +321,10 @@ async fn run( let result = domain.restore(request.metadata, &request.credential); drop(registry); if result.is_ok() { - progress.send_replace(Progress::Ready(format!( + ready.target = format!( "{origin}/?piik-client-port={}#owner={}&piik-client=1", app.port, domain.owner_key() - ))); + ); + progress.send_replace(Progress::Ready(ready.clone())); } else { for ((site, domain, user), credential) in restart { let permission = app.registry.lock().await.permission(&site).cloned(); @@ -354,3 +389,47 @@ async fn local_https(selected: Option<&str>, port: u16) -> Result + + {t("client.launch.localDetails")} +

{certificate.origin}

{t("client.launch.certificateHint")}

+ {vis ? "SHA-256" : t("client.launch.certificate")} + {bytes.map((byte, index) => {byte}{index < bytes.length - 1 && <>:})} + +
+ ; +} const MODES: Array<{ mode: AppMode; @@ -45,6 +66,7 @@ export function LauncherForm({ siteBusy, siteError, target, + localCertificate, onOpen, entryURL = target => target, lan, @@ -63,6 +85,7 @@ export function LauncherForm({ siteBusy?: boolean; siteError?: string; target?: string; + localCertificate?: LocalCertificate; onOpen?: (event: MouseEvent) => void; entryURL?: (target: string) => string; lan?: { @@ -140,9 +163,9 @@ export function LauncherForm({ {roomError} - {target ? + {target ? <> {vis ? null : {t("client.launch.go")}} - : <> + {localCertificate && } : <>

{t("client.launch.room")}

= { "client.launch.chooseAddress": "Choose an address", "client.launch.lanHint": "Choose an address on the same network as your friends.", "client.launch.localHTTPS": "Local invitations use HTTPS. Confirm the local certificate on your first visit.", + "client.launch.localDetails": "Local connection details", + "client.launch.certificate": "Certificate SHA-256 fingerprint", + "client.launch.certificateHint": "When a friend first opens your local invitation, they can compare this fingerprint with the browser's certificate details.", + "client.launch.copyCertificate": "Copy verification details", "client.launch.lanUnavailable": "No local network address is available. Connect to a network and refresh this page.", "client.launch.go": "Open Piik", "client.launch.starting": "Preparing Piik", diff --git a/src/client/locales/zh.ts b/src/client/locales/zh.ts index 7e32f1366..c485f2ff4 100644 --- a/src/client/locales/zh.ts +++ b/src/client/locales/zh.ts @@ -274,6 +274,10 @@ export const zh = { "client.launch.chooseAddress": "选择地址", "client.launch.lanHint": "选择与朋友处于同一网络的地址。", "client.launch.localHTTPS": "局域网邀请使用本地 HTTPS;首次访问需确认本地证书。", + "client.launch.localDetails": "局域网连接详情", + "client.launch.certificate": "证书 SHA-256 指纹", + "client.launch.certificateHint": "朋友首次打开局域网邀请时,可在浏览器的证书详情中核对这串指纹。", + "client.launch.copyCertificate": "复制核对信息", "client.launch.lanUnavailable": "没有可用的局域网地址,请连接网络后刷新页面", "client.launch.go": "进入 Piik", "client.launch.starting": "正在准备 Piik", diff --git a/src/client/pages/AppLauncherPage.tsx b/src/client/pages/AppLauncherPage.tsx index 48156fab0..b419dc0cd 100644 --- a/src/client/pages/AppLauncherPage.tsx +++ b/src/client/pages/AppLauncherPage.tsx @@ -6,7 +6,7 @@ import { HintComic } from "../components/living/hints"; import { LoadingStatus } from "../components/living/WaitingStatus"; import { AppReleaseNotice } from "../components/living/AppReleaseNotice"; import { AppHeader } from "../components/living/Header"; -import { LauncherForm } from "../components/living/LauncherForm"; +import { LauncherForm, type LocalCertificate } from "../components/living/LauncherForm"; import { Btn, Pill } from "../components/living/primitives"; import { hasCopyPreference, isCopyKey, useCopy } from "../ui/copy"; import { consoleLanguage } from "../locales"; @@ -17,10 +17,12 @@ import type { AppReleaseIdentity } from "../lib/release-update"; import { useReleaseUpdate } from "../lib/use-release-update"; import { downloadBlob } from "../lib/download"; +const localCertificateSchema = z.object({ origin: z.string().url(), sha256Fingerprint: z.string().regex(/^[A-Fa-f0-9]{64}$/) }); const launcherStateSchema = z.object({ sites: z.array(z.string()), startupSite: z.string(), target: z.string().optional(), + localCertificate: localCertificateSchema.optional(), starting: z.boolean().optional(), reason: z.string().optional(), detail: z.string().optional(), @@ -34,7 +36,7 @@ const launcherStateSchema = z.object({ selected: z.string(), }).optional(), }); -const launcherResultSchema = z.object({ target: z.string().url() }).strict(); +const launcherResultSchema = z.object({ target: z.string().url(), localCertificate: localCertificateSchema.optional() }).strict(); const launcherErrorSchema = z.object({ reason: z.string().optional(), detail: z.string() }); export function AppLauncherPage() { @@ -58,6 +60,7 @@ export function AppLauncherPage() { const version = build?.version === "development" && /^[a-f0-9]{40}$/i.test(build.revision) ? `${build.version} (${build.revision.slice(0, 7)})` : build?.version; const [target, setTarget] = useState(); + const [localCertificate, setLocalCertificate] = useState(); const [controlPort, setControlPort] = useState(); const [siteBusy, setSiteBusy] = useState(false); const [siteError, setSiteError] = useState(); @@ -112,6 +115,7 @@ export function AppLauncherPage() { } setControlPort(state.controlPort); setTarget(state.target); + setLocalCertificate(state.localCertificate); setStarting(state.starting === true); setSites(state.sites); setStartupSite(state.startupSite); @@ -371,6 +375,7 @@ export function AppLauncherPage() { siteBusy={siteBusy} siteError={siteError} target={target} + localCertificate={localCertificate} entryURL={launchURL} lan={lan && { ...lan, onChange: (selected) => setLan({ ...lan, selected }) }} onSubmit={launch} diff --git a/src/client/pages/ControlsPreview.tsx b/src/client/pages/ControlsPreview.tsx index be355c65c..38279c351 100644 --- a/src/client/pages/ControlsPreview.tsx +++ b/src/client/pages/ControlsPreview.tsx @@ -60,6 +60,7 @@ export function ControlsPreview() { const [launchSites, setLaunchSites] = useState(["https://demo.piik.tv"]); const [startupSite, setStartupSite] = useState(""); const [launchLan, setLaunchLan] = useState("192.0.2.10"); + const [launchReady, setLaunchReady] = useState(() => new URLSearchParams(location.search).has("local-certificate")); const [policy, setPolicy] = useState<"open" | "private">("open"); const [roomPassword, setRoomPassword] = useState(false); const [includeCredential, setIncludeCredential] = useState(true); @@ -332,6 +333,8 @@ export function ControlsPreview() {
setStartupSite(value => value === site ? "" : site)} sites={launchSites} onSelectSite={notify} onOpen={event => { event.preventDefault(); notify(); }} onRemoveSite={site => { setLaunchSites(sites => sites.filter(value => value !== site)); if (startupSite === site) setStartupSite(""); }} @@ -339,7 +342,7 @@ export function ControlsPreview() { { address: "192.0.2.10", name: "Wi-Fi" }, { address: "192.0.2.20", name: "vEthernet (Example Virtual Network Adapter with a Long Name)" }, ] }} - onSubmit={event => event.preventDefault()}> + onSubmit={event => { event.preventDefault(); if (launchMode === "local") setLaunchReady(true); }}> summary > svg:last-child { transition: transform 180ms var(--spring); } .lr-client-access-options[open] > summary > svg:last-child { transform: rotate(180deg); } .lr-client-access-hint { margin: 8px 0 0; color: var(--muted); font-size: 12px; line-height: 1.6; } +.lr-client-certificate { width: min(460px, 100%); } +.lr-client-certificate > div { display: grid; justify-items: start; gap: 10px; padding: 16px 0 0; text-align: start; font-size: 12px; line-height: 1.6; } +.lr-client-certificate p { margin: 0; color: var(--muted); overflow-wrap: anywhere; } +.lr-client-certificate code { width: 100%; font: 12px/1.8 var(--mono); user-select: text; } .lr-join { flex: 1; diff --git a/tests/app-launcher-recovery.test.ts b/tests/app-launcher-recovery.test.ts index 624647a9d..06c2811c0 100644 --- a/tests/app-launcher-recovery.test.ts +++ b/tests/app-launcher-recovery.test.ts @@ -5,7 +5,7 @@ import { renderToStaticMarkup } from "react-dom/server"; import ts from "typescript"; import { describe, expect, it, vi } from "vitest"; import { z } from "zod"; -import { LauncherForm } from "../src/client/components/living/LauncherForm"; +import { LauncherForm, type LocalCertificate } from "../src/client/components/living/LauncherForm"; import { Btn } from "../src/client/components/living/primitives"; import { siteEntryOrigin, siteEntryURL } from "../src/client/lib/site-address"; import { clientLaunchURL, readPreferredAppMode, savePreferredAppMode, type AppMode } from "../src/client/lib/app-launch"; @@ -25,7 +25,7 @@ function collect(node: ts.Node): void { && node.initializer && ts.isJsxExpression(node.initializer)) { diagnosticControl = node.initializer.expression!.getText(source); } - if (ts.isVariableDeclaration(node) && /^launcher.*Schema$/.test(node.name.getText(source))) { + if (ts.isVariableDeclaration(node) && /^(?:launcher.*|localCertificate)Schema$/.test(node.name.getText(source))) { declarations.push(`const ${node.getText(source)};`); } if (ts.isFunctionDeclaration(node) && ["beginStateChange", "changeMode", "changeSite", "approveSite", "enableDebug", "exportDebug", "launchURL", "launch"].includes(node.name?.text ?? "")) { @@ -53,14 +53,14 @@ const saved = { revision: "test", version: "development", debug: false, lan: { addresses: [{ address: "192.0.2.1", name: "LAN" }], selected: "192.0.2.1" }, }; -const response = (state: typeof saved & { detail?: string; target?: string } = saved) => ({ ok: true, status: 200, json: async () => state }); +const response = (state: typeof saved & { detail?: string; target?: string; localCertificate?: LocalCertificate } = saved) => ({ ok: true, status: 200, json: async () => state }); function mount(fetch: ReturnType, manualSite = false, { debug = false, mode }: { debug?: boolean; mode?: AppMode } = {}) { const downloads = vi.fn(); const initialMode = mode ?? runInNewContext(`(${modeInitializer})()`, { readPreferredAppMode }) as AppMode; const state: Record = { Mode: initialMode }; const setters = Object.fromEntries([ - "Mode", "Lan", "ControlPort", "Target", "Starting", "Sites", "StartupSite", + "Mode", "Lan", "ControlPort", "Target", "LocalCertificate", "Starting", "Sites", "StartupSite", "AppDebug", "Error", "Loading", "Build", "RemoteControlPrototype", "SiteBusy", "SiteError", "DebugBusy", "DebugError", "Reload", ].map(name => [`set${name}`, vi.fn((value: unknown) => { @@ -185,9 +185,15 @@ describe("App launcher state recovery", () => { }); it("uses the installed build identity without retaining a second presentation state", async () => { const revision = "a".repeat(40); - const page = mount(vi.fn(async () => response({ ...saved, version: "development", revision }))); + const localCertificate = { origin: "https://192.0.2.1:8787", sha256Fingerprint: "A1".repeat(32) }; + const fetch = vi.fn(async () => response({ ...saved, version: "development", revision, localCertificate })); + const page = mount(fetch); await settle(); expect(page.state.Build).toEqual({ version: "development", revision, packageTarget: undefined }); + expect(page.state.LocalCertificate).toEqual(localCertificate); + fetch.mockResolvedValueOnce(response(saved)); + page.focus(); await settle(); + expect(page.state.LocalCertificate).toBeUndefined(); page.cleanup(); }); @@ -204,7 +210,8 @@ describe("App launcher state recovery", () => { finish({ ok: false, status: 503, json: async () => ({ detail: "Startup failed" }) }); await first; expect(page.state).toMatchObject({ Starting: false, Error: { kind: "launch", detail: "Startup failed" } }); - fetch.mockResolvedValueOnce({ ok: true, status: 200, json: async () => ({ target: "https://room.example/#piik-client=1" }) }); + fetch.mockResolvedValueOnce({ ok: true, status: 200, json: async () => ({ target: "https://room.example/#piik-client=1", + localCertificate: { origin: "https://192.0.2.1:8787", sha256Fingerprint: "A1".repeat(32) } }) }); await page.launch(event); expect(page.navigate).toHaveBeenCalledWith("https://room.example/#piik-client=1&piik-lang=en&piik-mode=text&piik-theme=system"); page.cleanup();