diff --git a/capsules/assistant/browser/harness-host.js b/capsules/assistant/browser/harness-host.js index f30b5d7d3..97f328180 100644 --- a/capsules/assistant/browser/harness-host.js +++ b/capsules/assistant/browser/harness-host.js @@ -10,11 +10,18 @@ import { migrateLegacyWorkspaces, mergeWorkspaceDocuments } from "./workspace-tr that needs Home is asked for by message; anything that needs Runtime goes through the launch token like every other capsule. */ -const homeToken = (() => { +let homeToken = (() => { const params = new URLSearchParams(window.location.hash.replace(/^#/, "")); return params.get("home_token") || ""; })(); +const homeTokenListeners = new Set(); +export function onHomeTokenChanged(callback) { homeTokenListeners.add(callback); } +export function setHomeGuiLaunchToken(token) { + homeToken = token; + for (const callback of homeTokenListeners) callback(token); +} + /* ---- shell-core ------------------------------------------------------------ */ export function getHomeGuiLaunchToken() { diff --git a/capsules/assistant/browser/home-agent.js b/capsules/assistant/browser/home-agent.js index f6af18174..9880d1f9c 100644 --- a/capsules/assistant/browser/home-agent.js +++ b/capsules/assistant/browser/home-agent.js @@ -1,3 +1,5 @@ +import { createHomeNavigationClient } from "/apps/home/home-navigation-client.js"; +import { onHomeTokenChanged, setHomeGuiLaunchToken } from "./harness-host.js"; import { selectLiveOffer } from "./agent-live.js"; import { selectSession, renderSessions } from "./agent-sessions.js"; import { validModelCid } from "./model-selection.js"; @@ -201,12 +203,17 @@ document.addEventListener( true, ); -const homeClipboard = createHomeClipboardClient({ +const clipboardOptions = () => ({ targetId: "assistant", homeOrigin: homeOrigin(), homeToken: getHomeGuiLaunchToken(), }); +const homeClipboard = createHomeClipboardClient(clipboardOptions()); homeClipboard.start(); +onHomeTokenChanged(token => homeClipboard.setHomeToken(token)); +createHomeNavigationClient({ homeToken: getHomeGuiLaunchToken(), homeOrigin: homeOrigin(), + target: "assistant", onHomeToken: setHomeGuiLaunchToken }); + /* A copy Home would refuse for its size is refused here, by name, before Home is asked to confirm it. */ diff --git a/capsules/browser/browser/browser.js b/capsules/browser/browser/browser.js index 5a91c9781..08dffdbd1 100644 --- a/capsules/browser/browser/browser.js +++ b/capsules/browser/browser/browser.js @@ -1912,6 +1912,13 @@ function homeBrowserNavigateUrl(event) { } window.addEventListener("message", (event) => { + if (event.source === window.top && event.origin === homeParentOrigin && + event.data?.type === "elastos.home.authority.request/v1" && event.data.homeToken === launchToken && + Object.keys(event.data).sort().join(",") === "homeToken,type") { + requestHomeRelaunch("Renewing Browser session"); + return; + } + if (isHomeBrowserWindowCloseRequest(event)) { void handleHomeBrowserWindowCloseRequest(event); return; diff --git a/capsules/chat-room-ui/.chat_room_ui_source.sha256 b/capsules/chat-room-ui/.chat_room_ui_source.sha256 index 302ac4a61..7f2c1fc19 100644 --- a/capsules/chat-room-ui/.chat_room_ui_source.sha256 +++ b/capsules/chat-room-ui/.chat_room_ui_source.sha256 @@ -1,7 +1,7 @@ { "schema": "elastos.chat-room-ui-artifacts/v1", - "source_fingerprint_sha256": "53057710506e72e0eb0e28ca4004cc27ad3f8371ce767bfcbfb877e45bd7a53e", - "compiler_wasm_sha256": "80cbff18f83cc8b353ee7a1411d8638f18d2064077318ba8311c54784db40d57", - "browser_wasm_sha256": "bd994d2ad1b2062a8e8e96ba9cb52ac38d3b0cee0f269fe1c7f74bb8a1652c14", - "bindings_sha256": "8ff3aa18be1b7bfa1d0e6fafcc2c15e9d378d636b0c820680e4a3657c412c2fe" + "source_fingerprint_sha256": "986f8b68e2b5e5db7d59990324ee7895d35964c0a441e5a3d1e34e3a5ce71444", + "compiler_wasm_sha256": "52de6e8189d9cfc35ed0f1de1c8678746faeb4d87585aa540fc148d969468092", + "browser_wasm_sha256": "722865c7559fb2b7561a484f55814fd23add45a747298d1ec4efdfc48ba2954c", + "bindings_sha256": "17b375b8099472b15e7b745143ef333817697c769973bc21f581aa27d975eb30" } diff --git a/capsules/chat-room-ui/src/lib.rs b/capsules/chat-room-ui/src/lib.rs index 6beaab6ff..20525d1d4 100644 --- a/capsules/chat-room-ui/src/lib.rs +++ b/capsules/chat-room-ui/src/lib.rs @@ -155,6 +155,10 @@ struct AppState { /// offered whatever other message is showing. reconnect_needed: bool, reconnecting: bool, + room_expires_at: u64, + recovery_attempts: u32, + recovery_after_ms: f64, + recovery_terminal: bool, pending_direct_launch: Option, /// Unsent text of the conversations the composer does not show, with the /// revision it had when it left the composer. @@ -319,6 +323,8 @@ struct BrowserSessionStatusOutput { #[derive(Debug, Clone, Deserialize)] struct ShellSessionStartOutput { + #[serde(default)] + expires_at: u64, poll: RoomPollView, } @@ -1208,10 +1214,66 @@ impl App { .await; } - async fn poll_and_render_once(&self) { - if self.state.borrow().reconnect_needed { + fn recovery_failed(&self) { + if !self.is_shell_mode() { return; } + let mut state = self.state.borrow_mut(); + state.recovery_attempts = state.recovery_attempts.saturating_add(1); + state.recovery_after_ms = js_sys::Date::now() + + recovery_delay_ms(state.recovery_attempts, js_sys::Math::random()) as f64; + state.status_badge = "Reconnecting".into(); + } + + fn recovery_succeeded(&self) { + let mut state = self.state.borrow_mut(); + state.recovery_attempts = 0; + state.recovery_after_ms = 0.0; + if state.status_badge == "Reconnecting" { + state.status_badge = state.community_state.label().to_string(); + } + } + + async fn poll_and_render_once(&self) { + if self.is_shell_mode() { + { + let state = self.state.borrow(); + if state.recovery_terminal + || state.close_leave_sent + || state.reconnecting + || js_sys::Date::now() < state.recovery_after_ms + { + return; + } + } + if self.state.borrow().reconnect_needed { + if let Err(error) = self.reconnect_from_home().await { + self.state.borrow_mut().recovery_terminal = error.contains("Sign in to Home"); + apply_reconnect_failure(&mut self.state.borrow_mut(), error); + self.recovery_failed(); + } + let _ = self.render(); + return; + } + let renew_room = { + let state = self.state.borrow(); + state.session_active + && state.room_expires_at > 0 + && state.room_expires_at <= (js_sys::Date::now() / 1000.0) as u64 + 30 + }; + if renew_room { + let guard = current_selection_guard(&self.state.borrow()); + if let Err(error) = self.ensure_shell_session_for_guard(&guard).await { + if error == ShellSessionBootstrapFailure::Unauthorized { + self.handle_session_loss(self.session_loss_detail()); + } + self.set_transient_error(Some(error.detail().to_string())); + self.recovery_failed(); + let _ = self.render(); + return; + } + } + } if self.is_direct_mode() { let (selection_guard, polled_transient_error) = { let state = self.state.borrow(); @@ -1231,6 +1293,7 @@ impl App { } match result { Ok(changed) => { + self.recovery_succeeded(); let cleared_transient_error = { let mut state = self.state.borrow_mut(); if should_clear_polled_transient_error( @@ -1255,6 +1318,7 @@ impl App { let _ = self.render(); } Err(_) => { + self.recovery_failed(); self.set_transient_error(Some( "Direct messages are temporarily unavailable.".to_string(), )); @@ -1285,6 +1349,7 @@ impl App { { return; } + self.recovery_succeeded(); // Show current Shared messages before waiting for auxiliary metadata. let poll_rendered = changed && self.render().is_ok(); let mut shell_summary_changed = false; @@ -1354,6 +1419,7 @@ impl App { } } Err(err) => { + self.recovery_failed(); self.set_transient_error(Some(err)); let _ = self.render(); } @@ -1692,8 +1758,34 @@ impl App { reset_click.forget(); } + for event_name in ["online", "pageshow", "elastos-chat-authority-renewed"] { + let app = Rc::clone(self); + let wake = Closure::::wrap(Box::new(move |_event: Event| { + app.state.borrow_mut().recovery_after_ms = 0.0; + if let Some(window) = window() { + if let Ok(getter) = + Reflect::get(window.as_ref(), &JsValue::from_str("elastosChatHomeToken")) + .and_then(|value| value.dyn_into::()) + { + if let Ok(value) = getter.call0(&JsValue::NULL) { + if let Some(token) = value.as_string() { + *app.current_home_token.borrow_mut() = Some(token); + } + } + } + } + })); + if let Some(window) = window() { + window + .add_event_listener_with_callback(event_name, wake.as_ref().unchecked_ref())?; + } + wake.forget(); + } + let reconnect_app = Rc::clone(self); let reconnect_click = Closure::::wrap(Box::new(move |_event: Event| { + reconnect_app.state.borrow_mut().recovery_terminal = false; + reconnect_app.state.borrow_mut().recovery_after_ms = 0.0; reconnect_app.reconnect_shell_session(); })); self.reconnect_button @@ -2641,7 +2733,12 @@ impl App { reconnect.call0(&JsValue::NULL).map_err(js_error)?, )) .await - .map_err(js_error)? + .map_err(|error| { + Reflect::get(&error, &JsValue::from_str("message")) + .ok() + .and_then(|value| value.as_string()) + .unwrap_or_else(|| js_error(error)) + })? .as_string() .filter(|token| !token.is_empty()) .ok_or_else(|| "Home could not reopen Chat. Try again.".to_string())?; @@ -2671,7 +2768,9 @@ impl App { } } let guard = current_selection_guard(&self.state.borrow()); - self.ensure_shell_session_for_guard(&guard).await?; + self.ensure_shell_session_for_guard(&guard) + .await + .map_err(|error| error.detail().to_string())?; if self.selection_guard_is_current(&guard) && self.state.borrow().session_active && guard.selected_conversation_id.is_some() @@ -2699,6 +2798,7 @@ impl App { fn handle_session_loss(&self, detail: &str) { self.clear_browser_session_request_storage(); apply_session_loss(&mut self.state.borrow_mut(), self.is_shell_mode(), detail); + self.recovery_failed(); // Loss invalidates the request's selection guard. Render it here, // before that stale caller returns without updating the screen. let _ = self.render(); @@ -2829,7 +2929,7 @@ impl App { .map(|_| ()); if let Err(err) = bootstrap { if app.selection_guard_is_current(&shared_guard) { - app.set_error(Some(err)); + app.set_error(Some(err.detail().to_string())); } } else if app.selection_guard_is_current(&shared_guard) && app.state.borrow().session_active @@ -2924,8 +3024,17 @@ impl App { Ok(()) } - async fn ensure_shell_session_for_guard(&self, guard: &SelectionGuard) -> Result { - if !self.is_shell_mode() || self.state.borrow().session_active { + async fn ensure_shell_session_for_guard( + &self, + guard: &SelectionGuard, + ) -> Result { + let room_current = { + let state = self.state.borrow(); + state.session_active + && (state.room_expires_at == 0 + || state.room_expires_at > (js_sys::Date::now() / 1000.0) as u64 + 30) + }; + if !self.is_shell_mode() || room_current { return Ok(false); } if self.state.borrow().reconnect_needed && !self.state.borrow().reconnecting { @@ -2936,7 +3045,8 @@ impl App { &self.room_api_url("/summary"), &self.home_token_headers(), ) - .await?; + .await + .map_err(|error| ShellSessionBootstrapFailure::from_request_error(&error))?; if !self.selection_guard_is_current(guard) { return Ok(false); } @@ -2965,16 +3075,14 @@ impl App { } let poll_guard = begin_poll_request(&mut self.state.borrow_mut()); - let start: ShellSessionStartOutput = api_post_empty_json_with_headers( + let start: ShellSessionStartOutput = api_post_json_with_headers( &self.room_api_url("/session/start"), + &serde_json::json!({}), &self.home_token_headers(), + Some(REQUEST_DEADLINE_MS), ) .await - .map_err(|error| { - ShellSessionBootstrapFailure::from_request_error(&error) - .detail() - .to_string() - })?; + .map_err(|error| ShellSessionBootstrapFailure::from_request_error(&error))?; if !self.selection_guard_is_current(guard) { return Ok(false); } @@ -2983,6 +3091,7 @@ impl App { // the poll loop from starting. let changed = { let mut state = self.state.borrow_mut(); + state.room_expires_at = start.expires_at; let Some(changed) = apply_active_poll_if_current(&mut state, &poll_guard, start.poll) else { return Ok(false); @@ -3856,7 +3965,7 @@ impl App { if choice == "shared" { if let Err(error) = app.ensure_shell_session_for_guard(&selection_guard).await { if app.selection_guard_is_current(&selection_guard) { - app.set_error(Some(error)); + app.set_error(Some(error.detail().to_string())); } } } else if let Err(status) = app @@ -6304,6 +6413,13 @@ fn element_with_attribute(root: &Element, attribute: &str, value: &str) -> Optio /// The Reconnect action shows only inside Home, while a lost session has not /// come back. It does not depend on which message is showing. +fn recovery_delay_ms(attempt: u32, jitter: f64) -> u32 { + let ceiling = 1000u32 + .saturating_mul(1u32 << attempt.saturating_sub(1).min(5)) + .min(30_000); + (ceiling as f64 * (0.5 + 0.5 * jitter.clamp(0.0, 1.0))) as u32 +} + fn shows_reconnect(shell_mode: bool, session_active: bool, reconnect_needed: bool) -> bool { shell_mode && !session_active && reconnect_needed } @@ -6338,14 +6454,16 @@ fn apply_session_loss(state: &mut AppState, shell_mode: bool, detail: &str) { state.show_participants = false; state.show_access_controls = false; state.force_message_follow = true; - state.latest_seq = 0; - state.history = None; - state.objects.clear(); - state.participants.clear(); - state.active_sessions.clear(); - state.attachment_urls.clear(); - state.attachment_retry.clear(); - state.status_badge = if shell_mode { "Reconnect" } else { "Join" }.to_string(); + if !shell_mode { + state.latest_seq = 0; + state.history = None; + state.objects.clear(); + state.participants.clear(); + state.active_sessions.clear(); + state.attachment_urls.clear(); + state.attachment_retry.clear(); + } + state.status_badge = if shell_mode { "Reconnecting" } else { "Join" }.to_string(); state.status_detail = detail.to_string(); state.error_text = shell_mode.then(|| detail.to_string()); state.error_transient = false; @@ -6774,6 +6892,10 @@ fn load_state(session_storage: Option<&Storage>, config: &AppConfig) -> AppState composer_conversation: None, reconnect_needed: false, reconnecting: false, + room_expires_at: 0, + recovery_attempts: 0, + recovery_after_ms: 0.0, + recovery_terminal: false, pending_direct_launch: None, drafts: BTreeMap::new(), composer_revision: 0, @@ -6955,6 +7077,43 @@ mod tests { assert!(state.direct.selected_conversation_id.is_none()); } + #[test] + fn recovery_delay_has_jitter_and_never_exceeds_thirty_seconds() { + for attempt in 1..100 { + let low = super::recovery_delay_ms(attempt, 0.0); + let high = super::recovery_delay_ms(attempt, 1.0); + assert!(low > 0 && low < high); + assert!(high <= 30_000); + } + assert_eq!(super::recovery_delay_ms(1, 1.0), 1000); + assert_eq!(super::recovery_delay_ms(20, 1.0), 30_000); + } + + #[test] + fn automatic_session_recovery_keeps_cursor_and_saved_drafts() { + let mut state = AppState { + latest_seq: 41, + session_active: true, + ..AppState::default() + }; + state.drafts.insert(None, ("Keep this draft".into(), 7)); + apply_session_loss(&mut state, true, super::SHELL_SESSION_LOST_DETAIL); + assert_eq!(state.latest_seq, 41); + assert_eq!( + state.drafts.get(&None), + Some(&("Keep this draft".into(), 7)) + ); + assert_eq!(state.status_badge, "Reconnecting"); + assert!(state.reconnect_needed); + assert!(!state.session_active); + assert!(!super::is_session_error( + "request failed: 403 conversation access denied" + )); + assert!(super::is_session_error( + "request failed: 403 Gateway request requires an admitted host and caller" + )); + } + #[test] fn a_lost_home_session_shows_how_to_reconnect_until_it_is_back() { let poll = || RoomPollView { @@ -9877,7 +10036,11 @@ fn room_send_error_text(err: String) -> String { } fn is_session_error(err: &str) -> bool { - err.contains("invalid or expired session") || err.contains("request failed: 401") + err.contains("invalid or expired session") + || err.contains("request failed: 401") + || (err.contains("request failed: 403") + && (err.contains("Gateway request requires an admitted host and caller") + || err.contains("home launch token expired"))) } fn shell_summary_allows_session(summary: &SummaryView) -> bool { @@ -10362,7 +10525,15 @@ async fn direct_get_json( } let response = request.send().await.map_err(|_| 0u16)?; if response.status() != 200 { - return Err(response.status()); + let status = response.status(); + let body = response.text().await.unwrap_or_default(); + return Err( + if is_session_error(&format!("request failed: {status} {body}")) { + 401 + } else { + status + }, + ); } response.json::().await.map_err(|_| 500) } diff --git a/capsules/chat-room/browser/chat-room.js b/capsules/chat-room/browser/chat-room.js index 2c3e4f875..2acc01085 100644 --- a/capsules/chat-room/browser/chat-room.js +++ b/capsules/chat-room/browser/chat-room.js @@ -8,11 +8,13 @@ let chatHomeToken = new URLSearchParams(window.location.hash.replace(/^#/, "")).get("home_token") || ""; if (chatHomeToken) { const homeNavigation = createHomeNavigationClient({ homeToken: chatHomeToken, - homeOrigin: chatLaunchParams.get("home_origin") || "" }); - let currentQuery = chatLaunchParams.has("conversation_id") - ? { conversation_id: chatLaunchParams.get("conversation_id") } : {}; + homeOrigin: chatLaunchParams.get("home_origin") || "", target: "chat-room", + onHomeToken(token) { + homeClipboard.setHomeToken(token); + chatHomeToken = token; + window.dispatchEvent(new Event("elastos-chat-authority-renewed")); + } }); globalThis.elastosChatNavigation = (query) => { - currentQuery = { ...query }; homeNavigation.setQuery(query); }; const clipboardOptions = () => ({ @@ -20,7 +22,7 @@ homeOrigin: chatLaunchParams.get("home_origin") || "", homeToken: chatHomeToken, }); - let homeClipboard = createHomeClipboardClient(clipboardOptions()); + const homeClipboard = createHomeClipboardClient(clipboardOptions()); homeClipboard.start(); globalThis.elastosChatCopyInvite = (text) => homeClipboard.writeText(text, { purpose: "conversation.invite", @@ -29,59 +31,7 @@ purpose: "profile.id", }); globalThis.elastosChatHomeToken = () => chatHomeToken; - let pendingReconnect = null; - globalThis.elastosChatReconnect = () => { - if (pendingReconnect) return pendingReconnect; - const homeOrigin = chatLaunchParams.get("home_origin") || ""; - if (!homeOrigin || homeOrigin === "null" || homeOrigin === "*" || window.top === window) { - return Promise.reject(new Error("Open Chat from Home to reconnect.")); - } - const requestId = window.crypto.randomUUID(); - pendingReconnect = new Promise((resolve, reject) => { - const finish = (error, token) => { - window.clearTimeout(timer); - window.removeEventListener("message", receive); - pendingReconnect = null; - if (error) reject(error); else resolve(token); - }; - const receive = (event) => { - const data = event.data; - if (event.source !== window.top || event.origin !== homeOrigin - || data?.type !== "home:shell-response" || data.requestId !== requestId) return; - if (data.error) { - finish(new Error(data.status === 401 || data.status === 403 - ? "Sign in to Home, then reconnect Chat. Your drafts are kept." - : "Home could not reopen Chat. Try again.")); - return; - } - const launched = data.result; - let route; - try { route = new URL(launched?.route, homeOrigin); } catch { finish(new Error("Home returned an invalid Chat launch.")); return; } - const token = new URLSearchParams(route.hash.replace(/^#/, "")).get("home_token") || ""; - if (launched?.target !== "chat-room" || launched.attach_kind !== "iframe" - || (launched.launch_status && launched.launch_status !== "launched") - || route.origin !== homeOrigin || route.pathname !== "/apps/chat-room/" - || route.username || route.password - || !token || token === chatHomeToken || token !== token.trim()) { - finish(new Error("Home returned an invalid Chat launch.")); return; - } - homeClipboard.teardown(); - chatHomeToken = token; - homeNavigation.setHomeToken(token); - homeClipboard = createHomeClipboardClient(clipboardOptions()); - homeClipboard.start(); - window.dispatchEvent(new Event("elastos-chat-authority-renewed")); - finish(null, token); - }; - const timer = window.setTimeout(() => finish(new Error("Home did not answer. Try reconnecting again.")), 30000); - window.addEventListener("message", receive); - try { - window.top.postMessage({ type: "home:launch-target", requestId, target: "chat-room", - query: currentQuery, homeToken: chatHomeToken }, homeOrigin); - } catch (error) { finish(error); } - }); - return pendingReconnect; - }; + globalThis.elastosChatReconnect = () => homeNavigation.renewAuthority(); init({ module_or_path: new URL("./chat_room_ui_bg.wasm?v=chat-room-ui-20261008a", import.meta.url), }); diff --git a/capsules/chat-room/browser/chat_room_ui.js b/capsules/chat-room/browser/chat_room_ui.js index 2e44ddb85..8b316585f 100644 --- a/capsules/chat-room/browser/chat_room_ui.js +++ b/capsules/chat-room/browser/chat_room_ui.js @@ -218,24 +218,24 @@ export function start() { wasm.start(); } -function wasm_bindgen__convert__closures_____invoke__h1995bcb883d331b6(arg0, arg1, arg2) { - wasm.wasm_bindgen__convert__closures_____invoke__h1995bcb883d331b6(arg0, arg1, arg2); +function wasm_bindgen__convert__closures_____invoke__h76bc78299e8b98a7(arg0, arg1) { + wasm.wasm_bindgen__convert__closures_____invoke__h76bc78299e8b98a7(arg0, arg1); } -function wasm_bindgen__convert__closures_____invoke__hc1fba69bcc2973ea(arg0, arg1, arg2) { - wasm.wasm_bindgen__convert__closures_____invoke__hc1fba69bcc2973ea(arg0, arg1, arg2); +function wasm_bindgen__convert__closures_____invoke__ha7c4f365d4a8f965(arg0, arg1) { + wasm.wasm_bindgen__convert__closures_____invoke__ha7c4f365d4a8f965(arg0, arg1); } -function wasm_bindgen__convert__closures_____invoke__h76bc78299e8b98a7(arg0, arg1) { - wasm.wasm_bindgen__convert__closures_____invoke__h76bc78299e8b98a7(arg0, arg1); +function wasm_bindgen__convert__closures_____invoke__h1995bcb883d331b6(arg0, arg1, arg2) { + wasm.wasm_bindgen__convert__closures_____invoke__h1995bcb883d331b6(arg0, arg1, arg2); } function wasm_bindgen__convert__closures_____invoke__he5a716c89cafc3f6(arg0, arg1, arg2) { wasm.wasm_bindgen__convert__closures_____invoke__he5a716c89cafc3f6(arg0, arg1, arg2); } -function wasm_bindgen__convert__closures_____invoke__ha7c4f365d4a8f965(arg0, arg1) { - wasm.wasm_bindgen__convert__closures_____invoke__ha7c4f365d4a8f965(arg0, arg1); +function wasm_bindgen__convert__closures_____invoke__hc1fba69bcc2973ea(arg0, arg1, arg2) { + wasm.wasm_bindgen__convert__closures_____invoke__hc1fba69bcc2973ea(arg0, arg1, arg2); } const __wbindgen_enum_RequestCredentials = ["omit", "same-origin", "include"]; @@ -776,6 +776,10 @@ function __wbg_get_imports() { imports.wbg.__wbg_queueMicrotask_9d76cacb20c84d58 = function(arg0) { queueMicrotask(arg0); }; + imports.wbg.__wbg_random_babe96ffc73e60a2 = function() { + const ret = Math.random(); + return ret; + }; imports.wbg.__wbg_removeAttribute_993c4bef8df6e74d = function() { return handleError(function (arg0, arg1, arg2) { arg0.removeAttribute(getStringFromWasm0(arg1, arg2)); }, arguments) }; @@ -990,9 +994,9 @@ function __wbg_get_imports() { getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true); getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true); }; - imports.wbg.__wbindgen_cast_04778e6e8e472b4d = function(arg0, arg1) { - // Cast intrinsic for `Closure(Closure { dtor_idx: 254, function: Function { arguments: [Externref], shim_idx: 255, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`. - const ret = makeMutClosure(arg0, arg1, wasm.wasm_bindgen__closure__destroy__h7e0dbe805cce3b26, wasm_bindgen__convert__closures_____invoke__he5a716c89cafc3f6); + imports.wbg.__wbindgen_cast_200dd67c26f16f4e = function(arg0, arg1) { + // Cast intrinsic for `Closure(Closure { dtor_idx: 239, function: Function { arguments: [NamedExternref("MessageEvent")], shim_idx: 240, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`. + const ret = makeMutClosure(arg0, arg1, wasm.wasm_bindgen__closure__destroy__h121ee1b0b543bc1f, wasm_bindgen__convert__closures_____invoke__h1995bcb883d331b6); return ret; }; imports.wbg.__wbindgen_cast_2241b6af4c4b2941 = function(arg0, arg1) { @@ -1000,19 +1004,24 @@ function __wbg_get_imports() { const ret = getStringFromWasm0(arg0, arg1); return ret; }; - imports.wbg.__wbindgen_cast_77ff60530369ff12 = function(arg0, arg1) { - // Cast intrinsic for `Closure(Closure { dtor_idx: 237, function: Function { arguments: [NamedExternref("MessageEvent")], shim_idx: 238, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`. - const ret = makeMutClosure(arg0, arg1, wasm.wasm_bindgen__closure__destroy__h121ee1b0b543bc1f, wasm_bindgen__convert__closures_____invoke__h1995bcb883d331b6); + imports.wbg.__wbindgen_cast_363ab6ba52868a22 = function(arg0, arg1) { + // Cast intrinsic for `Closure(Closure { dtor_idx: 256, function: Function { arguments: [Externref], shim_idx: 257, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`. + const ret = makeMutClosure(arg0, arg1, wasm.wasm_bindgen__closure__destroy__h7e0dbe805cce3b26, wasm_bindgen__convert__closures_____invoke__he5a716c89cafc3f6); return ret; }; - imports.wbg.__wbindgen_cast_93404b3c70bb83e8 = function(arg0, arg1) { - // Cast intrinsic for `Closure(Closure { dtor_idx: 237, function: Function { arguments: [NamedExternref("Event")], shim_idx: 238, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`. + imports.wbg.__wbindgen_cast_45e5431b0628a8a0 = function(arg0, arg1) { + // Cast intrinsic for `Closure(Closure { dtor_idx: 239, function: Function { arguments: [NamedExternref("Event")], shim_idx: 240, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`. const ret = makeMutClosure(arg0, arg1, wasm.wasm_bindgen__closure__destroy__h121ee1b0b543bc1f, wasm_bindgen__convert__closures_____invoke__h1995bcb883d331b6); return ret; }; - imports.wbg.__wbindgen_cast_acceeae879873989 = function(arg0, arg1) { - // Cast intrinsic for `Closure(Closure { dtor_idx: 228, function: Function { arguments: [], shim_idx: 229, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`. - const ret = makeMutClosure(arg0, arg1, wasm.wasm_bindgen__closure__destroy__h421d3dbd1097f54c, wasm_bindgen__convert__closures_____invoke__h76bc78299e8b98a7); + imports.wbg.__wbindgen_cast_8134a3593b66533b = function(arg0, arg1) { + // Cast intrinsic for `Closure(Closure { dtor_idx: 207, function: Function { arguments: [NamedExternref("KeyboardEvent")], shim_idx: 208, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`. + const ret = makeMutClosure(arg0, arg1, wasm.wasm_bindgen__closure__destroy__h7021158ffcd55e43, wasm_bindgen__convert__closures_____invoke__hc1fba69bcc2973ea); + return ret; + }; + imports.wbg.__wbindgen_cast_a5fc102e1fcaf0ec = function(arg0, arg1) { + // Cast intrinsic for `Closure(Closure { dtor_idx: 239, function: Function { arguments: [], shim_idx: 242, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`. + const ret = makeMutClosure(arg0, arg1, wasm.wasm_bindgen__closure__destroy__h121ee1b0b543bc1f, wasm_bindgen__convert__closures_____invoke__ha7c4f365d4a8f965); return ret; }; imports.wbg.__wbindgen_cast_d6cd19b81560fd6e = function(arg0) { @@ -1020,14 +1029,9 @@ function __wbg_get_imports() { const ret = arg0; return ret; }; - imports.wbg.__wbindgen_cast_d81498041e0543d0 = function(arg0, arg1) { - // Cast intrinsic for `Closure(Closure { dtor_idx: 205, function: Function { arguments: [NamedExternref("KeyboardEvent")], shim_idx: 206, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`. - const ret = makeMutClosure(arg0, arg1, wasm.wasm_bindgen__closure__destroy__h7021158ffcd55e43, wasm_bindgen__convert__closures_____invoke__hc1fba69bcc2973ea); - return ret; - }; - imports.wbg.__wbindgen_cast_f1cca25156db87a1 = function(arg0, arg1) { - // Cast intrinsic for `Closure(Closure { dtor_idx: 237, function: Function { arguments: [], shim_idx: 240, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`. - const ret = makeMutClosure(arg0, arg1, wasm.wasm_bindgen__closure__destroy__h121ee1b0b543bc1f, wasm_bindgen__convert__closures_____invoke__ha7c4f365d4a8f965); + imports.wbg.__wbindgen_cast_fa406ee060147f26 = function(arg0, arg1) { + // Cast intrinsic for `Closure(Closure { dtor_idx: 230, function: Function { arguments: [], shim_idx: 231, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`. + const ret = makeMutClosure(arg0, arg1, wasm.wasm_bindgen__closure__destroy__h421d3dbd1097f54c, wasm_bindgen__convert__closures_____invoke__h76bc78299e8b98a7); return ret; }; imports.wbg.__wbindgen_init_externref_table = function() { diff --git a/capsules/chat-room/browser/chat_room_ui_bg.wasm b/capsules/chat-room/browser/chat_room_ui_bg.wasm index 190dfd861..0e570d868 100644 Binary files a/capsules/chat-room/browser/chat_room_ui_bg.wasm and b/capsules/chat-room/browser/chat_room_ui_bg.wasm differ diff --git a/capsules/documents/browser/documents.js b/capsules/documents/browser/documents.js index 97ba32179..4bff70c3f 100644 --- a/capsules/documents/browser/documents.js +++ b/capsules/documents/browser/documents.js @@ -30,7 +30,9 @@ const state = { // address. Decided once here; the current address may change later. const DOCUMENTS_INSIDE_HOME = window.top !== window && !!state.homeToken; const homeOrigin = new URLSearchParams(window.location.search).get("home_origin") || ""; -const homeNavigation = createHomeNavigationClient({ homeToken: state.homeToken, homeOrigin }); +const homeNavigation = createHomeNavigationClient({ homeToken: state.homeToken, homeOrigin, target: "documents", + onHomeToken(token) { state.homeToken = token; }, +}); const DOCUMENTS_WINDOW_CLOSE_REQUEST_TYPE = "elastos.documents.window-close.request/v1"; const DOCUMENTS_WINDOW_CLOSE_RESULT_TYPE = diff --git a/capsules/home-gui/browser/home-gui-shell.js b/capsules/home-gui/browser/home-gui-shell.js index 5cead4926..1354a7106 100644 --- a/capsules/home-gui/browser/home-gui-shell.js +++ b/capsules/home-gui/browser/home-gui-shell.js @@ -5,7 +5,7 @@ import { openHomeGuiTarget, relaunchHomeGuiWindowForToken, renewHomeGuiBrowserWindowAuthority, - renewHomeGuiChatWindowAuthority, + renewHomeGuiFrameAuthority, restoreHomeGuiSession, setHomeGuiMenuManifest, handleHomeGuiHomeNavigation, @@ -194,20 +194,20 @@ function handleGuiCommand(message) { if (command === "renew-browser-authority") { return handleBrowserAuthorityRenewalCommand(message); } - if (command === "renew-chat-authority") { + if (command === "renew-frame-authority") { if (!hasExactKeys(message, ["type", "command", "requestId", "homeToken", "launched", "expiresAt", "phase"]) || !/^[A-Za-z0-9-]{1,64}$/.test(message.requestId) || !Number.isSafeInteger(message.expiresAt) || !["prepare", "commit"].includes(message.phase)) return false; const freshHomeToken = new URLSearchParams(new URL(message.launched?.route, homeOrigin).hash.slice(1)).get("home_token") || ""; if (message.phase === "commit") { - const ok = renewHomeGuiChatWindowAuthority(message.homeToken, message.launched, homeOrigin); - postToHome({ type: "home:chat-authority-committed", requestId: message.requestId, + const ok = renewHomeGuiFrameAuthority(message.homeToken, message.launched, homeOrigin); + postToHome({ type: "home:frame-authority-committed", requestId: message.requestId, oldHomeToken: message.homeToken, freshHomeToken, ok }); return ok; } const ok = message.expiresAt > Date.now() - && renewHomeGuiChatWindowAuthority(message.homeToken, message.launched, homeOrigin, false); - postToHome({ type: "home:chat-authority-renewed", requestId: message.requestId, + && renewHomeGuiFrameAuthority(message.homeToken, message.launched, homeOrigin, false); + postToHome({ type: "home:frame-authority-renewed", requestId: message.requestId, oldHomeToken: message.homeToken, freshHomeToken, ok }); return ok; } diff --git a/capsules/home-gui/browser/home-gui.js b/capsules/home-gui/browser/home-gui.js index d42ee18f7..15a3ec62e 100644 --- a/capsules/home-gui/browser/home-gui.js +++ b/capsules/home-gui/browser/home-gui.js @@ -663,16 +663,16 @@ export function relaunchHomeGuiWindowForToken(homeToken) { return true; } -export function renewHomeGuiChatWindowAuthority(homeToken, launched, homeOrigin, apply = true) { +export function renewHomeGuiFrameAuthority(homeToken, launched, homeOrigin, apply = true) { const entry = homeGuiWindowEntryForToken(homeToken); const frame = entry?.node?.querySelector(".window-frame"); const freshToken = homeLaunchTokenFromRoute(launched?.route || ""); let route; try { route = new URL(launched?.route, homeOrigin); } catch { return false; } - if (!entry || entry.targetId !== "chat-room" || !frame?.contentWindow - || launched?.target !== "chat-room" || launched.attach_kind !== "iframe" + if (!entry || entry.targetId !== launched?.target || !frame?.contentWindow + || !["chat-room", "people", "documents", "assistant", "library"].includes(launched?.target) || launched.attach_kind !== "iframe" || (launched.launch_status && launched.launch_status !== "launched") - || route.origin !== homeOrigin || route.pathname !== "/apps/chat-room/" + || route.origin !== homeOrigin || route.pathname !== `/apps/${entry.targetId}/` || route.username || route.password || !freshToken || freshToken === homeToken) return false; if (!apply) return true; diff --git a/capsules/home/browser/home-clipboard-client.js b/capsules/home/browser/home-clipboard-client.js index 0ce445142..33468a672 100644 --- a/capsules/home/browser/home-clipboard-client.js +++ b/capsules/home/browser/home-clipboard-client.js @@ -461,6 +461,7 @@ export function createHomeClipboardClient({ } return { + setHomeToken(value) { homeToken = value; }, canRequest: available, cancel, handleMessage, diff --git a/capsules/home/browser/home-external-link.js b/capsules/home/browser/home-external-link.js index a4d822cf8..4a3740be2 100644 --- a/capsules/home/browser/home-external-link.js +++ b/capsules/home/browser/home-external-link.js @@ -127,9 +127,9 @@ export function requestHomeSharedContent({ context, data, prompt, fetchJson }) { || typeof source !== "object" || Array.isArray(source) || !hasExactKeys(source, ["conversation_id", "message_id"]) || ![source.conversation_id, source.message_id].every(value => typeof value === "string" && value.length > 0)))) return false; - const check = signal => fetchJson("/api/apps/home/shared-content/check", { + const check = (signal, homeToken = context.homeToken) => fetchJson("/api/apps/home/shared-content/check", { method: "POST", signal, - body: JSON.stringify({ schema: "elastos.home.shared-content.check/v1", app_token: context.homeToken, uri: data.uri, + body: JSON.stringify({ schema: "elastos.home.shared-content.check/v1", app_token: homeToken, uri: data.uri, ...(source === undefined ? {} : { source }) }), }); const get = (check_id, signal) => fetchJson("/api/apps/home/shared-content/get", { @@ -301,7 +301,7 @@ export function createHomeExternalLinkPrompt({ return; } } else { - const result = validatedSharedResult(await request.check(request.controller.signal), request.uri); + const result = validatedSharedResult(await request.check(request.controller.signal, request.homeToken), request.uri); if (!current()) return; if (!result) throw new Error("Invalid file check"); request.result = result; @@ -505,7 +505,10 @@ export function createHomeExternalLinkPrompt({ close(); } }, - // The sender's launch ended (closed, reloaded, reconnected): its request + transfer(oldToken, freshToken) { + if (active?.homeToken === oldToken) active.homeToken = freshToken; + }, + // The sender's document ended (closed or reloaded): its request // closes without opening anything. retire(homeToken) { if (active?.homeToken === homeToken) { diff --git a/capsules/home/browser/home-external-link.test.mjs b/capsules/home/browser/home-external-link.test.mjs index 122234413..53c3270a5 100644 --- a/capsules/home/browser/home-external-link.test.mjs +++ b/capsules/home/browser/home-external-link.test.mjs @@ -382,3 +382,29 @@ test('Home passes the cleaned name to Documents and Library and never lets it pi assert.equal(sharedFileName(' .\u001b.hidden '), 'hidden'); assert.equal(sharedFileName(undefined), ''); }); + + +test('frame renewal keeps a shown web link and its original click guard', () => { + const h = harness(); + const id = h.prompt.begin({ homeToken: 'launch', appId: 'chat-room' }); + h.prompt.show(id, { schema: 'elastos.home.external-link.result/v1', app_id: 'chat-room', + app_title: 'Chat', url: 'https://example.org/' }); + h.prompt.transfer('launch', 'fresh'); + h.prompt.retire('launch'); + assert.equal(h.root.hidden, false); + h.click(); assert.equal(h.opened.length, 0); + h.tick(); h.click(); assert.equal(h.opened.length, 1); +}); + +test('frame renewal keeps an in-flight shared file and uses fresh authority for retry', async () => { + const h = harness(); let finish, signal, checkToken; + const id = h.begin({ get: (_id, s) => { signal = s; return new Promise(resolve => { finish = resolve; }); }, + check: async (_signal, token) => { checkToken = token; return result(); } }); + h.prompt.show(id, result()); h.tick(); h.click(); + h.prompt.transfer('launch', 'fresh'); h.prompt.retire('launch'); + assert.equal(signal.aborted, false); + finish({ state: 'sender_offline' }); await settle(); + h.tick(); h.click(); await settle(); + assert.equal(checkToken, 'fresh'); + h.prompt.retire('fresh'); assert.equal(h.root.hidden, true); +}); diff --git a/capsules/home/browser/home-navigation-client.js b/capsules/home/browser/home-navigation-client.js index 0ca12c127..8a01ce9c4 100644 --- a/capsules/home/browser/home-navigation-client.js +++ b/capsules/home/browser/home-navigation-client.js @@ -1,38 +1,100 @@ -// Bounded presentation hints only. Runtime authorizes each restored launch. -export function createHomeNavigationClient({ homeToken, homeOrigin, enabled = true, windowRef = window }) { +// Home renews registered frame authority; Runtime authorizes each launch. +// Navigation hints carry bounded presentation state. +export function createHomeNavigationClient({ homeToken, homeOrigin, enabled = true, target = "", onHomeToken = null, windowRef = window }) { const documentNonce = windowRef.crypto.randomUUID(); let requestId = ""; let sequence = 0; let query = null; let unloading = false; - const attached = () => enabled && homeToken && homeOrigin && windowRef.top !== windowRef; + let pendingRenewal = null; + function renewAuthority() { + if (pendingRenewal) return pendingRenewal.promise; + if (!attached() || !target || unloading) return Promise.reject(new Error("Open this app from Home to reconnect.")); + const id = windowRef.crypto.randomUUID(); + let resolve, reject; + const promise = new Promise((yes, no) => { resolve = yes; reject = no; }); + const record = { id, promise, reject, timer: 0 }; + const finish = (error, token) => { + windowRef.clearTimeout(record.timer); + windowRef.removeEventListener("message", receive); + if (pendingRenewal === record) pendingRenewal = null; + if (error) reject(error); else resolve(token); + }; + const receive = event => { + const data = event.data; + if (event.source !== windowRef.top || event.origin !== homeOrigin || + data?.type !== "home:shell-response" || data.requestId !== id) return; + if (data.error) { + const error = new Error(data.status === 401 || data.status === 403 + ? "Sign in to Home. Your drafts are kept." : "Home could not reconnect this app. Try again."); + error.status = data.status; + finish(error); + return; + } + const launched = data.result; + let route; + try { route = new URL(launched?.route, homeOrigin); } catch { finish(new Error("Home returned an invalid app launch.")); return; } + const token = new URLSearchParams(route.hash.slice(1)).get("home_token") || ""; + if (launched?.target !== target || launched.attach_kind !== "iframe" || + (launched.launch_status && launched.launch_status !== "launched") || + route.origin !== homeOrigin || route.pathname !== `/apps/${target}/` || + route.username || route.password || !token || token === homeToken || token !== token.trim()) { + finish(new Error("Home returned an invalid app launch.")); return; + } + try { + onHomeToken?.(token); + setHomeToken(token); + finish(null, token); + } catch (error) { finish(error); } + }; + record.cancel = () => finish(new Error("App closed.")); + record.timer = windowRef.setTimeout(() => finish(new Error("Home did not answer. Try reconnecting again.")), 30000); + pendingRenewal = record; + windowRef.addEventListener("message", receive); + try { + windowRef.top.postMessage({ type: "home:launch-target", requestId: id, + target, query: query || {}, homeToken }, homeOrigin); + } catch (error) { finish(error); } + return promise; + } + function setHomeToken(value) { + homeToken = value; + requestId = ""; + sequence = 0; + if (attached()) windowRef.top.postMessage({ type: "home:frame-authority-ready", homeToken }, homeOrigin); + } + windowRef.addEventListener("message", event => { + const data = event.data; + if (attached() && !unloading && event.source === windowRef.top && event.origin === homeOrigin && + data?.type === "elastos.home.authority.request/v1" && data.homeToken === homeToken && + Object.keys(data).sort().join(",") === "homeToken,type") { + renewAuthority().catch(() => {}); + } + }); + const attached = () => homeToken && homeOrigin && homeOrigin !== "null" && homeOrigin !== "*" && windowRef.top !== windowRef; function publish(phase = "state") { - if (!attached() || !requestId || (unloading && phase !== "unloading")) return; + if (!enabled || !attached() || !requestId || (unloading && phase !== "unloading")) return; windowRef.top.postMessage({ type: "home:navigation-hint", homeToken, requestId, documentNonce, sequence: ++sequence, phase, query: phase === "unloading" ? null : query }, homeOrigin); } windowRef.addEventListener("message", (event) => { const data = event.data; - if (!attached() || unloading || event.source !== windowRef.parent || event.origin !== "null" || + if (!enabled || !attached() || unloading || event.source !== windowRef.parent || event.origin !== "null" || !data || Object.keys(data).sort().join(",") !== "homeToken,requestId,type" || data.type !== "elastos.home.navigation.request/v1" || data.homeToken !== homeToken || typeof data.requestId !== "string" || !/^[A-Za-z0-9-]{1,64}$/.test(data.requestId)) return; requestId = data.requestId; publish(); }); - windowRef.addEventListener("pagehide", () => { publish("unloading"); unloading = true; }); + windowRef.addEventListener("pagehide", () => { publish("unloading"); unloading = true; pendingRenewal?.cancel(); }); windowRef.addEventListener("pageshow", () => { unloading = false; if (attached()) windowRef.top.postMessage({ type: "home:app-ready", homeToken }, homeOrigin); }); return { setQuery(value) { query = { ...value }; publish(); }, - setHomeToken(value) { - homeToken = value; - requestId = ""; - sequence = 0; - if (attached()) windowRef.top.postMessage({ type: "home:app-ready", homeToken }, homeOrigin); - }, + setHomeToken, + renewAuthority, }; } diff --git a/capsules/home/browser/home-shell-host.js b/capsules/home/browser/home-shell-host.js index ab8f8a07b..98b5c8c15 100644 --- a/capsules/home/browser/home-shell-host.js +++ b/capsules/home/browser/home-shell-host.js @@ -230,7 +230,7 @@ function retireLaunchedAppContext(homeToken) { return false; } cancelBrowserAuthorityRenewalsForToken(homeToken); - cancelChatReconnect(context); + cancelFrameRenewal(context); cancelLibraryPicker(context); homeClipboardHost.retireFrame(context.clipboardState); homeExternalLinkPrompt.retire(homeToken); @@ -241,7 +241,7 @@ function retireLaunchedAppContext(homeToken) { function clearLaunchedAppContexts() { clearPendingBrowserAuthorityRenewals(); for (const context of launchedAppContexts.values()) { - cancelChatReconnect(context); + cancelFrameRenewal(context); cancelLibraryPicker(context); homeClipboardHost.retireFrame(context.clipboardState); } @@ -249,36 +249,69 @@ function clearLaunchedAppContexts() { homeExternalLinkPrompt.clear(); } -function cancelChatReconnect(context) { - const record = context.chatReconnectPending; +function cancelFrameRenewal(context) { + const record = context.frameRenewalPending; if (!record) return; - context.chatReconnectPending = null; + context.frameRenewalPending = null; window.clearTimeout(record.timeout); if (record.freshToken) retireLaunchedAppContext(record.freshToken); } -function settleChatReconnect(old, record, error = null) { - if (old.chatReconnectPending !== record) return false; - old.chatReconnectPending = null; +function transferFrameAssociations(old, fresh, freshToken) { + const oldToken = [...launchedAppContexts].find(([, context]) => context === old)?.[0]; + if (old.pickerRequest) { + const record = old.pickerRequest; + record.opener = fresh; + record.openerToken = freshToken; + fresh.pickerRequest = record; + old.pickerRequest = null; + } + if (old.pickerOwner) { + fresh.pickerOwner = old.pickerOwner; + fresh.pickerOwner.pickerToken = freshToken; + old.pickerOwner = null; + } + if (old.clipboardState) { + fresh.clipboardState = old.clipboardState; + fresh.clipboardState.homeToken = freshToken; + if (fresh.clipboardState.inFlight) fresh.clipboardState.inFlight.homeToken = freshToken; + old.clipboardState = null; + } + for (const record of pendingBrowserAuthorityRenewals.values()) { + // Keep the original wire token to correlate the GUI's outstanding reply. + if (record.frameToken === oldToken) record.frameToken = freshToken; + } + homeExternalLinkPrompt.transfer(oldToken, freshToken); + fresh.walletEffectState = old.walletEffectState; + old.walletEffectState = null; +} + +function settleFrameRenewal(old, record, error = null) { + if (old.frameRenewalPending !== record) return false; + old.frameRenewalPending = null; window.clearTimeout(record.timeout); if (error) { if (record.freshToken) retireLaunchedAppContext(record.freshToken); } else { const fresh = launchedAppContexts.get(record.freshToken); - if (launchedAppContexts.get(record.oldToken) !== old || old.source !== record.event.source - || fresh?.targetId !== "chat-room" || fresh.source || record.expiresAt <= Date.now()) { + if (!homeSummarySignedIn(shellState.currentSummary) + || record.principal !== shellState.currentSummary?.authority?.principal_id + || record.proofBinding !== shellState.currentSummary?.authority?.proof_binding_id + || launchedAppContexts.get(record.oldToken) !== old || old.source !== record.event.source + || fresh?.targetId !== old.targetId || fresh.source || record.expiresAt <= Date.now()) { if (record.freshToken) retireLaunchedAppContext(record.freshToken); - error = new Error("Home could not reopen this Chat window"); + error = new Error("Home could not reopen this app window"); } else { try { - requireHomeGuiActive("reconnect Chat"); - fresh.chatReconnectCommit = { requestId: record.requestId, oldToken: record.oldToken }; - if (!postToActiveShell({ type: "home:gui-command", command: "renew-chat-authority", + requireHomeGuiActive("reconnect this app"); + fresh.frameRenewalCommit = { requestId: record.requestId, oldToken: record.oldToken }; + if (!postToActiveShell({ type: "home:gui-command", command: "renew-frame-authority", phase: "commit", requestId: record.requestId, homeToken: record.oldToken, launched: record.launched, expiresAt: record.expiresAt })) { - throw new Error("Home GUI could not reopen Chat"); + throw new Error("Home GUI could not reopen this app"); } fresh.source = record.event.source; + transferFrameAssociations(old, fresh, record.freshToken); retireLaunchedAppContext(record.oldToken); } catch (failure) { retireLaunchedAppContext(record.freshToken); @@ -609,7 +642,7 @@ function postBrowserAuthorityRenewalResult(record, result) { function cancelBrowserAuthorityRenewalsForToken(homeToken) { for (const [requestId, record] of pendingBrowserAuthorityRenewals) { - if (record.oldHomeToken !== homeToken) { + if (record.frameToken !== homeToken) { continue; } window.clearTimeout(record.timeout); @@ -631,7 +664,7 @@ function settleBrowserAuthorityRenewal(record, result) { window.clearTimeout(record.timeout); pendingBrowserAuthorityRenewals.delete(record.requestId); if (result.ok) { - retireLaunchedAppContext(record.oldHomeToken); + retireLaunchedAppContext(record.frameToken); } postBrowserAuthorityRenewalResult(record, result); return true; @@ -667,7 +700,7 @@ function startBrowserAuthorityRenewal(event, context, message) { } const pendingForFrame = [...pendingBrowserAuthorityRenewals.values()].find( (record) => - record.oldHomeToken === context.homeToken && + record.frameToken === context.homeToken && record.browserInstance === browserInstance && record.source === event.source, ); @@ -694,6 +727,7 @@ function startBrowserAuthorityRenewal(event, context, message) { } const record = { requestId, + frameToken: context.homeToken, oldHomeToken: context.homeToken, browserInstance, source: event.source, @@ -770,7 +804,7 @@ function handleBrowserAuthorityRenewalResult(context, message) { reason: message.reason, }); } - const oldContext = launchedAppContexts.get(record.oldHomeToken); + const oldContext = launchedAppContexts.get(record.frameToken); const freshContext = launchedAppContexts.get(message.freshHomeToken); if ( message.reason !== "" || @@ -946,6 +980,7 @@ function rememberLaunchedAppContext(launched, readBackgroundImage) { } launchedAppContexts.set(token, { targetId: launched.target, + expiresAt: Number(launched.expires_at) * 1000, readBackgroundImage, browserInstance: launched.target === "browser" @@ -1722,6 +1757,13 @@ window.addEventListener("message", (event) => { } return; } + if (data.type === "home:frame-authority-ready") { + if (context.kind === "app-frame" && context.clipboardState && + hasExactMessageKeys(data, ["type", "homeToken"])) { + homeClipboardHost.resetFrame(context.clipboardState, context); + } + return; + } if (data.type === "home:app-ready") { if (context.kind === "app-frame" && ["documents", "library", "archive-manager", "gba-emulator", "chat-room"].includes(context.targetId) && hasExactMessageKeys(data, ["type", "homeToken"])) { @@ -1768,78 +1810,93 @@ window.addEventListener("message", (event) => { } return; } - if (data.type === "home:chat-authority-renewed") { + if (data.type === "home:frame-authority-renewed") { if (context.kind !== "shell-frame" || context.targetId !== HOME_GUI_SHELL_ID || !hasExactMessageKeys(data, ["type", "requestId", "oldHomeToken", "freshHomeToken", "ok", "homeToken"])) return; const old = launchedAppContexts.get(data.oldHomeToken); - const record = old?.chatReconnectPending; + const record = old?.frameRenewalPending; if (!record || record.requestId !== data.requestId || record.freshToken !== data.freshHomeToken || !record.launched || typeof data.ok !== "boolean") return; - settleChatReconnect(old, record, data.ok ? null : new Error("Home could not reopen this Chat window")); + settleFrameRenewal(old, record, data.ok ? null : new Error("Home could not reopen this app window")); return; } - if (data.type === "home:chat-authority-committed") { + if (data.type === "home:frame-authority-committed") { if (context.kind !== "shell-frame" || context.targetId !== HOME_GUI_SHELL_ID || !hasExactMessageKeys(data, ["type", "requestId", "oldHomeToken", "freshHomeToken", "ok", "homeToken"])) return; const fresh = launchedAppContexts.get(data.freshHomeToken); - const commit = fresh?.chatReconnectCommit; - if (fresh?.targetId !== "chat-room" || !commit || commit.requestId !== data.requestId + const commit = fresh?.frameRenewalCommit; + if (!fresh || !commit || commit.requestId !== data.requestId || commit.oldToken !== data.oldHomeToken || typeof data.ok !== "boolean") return; - delete fresh.chatReconnectCommit; + delete fresh.frameRenewalCommit; if (!data.ok) retireLaunchedAppContext(data.freshHomeToken); return; } if (data.type === "home:launch-target") { const requestId = typeof data.requestId === "string" ? data.requestId.trim() : ""; const target = typeof data.target === "string" ? data.target.trim() : ""; - if (context.kind === "app-frame" && context.targetId === "chat-room") { + if (context.kind === "app-frame" && ["chat-room", "people", "documents", "assistant", "library"].includes(context.targetId)) { const query = data.query; const keys = query && typeof query === "object" && !Array.isArray(query) ? Object.keys(query) : null; - const validQuery = keys && (keys.length === 0 || (keys.length === 1 && keys[0] === "conversation_id" - && typeof query.conversation_id === "string" && /^[A-Za-z0-9:._-]{1,512}$/.test(query.conversation_id))); + const allowedKeys = { + "chat-room": ["conversation_id"], people: [], assistant: [], + documents: ["doc", "objectUri"], library: ["uri", "pickerRequestId"], + }[context.targetId]; + const picker = launchedAppContexts.get(context.homeToken)?.pickerOwner; + const validQuery = keys && keys.length <= (context.targetId === "library" ? 2 : 1) + && keys.every(key => allowedKeys.includes(key) && typeof query[key] === "string" + && query[key].length > 0 && query[key].length <= 2048) + && (context.targetId !== "chat-room" || !keys.length || /^[A-Za-z0-9:._-]{1,512}$/.test(query.conversation_id)) + && (!keys.includes("pickerRequestId") || (currentLibraryPicker(picker) + && picker.id === query.pickerRequestId && picker.pickerToken === context.homeToken + && ["ready", "delivering"].includes(picker.phase))); if (!hasExactMessageKeys(data, ["type", "requestId", "target", "query", "homeToken"]) || !/^[A-Za-z0-9-]{1,64}$/.test(requestId) || requestId !== data.requestId - || target !== "chat-room" || target !== data.target || data.homeToken !== context.homeToken || !validQuery) { - replyToShellRequest(event, requestId, null, new Error("Home denied the Chat reconnect")); + || target !== context.targetId || target !== data.target || data.homeToken !== context.homeToken || !validQuery) { + replyToShellRequest(event, requestId, null, new Error("Home denied the app reconnect")); return; } const old = launchedAppContexts.get(context.homeToken); - if (old.chatReconnectPending) { - if (old.chatReconnectPending.requestId !== requestId) { - replyToShellRequest(event, requestId, null, new Error("Chat is already reconnecting")); + if (old.frameRenewalPending) { + if (old.frameRenewalPending.requestId !== requestId) { + replyToShellRequest(event, requestId, null, new Error("This app is already reconnecting")); } return; } const record = { requestId, oldToken: context.homeToken, event, freshToken: "", launched: null, + principal: shellState.currentSummary?.authority?.principal_id, + proofBinding: shellState.currentSummary?.authority?.proof_binding_id, expiresAt: Date.now() + 20000, timeout: 0 }; - old.chatReconnectPending = record; + old.frameRenewalPending = record; record.timeout = window.setTimeout(() => { - if (old.chatReconnectPending !== record) return; - settleChatReconnect(old, record, new Error("Home could not reopen Chat in time")); + if (old.frameRenewalPending !== record) return; + settleFrameRenewal(old, record, new Error("Home could not reopen this app in time")); }, 25000); let createdToken = ""; - launchHomeTarget("chat-room", query).then((launched) => { + // Transfer the existing picker with the frame; a renewal does not open a picker. + const launchQuery = { ...query }; + delete launchQuery.pickerRequestId; + launchHomeTarget(target, launchQuery).then((launched) => { const freshToken = homeLaunchTokenFromRoute(launched?.route || ""); createdToken = freshToken; const fresh = launchedAppContexts.get(freshToken); - if (launched?.target !== "chat-room" || launched.attach_kind !== "iframe" + if (launched?.target !== target || launched.attach_kind !== "iframe" || (launched.launch_status && launched.launch_status !== "launched") || !fresh || freshToken === context.homeToken || fresh.source || launchedAppContexts.get(context.homeToken) !== old || old.source !== event.source - || old.chatReconnectPending !== record) { + || old.frameRenewalPending !== record) { if (freshToken && freshToken !== context.homeToken) retireLaunchedAppContext(freshToken); - throw new Error("Home could not reopen this Chat window"); + throw new Error("Home could not reopen this app window"); } - requireHomeGuiActive("reconnect Chat"); + requireHomeGuiActive("reconnect this app"); record.freshToken = freshToken; record.launched = launched; - if (!postToActiveShell({ type: "home:gui-command", command: "renew-chat-authority", + if (!postToActiveShell({ type: "home:gui-command", command: "renew-frame-authority", phase: "prepare", requestId, homeToken: context.homeToken, launched, expiresAt: record.expiresAt })) { - throw new Error("Home GUI could not reopen Chat"); + throw new Error("Home GUI could not reopen this app"); } }).catch((error) => { if (createdToken && createdToken !== context.homeToken) retireLaunchedAppContext(createdToken); - settleChatReconnect(old, record, error); + settleFrameRenewal(old, record, error); }); return; } @@ -2480,6 +2537,10 @@ async function boot() { } function startShellTimers() { + if (!shellState.frameRenewalTimer) { + shellState.frameRenewalTimer = window.setInterval(renewExpiringFrames, 30_000); + window.addEventListener("online", () => refreshSignedHomeSession()); + } if (!shellState.sessionRefreshTimer) { shellState.sessionRefreshTimer = window.setInterval(() => { refreshSignedHomeSession(); @@ -2491,6 +2552,7 @@ function startShellTimers() { if (document.hidden) { return; } + refreshSignedHomeSession(); homeEventsReconnectAttempts = 0; requestShellSummaryRefresh({ reason: "visibilitychange", delay: 0 }); ensureHomeEventChannel(); @@ -2542,12 +2604,22 @@ function homeSummaryHasProofBoundSession(summary) { ); } +function renewExpiringFrames() { + if (!homeSummarySignedIn(shellState.currentSummary)) return; + for (const [homeToken, context] of launchedAppContexts) { + if (!context.source || context.frameRenewalPending || !Number.isFinite(context.expiresAt) + || context.expiresAt > Date.now() + 60_000) continue; + context.source.postMessage({ type: "elastos.home.authority.request/v1", homeToken }, OPAQUE_FRAME_TARGET); + } +} + function refreshSignedHomeSession() { if (!homeSummaryHasProofBoundSession(shellState.currentSummary)) { return Promise.resolve(null); } return refreshHomeSession() .then(() => refreshShellSummary()) + .then(() => renewExpiringFrames()) .catch((error) => { if (isHomeAuthError(error)) { showHostAuthGate({ presentation: "prompt" }).catch((unlockError) => { @@ -2669,6 +2741,7 @@ function refreshHomeAfterEventReconnect() { signal => refreshShellSummary({ signal })) : null) .then((summary) => { if (current() && homeSummarySignedIn(summary)) { + renewExpiringFrames(); broadcastHomeRuntimeEvents([{ kind: "home.summary.changed", scope: "home", diff --git a/capsules/library/browser/src/app.js b/capsules/library/browser/src/app.js index 2c235abb7..1fe02dce2 100644 --- a/capsules/library/browser/src/app.js +++ b/capsules/library/browser/src/app.js @@ -62,13 +62,18 @@ import { state.searchOpen = false; state.sidebarWidth = LIBRARY_SIDEBAR_WIDTH_DEFAULT; const homeOrigin = queryParams.get("home_origin") || ""; - const homeNavigation = createHomeNavigationClient({ homeToken: state.homeToken, homeOrigin, + const homeNavigation = createHomeNavigationClient({ homeToken: state.homeToken, homeOrigin, target: "library", + onHomeToken(token) { + homeClipboard.setHomeToken(token); + state.homeToken = token; + }, enabled: state.mode === "browse" && !queryParams.get("returnTarget") }); - const homeClipboard = createHomeClipboardClient({ + const clipboardOptions = () => ({ targetId: "library", homeOrigin, homeToken: state.homeToken, }); + const homeClipboard = createHomeClipboardClient(clipboardOptions()); homeClipboard.start(); const { providerApi: runtimeProviderApi, diff --git a/capsules/people/browser/people.js b/capsules/people/browser/people.js index 82ed8f558..573edad3a 100644 --- a/capsules/people/browser/people.js +++ b/capsules/people/browser/people.js @@ -1,3 +1,4 @@ +import { createHomeNavigationClient } from "/apps/home/home-navigation-client.js"; import { createHomeClipboardClient } from "/apps/home/home-clipboard-client.js?v=home-20260726a"; const lockedShell = document.getElementById("locked-shell"); @@ -30,7 +31,7 @@ const peopleCountNode = document.getElementById("people-count"); const discoveryVisibleCountNode = document.getElementById("discovery-visible-count"); const pageTitle = document.querySelector(".people-page-title"); const launchParams = new URLSearchParams(window.location.search); -const homeToken = new URLSearchParams(window.location.hash.replace(/^#/, "")).get("home_token") || ""; +let homeToken = new URLSearchParams(window.location.hash.replace(/^#/, "")).get("home_token") || ""; const homeParentOrigin = launchParams.get("home_origin") || ""; const DISCOVERY_SCHEMA = "elastos.people.discovery/v1"; const SECTION_TITLES = { @@ -39,11 +40,18 @@ const SECTION_TITLES = { discovery: "Public", }; -const homeClipboard = createHomeClipboardClient({ +const clipboardOptions = () => ({ targetId: "people", homeOrigin: homeParentOrigin, homeToken, }); +const homeClipboard = createHomeClipboardClient(clipboardOptions()); +createHomeNavigationClient({ homeToken, homeOrigin: homeParentOrigin, target: "people", + onHomeToken(token) { + homeClipboard.setHomeToken(token); + homeToken = token; + }, +}); let localProfileId = ""; let sendingContact = false; let refreshGeneration = 0; diff --git a/elastos/CHANGELOG.md b/elastos/CHANGELOG.md index 9a19081f8..7b8b72168 100644 --- a/elastos/CHANGELOG.md +++ b/elastos/CHANGELOG.md @@ -8,6 +8,7 @@ release's Added, Changed, Fixed, Removed and Security bullets before you update; ### Fixed +- Open apps, including Chat, stay connected while Home runs, and reconnect by themselves after a network drop or a restart. - Closing Browser no longer fails after a minute when another program happens to use a port Browser's media relay may need. ## [2.0.0] - 2026-11-02 diff --git a/elastos/crates/elastos-server/src/api/gateway_home_runtime.rs b/elastos/crates/elastos-server/src/api/gateway_home_runtime.rs index fc0de8915..45b91a598 100644 --- a/elastos/crates/elastos-server/src/api/gateway_home_runtime.rs +++ b/elastos/crates/elastos-server/src/api/gateway_home_runtime.rs @@ -111,15 +111,22 @@ pub(super) async fn home_launch( .viewer .as_deref() .unwrap_or(target_summary.target.as_str()); - let route = append_home_launch_token( + let token = issue_home_projection_launch_token_with_context( &state.data_dir, - &target_summary.route, &target_summary.target, executable_actor, - &req.query, &context, ) .map_err(gateway_internal_error)?; + let expires_at = gateway_home_token::require_carried_home_launch_token( + &state.data_dir, + &token, + &[executable_actor], + ) + .map_err(gateway_internal_error)? + .expires_at; + let route = append_home_launch_token_to_route(&target_summary.route, &req.query, &token) + .map_err(gateway_internal_error)?; let route = crate::api::browser_capsules::canonical_browser_capsule_route(&route).map_err(|error| { ( @@ -129,6 +136,7 @@ pub(super) async fn home_launch( })?; Ok(Json(HomeLaunchResponse { + expires_at, target: target_summary.target, window_policy: target_summary.window_policy, title: target_summary.title, diff --git a/elastos/crates/elastos-server/src/api/gateway_home_token.rs b/elastos/crates/elastos-server/src/api/gateway_home_token.rs index 65e3f39ce..da16434a7 100644 --- a/elastos/crates/elastos-server/src/api/gateway_home_token.rs +++ b/elastos/crates/elastos-server/src/api/gateway_home_token.rs @@ -87,6 +87,7 @@ struct HomeLaunchTokenEnvelope { #[derive(Debug, Clone)] pub(in crate::api) struct RequiredHomeLaunchToken { + pub(in crate::api) expires_at: u64, pub(in crate::api) launch_id: String, pub(in crate::api) launch_context: HomeLaunchContext, pub(in crate::api) context: HomeLaunchTokenContext, @@ -291,6 +292,26 @@ fn issue_home_launch_token_at( { anyhow::bail!("home launch token is missing authority context"); } + let mut expires_at = issued_at.saturating_add(HOME_LAUNCH_TOKEN_TTL_SECS); + // Home can replace a frame only under its current parent authority. + if launch_context.authority_actor == HOME_CAPSULE_ID + && launch_context.selected_resource != HOME_CAPSULE_ID + { + if let Some(proof_binding_id) = context.proof_binding_id.as_deref() { + let grant = crate::auth::load_active_session_grant( + &home_launch_auth_data_dir(data_dir), + &context.session_id, + now_ts(), + )?; + if grant.principal_id != context.principal_id + || grant.proof_binding_id != proof_binding_id + || grant.grant_id != context.grant_id + { + anyhow::bail!("home launch token authority context mismatch"); + } + expires_at = expires_at.min(grant.expires_at); + } + } let (signing_key, _did) = elastos_identity::load_or_create_did(data_dir)?; let envelope = HomeLaunchTokenEnvelope { payload: HomeLaunchTokenPayload { @@ -298,7 +319,7 @@ fn issue_home_launch_token_at( launch_id: format!("launch:{}", uuid_like_token()), launch_context: launch_context.clone(), iat: issued_at, - exp: issued_at.saturating_add(HOME_LAUNCH_TOKEN_TTL_SECS), + exp: expires_at, principal_id: context.principal_id.clone(), session_id: context.session_id.clone(), proof_binding_id: context.proof_binding_id.clone(), @@ -754,6 +775,7 @@ fn require_home_launch_token_value_from_expected_did( } } Ok(RequiredHomeLaunchToken { + expires_at: envelope.payload.exp, launch_id: envelope.payload.launch_id, launch_context: envelope.payload.launch_context, context: HomeLaunchTokenContext { @@ -1204,6 +1226,65 @@ mod tests { .contains("not authorized")); } + #[test] + fn frame_renewal_is_bounded_by_launch_ttl_and_current_parent_grant() { + let dir = tempfile::tempdir().unwrap(); + let now = now_ts(); + let context = HomeLaunchTokenContext { + principal_id: "person:local:alice".into(), + session_id: "auth:alice".into(), + proof_binding_id: Some("proof:alice".into()), + grant_id: "grant:alice".into(), + }; + let mut grant = elastos_runtime::auth::AuthSessionGrantV1 { + schema: elastos_runtime::auth::AuthSessionGrantV1::SCHEMA.into(), + principal_id: context.principal_id.clone(), + session_id: context.session_id.clone(), + proof_binding_id: context.proof_binding_id.clone().unwrap(), + grant_id: context.grant_id.clone(), + issued_at: now, + expires_at: now + 60, + apps: vec![HOME_CAPSULE_ID.into()], + }; + let renew = || { + issue_home_projection_launch_token_with_context( + dir.path(), + "chat-room", + "chat-room", + &context, + ) + }; + for lifetime in [60, HOME_LAUNCH_TOKEN_TTL_SECS * 2] { + grant.expires_at = now + lifetime; + crate::auth::store_session_grant(dir.path(), grant.clone()).unwrap(); + let token = renew().unwrap(); + let payload = decode_launch_token(&token).payload; + assert_eq!( + payload.exp, + grant + .expires_at + .min(payload.iat + HOME_LAUNCH_TOKEN_TTL_SECS) + ); + // An app launch cannot act as Home to obtain a replacement. + assert!(require_home_launch_token_context( + dir.path(), + &capsule_headers(&token), + HOME_CAPSULE_ID, + ) + .is_err()); + } + grant.expires_at = now; + crate::auth::store_session_grant(dir.path(), grant.clone()).unwrap(); + assert!(renew().is_err(), "expired parent"); + grant.expires_at = now + 60; + crate::auth::store_session_grant(dir.path(), grant.clone()).unwrap(); + crate::auth::revoke_session_grant(dir.path(), &grant.session_id, now).unwrap(); + assert!(renew().is_err(), "revoked parent"); + grant.principal_id = "person:local:bob".into(); + crate::auth::store_session_grant(dir.path(), grant).unwrap(); + assert!(renew().is_err(), "another principal's parent"); + } + #[test] fn proof_bound_home_projection_uses_home_as_its_non_transitive_authority() { let data_dir = tempfile::tempdir().unwrap(); diff --git a/elastos/crates/elastos-server/src/api/gateway_models.rs b/elastos/crates/elastos-server/src/api/gateway_models.rs index 6647cba65..743032d0c 100644 --- a/elastos/crates/elastos-server/src/api/gateway_models.rs +++ b/elastos/crates/elastos-server/src/api/gateway_models.rs @@ -947,6 +947,7 @@ enum HomeTargetKind { #[derive(Serialize)] struct HomeLaunchResponse { + expires_at: u64, target: String, #[serde(skip_serializing_if = "Option::is_none")] window_policy: Option, diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/collaboration_presence.rs b/elastos/crates/elastos-server/src/api/gateway_tests/collaboration_presence.rs index 0c0365e23..605aeb63e 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/collaboration_presence.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/collaboration_presence.rs @@ -1303,3 +1303,221 @@ async fn restarted_presence_get_keeps_legacy_core_bytes_until_lifecycle_repair() .records() .is_empty()); } + +// Reproduction controls: real gateway, isolated state, expiry moved without waiting. +#[tokio::test] +async fn chat_online_expired_frame_is_refused_while_home_session_remains_valid() { + let dir = tempfile::tempdir().unwrap(); + let (state, _) = configured_presence_state(dir.path()); + let authority = passkey_authority_with_name(dir.path(), Some("Owner")); + install_signed_profile(dir.path(), &authority, "Owner"); + let app = gateway_router(state); + let context = gateway_home_token::HomeLaunchTokenContext { + principal_id: authority.principal_id.clone(), + session_id: authority.session_id.clone(), + proof_binding_id: Some(authority.proof_binding_id.clone()), + grant_id: authority.grant_id.clone(), + }; + let live = gateway_home_token::issue_home_projection_launch_token_with_context( + dir.path(), + "chat-room", + "chat-room", + &context, + ) + .unwrap(); + gateway_home_token::require_home_launch_token_context( + dir.path(), + capsule_request("POST", "/api/apps/chat-room/poll", &live, "{}").headers(), + "chat-room", + ) + .expect("the frame authority is valid before expiry"); + // Age the same signed projection across its TTL using only fixture keys. + let codec = base64::engine::general_purpose::URL_SAFE_NO_PAD; + let mut envelope: serde_json::Value = + serde_json::from_slice(&codec.decode(&live).unwrap()).unwrap(); + envelope["payload"]["iat"] = json!(crate::auth::now_ts() - HOME_LAUNCH_TOKEN_TTL_SECS - 1); + envelope["payload"]["exp"] = json!(crate::auth::now_ts() - 1); + let (key, _) = elastos_identity::load_or_create_did(dir.path()).unwrap(); + let (signature, signer) = crate::crypto::domain_separated_sign( + &key, + HOME_LAUNCH_TOKEN_DOMAIN, + serde_json::to_string(&envelope["payload"]) + .unwrap() + .as_bytes(), + ); + envelope["signature"] = json!(signature); + envelope["signer_did"] = json!(signer); + let expired = codec.encode(serde_json::to_vec(&envelope).unwrap()); + let refused = app + .clone() + .oneshot(capsule_request( + "POST", + "/api/apps/chat-room/poll", + &expired, + r#"{"since":41}"#, + )) + .await + .unwrap(); + let status = refused.status(); + let reason = response_text(refused).await; + assert_eq!(status, StatusCode::FORBIDDEN, "{reason}"); + eprintln!("expired frame response: {status}: {reason}"); + assert!(gateway_home_token::require_home_launch_token_context( + dir.path(), + capsule_request("POST", "/api/apps/chat-room/poll", &expired, "{}").headers(), + "chat-room", + ) + .unwrap_err() + .to_string() + .contains("expired")); + crate::auth::load_active_session_grant( + dir.path(), + &authority.session_id, + crate::auth::now_ts(), + ) + .expect("the person's session is still valid"); + let refreshed = app + .clone() + .oneshot( + test_browser_request("localhost:61180", "http://localhost:61180") + .method("POST") + .uri("/api/auth/sessions/refresh") + .header("x-elastos-home-token", &authority.home_token) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(refreshed.status(), StatusCode::OK); + let fresh = gateway_home_token::issue_home_projection_launch_token_with_context( + dir.path(), + "chat-room", + "chat-room", + &context, + ) + .unwrap(); + let start = app + .clone() + .oneshot(capsule_request( + "POST", + "/api/apps/chat-room/session/start", + &fresh, + "{}", + )) + .await + .unwrap(); + let status = start.status(); + assert_eq!(status, StatusCode::OK, "{}", response_text(start).await); + let resumed = app + .oneshot(capsule_request( + "POST", + "/api/apps/chat-room/poll", + &fresh, + r#"{"since":41}"#, + )) + .await + .unwrap(); + assert_eq!(resumed.status(), StatusCode::OK); + eprintln!("chat_online frame: expired token -> 403 ({reason}); Home refresh 200; fresh frame -> session/start -> poll 200"); +} + +#[tokio::test] +async fn chat_online_configured_poll_does_not_renew_room_session() { + let dir = tempfile::tempdir().unwrap(); + let (state, _) = configured_presence_state(dir.path()); + let authority = passkey_authority_with_name(dir.path(), Some("Owner")); + install_signed_profile(dir.path(), &authority, "Owner"); + let app = gateway_router(state); + let context = gateway_home_token::HomeLaunchTokenContext { + principal_id: authority.principal_id.clone(), + session_id: authority.session_id.clone(), + proof_binding_id: Some(authority.proof_binding_id.clone()), + grant_id: authority.grant_id.clone(), + }; + let token = gateway_home_token::issue_home_projection_launch_token_with_context( + dir.path(), + "chat-room", + "chat-room", + &context, + ) + .unwrap(); + let started = app + .clone() + .oneshot(capsule_request( + "POST", + "/api/apps/chat-room/session/start", + &token, + "{}", + )) + .await + .unwrap(); + let status = started.status(); + assert_eq!(status, StatusCode::OK, "{}", response_text(started).await); + let path = elastos_common::localhost::rooted_localhost_fs_path( + dir.path(), + crate::room_service::room_root_uri(), + ) + .unwrap() + .join("local/sessions.json"); + let mut sessions: serde_json::Value = + serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!(sessions.as_array().unwrap().len(), 1); + let deadline = crate::auth::now_ts() + 60; + sessions[0]["expires_at"] = json!(deadline); + std::fs::write(&path, serde_json::to_vec(&sessions).unwrap()).unwrap(); + for _ in 0..3 { + let poll = app + .clone() + .oneshot(capsule_request( + "POST", + "/api/apps/chat-room/poll", + &token, + r#"{"since":41}"#, + )) + .await + .unwrap(); + assert_eq!(poll.status(), StatusCode::OK); + } + let after: serde_json::Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!( + after[0]["expires_at"], deadline, + "polls leave the deadline unchanged" + ); + sessions[0]["expires_at"] = json!(crate::auth::now_ts().saturating_sub(1)); + std::fs::write(&path, serde_json::to_vec(&sessions).unwrap()).unwrap(); + let refused = app + .clone() + .oneshot(capsule_request( + "POST", + "/api/apps/chat-room/poll", + &token, + r#"{"since":41}"#, + )) + .await + .unwrap(); + assert_eq!(refused.status(), StatusCode::UNAUTHORIZED); + let reason = response_text(refused).await; + assert!(reason.contains("invalid or expired session"), "{reason}"); + let started = app + .clone() + .oneshot(capsule_request( + "POST", + "/api/apps/chat-room/session/start", + &token, + "{}", + )) + .await + .unwrap(); + assert_eq!(started.status(), StatusCode::OK); + let resumed = app + .oneshot(capsule_request( + "POST", + "/api/apps/chat-room/poll", + &token, + r#"{"since":41}"#, + )) + .await + .unwrap(); + assert_eq!(resumed.status(), StatusCode::OK); + eprintln!("chat_online room: 3 polls leave expiry unchanged; expired room -> 401 ({reason}); session/start -> poll 200"); +} diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs index 61e211a0d..2959fb5a3 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs @@ -65,13 +65,26 @@ async fn test_home_wallet_connector_bridge_rejects_invalid_authority_before_wall &authority, ); let token_for = |context: HomeLaunchTokenContext| { - issue_home_projection_launch_token_with_context( - dir.path(), - WALLET_METAMASK_CAPSULE_ID, - WALLET_METAMASK_CAPSULE_ID, - &context, - ) - .unwrap() + // Issuance rejects these bindings; sign isolated malformed fixtures to + // retain coverage of the bridge's verification before provider calls. + let codec = base64::engine::general_purpose::URL_SAFE_NO_PAD; + let mut envelope: serde_json::Value = + serde_json::from_slice(&codec.decode(&valid_connector_token).unwrap()).unwrap(); + envelope["payload"]["principal_id"] = json!(context.principal_id); + envelope["payload"]["session_id"] = json!(context.session_id); + envelope["payload"]["proof_binding_id"] = json!(context.proof_binding_id); + envelope["payload"]["grant_id"] = json!(context.grant_id); + let (key, _) = elastos_identity::load_or_create_did(dir.path()).unwrap(); + let (signature, signer) = crate::crypto::domain_separated_sign( + &key, + HOME_LAUNCH_TOKEN_DOMAIN, + serde_json::to_string(&envelope["payload"]) + .unwrap() + .as_bytes(), + ); + envelope["signature"] = json!(signature); + envelope["signer_did"] = json!(signer); + codec.encode(serde_json::to_vec(&envelope).unwrap()) }; let wrong_principal = token_for(HomeLaunchTokenContext { principal_id: "principal:wrong".to_string(), diff --git a/scripts/chat-online-behavior.test.mjs b/scripts/chat-online-behavior.test.mjs new file mode 100644 index 000000000..c59883d6d --- /dev/null +++ b/scripts/chat-online-behavior.test.mjs @@ -0,0 +1,195 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { createServer } from "node:http"; +import { resolve, extname } from "node:path"; +import { pathToFileURL } from "node:url"; +import test from "node:test"; +import { checkArtifacts } from "./check-chat-ui-artifacts.mjs"; + +const root = resolve(new URL("..", import.meta.url).pathname); +const read = path => readFileSync(resolve(root, path), "utf8"); +assert.ok(process.env.BROWSER_OPERATOR_PLAYWRIGHT_CORE, + "Run ./scripts/test-behaviour.sh inputs and use the pinned BROWSER_OPERATOR_PLAYWRIGHT_CORE input"); +const sdkPath = resolve(process.env.BROWSER_OPERATOR_PLAYWRIGHT_CORE); +const metadata = JSON.parse(readFileSync(resolve(sdkPath, "package.json"), "utf8")); +assert.equal(metadata.name, "playwright-core"); +assert.equal(metadata.version, "1.59.1"); +const { chromium } = await import(pathToFileURL(resolve(sdkPath, "index.mjs")).href); +const serverSecret = "provider-secret-sk-session-start-fixture"; +const boundedStartFailure = "Chat session bootstrap failed. Reopen Chat from Home."; +async function fixture(t, direct = false, { startFault = null } = {}) { + checkArtifacts(); // Execute the committed WASM only when its source stamp matches. + const state = { now: 0, tokenExpiry: 60, roomExpiry: 60, fault: null, startFault, + polls: [], accepted: 0, starts: 0, renewals: 0, errors: [] }; + const transport = { configured: true, available: true, community_joined: true }; + const poll = () => ({ room_slug: "chat-room", display_name: "Owner", latest_seq: 41, + participants: [], objects: [], transport }); + const server = createServer(async (req, res) => { + const url = new URL(req.url, "http://fixture"); + const json = (status, value) => { res.writeHead(status, { "content-type": "application/json" }); res.end(JSON.stringify(value)); }; + if (url.pathname === "/") { + res.writeHead(200, { "content-type": "text/html" }); + res.end(` + `); + return; + } + if (url.pathname === "/fixture/renew") { state.renewals++; state.tokenExpiry = state.now + 60; json(200, {}); return; } + if (url.pathname.startsWith("/api/")) { + let body = ""; for await (const chunk of req) body += chunk; + if (url.pathname.endsWith("/poll") || url.pathname.endsWith("/messages")) { + const request = { ...JSON.parse(body || "{}"), token: req.headers["x-elastos-home-token"], now: state.now }; + state.polls.push(request); + if (state.fault === "network") { req.socket.destroy(); return; } + if (state.fault) { json(state.fault, { error: `request failed: ${state.fault}` }); return; } + if (state.now >= state.tokenExpiry) { res.writeHead(403); res.end("Gateway request requires an admitted host and caller"); return; } + if (state.now >= state.roomExpiry) { json(401, { error: "invalid or expired session for configured Chat" }); return; } + state.accepted++; + json(200, url.pathname.endsWith("/messages") ? { conversation_id: "direct:fixture", messages: [ + { message_id: "message:kept", direction: "incoming", text: "Kept history", created_at: 1, delivery_state: "received" }, + ] } : poll()); return; + } + if (url.pathname.endsWith("/session/start")) { + state.starts++; + if (state.startFault) { json(state.startFault, { error: serverSecret }); return; } + state.roomExpiry = state.now + 60; json(200, { poll: poll(), expires_at: state.roomExpiry }); return; + } + if (url.pathname.endsWith("/summary")) { + json(200, { room_slug: "chat-room", pending_count: 0, active_session_count: 1, transport }); return; + } + if (url.pathname.endsWith("/conversations")) { json(200, { conversations: direct ? [{ conversation_id: "direct:fixture", display_name: "Contact" }] : [], community_unread: false }); return; } + json(200, {}); return; + } + const relative = url.pathname.replace(/^\/apps\//, "capsules/").replace(/^(capsules\/[^/]+)\//, "$1/browser/"); + const file = resolve(root, relative + (url.pathname.endsWith("/") ? "index.html" : "")); + if (!file.startsWith(`${root}/capsules/`)) { res.writeHead(404); res.end(); return; } + try { + res.writeHead(200, { "content-type": ({ ".js": "text/javascript", ".wasm": "application/wasm", ".html": "text/html", ".css": "text/css" })[extname(file)] || "application/octet-stream" }); + res.end(readFileSync(file)); + } catch { res.end(); } + }); + await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)); + const origin = `http://127.0.0.1:${server.address().port}`; + let browser; + t.after(async () => { await browser?.close(); server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); }); + browser = await chromium.launch({ headless: true }); + const page = await browser.newPage(); + await page.addInitScript(secret => { + window.sessionStartSecretLeaks = []; + new MutationObserver(() => { + if (document.documentElement?.outerHTML.includes(secret)) window.sessionStartSecretLeaks.push(true); + }).observe(document, { subtree: true, childList: true, characterData: true, attributes: true }); + }, serverSecret); + page.on("pageerror", error => state.errors.push(error.message)); + await page.route("**/*", route => new URL(route.request().url()).origin === origin ? route.continue() : route.abort()); + await page.clock.install({ time: new Date(0) }); + await page.goto(origin); + const frame = page.frames().find(frame => frame.url().includes("/apps/chat-room/")); + if (startFault) { + await frame.waitForFunction(() => document.body.textContent.includes("session bootstrap") || document.body.textContent.includes("provider-secret")); + return { state, page, frame }; + } + if (direct) await frame.getByText("Kept history", { exact: true }).waitFor(); + else await frame.waitForSelector('body[data-room-session-active="true"]', { state: "attached", timeout: 10000 }); + await frame.locator("#message-input").fill("Keep this draft"); + const tick = async (count = 1) => { + for (let i = 0; i < count; i++) { + state.now += 1; + await page.clock.runFor(1100); + // Let real HTTP requests settle between virtual timer ticks. + await new Promise(resolve => setTimeout(resolve, 40)); + } + }; + await tick(2); + assert.ok(state.polls.length > 0, "the actual WASM is polling before the fault"); + if (!direct) assert.equal(state.polls.at(-1).since, 41); + assert.deepEqual(state.errors, []); + return { state, page, frame, tick }; +} + +for (const path of ["initial bootstrap", "room renewal", "Home recovery"]) { + test(`Chat bounds session-start server errors during ${path}`, { timeout: 30000 }, async t => { + const { state, frame, tick } = await fixture(t, false, + path === "initial bootstrap" ? { startFault: 503 } : {}); + if (tick) { + const starts = state.starts; + state.startFault = 503; + if (path === "room renewal") state.now = 31; + else state.fault = 401; + await tick(2); + state.fault = null; + await tick(35); + assert.ok(state.starts > starts, "the session-start call site reached the failing server"); + } + assert.ok(state.starts > 0); + const ui = await frame.locator("html").evaluate(element => element.outerHTML); + assert.ok(!ui.includes(serverSecret), "server response secret must never enter rendered UI state"); + assert.deepEqual(await frame.evaluate(() => window.sessionStartSecretLeaks), [], + "all rendered UI transitions keep the server body private"); + assert.ok(ui.includes(boundedStartFailure), "the call site renders only the bounded failure detail"); + assert.deepEqual(state.errors, []); + }); +} + +for (const direct of [false, true]) for (const failure of (direct + ? ["frame expiry", "401", "network", "503"] + : ["frame expiry", "401", "room expiry", "network", "503"])) { + test(`${direct ? "Direct" : "Community"} Chat resumes polling without a click after ${failure}`, { timeout: 30000 }, async t => { + const { state, frame, tick } = await fixture(t, direct); + const before = state.polls.length; + if (failure === "frame expiry") { state.now = 61; state.roomExpiry = 1000; } + else if (failure === "room expiry") { state.now = 61; state.tokenExpiry = 1000; } + else state.fault = failure === "401" ? 401 : failure === "503" ? 503 : "network"; + await tick(2); + assert.ok(state.polls.length > before, "the poll actually reached the fault"); + const atFailure = state.polls.length; + const acceptedAtFailure = state.accepted; + state.fault = null; + await tick(35); // More than the proposed maximum retry delay; no user event. + const observation = { before, atFailure, after: state.polls.length, acceptedAfterFault: state.accepted - acceptedAtFailure, starts: state.starts, + renewals: state.renewals, active: await frame.locator("body").getAttribute("data-room-session-active"), + status: await frame.locator("#status-badge").textContent(), + draft: await frame.locator("#message-input").inputValue() }; + t.diagnostic(JSON.stringify(observation)); + const automaticPolls = state.polls.length; + if (!direct && observation.active === "false") { + // Positive control: the same document and healthy backend work after the + // existing button is used. The failing assertion below tests automation. + await frame.locator("#reconnect-button").evaluate(button => button.click()); + await tick(3); + assert.equal(await frame.locator("body").getAttribute("data-room-session-active"), "true", + "fixture must recover through the existing user action"); + assert.ok(state.polls.length > automaticPolls); + t.diagnostic(`manual Reconnect control: active=true, polls=${state.polls.length}, renewals=${state.renewals}`); + } + assert.ok(automaticPolls > atFailure, `polling stayed stopped: ${JSON.stringify(observation)}`); + assert.ok(observation.acceptedAfterFault > 0, `no successful poll after recovery: ${JSON.stringify(observation)}`); + if (!direct) assert.equal(observation.active, "true"); + assert.equal(observation.draft, "Keep this draft"); + if (!direct) assert.equal(state.polls.at(-1).since, 41, "recovery keeps the cursor"); + else assert.equal(await frame.getByText("Kept history", { exact: true }).count(), 1, "recovery keeps history without duplicates"); + if (failure === "frame expiry") assert.ok(state.renewals > 0); + if (failure === "room expiry") assert.ok(state.starts > 1); + }); +} + + +test("A long outage bounds retries, shows Reconnecting and resumes on online", { timeout: 30000 }, async t => { + const { state, frame, tick } = await fixture(t); + state.fault = 503; + state.tokenExpiry = state.roomExpiry = 1000; // Isolate transport recovery from authority expiry. + const before = state.polls.length; + await tick(90); + const attempts = state.polls.length - before; + assert.ok(attempts >= 5 && attempts <= 12, `bounded retries: ${attempts}`); + assert.equal(await frame.locator("#status-badge").textContent(), "Reconnecting"); + state.fault = null; + const accepted = state.accepted; + await frame.evaluate(() => dispatchEvent(new Event("online"))); + await tick(2); + assert.ok(state.accepted > accepted); + assert.equal(await frame.locator("#message-input").inputValue(), "Keep this draft"); +}); diff --git a/scripts/chat-room-configured-layout-smoke.mjs b/scripts/chat-room-configured-layout-smoke.mjs index 37ab88ffe..0cc1eb035 100644 --- a/scripts/chat-room-configured-layout-smoke.mjs +++ b/scripts/chat-room-configured-layout-smoke.mjs @@ -2009,11 +2009,11 @@ async function runScenario(scenario) { "initial Direct401 performed automatic recovery work", trace); assert(await page.evaluate(() => window.fixtureReconnects) === 0, "initial Direct401 reopened itself"); const selectedByUser = scenario === "direct-initial-401-user-selection"; - if (selectedByUser) await clickSharedChoice(frame); await frame.locator("#error-text").waitFor({ state: "visible" }); assert((await frame.locator("#error-text").innerText()).trim(), "Reconnect lost its visible recovery explanation"); - await frame.locator("#reconnect-button").click(); + if (selectedByUser) await clickSharedChoice(frame); + else await frame.locator("#reconnect-button").click(); await frame.waitForFunction((shared) => document.body.dataset.roomSessionActive === "true" && document.querySelector("#reconnect-button")?.hidden === true && document.querySelector("[data-conversation-choice].active")?.dataset.conversationChoice diff --git a/scripts/chat-room-reconnect.test.mjs b/scripts/chat-room-reconnect.test.mjs index 103fe1b1b..61b3ff85b 100644 --- a/scripts/chat-room-reconnect.test.mjs +++ b/scripts/chat-room-reconnect.test.mjs @@ -33,7 +33,7 @@ function chatFixture() { const context = vm.createContext({ window, URL, URLSearchParams, Event, init() {}, createHomeNavigationClient: options => createHomeNavigationClient({ ...options, windowRef: window }), createHomeClipboardClient(options) { const client = { token: options.homeToken, started: false, retired: false, - start() { this.started = true; }, teardown() { this.retired = true; }, + start() { this.started = true; }, setHomeToken(token) { this.token = token; }, teardown() { this.retired = true; }, writes: [], writeText(text, options) { this.writes.push({ text, purpose: options.purpose }); return Promise.resolve(); } }; clipboard.push(client); return client; }, }); @@ -65,11 +65,13 @@ test("Reconnect uses one visible action and only the Home response renews the sa f.respond(request.data.requestId, launched("fresh")); assert.equal(await pending, "fresh"); assert.equal(f.context.elastosChatHomeToken(), "fresh"); - assert.equal(f.clipboard[0].retired, true); - assert.equal(f.clipboard[1].token, "fresh"); - assert.equal(f.clipboard[1].started, true); + assert.equal(f.clipboard.length, 1); + assert.equal(f.clipboard[0].retired, false); + assert.equal(f.clipboard[0].token, "fresh"); + assert.equal(f.clipboard[0].started, true); assert.equal(f.timers.size, 0); - assert.equal(f.messages.at(-1).data.type, "home:app-ready"); + assert.equal(f.messages.at(-1).data.type, "home:frame-authority-ready"); + assert.equal(f.messages.some(({ data }) => data.type === "home:app-ready"), false); // The actual navigation client keeps its selector and document nonce while // requiring a new GUI probe under the renewed token. f.window.dispatchEvent({ type: "message", source: f.parent, origin: "null", @@ -86,7 +88,7 @@ test("Expired Home and refused launches keep the old authority available for a u { result: { ...launched("fresh"), route: "https://evil.fixture/apps/chat-room/#home_token=fresh" } }]) { const f = chatFixture(); const pending = f.context.elastosChatReconnect(); - const rejection = assert.rejects(pending, /Sign in to Home|invalid Chat launch/); + const rejection = assert.rejects(pending, /Sign in to Home|invalid app launch/); f.respond(f.messages[0].data.requestId, reply.result, reply); await rejection; assert.equal(f.context.elastosChatHomeToken(), "old"); @@ -133,37 +135,37 @@ test("Home GUI accepts only the open Chat entry and keeps its iframe document", hasExactKeys: (value, keys) => Object.keys(value).sort().join(",") === keys.sort().join(","), }); const gui = read("capsules/home-gui/browser/home-gui.js"); - for (const name of ["homeLaunchTokenFromRoute", "homeGuiWindowEntryForToken", "renewHomeGuiChatWindowAuthority"]) + for (const name of ["homeLaunchTokenFromRoute", "homeGuiWindowEntryForToken", "renewHomeGuiFrameAuthority"]) vm.runInContext(sourceFunction(gui, name), context); vm.runInContext(sourceFunction(read("capsules/home-gui/browser/home-gui-shell.js"), "handleGuiCommand"), context); - const command = { type: "home:gui-command", command: "renew-chat-authority", requestId: "renew-chat", + const command = { type: "home:gui-command", command: "renew-frame-authority", requestId: "renew-chat", phase: "prepare", homeToken: "old", launched: launched("fresh"), expiresAt: Date.now() + 1000 }; assert.equal(context.handleGuiCommand({ ...command, expiresAt: Date.now() - 1 }), false); assert.equal(receipts.at(-1).ok, false); assert.equal(frame.dataset.route, oldRoute); - assert.equal(context.renewHomeGuiChatWindowAuthority("old", { ...launched("fresh"), target: "browser" }, homeOrigin), false); - assert.equal(context.renewHomeGuiChatWindowAuthority("old", { ...launched("fresh"), route: "https://evil.fixture/apps/chat-room/#home_token=fresh" }, homeOrigin), false); + assert.equal(context.renewHomeGuiFrameAuthority("old", { ...launched("fresh"), target: "browser" }, homeOrigin), false); + assert.equal(context.renewHomeGuiFrameAuthority("old", { ...launched("fresh"), route: "https://evil.fixture/apps/chat-room/#home_token=fresh" }, homeOrigin), false); assert.equal(context.handleGuiCommand(command), true); assert.equal(receipts.at(-1).ok, true); assert.equal(receipts.at(-1).freshHomeToken, "fresh"); assert.equal(frame.dataset.route, oldRoute, "an unaccepted prepare receipt must preserve retry lookup"); assert.equal(probes.length, 0); assert.equal(context.handleGuiCommand({ ...command, phase: "commit" }), true); - assert.equal(receipts.at(-1).type, "home:chat-authority-committed"); + assert.equal(receipts.at(-1).type, "home:frame-authority-committed"); assert.equal(receipts.at(-1).ok, true); assert.equal(frame.dataset.route, launched("fresh").route); assert.equal(frame.src, oldRoute, "renewal must retain the same iframe document and drafts"); assert.equal(entry.homeNavigation, null); assert.equal(probes.length, 1); - assert.equal(context.renewHomeGuiChatWindowAuthority("old", launched("later"), homeOrigin), false); + assert.equal(context.renewHomeGuiFrameAuthority("old", launched("later"), homeOrigin), false); const closedCommand = { ...command, homeToken: "fresh", launched: launched("later") }; assert.equal(context.handleGuiCommand(closedCommand), true); - assert.equal(receipts.at(-1).type, "home:chat-authority-renewed"); + assert.equal(receipts.at(-1).type, "home:frame-authority-renewed"); context.shellState.windows.clear(); assert.equal(context.handleGuiCommand({ ...closedCommand, phase: "commit" }), false); - assert.equal(receipts.at(-1).type, "home:chat-authority-committed"); + assert.equal(receipts.at(-1).type, "home:frame-authority-committed"); assert.equal(receipts.at(-1).ok, false, "a closed Chat entry must refuse the commit"); - assert.equal(context.renewHomeGuiChatWindowAuthority("fresh", launched("later"), homeOrigin), false); + assert.equal(context.renewHomeGuiFrameAuthority("fresh", launched("later"), homeOrigin), false); }); test("Copy DID uses its own Home purpose and the renewed launch token", async () => { @@ -175,6 +177,10 @@ test("Copy DID uses its own Home purpose and the renewed launch token", async () f.respond(f.messages[0].data.requestId, launched("fresh")); await pending; await f.context.elastosChatCopyProfileId("did:key:zOther"); - assert.equal(f.clipboard[0].writes.length, 1); - assert.deepEqual(f.clipboard[1].writes, [{ text: "did:key:zOther", purpose: "profile.id" }]); + assert.equal(f.clipboard.length, 1); + assert.equal(f.clipboard[0].token, "fresh"); + assert.deepEqual(f.clipboard[0].writes, [ + { text: "did:key:zProfile", purpose: "profile.id" }, + { text: "did:key:zOther", purpose: "profile.id" }, + ]); }); diff --git a/scripts/home-frame-renewal.test.mjs b/scripts/home-frame-renewal.test.mjs new file mode 100644 index 000000000..a1abfb11f --- /dev/null +++ b/scripts/home-frame-renewal.test.mjs @@ -0,0 +1,323 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; +import vm from "node:vm"; +import { createHomeClipboardClient } from "../capsules/home/browser/home-clipboard-client.js"; +import { createHomeClipboardHost, createHomeClipboardFrameState } from "../capsules/home/browser/home-clipboard-host.js"; +import { createHomeNavigationClient } from "../capsules/home/browser/home-navigation-client.js"; + +const homeOrigin = "https://home.fixture"; +const hostSource = readFileSync(new URL("../capsules/home/browser/home-shell-host.js", import.meta.url), "utf8"); +function sourceFunction(name) { + const start = hostSource.indexOf(`function ${name}(`); + assert.ok(start >= 0, name); + return hostSource.slice(hostSource.slice(start - 6, start) === "async " ? start - 6 : start, hostSource.indexOf("\n}", start) + 2); +} +function fixture(target = "chat-room", enabled = true) { + const listeners = new Map(), timers = new Map(), frames = new Map(), commands = [], launchQueries = []; + let next = 0, receive, launches = 0, refreshed = 0, currentToken = "old-frame", holdPrepare = false; + const authority = { signed_in: true, principal_id: "alice", proof_binding_id: "proof:alice" }; + const shell = {}, home = { location: { origin: homeOrigin, href: homeOrigin }, + setTimeout(fn) { timers.set(++next, fn); return next; }, clearTimeout(id) { timers.delete(id); }, + addEventListener(type, fn) { if (type === "message") receive = fn; }, + }; + const frame = { postMessage(data) { for (const fn of listeners.get("message") || []) fn({ data, source: home, origin: homeOrigin }); } }; + const windowRef = { top: home, parent: shell, crypto: { randomUUID: () => `request-${++next}` }, + setTimeout: home.setTimeout, clearTimeout: home.clearTimeout, + addEventListener(type, fn) { if (!listeners.has(type)) listeners.set(type, new Set()); listeners.get(type).add(fn); }, + removeEventListener(type, fn) { listeners.get(type)?.delete(fn); }, + }; + const message = (data, source = frame, origin = "null") => receive({ data, source, origin }); + home.postMessage = data => message(data); + const old = { targetId: target, source: frame, origin: "null", expiresAt: 60_000 }; + frames.set("old-frame", old); + const shellState = { currentSummary: { authority } }; + const receipt = command => message({ type: `home:frame-authority-${command.phase === "prepare" ? "renewed" : "committed"}`, + homeToken: "shell-token", requestId: command.requestId, oldHomeToken: command.homeToken, + freshHomeToken: "fresh-frame", ok: true }, shell); + const context = vm.createContext({ console, URL, URLSearchParams, Promise, crypto: { randomUUID: () => `picker-${++next}` }, window: home, + Date: class extends Date { static now() { return 59_000; } }, + shellState, launchedAppContexts: frames, + activeShellFrame: { contentWindow: shell, dataset: { route: "/apps/home-gui/#home_token=shell-token" } }, + activeShellRoot: { dataset: { target: "home-gui" } }, + OPAQUE_CAPSULE_ORIGIN: "null", OPAQUE_FRAME_TARGET: "*", HOME_GUI_SHELL_ID: "home-gui", + HOME_CLI_SHELL_ID: "home-cli", WALLET_CONNECTOR_EFFECT_TYPE: "wallet-effect", FORM_FACTOR_MESSAGE: "form-factor", + BROWSER_AUTHORITY_RENEWAL_REQUEST_TYPE: "browser-request", BROWSER_AUTHORITY_RENEWAL_RESULT_TYPE: "browser-result", + pendingBrowserAuthorityRenewals: new Map(), + homeExternalLinkPrompt: { retire() {}, transfer() {} }, + homeClipboardHost: { handle: () => false, retireFrame() {}, resetFrame() {} }, + handleHomeWalletConnectorEffect: () => false, + + hasExactMessageKeys: (data, keys) => Object.keys(data).sort().join() === [...keys].sort().join(), + requireHomeGuiActive() { assert.equal(authority.signed_in, true); }, + postToActiveShell(command) { + commands.push(command); + if (command.command === "renew-frame-authority" && (!holdPrepare || command.phase === "commit")) queueMicrotask(() => receipt(command)); + return true; + }, + refreshHomeSession: async () => { refreshed++; }, refreshShellSummary: async () => shellState.currentSummary, + isHomeAuthError: () => false, + launchHomeTarget: async (requested, query) => { + launches++; + launchQueries.push(query); + if (!authority.signed_in) throw Object.assign(new Error("Sign in"), { status: 401 }); + frames.set("fresh-frame", { targetId: requested, source: null, origin: "null", parentOrigin: homeOrigin, expiresAt: 120_000 }); + return { target: requested, attach_kind: "iframe", expires_at: 120, + route: `/apps/${requested}/#home_token=fresh-frame` }; + }, + }); + for (const name of ["homeMessageContext", "homeLaunchTokenFromRoute", "retireLaunchedAppContext", "cancelFrameRenewal", + "cancelBrowserAuthorityRenewalsForToken", "openLibraryPicker", "validPickerIdentity", "currentLibraryPicker", "settleLibraryPicker", "cancelLibraryPicker", "acceptLibraryPicker", + "deliverMessageToHomeGuiTargetFrame", "settleFrameRenewal", "replyToShellRequest", "homeSummarySignedIn", "homeSummaryHasProofBoundSession", + "renewExpiringFrames", "refreshSignedHomeSession"]) + vm.runInContext(sourceFunction(name), context); + if (hostSource.includes("function transferFrameAssociations(")) vm.runInContext(sourceFunction("transferFrameAssociations"), context); + const start = hostSource.indexOf('window.addEventListener("message", (event) => {'); + vm.runInContext(hostSource.slice(start, hostSource.indexOf("\n});", start) + 4), context); + const client = createHomeNavigationClient({ homeToken: currentToken, homeOrigin, target, enabled, windowRef, + onHomeToken(token) { currentToken = token; } }); + return { client, context, frames, message, receipt, commands, launchQueries, authority, frame, old, timers, home, windowRef, + hold() { holdPrepare = true; }, token: () => currentToken, launches: () => launches, refreshed: () => refreshed, + close() { context.retireLaunchedAppContext("old-frame"); }, + }; +} +const settle = async () => { for (let i = 0; i < 8; i++) await Promise.resolve(); }; + +for (const target of ["chat-room", "people", "documents", "assistant", "library"]) { + test(`Home refresh replaces an expiring open ${target} frame authority`, async () => { + const f = fixture(target); + await f.context.refreshSignedHomeSession(); await settle(); + assert.equal(f.refreshed(), 1); + assert.equal(f.token(), "fresh-frame"); + assert.equal(f.frames.has("old-frame"), false); + assert.equal(f.frames.get("fresh-frame").source, f.frame); + assert.equal(f.launches(), 1); + assert.equal(f.timers.size, 0); + }); +} + +test("A stolen frame token, wrong origin or another target cannot request renewal", async () => { + const f = fixture(); + const request = { type: "home:launch-target", homeToken: "old-frame", requestId: "renew-1", target: "chat-room", query: {} }; + f.message(request, {}); + f.message(request, f.frame, homeOrigin); + f.message({ ...request, target: "documents" }); + await settle(); + assert.equal(f.launches(), 0); + assert.equal(f.token(), "old-frame"); +}); + +for (const target of ["chat-room", "people", "documents", "assistant", "library"]) { + test(`${target} renewal refuses unexpected query keys and picker authority`, async () => { + for (const query of [{ unexpected: "value" }, { pickerRequestId: "foreign-picker" }]) { + const f = fixture(target); + f.client.setQuery(query); + await assert.rejects(f.client.renewAuthority(), /could not reconnect/); + assert.equal(f.launches(), 0); + assert.equal(f.token(), "old-frame"); + } + }); +} + +for (const [target, query] of [["chat-room", { conversation_id: "direct:fixture" }], + ["documents", { doc: "did:fixture" }], ["documents", { objectUri: "library://fixture/file" }], + ["library", { uri: "library://fixture/folder" }]]) { + test(`${target} renewal accepts its ${Object.keys(query)[0]} selector`, async () => { + const f = fixture(target); + f.client.setQuery(query); + await f.client.renewAuthority(); + assert.equal(f.token(), "fresh-frame"); + assert.deepEqual(JSON.parse(JSON.stringify(f.launchQueries[0])), query); + }); +} + +test("Home's own refused authority leaves the registered app unchanged", async () => { + const f = fixture(); f.authority.signed_in = false; + await assert.rejects(f.client.renewAuthority(), /Sign in to Home/); + assert.equal(f.token(), "old-frame"); + assert.equal(f.frames.has("fresh-frame"), false); +}); + +for (const invalidation of ["close", "principal", "sign-out"]) { + test(`${invalidation} during renewal rejects late receipts`, async () => { + const f = fixture(); f.hold(); + const pending = f.client.renewAuthority(); + const rejected = assert.rejects(pending); + assert.equal(f.client.renewAuthority(), pending); + await settle(); + const command = f.commands.find(c => c.phase === "prepare"); + assert.ok(command); + f.receipt({ ...command, requestId: "forged" }); + assert.equal(f.token(), "old-frame"); + if (invalidation === "close") f.close(); + if (invalidation === "principal") f.authority.principal_id = "bob"; + if (invalidation === "sign-out") f.authority.signed_in = false; + f.receipt(command); await settle(); + for (const timer of [...f.timers.values()]) timer(); + await rejected; + assert.equal(f.token(), "old-frame"); + assert.equal(f.frames.has("fresh-frame"), false); + }); +} + +function pickerFixture(renewTarget, openerTarget = "chat-room") { + const f = fixture(renewTarget, renewTarget !== "library"); + const opener = renewTarget === "library" ? { targetId: openerTarget, source: { postMessage(data) { delivered.push(data); } }, origin: "null" } : f.old; + const delivered = []; + if (opener === f.old) { + const post = f.frame.postMessage; + f.frame.postMessage = data => { delivered.push(data); post(data); }; + } + const picker = renewTarget === "library" ? f.old : { targetId: "library", source: {}, origin: "null" }; + const openerToken = opener === f.old ? "old-frame" : "opener"; + const pickerToken = picker === f.old ? "old-frame" : "picker"; + f.frames.set(openerToken, opener); f.frames.set(pickerToken, picker); + let record; + if (openerTarget === "chat-room") { + f.context.openTargetFromHomeGui = (target, { query }) => { + assert.equal(target, "library"); + record = opener.pickerRequest; + assert.equal(query.pickerRequestId, record.id); + record.pickerToken = pickerToken; + picker.pickerOwner = record; + }; + f.context.openLibraryPicker({ homeToken: openerToken, source: opener.source, targetId: openerTarget }, + { requestId: "pick-request", documentNonce: "document-nonce", query: { mode: "attach", returnTarget: openerTarget } }); + } else { + // Documents has no picker UI in this tree. Exercise association ownership + // without adding a new Documents selection contract to a renewal fix. + record = { id: "picker-id", requestId: "pick-request", documentNonce: "document-nonce", + openerToken, opener, source: opener.source, pickerToken, phase: "ready" }; + opener.pickerRequest = record; picker.pickerOwner = record; + } + return { ...f, record, delivered, opener, picker }; +} + +test("Library renewal accepts only its own in-flight picker without acquiring picker authority", async () => { + const f = pickerFixture("library"); + f.client.setQuery({ pickerRequestId: f.record.id }); + await f.client.renewAuthority(); + assert.equal(f.token(), "fresh-frame"); + assert.deepEqual(JSON.parse(JSON.stringify(f.launchQueries[0])), {}); + assert.equal(f.frames.get("fresh-frame").pickerOwner, f.record); +}); + +for (const invalidation of ["foreign token", "retired", "foreign record"]) { + test(`Library renewal refuses a picker with ${invalidation}`, async () => { + const f = pickerFixture("library"); + if (invalidation === "foreign token") f.record.pickerToken = "another-frame"; + if (invalidation === "retired") f.record.phase = "retired"; + if (invalidation === "foreign record") f.old.pickerOwner = { ...f.record }; + f.client.setQuery({ pickerRequestId: f.record.id }); + await assert.rejects(f.client.renewAuthority(), /could not reconnect/); + assert.equal(f.launches(), 0); + }); +} + +for (const target of ["chat-room", "library"]) { + test(`Library selection survives renewal of the ${target} frame`, async () => { + const f = pickerFixture(target); + await f.client.renewAuthority(); await settle(); + const fresh = f.frames.get("fresh-frame"); + assert.equal(f.context.currentLibraryPicker(f.record), true); + if (target === "library") { + assert.equal(f.record.pickerToken, "fresh-frame"); + assert.equal(fresh.pickerOwner, f.record); + assert.equal(f.old.pickerOwner, null); + } else { + assert.equal(f.record.opener, fresh); + assert.equal(f.record.openerToken, "fresh-frame"); + assert.equal(f.old.pickerRequest, null); + } + if (target === "library") { + assert.equal(await f.context.deliverMessageToHomeGuiTargetFrame("chat-room", { type: "chat-room:attach-library-item" }, + { targetId: "library", homeToken: "old-frame", source: f.picker.source }, f.record.id), false); + } + const delivery = f.context.deliverMessageToHomeGuiTargetFrame("chat-room", { type: "chat-room:attach-library-item" }, + { targetId: "library", homeToken: f.record.pickerToken, source: f.picker.source }, f.record.id); + const data = f.delivered.at(-1); + assert.equal(data.pickerId, f.record.id); + const reply = { ...data, type: "home:picker-accepted", accepted: true }; + assert.equal(f.context.acceptLibraryPicker({ homeToken: "old-frame", source: f.record.source }, reply), false); + assert.equal(f.record.phase, "delivering"); + assert.equal(f.context.acceptLibraryPicker({ homeToken: f.record.openerToken, source: f.record.source }, reply), true); + assert.equal(await delivery, true); + }); +} + +for (const target of ["documents", "library"]) { + test(`A Documents-owned picker record survives ${target} renewal`, async () => { + const f = pickerFixture(target, "documents"); + await f.client.renewAuthority(); await settle(); + assert.equal(f.context.currentLibraryPicker(f.record), true); + assert.equal(f.record.phase, "ready"); + assert.equal(f.record.openerToken, target === "documents" ? "fresh-frame" : "opener"); + assert.equal(f.record.pickerToken, target === "library" ? "fresh-frame" : "picker"); + }); +} + +for (const target of ["chat-room", "library"]) for (const closed of ["opener", "picker"]) { + test(`Closing ${closed} cancels the picker during ${target} renewal`, async () => { + const f = pickerFixture(target); f.hold(); + const pending = f.client.renewAuthority(); + const result = pending.catch(() => {}); + await settle(); + f.context.retireLaunchedAppContext(f.record[`${closed}Token`]); + assert.equal(f.record.phase, "retired"); + const prepare = f.commands.find(command => command.phase === "prepare"); + f.receipt(prepare); await settle(); + for (const timer of [...f.timers.values()]) timer(); + await result; + assert.equal(f.context.acceptLibraryPicker({ homeToken: f.record.openerToken, source: f.record.source }, {}), false); + assert.equal(f.record.phase, "retired"); + }); +} + + +test("Clipboard confirmation and replay state survive frame renewal", async () => { + const f = fixture("chat-room"); + let allow; + const writes = []; + const host = createHomeClipboardHost({ + clipboard: { writeText: async text => writes.push(text) }, + prompt: { request: () => new Promise(resolve => { allow = resolve; }), cancel() {} }, + cryptoRef: { randomUUID: () => "clipboard-generation" }, + setTimeoutFn: f.home.setTimeout, clearTimeoutFn: f.home.clearTimeout, + }); + f.context.homeClipboardHost = host; + f.old.clipboardState = createHomeClipboardFrameState(); + f.old.parentOrigin = homeOrigin; + const client = createHomeClipboardClient({ targetId: "chat-room", homeOrigin, homeToken: "old-frame", + targetWindow: f.home, sourceWindow: f.windowRef, cryptoRef: { randomUUID: () => "copy-request" }, + setTimeoutFn: f.home.setTimeout, clearTimeoutFn: f.home.clearTimeout }); + client.start(); + const state = f.old.clipboardState; + const generation = state.generation; + const copied = client.writeText("hello", { purpose: "profile.id" }); + await settle(); + assert.equal(typeof allow, "function"); + await f.client.renewAuthority(); + client.setHomeToken("fresh-frame"); + assert.equal(f.frames.get("fresh-frame").clipboardState, state); + assert.equal(f.old.clipboardState, null); + assert.equal(state.generation, generation); + assert.equal(state.retired, false); + assert.equal(state.inFlight.homeToken, "fresh-frame"); + assert.equal(state.replayIds.has("copy-request"), true); + allow(true); + assert.equal(await copied, true); + assert.deepEqual(writes, ["hello"]); + client.teardown(); +}); + +test("Pending Browser requests move ownership and retain their GUI reply identity", async () => { + const f = fixture(); + const record = { requestId: "browser-request", oldHomeToken: "old-frame", frameToken: "old-frame", timeout: 0 }; + f.context.pendingBrowserAuthorityRenewals.set(record.requestId, record); + await f.client.renewAuthority(); + assert.equal(f.context.pendingBrowserAuthorityRenewals.get(record.requestId), record); + assert.equal(record.frameToken, "fresh-frame"); + assert.equal(record.oldHomeToken, "old-frame"); + f.context.retireLaunchedAppContext("fresh-frame"); + assert.equal(f.context.pendingBrowserAuthorityRenewals.size, 0); +}); diff --git a/scripts/home-navigation-consumers-smoke.mjs b/scripts/home-navigation-consumers-smoke.mjs index 22d2d9912..77d5385a8 100644 --- a/scripts/home-navigation-consumers-smoke.mjs +++ b/scripts/home-navigation-consumers-smoke.mjs @@ -153,7 +153,8 @@ export async function exerciseNavigationConsumers(makeClient) { vm.runInContext(bridge[0], chat); chat.globalThis.elastosChatNavigation({ conversation_id: "direct:sha256:conversation-b" }); assert.deepEqual(reports["chat-room"], { conversation_id: "direct:sha256:conversation-b" }); - assert.equal(chat.currentQuery.conversation_id, "direct:sha256:conversation-b", "Reconnect must use the settled Chat selection"); + // The shared client retains this query for renewal; chat-room-reconnect.test.mjs + // exercises the real client and checks its launch request. chat.globalThis.elastosChatNavigation({}); assert.deepEqual(reports["chat-room"], {}, "explicit default retained direct selection"); chat.globalThis.elastosChatNavigation({ conversation_id: "direct:sha256:conversation-b" }); diff --git a/scripts/home-shell-bridge-smoke.mjs b/scripts/home-shell-bridge-smoke.mjs index 2171c7bed..8ee2393fd 100644 --- a/scripts/home-shell-bridge-smoke.mjs +++ b/scripts/home-shell-bridge-smoke.mjs @@ -2719,7 +2719,7 @@ await new Promise(resolve => setTimeout(resolve, 0)); assert(allLaunches() === beforeAllWrongChatMessages, "Chat recovery accepted a wrong source/token/origin/target/query", requests); async function waitForChatPrepare(requestId) { for (let attempt = 0; attempt < 30; attempt += 1) { - const command = shellMessages.find(m => m.payload?.command === "renew-chat-authority" + const command = shellMessages.find(m => m.payload?.command === "renew-frame-authority" && m.payload?.phase === "prepare" && m.payload?.requestId === requestId)?.payload; if (command) return command; await new Promise(resolve => setTimeout(resolve, 0)); @@ -2728,7 +2728,7 @@ async function waitForChatPrepare(requestId) { } function acknowledgeChat(command, ok, source = shellFrameWindow, extra = {}) { const freshHomeToken = new URL(command.launched.route, window.location.origin).hash.split("home_token=")[1]; - sendChildMessage("null", source, { type: "home:chat-authority-renewed", requestId: command.requestId, + sendChildMessage("null", source, { type: "home:frame-authority-renewed", requestId: command.requestId, oldHomeToken: command.homeToken, freshHomeToken, ok, homeToken: "gui-token", ...extra }); return freshHomeToken; } @@ -2775,8 +2775,7 @@ assert(unavailableReply.payload.error && chatReconnectTimers.size === 0, "GUI failure leaked fresh authority or recovery timer", chatReplies); assertChatTokenRetired(`chat-token-${chatLaunchCount}`); -// Reconnect: Chat's link request under its old authority closes when the -// reconnect retires that authority; the fresh authority can ask again. +// Renewal keeps Chat's pending link in the same document. window.open = recordLinkOpen; askLink(chatFrameWindow, "chat-token-1", "https://example.com/chat-old"); await settleLinks(); @@ -2786,9 +2785,9 @@ sendChildMessage("null", chatFrameWindow, reconnect("chat-success")); const successfulPrepare = await waitForChatPrepare("chat-success"); const freshChatToken = acknowledgeChat(successfulPrepare, true); const chatSuccess = await waitForShellResponse(chatReplies, "chat-success"); -assert(linkSheet().hidden, "reconnect left the old Chat link request open", linkSheet()); +assert(!linkSheet().hidden, "renewal closed the pending Chat link", linkSheet()); pressLink("open"); -assertOpenedLinks([], "the retired Chat authority's link opened"); +assertOpenedLinks(["https://example.com/chat-old"], "renewal lost the confirmed Chat link", "browser"); askLink(chatFrameWindow, freshChatToken, "https://example.com/chat-new"); await settleLinks(); assert(JSON.stringify(linkSheet()) === shownLinkSheet("Chat", "example.com", "https://example.com/chat-new"), @@ -2798,10 +2797,10 @@ assertOpenedLinks(["https://example.com/chat-new"], "the reconnected Chat link d window.open = strictWindowOpen; assert(chatSuccess.payload.result.route === successfulPrepare.launched.route && chatReconnectTimers.size === 0, "GUI acceptance did not return the canonical Runtime Chat launch", chatReplies); -assert(shellMessages.some(m => m.payload?.command === "renew-chat-authority" +assert(shellMessages.some(m => m.payload?.command === "renew-frame-authority" && m.payload.phase === "commit" && m.payload.requestId === "chat-success"), "Home omitted the same-frame metadata commit", shellMessages); function acknowledgeChatCommit(command, ok, source = shellFrameWindow) { - sendChildMessage("null", source, { type: "home:chat-authority-committed", requestId: command.requestId, + sendChildMessage("null", source, { type: "home:frame-authority-committed", requestId: command.requestId, oldHomeToken: command.homeToken, freshHomeToken: new URL(command.launched.route, window.location.origin).hash.split("home_token=")[1], ok, homeToken: "gui-token" }); @@ -2849,9 +2848,8 @@ for (const did of [contactDid, `did:key:z${"1".repeat(503)}`]) { "Home dropped the Chat DID before it reached People", opened); } assert(openCommands() === beforeDidActions + 2, "Home did not forward each valid DID once"); -// Stale result inside one app: the old authority's Runtime check is still in -// flight when the reconnect retires it and the new authority asks. The old -// result arrives first and is dropped; only the new request shows and opens. +// A Runtime link check in flight stays bound to the same document through +// renewal. The occupied prompt slot still prevents a second request. window.open = recordLinkOpen; externalLinkGate = deferred(); askLink(chatFrameWindow, freshChatToken, "https://example.com/chat-stale"); @@ -2863,17 +2861,16 @@ await waitForShellResponse(chatReplies, "chat-commit-refused"); askLink(chatFrameWindow, refusedCommitToken, "https://example.com/chat-current"); await settleLinks(); assert(linkSheet().hidden, "a link sheet showed before either Runtime check returned", linkSheet()); -const staleAndCurrentChecks = requests.filter((request) => request.url === "/api/apps/home/external-link").slice(-2); -assert(JSON.stringify(staleAndCurrentChecks.map((request) => request.body.app_token)) === - JSON.stringify([freshChatToken, refusedCommitToken]), -"the new Chat authority could not ask while the old check was in flight", staleAndCurrentChecks); +const pendingLinkCheck = requests.filter((request) => request.url === "/api/apps/home/external-link").at(-1); +assert(pendingLinkCheck.body.app_token === freshChatToken && pendingLinkCheck.body.url === "https://example.com/chat-stale", + "renewal replaced the pending link check", pendingLinkCheck); externalLinkGate.resolve(); externalLinkGate = null; await settleLinks(); -assert(JSON.stringify(linkSheet()) === shownLinkSheet("Chat", "example.com", "https://example.com/chat-current"), - "the old authority's late result replaced or hid the current request", linkSheet()); +assert(JSON.stringify(linkSheet()) === shownLinkSheet("Chat", "example.com", "https://example.com/chat-stale"), + "renewal lost the pending Runtime result", linkSheet()); pressLink("open"); -assertOpenedLinks(["https://example.com/chat-current"], "a stale Chat result opened instead of the current one", "browser"); +assertOpenedLinks(["https://example.com/chat-stale"], "the renewed Chat request did not open", "browser"); window.open = strictWindowOpen; acknowledgeChatCommit(refusedCommitPrepare, false, {}); const beforeWrongCommitReceipt = openCommands(); diff --git a/scripts/home-shell-recovery-smoke.mjs b/scripts/home-shell-recovery-smoke.mjs index 98b4e2f08..2eccfbec6 100644 --- a/scripts/home-shell-recovery-smoke.mjs +++ b/scripts/home-shell-recovery-smoke.mjs @@ -353,7 +353,9 @@ assert(window.location.href === "/home/", "recovery reload fallback did not retu // Exercise the real event-channel functions with an isolated clock and transport. const hostSource = readFileSync(new URL("../capsules/home/browser/home-shell-host.js", import.meta.url), "utf8"); -const eventFunctions = hostSource.slice(hostSource.indexOf("function bindHomeEventLifecycle() {")); +const renewalStart = hostSource.indexOf("function renewExpiringFrames() {"); +const eventFunctions = hostSource.slice(renewalStart, hostSource.indexOf("\n}", renewalStart) + 2) + + "\n" + hostSource.slice(hostSource.indexOf("function bindHomeEventLifecycle() {")); const eventConstants = hostSource.split("\n").filter(line => /^const HOME_EVENTS_/.test(line)).join("\n"); const settleEventTasks = () => new Promise(resolve => setImmediate(resolve)); @@ -412,6 +414,8 @@ function eventFixture() { { const f = eventFixture(); f.context.ensureHomeEventChannel(); + const renewalRequests = []; + f.context.launchedAppContexts.set("expired-frame", { expiresAt: 0, source: { postMessage: data => { if (data.type === "elastos.home.authority.request/v1") renewalRequests.push(data); } } }); const initial = f.streams[0]; initial.onerror(new TypeError("Home is offline")); assert(initial.closed, "the failed event stream stayed open"); @@ -427,6 +431,8 @@ function eventFixture() { await f.fireNext(); assert(f.counts().sessions === 1 && f.counts().summaries === 1, "recovery did not refresh the same signed session and summary"); assert(f.state.homeEventsCursor === "same-session", "recovery lost the event cursor"); + assert(renewalRequests.length === 1 && renewalRequests[0].homeToken === "expired-frame", + "event recovery did not renew the open frame"); assert(f.streams.length === 2 && !f.streams[1].closed, "recovery did not restore the event stream"); assert(f.streams[1].options.withCredentials === true, "recovery lost signed stream credentials"); assert(f.deadlines.every(ms => ms === 10_000), "outage probes or recovery refreshes lost their request deadline", f.deadlines); diff --git a/scripts/library-performance-smoke.mjs b/scripts/library-performance-smoke.mjs index cf14f88f2..76388dee2 100644 --- a/scripts/library-performance-smoke.mjs +++ b/scripts/library-performance-smoke.mjs @@ -9,6 +9,7 @@ const require = createRequire(new URL("../elastos/tools/browser-playwright-engin const { chromium } = require("playwright"); const capsuleRoot = path.resolve("capsules/library/browser"); +const homeNavigationClientPath = path.resolve("capsules/home/browser/home-navigation-client.js"); const homeClipboardClientPath = path.resolve( "capsules/home/browser/home-clipboard-client.js", ); @@ -132,6 +133,11 @@ function createAppServer() { return; } + if (url.pathname === "/apps/home/home-navigation-client.js") { + res.writeHead(200, { "content-type": "text/javascript; charset=utf-8" }); + createReadStream(homeNavigationClientPath).pipe(res); + return; + } if (url.pathname === "/apps/home/home-clipboard-client.js") { res.writeHead(200, { "content-type": "text/javascript; charset=utf-8" }); createReadStream(homeClipboardClientPath).pipe(res); diff --git a/scripts/open-app-token-consumers.test.mjs b/scripts/open-app-token-consumers.test.mjs new file mode 100644 index 000000000..ebac1ccf4 --- /dev/null +++ b/scripts/open-app-token-consumers.test.mjs @@ -0,0 +1,101 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; +import vm from "node:vm"; + +const read = path => readFileSync(new URL(`../${path}`, import.meta.url), "utf8"); +function fn(source, name) { + const plain = source.indexOf(`function ${name}(`); + assert.ok(plain >= 0, name); + const start = source.slice(plain - 6, plain) === "async " ? plain - 6 : plain; + return source.slice(start, source.indexOf("\n}", plain) + 2); +} +function fixture() { + const requests = [], clips = []; + let options; + const window = { location: { hash: "#home_token=old", search: "?home_origin=https://home.fixture" }, top: {}, + setTimeout, clearTimeout }; + const context = vm.createContext({ window, URLSearchParams, Headers, AbortController, + document: { getElementById: () => ({}), querySelector: () => ({}) }, + createHomeNavigationClient(value) { options = value; return {}; }, + createHomeClipboardClient(value) { + const clip = { token: value.homeToken, retired: false, start() {}, setHomeToken(token) { this.token = token; }, teardown() { this.retired = true; } }; + clips.push(clip); return clip; + }, + fetch: async (path, options) => { + requests.push({ path, token: new Headers(options.headers).get("x-elastos-home-token"), body: options.body }); + return { ok: true, status: 200, headers: new Headers({ "content-type": "application/json" }), + text: async () => "{}", json: async () => ({}) }; + }, + sharedFileName: value => value || "", readText: value => value || "", + DOCUMENTS_REQUEST_DEADLINE_MS: 1000, + }); + return { context, requests, clips, renew() { assert.ok(options?.onHomeToken); options.onHomeToken("fresh"); } }; +} + +test("People requests and Clipboard use the replacement token", async () => { + const f = fixture(), source = read("capsules/people/browser/people.js"); + vm.runInContext(source.slice(source.indexOf("const lockedShell"), source.indexOf("let localProfileId")), f.context); + vm.runInContext(fn(source, "fetchJson"), f.context); + await f.context.fetchJson("/people"); f.renew(); await f.context.fetchJson("/people"); + assert.deepEqual(f.requests.map(r => r.token), ["old", "fresh"]); + assert.equal(f.clips.length, 1); assert.equal(f.clips[0].retired, false); assert.equal(f.clips[0].token, "fresh"); +}); + +test("Documents keeps its draft and sends the next save with the replacement token", async () => { + const f = fixture(), source = read("capsules/documents/browser/documents.js"); + vm.runInContext(source.slice(source.indexOf("const state"), source.indexOf("const DOCUMENTS_WINDOW_CLOSE_REQUEST_TYPE")), f.context); + vm.runInContext(fn(source, "documentsApi"), f.context); + vm.runInContext('state.dirty = true; state.current = { text: "Keep my edits" };', f.context); + await f.context.documentsApi("/save", { method: "POST", body: "first revision" }); + f.renew(); + await f.context.documentsApi("/save", { method: "POST", body: "saved revision" }); + assert.deepEqual(f.requests.map(r => r.token), ["old", "fresh"]); + assert.equal(f.requests[1].body, "saved revision"); + assert.equal(vm.runInContext("state.dirty && state.current.text", f.context), "Keep my edits"); +}); + +test("Assistant requests and token listeners receive the replacement", async () => { + const f = fixture(), source = read("capsules/assistant/browser/harness-host.js"); + vm.runInContext(source.slice(source.indexOf("let homeToken"), source.indexOf("/* ---- shell-core")).replaceAll("export ", ""), f.context); + vm.runInContext(fn(source, "fetchJson"), f.context); + f.context.homeOrigin = () => "https://home.fixture"; + vm.runInContext(fn(source, "getHomeGuiLaunchToken"), f.context); + const app = read("capsules/assistant/browser/home-agent.js"); + vm.runInContext(app.slice(app.indexOf("const clipboardOptions"), app.indexOf("/* A copy Home")), f.context); + let observed; f.context.onHomeTokenChanged(token => { observed = token; }); + await f.context.fetchJson("/assistant"); f.renew(); await f.context.fetchJson("/assistant"); + assert.deepEqual(f.requests.map(r => r.token), ["old", "fresh"]); + assert.equal(observed, "fresh"); + assert.equal(f.clips[0].token, "fresh"); + assert.equal(f.clips[0].retired, false); +}); + +test("Library requests read the renewed state and replace Clipboard authority", async () => { + const f = fixture(), source = read("capsules/library/browser/src/app.js"); + vm.runInContext('const state = { homeToken: "old", mode: "browse" }; const queryParams = new URLSearchParams(window.location.search);', f.context); + vm.runInContext(read("capsules/library/browser/src/api.js").replaceAll("export ", ""), f.context); + vm.runInContext(source.slice(source.indexOf(' const homeOrigin ='), source.indexOf(' const elements =')), f.context); + await vm.runInContext('runtimeProviderApi("read", {})', f.context); + f.renew(); + await vm.runInContext('runtimeProviderApi("write", { text: "saved" })', f.context); + assert.deepEqual(f.requests.map(r => r.token), ["old", "fresh"]); + assert.equal(f.clips.length, 1); assert.equal(f.clips[0].retired, false); assert.equal(f.clips[0].token, "fresh"); +}); + +test("Only Home's exact proactive request reaches Browser's renewal adapter", () => { + const source = read("capsules/browser/browser/browser.js"); + const start = source.indexOf('window.addEventListener("message", (event) => {'); + let receive, renewals = 0; + const top = {}; + const context = vm.createContext({ window: { top, addEventListener(type, callback) { receive = callback; } }, + homeParentOrigin: "https://home.fixture", launchToken: "browser-old", requestHomeRelaunch() { renewals++; } }); + vm.runInContext(source.slice(start, source.indexOf(" if (isHomeBrowserWindowCloseRequest", start)) + "});", context); + const data = { type: "elastos.home.authority.request/v1", homeToken: "browser-old" }; + receive({ data, source: {}, origin: "https://home.fixture" }); + receive({ data, source: top, origin: "https://evil.fixture" }); + receive({ data: { ...data, homeToken: "other" }, source: top, origin: "https://home.fixture" }); + assert.equal(renewals, 0); + receive({ data, source: top, origin: "https://home.fixture" }); + assert.equal(renewals, 1); +}); diff --git a/scripts/people-discovery-smoke.mjs b/scripts/people-discovery-smoke.mjs index d63c1f4b4..16ce1874a 100644 --- a/scripts/people-discovery-smoke.mjs +++ b/scripts/people-discovery-smoke.mjs @@ -164,6 +164,7 @@ function setupEnvironment(name, replies) { }, }; globalThis.window = { + crypto: globalThis.crypto, location: { search: "?home_origin=http%3A%2F%2Flocalhost%3A61180", hash: "#home_token=people-test-token", @@ -214,6 +215,7 @@ function setupEnvironment(name, replies) { async function loadPeople() { const source = readFileSync(new URL("../capsules/people/browser/people.js", import.meta.url), "utf8") + .replace('"/apps/home/home-navigation-client.js"', JSON.stringify(new URL("../capsules/home/browser/home-navigation-client.js", import.meta.url).href)) .replace(/import \{ createHomeClipboardClient \} from [^;]+;/, "const createHomeClipboardClient = globalThis.createClipboardFixture;"); await import(`data:text/javascript;base64,${Buffer.from(source).toString("base64")}`); diff --git a/scripts/people-product-layout-smoke.mjs b/scripts/people-product-layout-smoke.mjs index 2d3547d85..7207a0489 100644 --- a/scripts/people-product-layout-smoke.mjs +++ b/scripts/people-product-layout-smoke.mjs @@ -265,7 +265,7 @@ function startServer() { return; } - if (["/apps/home/home-clipboard-client.js", "/apps/home/home-clipboard-protocol.js"].includes(url.pathname)) { + if (["/apps/home/home-navigation-client.js", "/apps/home/home-clipboard-client.js", "/apps/home/home-clipboard-protocol.js"].includes(url.pathname)) { const body = await readFile(join(repoRoot, "capsules/home/browser", url.pathname.split("/").at(-1))); response.writeHead(200, { "access-control-allow-origin": "null", "content-type": "text/javascript" }); response.end(body);