Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
feat(web): enable native desktop oauth sign-in (#726)
Genereed535647921
diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex dc78a30db..b306978d4 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -550,6 +550,9 @@ importers:unique-names-generator:specifier: ^4.7.1version: 4.7.1+ zod:+ specifier: ^4.4.3+ version: 4.4.3zustand:specifier: ^4.5.7version: 4.5.7(@types/[email protected])([email protected])diff --git a/scripts/ci/native-oauth-desktop.test.ts b/scripts/ci/native-oauth-desktop.test.tsnew file mode 100644index 000000000..296056a86--- /dev/null+++ b/scripts/ci/native-oauth-desktop.test.ts@@ -0,0 +1,52 @@+import { readFileSync } from "node:fs"+import { resolve } from "node:path"+import { describe, expect, it } from "vitest"+const root = resolve(import.meta.dirname, "../../src/desktop/src-tauri")+const read = (file: string) => readFileSync(resolve(root, file), "utf8")+type Capability = { identifier: string; local?: boolean; remote?: { urls: string[] }; windows: string[]; platforms?: string[]; permissions: (string | { identifier: string })[] }+type Config = { app: { security: { capabilities: (string | Capability)[] } }; plugins?: { "deep-link"?: unknown } }+const production: Config = JSON.parse(read("tauri.conf.json"))+const development: Config = JSON.parse(read("tauri.dev.conf.json"))+const capabilities = (config: Config): Capability[] => config.app.security.capabilities.map(c => typeof c === "string" ? JSON.parse(read(`capabilities/${c === "desktop-capability" ? "desktop" : c}.json`)) : c)++describe("desktop native OAuth security configuration", () => {+ it.each([production, development])("merged permissions cannot listen to raw events or read native storage/deep-link state", config => {+ const merged = capabilities(config)+ for (const permission of merged.flatMap(c => c.permissions).map(p => typeof p === "string" ? p : p.identifier)) {+ expect(permission).not.toMatch(/^(?:core:default$|core:event:|deep-link:|store:)/)+ }+ const oauth = merged.find(c => c.permissions.includes("native-oauth"))!+ expect(oauth.windows).toEqual(["main"])+ expect(oauth.platforms).toEqual(["linux", "macOS", "windows"])+ expect(oauth.remote?.urls).toEqual(config === production ? ["https://alook.ai"] : ["http://localhost:3000"])+ expect(oauth.local).toBe(config === development)+ })+ it("requires explicit command ACL while preserving preexisting desktop custom commands", () => {+ const build = read("build.rs")+ const native = read("permissions/native-oauth.toml")+ const existing = read("permissions/desktop-commands.toml")+ for (const command of ["snapshot", "listen", "unlisten", "prepare", "open_start", "pending_exchange", "reject_candidate", "finish", "cancel"]) {+ expect(build).toContain(`"native_oauth_${command}"`)+ expect(native).toContain(`"native_oauth_${command}"`)+ }+ for (const command of ["daemon_runtime_capability", "daemon_pair", "set_window_theme", "close_splashscreen", "desktop_zoom_shortcut"]) {+ expect(build).toContain(`"${command}"`)+ expect(existing).toContain(`"${command}"`)+ }+ expect(capabilities(production).find(c => c.identifier === "desktop-capability")?.permissions).toContain("desktop-commands")+ })+ it("registers desktop-only scheme and ordered single-instance intake without activating mobile", () => {+ expect(production.plugins?.["deep-link"]).toEqual({ desktop: { schemes: ["ai.alook.desktop"] } })+ const source = read("src/lib.rs")+ expect(source.indexOf("tauri_plugin_single_instance::init")).toBeLessThan(source.indexOf("tauri_plugin_deep_link::init"))+ expect(source.indexOf("tauri_plugin_deep_link::init")).toBeLessThan(source.indexOf("tauri_plugin_opener::init"))+ expect(read("Cargo.toml")).toContain('tauri-plugin-single-instance = { version = "2", features = ["deep-link"] }')+ const runtime = read("src/native_oauth_runtime.rs")+ expect(runtime.indexOf(".on_open_url(")).toBeLessThan(runtime.indexOf(".get_current()"))+ expect(runtime).toContain('#[cfg(target_os = "linux")]')+ expect(runtime).toContain(".register_all()")+ expect(runtime).toContain("channel.send(())")+ expect(source).toContain("PageLoadEvent::Started")+ expect(source).toContain("WindowEvent::Destroyed")+ })+})diff --git a/scripts/ci/workflow-contract.test.ts b/scripts/ci/workflow-contract.test.tsindex 43d52b088..c3d284484 100644--- a/scripts/ci/workflow-contract.test.ts+++ b/scripts/ci/workflow-contract.test.ts@@ -1017,11 +1017,12 @@ describe("Desktop image clipboard", () => {platforms: ["linux", "macOS", "windows"],local: true,remote: { urls: ["https://alook.ai"] },- permissions: [writeImagePermission],+ permissions: [writeImagePermission, "desktop-commands"],})expect(desktopDevConfig.app.security.capabilities).toEqual(["desktop-capability","external-links",+ expect.objectContaining({ identifier: "native-oauth-dev", local: true, remote: { urls: ["http://localhost:3000"] }, permissions: ["native-oauth"] }),])})})diff --git a/src/desktop/src-tauri/.gitignore b/src/desktop/src-tauri/.gitignoreindex ca0fe8d4d..03dd5a01b 100644--- a/src/desktop/src-tauri/.gitignore+++ b/src/desktop/src-tauri/.gitignore@@ -23,3 +23,5 @@/gen/android/app/tauri.properties/gen/android/app/src/main/jniLibs//gen/android/app/src/main/java/ai/alook/desktop/generated/++/permissions/autogenerated/diff --git a/src/desktop/src-tauri/Cargo.lock b/src/desktop/src-tauri/Cargo.lockindex 80346d68d..810880c3d 100644--- a/src/desktop/src-tauri/Cargo.lock+++ b/src/desktop/src-tauri/Cargo.lock@@ -38,20 +38,26 @@ version = "0.1.32"dependencies = ["base64 0.22.1","command-group",+ "getrandom 0.3.4","objc2","objc2-app-kit","objc2-foundation","serde","serde_json",+ "sha2",+ "subtle","tauri","tauri-build","tauri-plugin-clipboard-manager",+ "tauri-plugin-deep-link","tauri-plugin-dialog","tauri-plugin-notification","tauri-plugin-opener","tauri-plugin-single-instance",+ "tauri-plugin-store","tauri-plugin-updater","tokio",+ "url",][[package]]@@ -561,6 +567,26 @@ dependencies = ["crossbeam-utils",]+[[package]]+name = "const-random"+version = "0.1.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "87e00182fe74b066627d63b85fd550ac2998d4b0bd86bfed477a0ae4c7c71359"+dependencies = [+ "const-random-macro",+]++[[package]]+name = "const-random-macro"+version = "0.1.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f9d839f2a20b0aee515dc581a6172f2321f96cab76c1a38a4c584a194955390e"+dependencies = [+ "getrandom 0.2.17",+ "once_cell",+ "tiny-keccak",+]+[[package]]name = "cookie"version = "0.18.1"@@ -863,6 +889,15 @@ dependencies = ["syn 2.0.117",]+[[package]]+name = "dlv-list"+version = "0.5.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "442039f5147480ba31067cb00ada1adae6892028e40e45fc5de7b7df6dcc1b5f"+dependencies = [+ "const-random",+]+[[package]]name = "dom_query"version = "0.27.0"@@ -1557,6 +1592,12 @@ version = "0.12.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"+[[package]]+name = "hashbrown"+version = "0.14.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"+[[package]]name = "hashbrown"version = "0.15.5"@@ -2624,6 +2665,16 @@ version = "0.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"+[[package]]+name = "ordered-multimap"+version = "0.7.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "49203cdcae0030493bad186b28da2fa25645fa276a51b6fec8010d281e02ef79"+dependencies = [+ "dlv-list",+ "hashbrown 0.14.5",+]+[[package]]name = "ordered-stream"version = "0.2.0"@@ -3201,6 +3252,16 @@ dependencies = ["windows-sys 0.52.0",]+[[package]]+name = "rust-ini"+version = "0.21.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "796e8d2b6696392a43bea58116b667fb4c29727dc5abd27d6acf338bb4f688c7"+dependencies = [+ "cfg-if",+ "ordered-multimap",+]+[[package]]name = "rustc-hash"version = "2.1.2"@@ -4038,6 +4099,27 @@ dependencies = ["thiserror 2.0.18",]+[[package]]+name = "tauri-plugin-deep-link"+version = "2.4.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "92d489b8ecceae1cd09f6e1f7606f2095ac721cc8d54cf2f0e6bb377cc52cff6"+dependencies = [+ "dunce",+ "plist",+ "rust-ini",+ "serde",+ "serde_json",+ "tauri",+ "tauri-plugin",+ "tauri-utils",+ "thiserror 2.0.18",+ "tracing",+ "url",+ "windows-registry",+ "windows-result 0.3.4",+]+[[package]]name = "tauri-plugin-dialog"version = "2.7.1"@@ -4130,6 +4212,7 @@ dependencies = ["serde","serde_json","tauri",+ "tauri-plugin-deep-link","thiserror 2.0.18","tokio","tracing",@@ -4137,6 +4220,22 @@ dependencies = ["zbus",]+[[package]]+name = "tauri-plugin-store"+version = "2.4.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6708afbe549f176b712066e71648ba8fafba20789453718260c7ca356733cb0c"+dependencies = [+ "dunce",+ "serde",+ "serde_json",+ "tauri",+ "tauri-plugin",+ "thiserror 2.0.18",+ "tokio",+ "tracing",+]+[[package]]name = "tauri-plugin-updater"version = "2.10.1"@@ -4390,6 +4489,15 @@ dependencies = ["time-core",]+[[package]]+name = "tiny-keccak"+version = "2.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237"+dependencies = [+ "crunchy",+]+[[package]]name = "tinystr"version = "0.8.3"@@ -5349,6 +5457,17 @@ dependencies = ["windows-link 0.1.3",]+[[package]]+name = "windows-registry"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5b8a9ed28765efc97bbc954883f4e6796c33a06546ebafacbabee9696967499e"+dependencies = [+ "windows-link 0.1.3",+ "windows-result 0.3.4",+ "windows-strings 0.4.2",+]+[[package]]name = "windows-result"version = "0.3.4"diff --git a/src/desktop/src-tauri/Cargo.toml b/src/desktop/src-tauri/Cargo.tomlindex 9e7968497..80e10ae57 100644--- a/src/desktop/src-tauri/Cargo.toml+++ b/src/desktop/src-tauri/Cargo.toml@@ -17,9 +17,6 @@ serde = { version = "1", features = ["derive"] }serde_json = "1"tauri-plugin-opener = "2"-[package.metadata.cargo-machete]-ignored = ["serde_json"]-[target."cfg(not(any(target_os = \"android\", target_os = \"ios\")))".dependencies]tauri-plugin-notification = "2"tauri-plugin-updater = "2"@@ -28,7 +25,13 @@ tauri-plugin-clipboard-manager = "2"base64 = "0.22"tokio = { version = "1", features = ["macros"] }command-group = "5.0.1"-tauri-plugin-single-instance = "2"+tauri-plugin-single-instance = { version = "2", features = ["deep-link"] }+tauri-plugin-deep-link = "2"+tauri-plugin-store = "2"+getrandom = "0.3"+sha2 = "0.10"+subtle = "2"+url = "2"[target."cfg(target_os = \"macos\")".dependencies]objc2 = "0.6"diff --git a/src/desktop/src-tauri/build.rs b/src/desktop/src-tauri/build.rsindex d860e1e6a..505217d0f 100644--- a/src/desktop/src-tauri/build.rs+++ b/src/desktop/src-tauri/build.rs@@ -1,3 +1,21 @@fn main() {- tauri_build::build()+ tauri_build::try_build(tauri_build::Attributes::new().app_manifest(+ tauri_build::AppManifest::new().commands(&[+ "daemon_runtime_capability",+ "daemon_pair",+ "set_window_theme",+ "close_splashscreen",+ "desktop_zoom_shortcut",+ "native_oauth_snapshot",+ "native_oauth_listen",+ "native_oauth_unlisten",+ "native_oauth_prepare",+ "native_oauth_open_start",+ "native_oauth_pending_exchange",+ "native_oauth_reject_candidate",+ "native_oauth_finish",+ "native_oauth_cancel",+ ]),+ ))+ .expect("failed to build application permissions");}diff --git a/src/desktop/src-tauri/capabilities/desktop.json b/src/desktop/src-tauri/capabilities/desktop.jsonindex 07c810b86..2778a2c37 100644--- a/src/desktop/src-tauri/capabilities/desktop.json+++ b/src/desktop/src-tauri/capabilities/desktop.json@@ -8,5 +8,5 @@"remote": {"urls": ["https://alook.ai"]},- "permissions": ["clipboard-manager:allow-write-image"]+ "permissions": ["clipboard-manager:allow-write-image", "desktop-commands"]}diff --git a/src/desktop/src-tauri/capabilities/native-oauth.json b/src/desktop/src-tauri/capabilities/native-oauth.jsonnew file mode 100644index 000000000..d90d3928b--- /dev/null+++ b/src/desktop/src-tauri/capabilities/native-oauth.json@@ -0,0 +1,22 @@+{+ "$schema": "../gen/schemas/desktop-schema.json",+ "identifier": "native-oauth",+ "description": "Native OAuth commands without raw event, store or deep-link access",+ "windows": [+ "main"+ ],+ "platforms": [+ "linux",+ "macOS",+ "windows"+ ],+ "local": false,+ "remote": {+ "urls": [+ "https://alook.ai"+ ]+ },+ "permissions": [+ "native-oauth"+ ]+}diff --git a/src/desktop/src-tauri/permissions/desktop-commands.toml b/src/desktop/src-tauri/permissions/desktop-commands.tomlnew file mode 100644index 000000000..70ba98e88--- /dev/null+++ b/src/desktop/src-tauri/permissions/desktop-commands.toml@@ -0,0 +1,4 @@+[[permission]]+identifier = "desktop-commands"+description = "Existing main-window desktop commands"+commands.allow = ["daemon_runtime_capability", "daemon_pair", "set_window_theme", "close_splashscreen", "desktop_zoom_shortcut"]diff --git a/src/desktop/src-tauri/permissions/native-oauth.toml b/src/desktop/src-tauri/permissions/native-oauth.tomlnew file mode 100644index 000000000..02baec393--- /dev/null+++ b/src/desktop/src-tauri/permissions/native-oauth.toml@@ -0,0 +1,4 @@+[[permission]]+identifier = "native-oauth"+description = "Native OAuth orchestration for the trusted main WebView"+commands.allow = ["native_oauth_snapshot", "native_oauth_listen", "native_oauth_unlisten", "native_oauth_prepare", "native_oauth_open_start", "native_oauth_pending_exchange", "native_oauth_reject_candidate", "native_oauth_finish", "native_oauth_cancel"]diff --git a/src/desktop/src-tauri/src/commands.rs b/src/desktop/src-tauri/src/commands.rsindex 286025c10..389895368 100644--- a/src/desktop/src-tauri/src/commands.rs+++ b/src/desktop/src-tauri/src/commands.rs@@ -954,7 +954,7 @@ mod tests {let app_source = include_str!("lib.rs");let cargo_manifest = include_str!("../Cargo.toml");- for removed in ["autostart", "global_shortcut", "deep_link"] {+ for removed in ["autostart", "global_shortcut"] {assert!(!app_source.contains(removed));assert!(!cargo_manifest.contains(&removed.replace('_', "-")));}diff --git a/src/desktop/src-tauri/src/lib.rs b/src/desktop/src-tauri/src/lib.rsindex ef201d6c6..756f2b2ff 100644--- a/src/desktop/src-tauri/src/lib.rs+++ b/src/desktop/src-tauri/src/lib.rs@@ -1,5 +1,13 @@mod commands;+#[cfg(desktop)]+use tauri::Manager;++#[cfg(desktop)]+mod native_oauth;+#[cfg(desktop)]+mod native_oauth_runtime;+#[cfg(desktop)]mod updater;@@ -11,7 +19,15 @@ mod macos_window;#[cfg_attr(mobile, tauri::mobile_entry_point)]pub fn run() {- let builder = tauri::Builder::default().plugin(tauri_plugin_opener::init());+ let builder = tauri::Builder::default();+ #[cfg(desktop)]+ let builder = builder+ .plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| {+ commands::show_main_window(app);+ }))+ .plugin(tauri_plugin_deep_link::init())+ .plugin(tauri_plugin_store::Builder::default().build());+ let builder = builder.plugin(tauri_plugin_opener::init());// Desktop-only plugins#[cfg(desktop)]@@ -20,9 +36,6 @@ pub fn run() {.manage(zoom::ZoomState::default()).manage(updater::UpdatePromptState::default()).append_invoke_initialization_script(zoom::shortcut_script(std::env::consts::OS))- .plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| {- commands::show_main_window(app);- })).plugin(tauri_plugin_notification::init()).plugin(tauri_plugin_updater::Builder::new().build()).plugin(tauri_plugin_dialog::init())@@ -66,10 +79,22 @@ fn run_desktop(mut builder: tauri::Builder<tauri::Wry>) {commands::set_window_theme,commands::close_splashscreen,zoom::desktop_zoom_shortcut,+ native_oauth_runtime::native_oauth_snapshot,+ native_oauth_runtime::native_oauth_listen,+ native_oauth_runtime::native_oauth_unlisten,+ native_oauth_runtime::native_oauth_prepare,+ native_oauth_runtime::native_oauth_open_start,+ native_oauth_runtime::native_oauth_pending_exchange,+ native_oauth_runtime::native_oauth_reject_candidate,+ native_oauth_runtime::native_oauth_finish,+ native_oauth_runtime::native_oauth_cancel,]);// System tray + window setup (desktop only)builder = builder.setup(|app| {+ if native_oauth_runtime::setup(app.handle()).is_err() {+ eprintln!("native OAuth storage unavailable");+ }zoom::restore(app)?;commands::setup_tray(app)?;updater::auto_check_updates(app.handle().clone());@@ -93,7 +118,6 @@ fn run_desktop(mut builder: tauri::Builder<tauri::Wry>) {// macOS: inset the webview with rounded corners, window bg as frame#[cfg(target_os = "macos")]{- use tauri::Manager;if let Some(window) = app.get_webview_window("main") {commands::set_window_theme(window.clone(), false);macos_window::setup_inset_webview(&window);@@ -103,7 +127,18 @@ fn run_desktop(mut builder: tauri::Builder<tauri::Wry>) {Ok(())});+ builder = builder.on_page_load(|webview, payload| {+ if webview.label() == "main"+ && matches!(payload.event(), tauri::webview::PageLoadEvent::Started)+ {+ native_oauth_runtime::retire_listener(webview.app_handle());+ }+ });+builder = builder.on_window_event(|window, event| {+ if window.label() == "main" && matches!(event, tauri::WindowEvent::Destroyed) {+ native_oauth_runtime::retire_listener(window.app_handle());+ }#[cfg(target_os = "macos")]if window.label() == "main"&& matches!(@@ -111,7 +146,6 @@ fn run_desktop(mut builder: tauri::Builder<tauri::Wry>) {tauri::WindowEvent::Resized(_) | tauri::WindowEvent::ScaleFactorChanged { .. }){- use tauri::Manager;if let Some(webview) = window.app_handle().get_webview_window("main") {macos_window::update_inset_webview(&webview);}diff --git a/src/desktop/src-tauri/src/native_oauth.rs b/src/desktop/src-tauri/src/native_oauth.rsnew file mode 100644index 000000000..11d75fa98--- /dev/null+++ b/src/desktop/src-tauri/src/native_oauth.rs@@ -0,0 +1,675 @@+use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};+use serde::{Deserialize, Serialize};+use sha2::{Digest, Sha256};+use subtle::ConstantTimeEq;++pub const ATTEMPT_TTL: u64 = 10 * 60 * 1000;+const CANDIDATE_TTL: u64 = 2 * 60 * 1000;+const MAX_CANDIDATES: usize = 8;++fn random_secret() -> Result<String, &'static str> {+ let mut bytes = [0u8; 32];+ getrandom::fill(&mut bytes).map_err(|_| "random_unavailable")?;+ Ok(URL_SAFE_NO_PAD.encode(bytes))+}++fn hash(value: &str) -> String {+ Sha256::digest(value.as_bytes())+ .iter()+ .map(|b| format!("{b:02x}"))+ .collect()+}++fn challenge(value: &str) -> String {+ URL_SAFE_NO_PAD.encode(Sha256::digest(value.as_bytes()))+}++fn equal(a: &str, b: &str) -> bool {+ bool::from(a.as_bytes().ct_eq(b.as_bytes()))+}++fn token(value: &str, min: usize, max: usize) -> bool {+ (min..=max).contains(&value.len())+ && value+ .bytes()+ .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')+}++fn safe_candidate(value: &str) -> bool {+ value.starts_with('/')+ && !value.starts_with("//")+ && !value.contains(['\\', '#'])+ && !value.chars().any(|c| c <= '\u{1f}' || c == '\u{7f}')+}++fn decode(value: &str) -> Option<String> {+ let mut result = Vec::new();+ let mut bytes = value.bytes();+ while let Some(b) = bytes.next() {+ if b == b'%' {+ let high = (bytes.next()? as char).to_digit(16)?;+ let low = (bytes.next()? as char).to_digit(16)?;+ result.push((high * 16 + low) as u8);+ } else {+ result.push(b);+ }+ }+ String::from_utf8(result).ok()+}++pub fn safe_redirect(value: &str) -> bool {+ if value.len() > 2048 || !safe_candidate(value) {+ return false;+ }+ let mut current = value.to_string();+ for depth in 0..8 {+ let Some(next) = decode(¤t) else {+ return depth > 0;+ };+ if next == current {+ break;+ }+ if !safe_candidate(&next) {+ return false;+ }+ current = next;+ if depth == 7 {+ return false;+ }+ }+ let base = url::Url::parse("https://alook.invalid").unwrap();+ base.join(value).is_ok_and(|u| u.origin() == base.origin())+}++#[derive(Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase", deny_unknown_fields)]+struct Candidate {+ id: String,+ code: Option<String>,+ status: Option<String>,+ expires_at: u64,+ dispatched: bool,+}++#[derive(Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase", deny_unknown_fields)]+struct Attempt {+ id: String,+ state: String,+ verifier: String,+ provider: String,+ redirect_path: String,+ expires_at: u64,+ waiting: bool,+ candidates: Vec<Candidate>,+}++#[derive(Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase", deny_unknown_fields)]+pub struct Record {+ version: u8,+ owner_key: String,+ attempt: Option<Attempt>,+}++#[derive(Serialize)]+#[serde(rename_all = "camelCase")]+pub struct Registration {+ pub attempt_id: String,+ state_hash: String,+ code_challenge: String,+ instance_key_hash: String,+ provider: String,+ platform: String,+ redirect_path: String,+}++#[derive(Serialize)]+#[serde(rename_all = "camelCase")]+pub struct Snapshot {+ pub attempt_id: String,+ provider: String,+ redirect_path: String,+ expires_at: u64,+ waiting: bool,+}++#[derive(Serialize)]+#[serde(rename_all = "camelCase")]+pub struct Proof {+ attempt_id: String,+ state: String,+ verifier: String,+}++#[derive(Serialize)]+#[serde(rename_all = "camelCase")]+pub struct Exchange {+ #[serde(flatten)]+ proof: Proof,+ candidate_id: String,+ code: Option<String>,+ status: Option<String>,+ was_dispatched: bool,+}++fn allowed_status(value: &str) -> bool {+ matches!(+ value,+ "access_denied"+ | "provider_error"+ | "oauth_callback_failed"+ | "start_failed"+ | "invalid_handoff"+ )+}++fn parse_callback(serialized: &str) -> Option<(String, Option<String>, Option<String>)> {+ if serialized.len() > 512 {+ return None;+ }+ let query = serialized.strip_prefix("ai.alook.desktop://auth/native/return?")?;+ let mut attempt = None;+ let mut code = None;+ let mut status = None;+ let mut count = 0;+ for pair in query.split('&') {+ count += 1;+ let (key, value) = pair.split_once('=')?;+ match key {+ "attempt" if attempt.is_none() && token(value, 22, 64) => {+ attempt = Some(value.to_string())+ }+ "code" if code.is_none() && token(value, 32, 128) => code = Some(value.to_string()),+ "status" if status.is_none() && allowed_status(value) => {+ status = Some(value.to_string())+ }+ _ => return None,+ }+ }+ if count != 2 || code.is_some() == status.is_some() {+ return None;+ }+ Some((attempt?, code, status))+}++pub fn valid_start(raw: &str, attempt: &str, debug: bool) -> bool {+ let origin = if debug {+ "http://localhost:3000"+ } else {+ "https://alook.ai"+ };+ token(attempt, 22, 64) && raw == format!("{origin}/auth/native/start?attempt={attempt}")+}++impl Record {+ pub fn new() -> Result<Self, &'static str> {+ Ok(Self {+ version: 1,+ owner_key: random_secret()?,+ attempt: None,+ })+ }++ pub fn restore(value: serde_json::Value, now: u64) -> Result<Self, &'static str> {+ let mut record: Self = serde_json::from_value(value).map_err(|_| "invalid_store")?;+ if record.version != 1 || !token(&record.owner_key, 43, 43) {+ return Err("invalid_store");+ }+ if let Some(a) = &record.attempt {+ if !token(&a.id, 43, 43)+ || !token(&a.state, 43, 43)+ || !token(&a.verifier, 43, 43)+ || !matches!(a.provider.as_str(), "github" | "google")+ || !safe_redirect(&a.redirect_path)+ || a.expires_at > now.saturating_add(ATTEMPT_TTL)+ || a.candidates.len() > MAX_CANDIDATES+ || a.candidates.iter().any(|c| {+ !token(&c.id, 43, 43)+ || c.code.is_some() == c.status.is_some()+ || c.code.as_ref().is_some_and(|v| !token(v, 32, 128))+ || c.status.as_ref().is_some_and(|v| !allowed_status(v))+ || c.expires_at > a.expires_at+ || c.expires_at > now.saturating_add(CANDIDATE_TTL)+ })+ {+ return Err("invalid_store");+ }+ }+ record.cleanup(now);+ Ok(record)+ }++ pub fn cleanup(&mut self, now: u64) {+ if self.attempt.as_ref().is_some_and(|a| a.expires_at <= now) {+ self.attempt = None;+ }+ if let Some(a) = &mut self.attempt {+ a.candidates.retain(|c| c.expires_at > now);+ }+ }++ pub fn prepare(+ &mut self,+ provider: &str,+ redirect_path: &str,+ platform: &str,+ now: u64,+ ) -> Result<Registration, &'static str> {+ if !matches!(provider, "github" | "google")+ || !safe_redirect(redirect_path)+ || !matches!(platform, "macos" | "windows" | "linux")+ {+ return Err("invalid_request");+ }+ let a = Attempt {+ id: random_secret()?,+ state: random_secret()?,+ verifier: random_secret()?,+ provider: provider.into(),+ redirect_path: redirect_path.into(),+ expires_at: now + ATTEMPT_TTL,+ waiting: false,+ candidates: Vec::new(),+ };+ let registration = Registration {+ attempt_id: a.id.clone(),+ state_hash: hash(&a.state),+ code_challenge: challenge(&a.verifier),+ instance_key_hash: hash(&self.owner_key),+ provider: provider.into(),+ platform: platform.into(),+ redirect_path: redirect_path.into(),+ };+ self.attempt = Some(a);+ Ok(registration)+ }++ pub fn snapshot(&self) -> Option<Snapshot> {+ self.attempt.as_ref().map(|a| Snapshot {+ attempt_id: a.id.clone(),+ provider: a.provider.clone(),+ redirect_path: a.redirect_path.clone(),+ expires_at: a.expires_at,+ waiting: a.waiting,+ })+ }++ pub fn open(+ &mut self,+ attempt_id: &str,+ start_url: &str,+ debug: bool,+ ) -> Result<(), &'static str> {+ let a = self.attempt.as_mut().ok_or("no_attempt")?;+ if !equal(&a.id, attempt_id) || a.waiting || !valid_start(start_url, attempt_id, debug) {+ return Err("invalid_start");+ }+ a.waiting = true;+ Ok(())+ }++ pub fn intake(&mut self, url: &url::Url, now: u64) -> Result<bool, &'static str> {+ let Some((id, code, status)) = parse_callback(url.as_str()) else {+ return Ok(false);+ };+ let Some(a) = self.attempt.as_mut() else {+ return Ok(false);+ };+ if !equal(&a.id, &id) || !a.waiting || a.expires_at <= now {+ return Ok(false);+ }+ if a.candidates+ .iter()+ .any(|c| c.code == code && c.status == status)+ {+ return Ok(false);+ }+ if a.candidates.len() >= MAX_CANDIDATES {+ return Ok(false);+ }+ a.candidates.push(Candidate {+ id: random_secret()?,+ code,+ status,+ expires_at: (now + CANDIDATE_TTL).min(a.expires_at),+ dispatched: false,+ });+ Ok(true)+ }++ pub fn pending(&mut self) -> Option<Exchange> {+ let a = self.attempt.as_mut()?;+ let c = a.candidates.first_mut()?;+ let result = Exchange {+ proof: Proof {+ attempt_id: a.id.clone(),+ state: a.state.clone(),+ verifier: a.verifier.clone(),+ },+ candidate_id: c.id.clone(),+ code: c.code.clone(),+ status: c.status.clone(),+ was_dispatched: c.dispatched,+ };+ c.dispatched = true;+ Some(result)+ }++ pub fn reject(&mut self, attempt_id: &str, candidate_id: &str) {+ if let Some(a) = self.attempt.as_mut().filter(|a| equal(&a.id, attempt_id)) {+ a.candidates.retain(|c| !equal(&c.id, candidate_id));+ }+ }++ pub fn finish(&mut self, attempt_id: &str, candidate_id: &str) {+ if self.attempt.as_ref().is_some_and(|a| {+ equal(&a.id, attempt_id) && a.candidates.iter().any(|c| equal(&c.id, candidate_id))+ }) {+ self.attempt = None;+ }+ }++ pub fn cancel(&mut self, attempt_id: &str) -> Result<Option<Proof>, &'static str> {+ if !self+ .attempt+ .as_ref()+ .is_some_and(|a| equal(&a.id, attempt_id))+ {+ return Ok(None);+ }+ let owner_key = random_secret()?;+ let a = self.attempt.take().unwrap();+ self.owner_key = owner_key;+ Ok(Some(Proof {+ attempt_id: a.id,+ state: a.state,+ verifier: a.verifier,+ }))+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ const NOW: u64 = 1_000_000;+ fn waiting() -> Record {+ let mut r = Record::new().unwrap();+ let p = r.prepare("github", "/c/me?one=1", "macos", NOW).unwrap();+ r.open(+ &p.attempt_id,+ &format!(+ "https://alook.ai/auth/native/start?attempt={}",+ p.attempt_id+ ),+ false,+ )+ .unwrap();+ r+ }+ fn callback(r: &Record, value: &str) -> String {+ format!(+ "ai.alook.desktop://auth/native/return?attempt={}&code={value}",+ r.attempt.as_ref().unwrap().id+ )+ }+ #[test]+ fn pkce_and_registration_keep_secrets_native() {+ assert_eq!(+ challenge("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"),+ "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"+ );+ let mut r = Record::new().unwrap();+ let p = r.prepare("github", "/c/me", "macos", NOW).unwrap();+ let json = serde_json::to_string(&p).unwrap();+ let a = r.attempt.as_ref().unwrap();+ for secret in [&a.state, &a.verifier, &r.owner_key] {+ assert!(!json.contains(secret));+ }+ assert_ne!(a.state, a.verifier);+ let old_id = p.attempt_id;+ let next = r.prepare("google", "/c/me", "windows", NOW).unwrap();+ assert_eq!(p.instance_key_hash, next.instance_key_hash);+ assert_ne!(old_id, next.attempt_id);+ r.cancel(&next.attempt_id).unwrap();+ let next = r.prepare("google", "/c/me", "linux", NOW).unwrap();+ assert_ne!(p.instance_key_hash, next.instance_key_hash);+ }+ #[test]+ fn redirects_match_the_shared_nested_decode_contract() {+ for path in ["/c/me", "/c/me?tab=hello%20world", "/c?x=%25", "/%E4%B8%AD"] {+ assert!(safe_redirect(path), "{path}");+ }+ for path in [+ "https://evil.test",+ "//evil",+ "/\\evil",+ "/a#b",+ "/%5cevil",+ "/%252f%252fevil",+ "/x\n",+ "/%00",+ "/%zz",+ ] {+ assert!(!safe_redirect(path), "{path}");+ }+ assert!(!safe_redirect(&format!("/{}", "a".repeat(2048))));+ }+ #[test]+ fn serialized_callback_parser_rejects_noncanonical_direct_input() {+ let r = waiting();+ let good = callback(&r, &"c".repeat(32));+ assert!(parse_callback(&good).is_some());+ for bad in [+ format!("{good}&x=1"),+ format!("{good}&status=access_denied"),+ format!("{good}#fragment"),+ good.replace("//auth/", "//user@auth/"),+ good.replace("/native/", "/x/../native/"),+ good.replace("attempt=", "attempt=x&attempt="),+ good.replace("code=", "code=&code="),+ good.replace("ai.alook.desktop", "ai.alook"),+ good.replace("code=", "c%6fde="),+ ] {+ assert!(parse_callback(&bad).is_none());+ }+ }+ #[test]+ fn parsed_callback_intake_accepts_canonical_paths_and_deduplicates_aliases() {+ let original = waiting();+ let good = callback(&original, &"c".repeat(32));+ let aliases = [+ good.clone(),+ good.replace("/native/", "/x/../native/"),+ good.replace("/native/", "/%2e/native/"),+ ];+ for raw in &aliases {+ let url = url::Url::parse(raw).unwrap();+ assert_eq!(url.as_str(), good);+ let mut record = original.clone();+ assert!(record.intake(&url, NOW).unwrap());+ assert_eq!(+ record.pending().unwrap().code.as_deref(),+ Some("c".repeat(32).as_str())+ );+ }+ let mut record = original;+ for (index, raw) in aliases.iter().enumerate() {+ assert_eq!(+ record.intake(&url::Url::parse(raw).unwrap(), NOW).unwrap(),+ index == 0+ );+ }+ assert_eq!(record.attempt.as_ref().unwrap().candidates.len(), 1);+ let status = good.replace(&format!("code={}", "c".repeat(32)), "status=access_denied");+ assert!(record+ .intake(&url::Url::parse(&status).unwrap(), NOW)+ .unwrap());+ assert_eq!(record.attempt.as_ref().unwrap().candidates.len(), 2);+ }++ #[test]+ fn parsed_callback_intake_rejects_invalid_identity_query_and_attempt_without_mutation() {+ let mut record = waiting();+ let good = callback(&record, &"c".repeat(32));+ assert!(record+ .intake(&url::Url::parse(&good).unwrap(), NOW)+ .unwrap());+ let before = serde_json::to_value(&record).unwrap();+ let id = &record.attempt.as_ref().unwrap().id;+ for raw in [+ good.replace("ai.alook.desktop:", "ai.alook:"),+ good.replace("//auth/", "//evil/"),+ good.replace("//auth/", "//auth.evil/"),+ good.replace("//auth/", "//user@auth/"),+ good.replace("//auth/", "//auth:443/"),+ good.replace("/native/return", "/native/other"),+ good.replace("/native/return", "/%6eative/return"),+ format!("{good}#fragment"),+ format!("{good}#"),+ format!("{good}&extra=1"),+ format!("{good}&attempt={id}"),+ format!("{good}&code={}", "d".repeat(32)),+ format!("{good}&status=access_denied"),+ good.replace("attempt=", "att%65mpt="),+ good.replace("code=", "c%6fde="),+ good.replace(&"c".repeat(32), "%63"),+ good.replace(&"c".repeat(32), &"c".repeat(129)),+ good.replace(&format!("&code={}", "c".repeat(32)), ""),+ good.replace(&format!("code={}", "c".repeat(32)), "status=unknown"),+ good.replace(id, &"x".repeat(43)),+ ] {+ let url = url::Url::parse(&raw).unwrap();+ assert!(!record.intake(&url, NOW).unwrap());+ assert_eq!(serde_json::to_value(&record).unwrap(), before);+ }+ let next = url::Url::parse(&good.replace(&"c".repeat(32), &"d".repeat(32))).unwrap();+ assert!(!record.intake(&next, NOW + ATTEMPT_TTL).unwrap());+ assert_eq!(serde_json::to_value(&record).unwrap(), before);+ }++ #[test]+ fn callback_length_bound_applies_to_serialized_url() {+ let mut record = waiting();+ let good = callback(&record, &"c".repeat(32));+ let raw = good.replace("/native/", &format!("/{}../native/", "x".repeat(600) + "/"));+ assert!(raw.len() > 512);+ let url = url::Url::parse(&raw).unwrap();+ assert_eq!(url.as_str(), good);+ assert!(record.intake(&url, NOW).unwrap());+ let before = serde_json::to_value(&record).unwrap();+ let oversized = url::Url::parse(&format!("{good}&extra={}", "x".repeat(512))).unwrap();+ assert!(oversized.as_str().len() > 512);+ assert!(!record.intake(&oversized, NOW).unwrap());+ assert_eq!(serde_json::to_value(&record).unwrap(), before);+ }++ #[test]+ fn queue_is_bounded_deduplicated_and_wrong_candidate_cannot_delete_attempt() {+ let mut r = waiting();+ for i in 0..10 {+ let raw = callback(&r, &format!("{i:032}"));+ assert_eq!(+ r.intake(&url::Url::parse(&raw).unwrap(), NOW).unwrap(),+ i < 8+ );+ }+ let raw = callback(&r, &format!("{:032}", 0));+ assert!(!r.intake(&url::Url::parse(&raw).unwrap(), NOW).unwrap());+ let first = r.pending().unwrap();+ assert!(!first.was_dispatched);+ assert!(r.pending().unwrap().was_dispatched);+ r.reject("old", &first.candidate_id);+ assert_eq!(r.attempt.as_ref().unwrap().candidates.len(), 8);+ r.reject(&first.proof.attempt_id, &first.candidate_id);+ assert_eq!(r.attempt.as_ref().unwrap().candidates.len(), 7);+ assert_eq!(+ r.pending().unwrap().code.as_deref(),+ Some(format!("{:032}", 1).as_str())+ );+ assert!(r.snapshot().is_some());+ }+ #[test]+ fn cold_reload_expiry_and_corruption_fail_closed() {+ let mut r = waiting();+ let raw = callback(&r, &"c".repeat(32));+ r.intake(&url::Url::parse(&raw).unwrap(), NOW).unwrap();+ let first = r.pending().unwrap();+ let stored = serde_json::to_value(&r).unwrap();+ let mut restored = Record::restore(stored.clone(), NOW + 1).unwrap();+ assert!(restored.pending().unwrap().was_dispatched);+ restored.cleanup(NOW + CANDIDATE_TTL);+ assert!(restored.pending().is_none());+ assert!(restored.snapshot().is_some());+ restored.cleanup(NOW + ATTEMPT_TTL);+ assert!(restored.snapshot().is_none());+ let mut corrupt = stored;+ corrupt["version"] = 2.into();+ assert!(Record::restore(corrupt, NOW).is_err());+ assert!(Record::restore(serde_json::json!({"version":1}), NOW).is_err());+ r.finish(&first.proof.attempt_id, &first.candidate_id);+ assert!(r.snapshot().is_none());+ }+ #[test]+ fn replacement_cancel_and_old_completion_are_isolated() {+ let mut r = waiting();+ let raw = callback(&r, &"c".repeat(32));+ r.intake(&url::Url::parse(&raw).unwrap(), NOW).unwrap();+ let old = r.pending().unwrap();+ let new = r.prepare("google", "/c/me", "linux", NOW).unwrap();+ assert!(!r.intake(&url::Url::parse(&raw).unwrap(), NOW).unwrap());+ r.finish(&old.proof.attempt_id, &old.candidate_id);+ assert!(r.cancel(&old.proof.attempt_id).unwrap().is_none());+ let proof = r.cancel(&new.attempt_id).unwrap().unwrap();+ assert_eq!(proof.attempt_id, new.attempt_id);+ assert!(r.snapshot().is_none());+ assert!(r.cancel(&new.attempt_id).unwrap().is_none());+ }+ #[test]+ fn authenticated_cleanup_requires_current_attempt_and_survives_candidate_expiry() {+ let mut r = waiting();+ let raw = callback(&r, &"c".repeat(32));+ r.intake(&url::Url::parse(&raw).unwrap(), NOW).unwrap();+ let attempt_id = r.attempt.as_ref().unwrap().id.clone();+ let original_owner = r.owner_key.clone();+ let unchanged = serde_json::to_value(&r).unwrap();++ assert!(r.cancel("stale-attempt").unwrap().is_none());+ assert_eq!(serde_json::to_value(&r).unwrap(), unchanged);++ r.cleanup(NOW + CANDIDATE_TTL);+ assert!(r.attempt.as_ref().unwrap().candidates.is_empty());+ assert!(r.snapshot().is_some());++ let proof = r.cancel(&attempt_id).unwrap().unwrap();+ assert_eq!(proof.attempt_id, attempt_id);+ assert!(r.snapshot().is_none());+ assert_ne!(r.owner_key, original_owner);+ let rotated_owner = r.owner_key.clone();++ assert!(r.cancel(&attempt_id).unwrap().is_none());+ assert_eq!(r.owner_key, rotated_owner);+ }+ #[test]+ fn open_requires_current_unopened_attempt_and_fixed_build_origin() {+ let mut r = Record::new().unwrap();+ let p = r.prepare("github", "/c/me", "macos", NOW).unwrap();+ let good = format!(+ "https://alook.ai/auth/native/start?attempt={}",+ p.attempt_id+ );+ assert!(!valid_start(&good, &p.attempt_id, true));+ for url in [+ format!("{good}&extra=1"),+ good.replace("alook.ai", "evil.test"),+ format!("{good}#x"),+ ] {+ assert!(!valid_start(&url, &p.attempt_id, false));+ }+ assert!(r.open("old", &good, false).is_err());+ r.open(&p.attempt_id, &good, false).unwrap();+ assert!(r.open(&p.attempt_id, &good, false).is_err());+ assert!(r.prepare("apple", "/c/me", "macos", NOW).is_err());+ assert!(r.prepare("google", "/c/me", "ios", NOW).is_err());+ }+}diff --git a/src/desktop/src-tauri/src/native_oauth_runtime.rs b/src/desktop/src-tauri/src/native_oauth_runtime.rsnew file mode 100644index 000000000..9aa5db4bb--- /dev/null+++ b/src/desktop/src-tauri/src/native_oauth_runtime.rs@@ -0,0 +1,418 @@+use crate::native_oauth::{Exchange, Proof, Record, Registration, Snapshot};+use std::sync::{Arc, Mutex};+use tauri::{ipc::Channel, AppHandle, Manager, WebviewWindow};+use tauri_plugin_deep_link::DeepLinkExt;+use tauri_plugin_opener::OpenerExt;+use tauri_plugin_store::{Store, StoreExt};++#[derive(Default)]+struct Notifications<T> {+ next_id: u64,+ current: Option<(u64, T)>,+}++impl<T> Notifications<T> {+ fn install(&mut self, channel: T) -> u64 {+ self.next_id += 1;+ self.current = Some((self.next_id, channel));+ self.next_id+ }+ fn remove(&mut self, id: u64) {+ if self+ .current+ .as_ref()+ .is_some_and(|(current, _)| *current == id)+ {+ self.current = None;+ }+ }+ fn notify(&mut self, send: impl FnOnce(&T) -> bool) {+ if self+ .current+ .as_ref()+ .is_some_and(|(_, channel)| !send(channel))+ {+ self.current = None;+ }+ }+}++pub struct NativeOauthState {+ record: Mutex<Record>,+ store: Arc<Store<tauri::Wry>>,+ notifications: Mutex<Notifications<Channel<()>>>,+}++fn now() -> u64 {+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap_or_default()+ .as_millis() as u64+}++fn caller_allowed(label: &str, url: &url::Url, debug: bool) -> bool {+ let expected = if debug {+ "http://localhost:3000"+ } else {+ "https://alook.ai"+ };+ label == "main"+ && url.origin().ascii_serialization() == expected+ && url.username().is_empty()+ && url.password().is_none()+}++fn guard(window: &WebviewWindow) -> Result<(), &'static str> {+ let url = window.url().map_err(|_| "untrusted_caller")?;+ if caller_allowed(window.label(), &url, cfg!(debug_assertions)) {+ Ok(())+ } else {+ Err("untrusted_caller")+ }+}++fn commit_record<T>(+ current: &mut Record,+ time: u64,+ action: impl FnOnce(&mut Record) -> Result<T, &'static str>,+ persist: impl FnOnce(&Record, &Record) -> Result<(), &'static str>,+) -> Result<T, &'static str> {+ let mut next = current.clone();+ next.cleanup(time);+ let result = action(&mut next)?;+ persist(&next, current)?;+ *current = next;+ Ok(result)+}++impl NativeOauthState {+ fn transact<T>(+ &self,+ action: impl FnOnce(&mut Record) -> Result<T, &'static str>,+ ) -> Result<T, &'static str> {+ let mut current = self.record.lock().map_err(|_| "store_unavailable")?;+ commit_record(&mut current, now(), action, |next, prior| {+ self.store.set(+ "record",+ serde_json::to_value(next).map_err(|_| "store_unavailable")?,+ );+ if self.store.save().is_err() {+ self.store.set(+ "record",+ serde_json::to_value(prior).map_err(|_| "store_unavailable")?,+ );+ return Err("store_unavailable");+ }+ Ok(())+ })+ }+ fn notify(&self) {+ if let Ok(mut listeners) = self.notifications.lock() {+ listeners.notify(|channel| channel.send(()).is_ok());+ }+ }+}++pub fn retire_listener(app: &AppHandle) {+ if let Some(state) = app.try_state::<NativeOauthState>() {+ if let Ok(mut listeners) = state.notifications.lock() {+ listeners.current = None;+ }+ }+}++fn intake(app: &AppHandle, url: &url::Url) {+ let Some(state) = app.try_state::<NativeOauthState>() else {+ return;+ };+ if state+ .transact(|record| record.intake(url, now()))+ .unwrap_or(false)+ {+ crate::commands::show_main_window(app);+ state.notify();+ }+}++pub fn setup(app: &AppHandle) -> Result<(), Box<dyn std::error::Error>> {+ let path = app.path().app_data_dir()?.join("native-oauth.json");+ std::fs::create_dir_all(path.parent().ok_or("store_unavailable")?)?;+ #[cfg(unix)]+ {+ use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};+ std::fs::OpenOptions::new()+ .create(true)+ .write(true)+ .mode(0o600)+ .open(&path)?;+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?;+ }+ let store = app.store_builder(path).disable_auto_save().build()?;+ let record = store+ .get("record")+ .and_then(|value| Record::restore(value, now()).ok())+ .map(Ok)+ .unwrap_or_else(Record::new)?;+ let state = NativeOauthState {+ record: Mutex::new(record),+ store,+ notifications: Mutex::new(Notifications {+ next_id: 0,+ current: None,+ }),+ };+ state.transact(|_| Ok(()))?;+ #[cfg(target_os = "linux")]+ app.deep_link().register_all()?;+ app.manage(state);+ let handle = app.clone();+ app.deep_link().on_open_url(move |event| {+ for url in event.urls() {+ intake(&handle, &url);+ }+ });+ if let Some(urls) = app.deep_link().get_current()? {+ for url in urls {+ intake(app, &url);+ }+ }+ Ok(())+}++#[tauri::command]+pub fn native_oauth_snapshot(+ window: WebviewWindow,+ state: tauri::State<'_, NativeOauthState>,+) -> Result<Option<Snapshot>, &'static str> {+ guard(&window)?;+ state.transact(|record| Ok(record.snapshot()))+}++#[tauri::command]+pub fn native_oauth_listen(+ window: WebviewWindow,+ channel: Channel<()>,+) -> Result<u64, &'static str> {+ guard(&window)?;+ let state = window+ .app_handle()+ .try_state::<NativeOauthState>()+ .ok_or("store_unavailable")?;+ let id = state+ .notifications+ .lock()+ .map_err(|_| "listener_unavailable")?+ .install(channel);+ Ok(id)+}++#[tauri::command]+pub fn native_oauth_unlisten(+ window: WebviewWindow,+ state: tauri::State<'_, NativeOauthState>,+ registration_id: u64,+) -> Result<(), &'static str> {+ guard(&window)?;+ state+ .notifications+ .lock()+ .map_err(|_| "listener_unavailable")?+ .remove(registration_id);+ Ok(())+}++#[tauri::command]+pub fn native_oauth_prepare(+ window: WebviewWindow,+ state: tauri::State<'_, NativeOauthState>,+ provider: String,+ redirect_path: String,+) -> Result<Registration, &'static str> {+ guard(&window)?;+ state.transact(|record| record.prepare(&provider, &redirect_path, std::env::consts::OS, now()))+}++#[tauri::command]+pub fn native_oauth_open_start(+ window: WebviewWindow,+ state: tauri::State<'_, NativeOauthState>,+ attempt_id: String,+ start_url: String,+) -> Result<(), &'static str> {+ guard(&window)?;+ state.transact(|record| record.open(&attempt_id, &start_url, cfg!(debug_assertions)))?;+ window+ .app_handle()+ .opener()+ .open_url(start_url, None::<&str>)+ .map_err(|_| "browser_unavailable")+}++#[tauri::command]+pub fn native_oauth_pending_exchange(+ window: WebviewWindow,+ state: tauri::State<'_, NativeOauthState>,+) -> Result<Option<Exchange>, &'static str> {+ guard(&window)?;+ state.transact(|record| Ok(record.pending()))+}++#[tauri::command]+pub fn native_oauth_reject_candidate(+ window: WebviewWindow,+ state: tauri::State<'_, NativeOauthState>,+ attempt_id: String,+ candidate_id: String,+) -> Result<(), &'static str> {+ guard(&window)?;+ state.transact(|record| {+ record.reject(&attempt_id, &candidate_id);+ Ok(())+ })+}++#[tauri::command]+pub fn native_oauth_finish(+ window: WebviewWindow,+ state: tauri::State<'_, NativeOauthState>,+ attempt_id: String,+ candidate_id: String,+) -> Result<(), &'static str> {+ guard(&window)?;+ state.transact(|record| {+ record.finish(&attempt_id, &candidate_id);+ Ok(())+ })+}++#[tauri::command]+pub fn native_oauth_cancel(+ window: WebviewWindow,+ state: tauri::State<'_, NativeOauthState>,+ attempt_id: Option<String>,+) -> Result<Option<Proof>, &'static str> {+ guard(&window)?;+ state.transact(|record| {+ let id = attempt_id.or_else(|| record.snapshot().map(|a| a.attempt_id));+ match id {+ Some(id) => record.cancel(&id),+ None => Ok(None),+ }+ })+}++#[cfg(test)]+mod tests {+ use super::*;+ #[test]+ fn durable_commit_precedes_proof_release_and_notification() {+ let time = 1_000_000;+ let mut record = Record::new().unwrap();+ let attempt = record.prepare("github", "/c/me", "macos", time).unwrap();+ let before = serde_json::to_value(&record).unwrap();+ let failed = commit_record(+ &mut record,+ time,+ |r| r.cancel(&attempt.attempt_id),+ |_, _| Err("disk_full"),+ );+ assert!(matches!(failed, Err("disk_full")));+ assert_eq!(serde_json::to_value(&record).unwrap(), before);+ let mut disk = serde_json::Value::Null;+ let proof = commit_record(+ &mut record,+ time,+ |r| r.cancel(&attempt.attempt_id),+ |next, _| {+ disk = serde_json::to_value(next).unwrap();+ Ok(())+ },+ )+ .unwrap();+ assert!(proof.is_some());+ assert!(Record::restore(disk, time).unwrap().snapshot().is_none());+ }++ #[test]+ fn candidates_arriving_before_listener_or_after_failed_send_survive_reload() {+ let time = 1_000_000;+ let mut record = Record::new().unwrap();+ let attempt = record.prepare("github", "/c/me", "macos", time).unwrap();+ record+ .open(+ &attempt.attempt_id,+ &format!(+ "https://alook.ai/auth/native/start?attempt={}",+ attempt.attempt_id+ ),+ false,+ )+ .unwrap();+ let raw = format!(+ "ai.alook.desktop://auth/native/return?attempt={}&code={}",+ attempt.attempt_id,+ "c".repeat(32)+ );+ let mut disk = serde_json::Value::Null;+ let accepted = commit_record(+ &mut record,+ time,+ |r| r.intake(&url::Url::parse(&raw).unwrap(), time),+ |next, _| {+ disk = serde_json::to_value(next).unwrap();+ Ok(())+ },+ )+ .unwrap();+ assert!(accepted);+ let mut slots = Notifications::<()>::default();+ slots.notify(|_| panic!("not registered"));+ slots.install(());+ slots.notify(|_| false);+ let mut restored = Record::restore(disk, time).unwrap();+ assert!(restored.pending().is_some());+ assert!(!restored+ .intake(&url::Url::parse(&raw).unwrap(), time)+ .unwrap());+ }++ #[test]+ fn commands_require_main_and_exact_build_origin() {+ for (url, debug, expected) in [+ ("https://alook.ai/sign-in", false, true),+ ("http://localhost:3000/sign-in", true, true),+ ("http://localhost:3000/sign-in", false, false),+ ("https://alook.ai.evil.test", false, false),+ ("https://auth.alook.ai", false, false),+ ("https://alook.ai:8443", false, false),+ ("https://[email protected]", false, false),+ ] {+ let url = url::Url::parse(url).unwrap();+ assert_eq!(caller_allowed("main", &url, debug), expected);+ assert!(!caller_allowed("splash", &url, debug));+ }+ }+ #[test]+ fn listener_replacement_late_cleanup_and_failed_delivery_do_not_touch_candidates() {+ let mut slots = Notifications::<u8>::default();+ slots.notify(|_| panic!("no listener"));+ let old = slots.install(1);+ let new = slots.install(2);+ slots.remove(old);+ slots.notify(|value| {+ assert_eq!(*value, 2);+ true+ });+ slots.notify(|value| {+ assert_eq!(*value, 2);+ true+ });+ slots.notify(|_| false);+ assert!(slots.current.is_none());+ let latest = slots.install(3);+ slots.remove(new);+ assert_eq!(slots.current, Some((latest, 3)));+ slots.remove(latest);+ assert!(slots.current.is_none());+ }+}diff --git a/src/desktop/src-tauri/tauri.conf.json b/src/desktop/src-tauri/tauri.conf.jsonindex 98f8ed807..cfb99e9cd 100644--- a/src/desktop/src-tauri/tauri.conf.json+++ b/src/desktop/src-tauri/tauri.conf.json@@ -46,7 +46,8 @@"security": {"capabilities": ["desktop-capability",- "external-links"+ "external-links",+ "native-oauth"]}},@@ -56,6 +57,13 @@"https://alook.ai/api/desktop/update/{{target}}/{{arch}}/{{current_version}}?bundle_type={{bundle_type}}"],"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDg4QUQ2RTkxNENEOTZGRDEKUldUUmI5bE1rVzZ0aUY5SGgxVmRjZkUxeTNUKzlpZC8rQXQ3R0xDTFBsUFV4Kzc0U3pXc3hRV1MK"+ },+ "deep-link": {+ "desktop": {+ "schemes": [+ "ai.alook.desktop"+ ]+ }}}}diff --git a/src/desktop/src-tauri/tauri.dev.conf.json b/src/desktop/src-tauri/tauri.dev.conf.jsonindex 7d09a1df0..5e2974493 100644--- a/src/desktop/src-tauri/tauri.dev.conf.json+++ b/src/desktop/src-tauri/tauri.dev.conf.json@@ -2,7 +2,35 @@"$schema": "./gen/schemas/desktop-schema.json","app": {"security": {- "capabilities": ["desktop-capability", "external-links"]+ "capabilities": [+ "desktop-capability",+ "external-links",+ {+ "$schema": "../gen/schemas/desktop-schema.json",+ "identifier": "native-oauth-dev",+ "description": "Native OAuth commands without raw event, store or deep-link access",+ "windows": [+ "main"+ ],+ "platforms": [+ "linux",+ "macOS",+ "windows"+ ],+ "local": true,+ "remote": {+ "urls": [+ "http://localhost:3000"+ ]+ },+ "permissions": [+ "native-oauth"+ ]+ }+ ]}+ },+ "build": {+ "frontendDist": "http://localhost:3000/c"}}diff --git a/src/web/auth/index.test.ts b/src/web/auth/index.test.tsindex 80528713c..fd3d3c54d 100644--- a/src/web/auth/index.test.ts+++ b/src/web/auth/index.test.ts@@ -5,10 +5,12 @@ import { renderFaceSvg } from "../src/lib/avatar/face";import handler, {ANDROID_ASSET_LINKS,APPLE_APP_SITE_ASSOCIATION,+ AUTH_STATUS_PAGE_CSP,AUTH_RETURN_AVATAR_SEEDS,AUTH_WORKER_AASA_PATH,AUTH_WORKER_ASSET_LINKS_PATH,AUTH_WORKER_RETURN_PATH,+ renderAuthStatusPage,} from "./index";const ATTEMPT = "attempt_1234567890123456";@@ -117,6 +119,23 @@ describe("alook-auth Worker", () => {expect(body).not.toMatch(/<(?:img|link)\b/i);});+ it("shares the static no-action visual for unavailable native sign-in", () => {+ const body = renderAuthStatusPage("unavailable");++ expect(AUTH_STATUS_PAGE_CSP.split("; ")).toContain("script-src 'none'");+ expect(AUTH_STATUS_PAGE_CSP.split("; ")).toContain("font-src data:");+ expect(body).toContain(CANONICAL_LOGO);+ expect(body).toContain('<div class="avatar-field" aria-hidden="true">');+ expect(body.match(/class="avatar avatar-\d"/g)).toHaveLength(+ AUTH_RETURN_AVATAR_SEEDS.length,+ );+ expect(body).toContain('<h1 id="return-title">Sign-in unavailable</h1>');+ expect(body).toContain("Close this page and return to Alook to try again.");+ expect(body).not.toMatch(+ /(?:href|src)\s*=|<(?:script|form|img|link|iframe|object|embed)\b|data-open-alook|http-equiv=["']?refresh/i,+ );+ });+it.each(["",`?attempt=bad&code=${CODE}`,diff --git a/src/web/auth/index.ts b/src/web/auth/index.tsindex 0e4190acc..e77ed4d7f 100644--- a/src/web/auth/index.ts+++ b/src/web/auth/index.ts@@ -133,11 +133,22 @@ const SECURITY_HEADERS = {"Permissions-Policy": "camera=(), microphone=(), geolocation=()",} as const;-const RETURN_CSP = [+const AUTH_STATUS_PAGE_CSP_BASE = ["default-src 'none'","base-uri 'none'","form-action 'none'","frame-ancestors 'none'",+];++export const AUTH_STATUS_PAGE_CSP = [+ ...AUTH_STATUS_PAGE_CSP_BASE,+ "script-src 'none'",+ "style-src 'unsafe-inline'",+ "font-src data:",+].join("; ");++const RETURN_CSP = [+ ...AUTH_STATUS_PAGE_CSP_BASE,`script-src 'sha256-${RETURN_SCRIPT_SHA256}'`,"style-src 'unsafe-inline'","font-src data:",@@ -282,14 +293,40 @@ const PAGE_STYLE = `}`;-function returnPage(valid: boolean): string {- const detail = valid- ? "Continue in the Alook app to finish this sign-in."- : "This sign-in link is invalid.";- const control = valid+export type AuthStatusPageVariant = "return" | "invalid" | "unavailable";++const AUTH_STATUS_PAGE_COPY = {+ return: {+ documentTitle: "Return to Alook",+ heading: "Return to Alook",+ detail: "Continue in the Alook app to finish this sign-in.",+ },+ invalid: {+ documentTitle: "Return to Alook",+ heading: "Return to Alook",+ detail: "This sign-in link is invalid.",+ },+ unavailable: {+ documentTitle: "Sign-in unavailable · Alook",+ heading: "Sign-in unavailable",+ detail: "Close this page and return to Alook to try again.",+ },+} as const satisfies Record<AuthStatusPageVariant, {+ documentTitle: string;+ heading: string;+ detail: string;+}>;++export function renderAuthStatusPage(variant: AuthStatusPageVariant): string {+ const copy = AUTH_STATUS_PAGE_COPY[variant];+ const control = variant === "return"? `<button type="button" data-open-alook>Open Alook</button><script>${RETURN_SCRIPT}</script>`: "";- return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="light dark"><title>Return to Alook</title><style>${PAGE_STYLE}</style></head><body>${AVATAR_FIELD}<main><div class="brand"><span class="brand-mark" aria-hidden="true">${ALOOK_LOGO}</span><span class="brand-name">Alook</span></div><section aria-labelledby="return-title"><h1 id="return-title">Return to Alook</h1><p>${detail}</p>${control}</section></main></body></html>`;+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="light dark"><title>${copy.documentTitle}</title><style>${PAGE_STYLE}</style></head><body>${AVATAR_FIELD}<main><div class="brand"><span class="brand-mark" aria-hidden="true">${ALOOK_LOGO}</span><span class="brand-name">Alook</span></div><section aria-labelledby="return-title"><h1 id="return-title">${copy.heading}</h1><p>${copy.detail}</p>${control}</section></main></body></html>`;+}++function returnPage(valid: boolean): string {+ return renderAuthStatusPage(valid ? "return" : "invalid");}function response(diff --git a/src/web/package.json b/src/web/package.jsonindex 026b0b81b..8bc92709c 100644--- a/src/web/package.json+++ b/src/web/package.json@@ -128,6 +128,7 @@"tailwind-merge": "^3.6.0","tw-animate-css": "^1.4.0","unique-names-generator": "^4.7.1",+ "zod": "^4.4.3","zustand": "^4.5.7"},"devDependencies": {diff --git a/src/web/src/app/(app)/layout.tsx b/src/web/src/app/(app)/layout.tsxindex 2042dae5a..8d7ef3d6c 100644--- a/src/web/src/app/(app)/layout.tsx+++ b/src/web/src/app/(app)/layout.tsx@@ -5,6 +5,7 @@ import { SignupTracker } from "@/components/signup-tracker";import { SigninTracker } from "@/components/signin-tracker";import { DaemonUpdateNotice } from "@/components/daemon-update-notice";import { AuthenticatedContextMenuBoundary } from "@/components/authenticated-context-menu-boundary";+import { AuthenticatedNativeOauthCleanup } from "@/components/authenticated-native-oauth-cleanup";export const metadata: Metadata = {robots: { index: false, follow: false },@@ -20,6 +21,7 @@ export default async function AppLayout({return (<AuthenticatedContextMenuBoundary>+ <AuthenticatedNativeOauthCleanup /><SignupTracker /><SigninTracker /><DaemonUpdateNotice userId={session.user.id} />diff --git a/src/web/src/app/(auth)/sign-in/sign-in-client.tsx b/src/web/src/app/(auth)/sign-in/sign-in-client.tsxindex 4e0602883..7a6403d87 100644--- a/src/web/src/app/(auth)/sign-in/sign-in-client.tsx+++ b/src/web/src/app/(auth)/sign-in/sign-in-client.tsx@@ -12,7 +12,7 @@ import {FieldSeparator,} from "@/components/ui/field"import { SignInEmailField, SignInOtpField } from "./sign-in-fields"-import { SiGithub, SiGoogle } from "@icons-pack/react-simple-icons"+import { SocialSignIn } from "./social-sign-in"import { GradientBackground } from "@/components/gradient-background"import { Logo } from "@/components/logo"import { LandingShellMotion } from "@/components/home/landing-shell-motion"@@ -233,28 +233,7 @@ function SignInForm({ postLoginUrl, isProd }: { postLoginUrl: string; isProd: bo<FieldSeparator className="*:data-[slot=field-separator-content]:bg-card">Or continue with</FieldSeparator>- <Field className="grid grid-cols-2 gap-4">- <Button- variant="outline"- type="button"- onClick={() =>- signIn.social({ provider: "github", callbackURL: postLoginUrl })- }- >- <SiGithub className="size-4" />- GitHub- </Button>- <Button- variant="outline"- type="button"- onClick={() =>- signIn.social({ provider: "google", callbackURL: postLoginUrl })- }- >- <SiGoogle className="size-4" />- </Button>- </Field>+ <SocialSignIn postLoginUrl={postLoginUrl} /></FieldGroup>)}diff --git a/src/web/src/app/(auth)/sign-in/social-sign-in.test.ts b/src/web/src/app/(auth)/sign-in/social-sign-in.test.tsnew file mode 100644index 000000000..bb7f48b7d--- /dev/null+++ b/src/web/src/app/(auth)/sign-in/social-sign-in.test.ts@@ -0,0 +1,47 @@+import { createElement } from "react"+import TestRenderer, { act } from "react-test-renderer"+import { afterEach, describe, expect, it, vi } from "vitest"+import type { NativeOauthView } from "@/lib/native-oauth-client"+const mocks = vi.hoisted(() => ({ tauri: false, social: vi.fn(), start: vi.fn(), cancel: vi.fn(), dispose: vi.fn(), emit: undefined as undefined | ((view: NativeOauthView) => void) }))+vi.mock("@alook/shared", async importOriginal => ({ ...await importOriginal<typeof import("@alook/shared")>(), isTauri: () => mocks.tauri }))+vi.mock("@/lib/auth-client", () => ({ signIn: { social: mocks.social } }))+vi.mock("@/lib/native-oauth-client", () => ({ nativeOauthBrowserDeps: {}, createNativeOauthController: (_deps: unknown, changed: (view: NativeOauthView) => void) => {+ mocks.emit = changed+ return { connect: async () => changed({ phase: "idle", attempt: null }), start: mocks.start, cancel: mocks.cancel, dispose: mocks.dispose }+} }))+import { SocialSignIn } from "./social-sign-in"+let renderer: TestRenderer.ReactTestRenderer | undefined+afterEach(async () => { await act(async () => { renderer?.unmount() }); renderer = undefined; mocks.tauri = false; vi.clearAllMocks() })+function button(id: string) { return renderer!.root.findAllByType("button").find(b => b.props["data-testid"] === id)! }+describe("social sign-in native boundary", () => {+ it("preserves normal browser social login and callback destination", async () => {+ await act(async () => { renderer = TestRenderer.create(createElement(SocialSignIn, { postLoginUrl: "/c/me?tab=1" })) })+ await act(async () => { button("native-oauth-google").props.onClick() })+ expect(mocks.social).toHaveBeenCalledWith({ provider: "google", callbackURL: "/c/me?tab=1" })+ expect(mocks.start).not.toHaveBeenCalled()+ })+ it("never falls back to embedded social OAuth in Tauri, including unsupported apps", async () => {+ mocks.tauri = true+ await act(async () => { renderer = TestRenderer.create(createElement(SocialSignIn, { postLoginUrl: "/%5cevil" })) })+ await act(async () => { button("native-oauth-github").props.onClick() })+ expect(mocks.start).toHaveBeenCalledWith("github", "/c/me")+ expect(mocks.social).not.toHaveBeenCalled()+ await act(async () => { mocks.emit!({ phase: "unsupported", attempt: null }) })+ expect(button("native-oauth-google").props.disabled).toBe(true)+ expect(JSON.stringify(renderer!.toJSON())).toContain("You can still use email")+ })+ it("shows bounded progress, Cancel and Retry controls without rendering proof data", async () => {+ mocks.tauri = true+ await act(async () => { renderer = TestRenderer.create(createElement(SocialSignIn, { postLoginUrl: "/c/me" })) })+ const attempt = { attemptId: "opaque-id", provider: "google" as const, redirectPath: "/c/me", expiresAt: Date.now()+600_000, waiting: true }+ await act(async () => { mocks.emit!({ phase: "exchanging", attempt }) })+ expect(button("native-oauth-retry").props.disabled).toBe(true)+ expect(button("native-oauth-cancel").props.disabled).not.toBe(true)+ await act(async () => { button("native-oauth-cancel").props.onClick() })+ expect(mocks.cancel).toHaveBeenCalledOnce()+ await act(async () => { mocks.emit!({ phase: "error", message: "retry_required", attempt }) })+ await act(async () => { button("native-oauth-retry").props.onClick() })+ expect(mocks.start).toHaveBeenCalledWith("google", "/c/me")+ expect(JSON.stringify(renderer!.toJSON())).not.toContain("opaque-id")+ })+})diff --git a/src/web/src/app/(auth)/sign-in/social-sign-in.tsx b/src/web/src/app/(auth)/sign-in/social-sign-in.tsxnew file mode 100644index 000000000..76cdf6ebc--- /dev/null+++ b/src/web/src/app/(auth)/sign-in/social-sign-in.tsx@@ -0,0 +1,63 @@+"use client"++import { useEffect, useRef, useState } from "react"+import { isTauri, safeRedirectPath } from "@alook/shared"+import { SiGithub, SiGoogle } from "@icons-pack/react-simple-icons"+import { Button } from "@/components/ui/button"+import { Field } from "@/components/ui/field"+import { signIn } from "@/lib/auth-client"+import { createNativeOauthController, nativeOauthBrowserDeps, type NativeOauthView } from "@/lib/native-oauth-client"++const messages = {+ start_failed: "Couldn't open sign-in. Try again.",+ expired: "This sign-in attempt expired. Try again.",+ denied: "Sign-in was cancelled in your browser. You can try again.",+ invalid_callback: "That sign-in link wasn't valid. Waiting for your browser to finish.",+ retry_required: "Couldn't confirm sign-in. Try again to start a new attempt.",+ unavailable: "Sign-in is unavailable. Try again or use email.",+} as const++export function SocialSignIn({ postLoginUrl }: { postLoginUrl: string }) {+ const controller = useRef<ReturnType<typeof createNativeOauthController> | null>(null)+ const [native, setNative] = useState<NativeOauthView | null>(null)+ const lastProvider = useRef<"github" | "google">("github")+ useEffect(() => {+ if (!isTauri()) return+ const instance = createNativeOauthController(nativeOauthBrowserDeps, setNative)+ controller.current = instance+ void instance.connect()+ return () => { instance.dispose(); if (controller.current === instance) controller.current = null }+ }, [])+ const begin = (provider: "github" | "google") => {+ lastProvider.current = provider+ if (!isTauri()) { void signIn.social({ provider, callbackURL: postLoginUrl }); return }+ if (controller.current) void controller.current.start(provider, safeRedirectPath(postLoginUrl))+ }+ const busy = native?.phase === "initializing" || native?.phase === "preparing" || native?.phase === "exchanging" || native?.phase === "checking_status"+ const unsupported = native?.phase === "unsupported"+ const text = unsupported ? "Update Alook to sign in with GitHub or Google. You can still use email."+ : native?.message ? messages[native.message]+ : native?.phase === "preparing" ? "Opening sign-in in your browser…"+ : native?.phase === "exchanging" || native?.phase === "checking_status" ? "Confirming sign-in…"+ : native?.phase === "waiting" ? "Finish signing in in your browser."+ : undefined+ return (+ <>+ <Field className="grid grid-cols-2 gap-4">+ <Button variant="outline" type="button" disabled={busy || unsupported} data-testid="native-oauth-github" onClick={() => begin("github")}>+ <SiGithub className="size-4" />GitHub+ </Button>+ <Button variant="outline" type="button" disabled={busy || unsupported} data-testid="native-oauth-google" onClick={() => begin("google")}>+ <SiGoogle className="size-4" />Google+ </Button>+ </Field>+ {text && <p role={native?.phase === "error" || unsupported ? "alert" : "status"} className="text-sm text-muted-foreground" data-testid="native-oauth-status">{text}</p>}+ {!unsupported && native && (native.attempt || native.phase === "error" || native.phase === "preparing") && (+ <div className="flex gap-2">+ {(native.attempt || native.phase === "preparing") && <Button type="button" variant="ghost" data-testid="native-oauth-cancel" onClick={() => { void controller.current?.cancel() }}>Cancel</Button>}+ <Button type="button" variant="outline" disabled={busy} data-testid="native-oauth-retry" onClick={() => begin(native.attempt?.provider ?? lastProvider.current)}>Try again</Button>+ </div>+ )}+ </>+ )+}diff --git a/src/web/src/app/api/auth/native/native-routes.test.ts b/src/web/src/app/api/auth/native/native-routes.test.tsindex 627d5280a..165556465 100644--- a/src/web/src/app/api/auth/native/native-routes.test.ts+++ b/src/web/src/app/api/auth/native/native-routes.test.ts@@ -112,6 +112,31 @@ async function loadCallbackRoute() {return (await import("../../../auth/native/callback/route")).GET;}+async function expectNativeOauthErrorPage(response: Response, status: number) {+ expect(response.status).toBe(status);+ expect(response.headers.get("Cache-Control")).toContain("no-store");+ expect(response.headers.get("Content-Security-Policy")).toContain("default-src 'none'");+ expect(response.headers.get("Content-Security-Policy")).toContain("script-src 'none'");+ expect(response.headers.get("Content-Security-Policy")).toContain("font-src data:");+ const body = await response.text();+ expect(body).toContain('<div class="avatar-field" aria-hidden="true">');+ expect(body.match(/class="avatar avatar-\d"/g)).toHaveLength(7);+ expect(body).toContain('<span class="brand-mark" aria-hidden="true">');+ expect(body).toContain('<span class="brand-name">Alook</span>');+ expect(body).toContain('font-family: "DM Sans"');+ expect(body).toContain('font-family: "Caveat"');+ expect(body).toContain("@media (prefers-color-scheme: dark)");+ expect(body).toContain("@media (prefers-reduced-motion: reduce)");+ expect(body).toContain('<section aria-labelledby="return-title">');+ expect(body).toContain('<h1 id="return-title">Sign-in unavailable</h1>');+ expect(body).toContain("Close this page and return to Alook to try again.");+ expect(body).not.toContain(ATTEMPT);+ expect(body).not.toMatch(+ /(?:href|src)\s*=|<(?:script|form|img|link|iframe|object|embed)\b|data-open-alook|http-equiv=["']?refresh/i,+ );+ return body;+}+describe("native OAuth routes", () => {beforeEach(() => {vi.resetModules();@@ -227,7 +252,7 @@ describe("native OAuth routes", () => {const invalidStart = await start(new Request(`${BASE_URL}/auth/native/start?attempt=invalid`),);- expect(invalidStart.status).toBe(400);+ const startBody = await expectNativeOauthErrorPage(invalidStart, 400);expect(queryMocks.claimStart).not.toHaveBeenCalled();vi.resetModules();@@ -237,7 +262,8 @@ describe("native OAuth routes", () => {`${BASE_URL}/auth/native/callback?attempt=${ATTEMPT}&kind=invalid`,),);- expect(invalidCallback.status).toBe(400);+ const callbackBody = await expectNativeOauthErrorPage(invalidCallback, 400);+ expect(callbackBody).toBe(startBody);expect(queryMocks.getOpenedAttempt).not.toHaveBeenCalled();});@@ -271,7 +297,7 @@ describe("native OAuth routes", () => {}),}),);- expect(second.status).toBe(410);+ await expectNativeOauthErrorPage(second, 410);expect(authMocks.signInSocial).toHaveBeenCalledOnce();});@@ -290,7 +316,7 @@ describe("native OAuth routes", () => {new Request(`${BASE_URL}/auth/native/start?attempt=${ATTEMPT}`),);- expect(response.status).toBe(502);+ await expectNativeOauthErrorPage(response, 502);expect(queryMocks.failOpenedAttempt).toHaveBeenCalledWith(db,ATTEMPT,@@ -305,8 +331,7 @@ describe("native OAuth routes", () => {new Request(`${BASE_URL}/auth/native/start?attempt=${ATTEMPT}`),);- expect(response.status).toBe(503);- expect(response.headers.get("Cache-Control")).toContain("no-store");+ await expectNativeOauthErrorPage(response, 503);});it("hashes the callback handoff and never exposes it in stored form", async () => {@@ -368,7 +393,7 @@ describe("native OAuth routes", () => {),);- expect(response.status).toBe(410);+ await expectNativeOauthErrorPage(response, 410);expect(authMocks.generateOneTimeToken).not.toHaveBeenCalled();});@@ -386,7 +411,7 @@ describe("native OAuth routes", () => {),);- expect(response.status).toBe(410);+ await expectNativeOauthErrorPage(response, 410);});it("fails the attempt when callback handoff generation fails", async () => {@@ -423,8 +448,7 @@ describe("native OAuth routes", () => {),);- expect(response.status).toBe(503);- expect(response.headers.get("Cache-Control")).toContain("no-store");+ await expectNativeOauthErrorPage(response, 503);});it("rejects a malformed exchange before D1 or OTT verification", async () => {diff --git a/src/web/src/app/auth/native/callback/route.ts b/src/web/src/app/auth/native/callback/route.tsindex 27ce38d6f..34926d4d9 100644--- a/src/web/src/app/auth/native/callback/route.ts+++ b/src/web/src/app/auth/native/callback/route.ts@@ -6,12 +6,12 @@ import {expireBrowserAnalyticsCookies,isNativeOauthAttemptId,isNativeOauthRequestTarget,- nativeOauthHtml,nativeOauthRedirect,nativeOauthReturnUrl,sanitizeOauthFailure,sha256Hex,} from "@/lib/native-oauth";+import { nativeOauthErrorPage } from "../error-page";const log = createLogger({ service: "native-oauth/callback" });type CallbackKind = "signin" | "signup" | "error";@@ -20,13 +20,6 @@ function isCallbackKind(value: string | null): value is CallbackKind {return value === "signin" || value === "signup" || value === "error";}-function errorPage(status: number): Response {- return nativeOauthHtml(- "<!doctype html><title>Sign-in unavailable</title><p>This sign-in request is unavailable.</p>",- { status },- );-}-export const GET = withEnv(async (request, ctx) => {const requestUrl = new URL(request.url);const baseUrl = new URL(ctx.env.BETTER_AUTH_URL);@@ -37,13 +30,13 @@ export const GET = withEnv(async (request, ctx) => {!isNativeOauthAttemptId(attemptId) ||!isCallbackKind(kind)) {- return errorPage(400);+ return nativeOauthErrorPage(400);}try {const db = getPrimaryDb(ctx.env.DB);const attempt = await queries.nativeOauth.getOpenedAttempt(db, attemptId);- if (!attempt) return errorPage(410);+ if (!attempt) return nativeOauthErrorPage(410);if (kind === "error") {const failureCode = sanitizeOauthFailure(requestUrl.searchParams.get("error"));@@ -64,7 +57,7 @@ export const GET = withEnv(async (request, ctx) => {handoffCodeHash: await sha256Hex(handoffCode),authKind: kind,});- if (!attached) return errorPage(410);+ if (!attached) return nativeOauthErrorPage(410);const responseHeaders = new Headers(generated.headers);expireBrowserAnalyticsCookies(@@ -90,6 +83,6 @@ export const GET = withEnv(async (request, ctx) => {}} catch {log.error("native OAuth callback unavailable");- return errorPage(503);+ return nativeOauthErrorPage(503);}});diff --git a/src/web/src/app/auth/native/error-page.ts b/src/web/src/app/auth/native/error-page.tsnew file mode 100644index 000000000..fe5bb9820--- /dev/null+++ b/src/web/src/app/auth/native/error-page.ts@@ -0,0 +1,14 @@+import {+ AUTH_STATUS_PAGE_CSP,+ renderAuthStatusPage,+} from "../../../../auth";+import { nativeOauthHtml } from "@/lib/native-oauth";++export function nativeOauthErrorPage(status: number): Response {+ return nativeOauthHtml(renderAuthStatusPage("unavailable"), {+ status,+ headers: {+ "Content-Security-Policy": AUTH_STATUS_PAGE_CSP,+ },+ });+}diff --git a/src/web/src/app/auth/native/start/route.ts b/src/web/src/app/auth/native/start/route.tsindex de095841b..0e17e8fe6 100644--- a/src/web/src/app/auth/native/start/route.ts+++ b/src/web/src/app/auth/native/start/route.ts@@ -6,19 +6,12 @@ import {isNativeOauthAttemptId,isNativeOauthRequestTarget,nativeOauthCallbackUrls,- nativeOauthHtml,nativeOauthRedirect,} from "@/lib/native-oauth";+import { nativeOauthErrorPage } from "../error-page";const log = createLogger({ service: "native-oauth/start" });-function errorPage(status: number): Response {- return nativeOauthHtml(- "<!doctype html><title>Sign-in unavailable</title><p>This sign-in request is unavailable.</p>",- { status },- );-}-export const GET = withEnv(async (request, ctx) => {const requestUrl = new URL(request.url);const attemptId = requestUrl.searchParams.get("attempt");@@ -26,13 +19,13 @@ export const GET = withEnv(async (request, ctx) => {!isNativeOauthRequestTarget(request, ctx.env.BETTER_AUTH_URL) ||!isNativeOauthAttemptId(attemptId)) {- return errorPage(400);+ return nativeOauthErrorPage(400);}try {const db = getPrimaryDb(ctx.env.DB);const attempt = await queries.nativeOauth.claimStart(db, attemptId);- if (!attempt) return errorPage(410);+ if (!attempt) return nativeOauthErrorPage(410);try {const result = await createAuth(ctx.env).api.signInSocial({@@ -49,10 +42,10 @@ export const GET = withEnv(async (request, ctx) => {} catch {await queries.nativeOauth.failOpenedAttempt(db, attempt.id, "start_failed");log.warn("native OAuth provider start failed");- return errorPage(502);+ return nativeOauthErrorPage(502);}} catch {log.error("native OAuth start unavailable");- return errorPage(503);+ return nativeOauthErrorPage(503);}});diff --git a/src/web/src/app/c/layout.test.ts b/src/web/src/app/c/layout.test.tsindex dabd172fb..08e1a1752 100644--- a/src/web/src/app/c/layout.test.ts+++ b/src/web/src/app/c/layout.test.ts@@ -30,6 +30,9 @@ vi.mock("@/components/community/shell/community-session-pending-frame", () => ({vi.mock("@/components/signup-tracker", () => ({SignupTracker: (props: Record<string, unknown>) => createElement("signup-tracker", props),}))+vi.mock("@/components/authenticated-native-oauth-cleanup", () => ({+ AuthenticatedNativeOauthCleanup: () => createElement("native-oauth-cleanup"),+}))import CommunityLayout from "./layout"function render() {@@ -53,6 +56,7 @@ describe("CommunityLayout session boundary", () => {const renderer = render()expect(renderer.root.findByType("session-pending").props.pathname).toBe("/c/me")expect(renderer.root.findAllByType("community-shell")).toHaveLength(0)+ expect(renderer.root.findAllByType("native-oauth-cleanup")).toHaveLength(0)expect(mocks.retireAttempt).not.toHaveBeenCalled()expect(mocks.clearAttempts).not.toHaveBeenCalled()})@@ -63,6 +67,7 @@ describe("CommunityLayout session boundary", () => {expect(mocks.replace).toHaveBeenCalledWith("/sign-in")expect(mocks.clearAttempts).toHaveBeenCalledTimes(1)expect(renderer.root.findByType("session-pending").props.pathname).toBe("/c/me")+ expect(renderer.root.findAllByType("native-oauth-cleanup")).toHaveLength(0)})it("constructs the shell only after identity is available", () => {@@ -77,6 +82,7 @@ describe("CommunityLayout session boundary", () => {expect(shell.props.currentUser.id).toBe("u1")expect(mocks.retireAttempt).toHaveBeenCalledWith("u1", "/c/me")expect(mocks.clearAttempts).not.toHaveBeenCalled()+ expect(renderer.root.findAllByType("native-oauth-cleanup")).toHaveLength(1)})it("preserves the public invite bypass", () => {@@ -85,6 +91,7 @@ describe("CommunityLayout session boundary", () => {expect(renderer.root.findAllByType("child")).toHaveLength(1)expect(renderer.root.findAllByType("session-pending")).toHaveLength(0)expect(mocks.replace).not.toHaveBeenCalled()+ expect(renderer.root.findAllByType("native-oauth-cleanup")).toHaveLength(0)})it("does not broaden the public bypass to malformed invite descendants", () => {diff --git a/src/web/src/app/c/layout.tsx b/src/web/src/app/c/layout.tsxindex bbb41a884..8a3d0bb2c 100644--- a/src/web/src/app/c/layout.tsx+++ b/src/web/src/app/c/layout.tsx@@ -9,6 +9,7 @@ import { SignupTracker } from "@/components/signup-tracker"import { CommunitySessionPendingFrame } from "@/components/community/shell/community-session-pending-frame"import { resolveCommunityModulePlan } from "@/lib/community/community-route"import { AuthenticatedContextMenuBoundary } from "@/components/authenticated-context-menu-boundary"+import { AuthenticatedNativeOauthCleanup } from "@/components/authenticated-native-oauth-cleanup"import {clearCommunityColdEntryAttempts,retireCommunityColdEntryAttempt,@@ -66,6 +67,7 @@ export default function CommunityLayout({return (<AuthenticatedContextMenuBoundary>+ <AuthenticatedNativeOauthCleanup /><SignupTracker redirectTo="/c/me/machines" /><CommunityShell currentUser={currentUser}>{children}</CommunityShell></AuthenticatedContextMenuBoundary>diff --git a/src/web/src/components/authenticated-native-oauth-cleanup.tsx b/src/web/src/components/authenticated-native-oauth-cleanup.tsxnew file mode 100644index 000000000..2a5050e2d--- /dev/null+++ b/src/web/src/components/authenticated-native-oauth-cleanup.tsx@@ -0,0 +1,11 @@+"use client"++import { useEffect } from "react"+import { cleanupAuthenticatedNativeOauthResidue } from "@/lib/native-oauth-authenticated-cleanup"++export function AuthenticatedNativeOauthCleanup() {+ useEffect(() => {+ void cleanupAuthenticatedNativeOauthResidue().catch(() => {})+ }, [])+ return null+}diff --git a/src/web/src/lib/native-oauth-authenticated-cleanup.test.ts b/src/web/src/lib/native-oauth-authenticated-cleanup.test.tsnew file mode 100644index 000000000..d55d12396--- /dev/null+++ b/src/web/src/lib/native-oauth-authenticated-cleanup.test.ts@@ -0,0 +1,200 @@+import { readFileSync } from "node:fs"+import { beforeEach, describe, expect, it, vi } from "vitest"+import { cleanupAuthenticatedNativeOauthResidue } from "./native-oauth-authenticated-cleanup"++const sharedMocks = vi.hoisted(() => ({+ isDesktop: vi.fn(),+ isTauri: vi.fn(),+ tauriInvoke: vi.fn(),+}))++vi.mock("@alook/shared", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@alook/shared")>()+ return { ...actual, ...sharedMocks }+})++const snapshot = {+ attemptId: "a".repeat(43),+ provider: "google",+ redirectPath: "/c/me/machines",+ expiresAt: Date.now() + 60_000,+ waiting: true,+} as const++const proof = {+ attemptId: snapshot.attemptId,+ state: "s".repeat(43),+ verifier: "v".repeat(43),+}++function makeDeps() {+ return {+ isDesktopTauri: vi.fn(() => true),+ invoke: vi.fn(async (command: string) => {+ if (command === "native_oauth_snapshot") return snapshot+ if (command === "native_oauth_cancel") return proof+ throw new Error(`unexpected command: ${command}`)+ }),+ postCancel: vi.fn(async () => new Response(null, { status: 204 })),+ }+}++describe("cleanupAuthenticatedNativeOauthResidue", () => {+ beforeEach(() => {+ vi.restoreAllMocks()+ vi.clearAllMocks()+ sharedMocks.isDesktop.mockReturnValue(false)+ sharedMocks.isTauri.mockReturnValue(false)+ sharedMocks.tauriInvoke.mockReset()+ })++ it("uses the browser adapter for desktop Tauri cleanup", async () => {+ sharedMocks.isDesktop.mockReturnValue(true)+ sharedMocks.isTauri.mockReturnValue(true)+ sharedMocks.tauriInvoke.mockImplementation(async (command: string) => {+ if (command === "native_oauth_snapshot") return snapshot+ if (command === "native_oauth_cancel") return proof+ throw new Error(`unexpected command: ${command}`)+ })+ const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(+ new Response(null, { status: 204 }),+ )++ await cleanupAuthenticatedNativeOauthResidue()++ expect(sharedMocks.tauriInvoke.mock.calls).toEqual([+ ["native_oauth_snapshot"],+ ["native_oauth_cancel", { attemptId: snapshot.attemptId }],+ ])+ expect(fetchMock).toHaveBeenCalledExactlyOnceWith(+ "/api/auth/native/cancel",+ expect.objectContaining({+ method: "POST",+ credentials: "same-origin",+ cache: "no-store",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(proof),+ signal: expect.any(AbortSignal),+ }),+ )+ })++ it("is a no-op outside desktop Tauri", async () => {+ const deps = makeDeps()+ deps.isDesktopTauri.mockReturnValue(false)++ await cleanupAuthenticatedNativeOauthResidue(deps)++ expect(deps.invoke).not.toHaveBeenCalled()+ expect(deps.postCancel).not.toHaveBeenCalled()+ })++ it("only reads the snapshot when no attempt exists", async () => {+ const deps = makeDeps()+ deps.invoke.mockResolvedValue(null)++ await cleanupAuthenticatedNativeOauthResidue(deps)++ expect(deps.invoke).toHaveBeenCalledExactlyOnceWith("native_oauth_snapshot")+ expect(deps.postCancel).not.toHaveBeenCalled()+ })++ it("does not contact the server when native cancel finds no current attempt", async () => {+ const deps = makeDeps()+ deps.invoke+ .mockResolvedValueOnce(snapshot)+ .mockResolvedValueOnce(null)++ await cleanupAuthenticatedNativeOauthResidue(deps)++ expect(deps.invoke.mock.calls).toEqual([+ ["native_oauth_snapshot"],+ ["native_oauth_cancel", { attemptId: snapshot.attemptId }],+ ])+ expect(deps.postCancel).not.toHaveBeenCalled()+ })++ it("cancels the exact residue locally before posting the proof", async () => {+ const deps = makeDeps()++ await cleanupAuthenticatedNativeOauthResidue(deps)++ expect(deps.invoke.mock.calls).toEqual([+ ["native_oauth_snapshot"],+ ["native_oauth_cancel", { attemptId: snapshot.attemptId }],+ ])+ expect(deps.postCancel).toHaveBeenCalledExactlyOnceWith(proof)+ })++ it.each(["snapshot", "cancel"])(+ "does not contact the server when native %s fails",+ async (failure) => {+ const deps = makeDeps()+ deps.invoke.mockImplementation(async (command: string) => {+ if (command === "native_oauth_snapshot") {+ if (failure === "snapshot") throw new Error("store unavailable")+ return snapshot+ }+ if (command === "native_oauth_cancel") throw new Error("store unavailable")+ throw new Error(`unexpected command: ${command}`)+ })++ await expect(cleanupAuthenticatedNativeOauthResidue(deps)).rejects.toThrow(+ "store unavailable",+ )+ expect(deps.postCancel).not.toHaveBeenCalled()+ },+ )++ it("retries native cleanup on a later authenticated mount", async () => {+ const deps = makeDeps()+ deps.invoke.mockRejectedValueOnce(new Error("store unavailable"))++ await expect(cleanupAuthenticatedNativeOauthResidue(deps)).rejects.toThrow(+ "store unavailable",+ )+ expect(deps.postCancel).not.toHaveBeenCalled()++ await cleanupAuthenticatedNativeOauthResidue(deps)++ expect(deps.invoke.mock.calls.slice(-2)).toEqual([+ ["native_oauth_snapshot"],+ ["native_oauth_cancel", { attemptId: snapshot.attemptId }],+ ])+ expect(deps.postCancel).toHaveBeenCalledExactlyOnceWith(proof)+ })++ it("keeps completed local cleanup final when server cancellation returns 503", async () => {+ const deps = makeDeps()+ deps.postCancel.mockResolvedValue(new Response(null, { status: 503 }))++ await expect(cleanupAuthenticatedNativeOauthResidue(deps)).resolves.toBeUndefined()+ expect(deps.invoke.mock.calls).toEqual([+ ["native_oauth_snapshot"],+ ["native_oauth_cancel", { attemptId: snapshot.attemptId }],+ ])+ })++ it("keeps completed local cleanup final when server cancellation rejects", async () => {+ const deps = makeDeps()+ deps.postCancel.mockRejectedValue(new Error("server unavailable"))++ await expect(cleanupAuthenticatedNativeOauthResidue(deps)).resolves.toBeUndefined()+ expect(deps.invoke.mock.calls).toEqual([+ ["native_oauth_snapshot"],+ ["native_oauth_cancel", { attemptId: snapshot.attemptId }],+ ])+ })++ it("mounts only behind both authenticated layout gates", () => {+ const appLayout = readFileSync(new URL("../app/(app)/layout.tsx", import.meta.url), "utf8")+ const communityLayout = readFileSync(new URL("../app/c/layout.tsx", import.meta.url), "utf8")++ expect(appLayout.indexOf("if (!session) redirect")).toBeLessThan(+ appLayout.indexOf("<AuthenticatedNativeOauthCleanup />"),+ )+ expect(communityLayout.indexOf("if (isPending || !session)")).toBeLessThan(+ communityLayout.indexOf("<AuthenticatedNativeOauthCleanup />"),+ )+ })+})diff --git a/src/web/src/lib/native-oauth-authenticated-cleanup.ts b/src/web/src/lib/native-oauth-authenticated-cleanup.tsnew file mode 100644index 000000000..f01483ab6--- /dev/null+++ b/src/web/src/lib/native-oauth-authenticated-cleanup.ts@@ -0,0 +1,39 @@+import {+ isDesktop,+ isTauri,+ nativeOauthProofSchema,+ tauriInvoke,+} from "@alook/shared"+import { nativeOauthSnapshotSchema } from "@/lib/native-oauth-schema"++const browserDeps = {+ isDesktopTauri: () => isTauri() && isDesktop(),+ invoke: tauriInvoke,+ postCancel: (proof: unknown) => fetch("/api/auth/native/cancel", {+ method: "POST",+ credentials: "same-origin",+ cache: "no-store",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(proof),+ signal: AbortSignal.timeout(15_000),+ }),+}++export async function cleanupAuthenticatedNativeOauthResidue(+ deps: {+ isDesktopTauri: () => boolean+ invoke: <T>(command: string, args?: Record<string, unknown>) => Promise<T>+ postCancel: (proof: unknown) => Promise<unknown>+ } = browserDeps,+): Promise<void> {+ if (!deps.isDesktopTauri()) return+ const snapshot = nativeOauthSnapshotSchema.nullable().parse(+ await deps.invoke("native_oauth_snapshot"),+ )+ if (!snapshot) return+ const proof = nativeOauthProofSchema.nullable().parse(+ await deps.invoke("native_oauth_cancel", { attemptId: snapshot.attemptId }),+ )+ if (!proof) return+ await deps.postCancel(proof).catch(() => {})+}diff --git a/src/web/src/lib/native-oauth-client.test.ts b/src/web/src/lib/native-oauth-client.test.tsnew file mode 100644index 000000000..8569de700--- /dev/null+++ b/src/web/src/lib/native-oauth-client.test.ts@@ -0,0 +1,265 @@+import { afterEach, describe, expect, it, vi } from "vitest"+import { createNativeOauthController, nativeOauthBrowserDeps, type NativeOauthDeps, type NativeOauthSnapshot, type NativeOauthView } from "./native-oauth-client"++function deferred<T>() {+ let resolve!: (value: T) => void+ let reject!: (reason?: unknown) => void+ const promise = new Promise<T>((yes, no) => { resolve = yes; reject = no })+ return { promise, resolve, reject }+}+function setup() {+ let snapshot: NativeOauthSnapshot | null = null+ let pending: { attemptId: string; state: string; verifier: string; candidateId: string; code: string | null; status: string | null; wasDispatched: boolean }[] = []+ let ready = () => {}+ let count = 0+ const events: string[] = []+ const views: NativeOauthView[] = []+ const stop = vi.fn()+ const invoke = vi.fn(async (command: string, args?: Record<string, unknown>): Promise<unknown> => {+ events.push(command)+ if (command === "native_oauth_snapshot") return snapshot && { ...snapshot }+ if (command === "native_oauth_prepare") {+ snapshot = { attemptId: `attempt_${String(++count).padStart(24, "0")}`, provider: args!.provider as "github" | "google", redirectPath: args!.redirectPath as string, expiresAt: Date.now() + 600_000, waiting: false }+ pending = []+ return { attemptId: snapshot.attemptId, provider: snapshot.provider, redirectPath: snapshot.redirectPath, platform: "macos", stateHash: "a".repeat(64), codeChallenge: "b".repeat(43), instanceKeyHash: "c".repeat(64) }+ }+ if (command === "native_oauth_open_start") { snapshot!.waiting = true; return }+ if (command === "native_oauth_pending_exchange") {+ if (!pending.length) return null+ const result = { ...pending[0] }; pending[0].wasDispatched = true; return result+ }+ if (command === "native_oauth_reject_candidate") { pending = pending.filter(c => c.candidateId !== args!.candidateId); return }+ if (command === "native_oauth_finish") { if (snapshot?.attemptId === args!.attemptId) { snapshot = null; pending = [] }; return }+ if (command === "native_oauth_cancel") {+ if (!snapshot || (args?.attemptId && snapshot.attemptId !== args.attemptId)) return null+ const proof = { attemptId: snapshot.attemptId, state: "s".repeat(43), verifier: "v".repeat(43) }+ snapshot = null; pending = []; return proof+ }+ throw new Error("unexpected command")+ })+ const post = vi.fn(async (endpoint: string): Promise<{ ok: boolean; data: unknown }> => {+ events.push(endpoint)+ if (endpoint === "attempt") return { ok: true, data: { startUrl: `https://alook.ai/auth/native/start?attempt=${snapshot!.attemptId}` } }+ if (endpoint === "exchange") return { ok: true, data: { redirectPath: "/c/me" } }+ if (endpoint === "status") return { ok: true, data: { status: "ready" } }+ return { ok: true, data: { status: "cancelled" } }+ })+ const listen = vi.fn(async (callback: () => void) => { events.push("listen"); ready = callback; return stop })+ const hasSession = vi.fn(async () => false)+ const navigate = vi.fn()+ const deps: NativeOauthDeps = { invoke: invoke as NativeOauthDeps["invoke"], post, listen, hasSession, navigate }+ const make = () => createNativeOauthController(deps, view => { views.push(view) })+ const controller = make()+ return { controller, make, deps, invoke, post, listen, stop, hasSession, navigate, events, views,+ view: () => views.at(-1)!, wake: () => ready(), snapshot: () => snapshot,+ queue: (code: string | null = "k".repeat(32), status: string | null = null, wasDispatched = false) => {+ pending.push({ attemptId: snapshot!.attemptId, candidateId: `candidate-${pending.length}`, state: "s".repeat(43), verifier: "v".repeat(43), code, status, wasDispatched })+ },+ }+}+const controllers: ReturnType<typeof createNativeOauthController>[] = []+function fixture() { const f = setup(); controllers.push(f.controller); return f }+afterEach(() => { for (const c of controllers.splice(0)) c.dispose(); vi.unstubAllGlobals(); vi.useRealTimers() })++ describe("native OAuth controller", () => {+ it("registers the listener before reading pending, opens only the registered start, and keeps proofs out of view state", async () => {+ const f = fixture(); await f.controller.connect(); await f.controller.start("github", "/c/me")+ expect(f.events.indexOf("listen")).toBeLessThan(f.events.indexOf("native_oauth_pending_exchange"))+ expect(f.events.indexOf("attempt")).toBeLessThan(f.events.indexOf("native_oauth_open_start"))+ expect(f.view().phase).toBe("waiting")+ f.queue(); f.wake(); f.wake()+ await vi.waitFor(() => expect(f.navigate).toHaveBeenCalledWith("/c/me"))+ expect(f.post.mock.calls.filter(([endpoint]) => endpoint === "exchange")).toHaveLength(1)+ const text = JSON.stringify(f.views)+ expect(text).not.toContain("s".repeat(43)); expect(text).not.toContain("v".repeat(43)); expect(text).not.toContain("k".repeat(32))+ expect(f.invoke).toHaveBeenCalledWith("native_oauth_finish", expect.anything())+ })+ it("rejects only a forged candidate and processes a later real code after durable retirement", async () => {+ const f = fixture(); await f.controller.connect(); await f.controller.start("google", "/c/me")+ const normal = f.post.getMockImplementation()!+ let exchanges = 0+ f.post.mockImplementation(async endpoint => endpoint === "exchange" && ++exchanges === 1 ? { ok: false, data: { error: "invalid_handoff" } } : normal(endpoint))+ f.queue("x".repeat(32)); f.queue(); f.wake()+ await vi.waitFor(() => expect(f.navigate).toHaveBeenCalledOnce())+ expect(f.events.indexOf("native_oauth_reject_candidate")).toBeLessThan(f.events.lastIndexOf("exchange"))+ expect(f.invoke.mock.calls.filter(([name]) => name === "native_oauth_reject_candidate")).toHaveLength(1)+ })+ it("retires a known-invalid code even with status offline, then exchanges a genuine callback after reload", async () => {+ const f = fixture(); await f.controller.connect(); await f.controller.start("google", "/c/me")+ const normal = f.post.getMockImplementation()!+ let exchanges = 0+ f.post.mockImplementation(async endpoint => {+ if (endpoint === "status") throw new Error("offline")+ if (endpoint === "exchange" && ++exchanges === 1) return { ok: false, data: { error: "invalid_handoff" } }+ return normal(endpoint)+ })+ const attempt = f.snapshot()?.attemptId+ f.queue("x".repeat(32)); f.wake()+ await vi.waitFor(() => expect(f.view().message).toBe("invalid_callback"))+ expect(f.snapshot()?.attemptId).toBe(attempt)+ expect(f.hasSession).not.toHaveBeenCalled()+ expect(f.post.mock.calls.some(([endpoint]) => endpoint === "status")).toBe(false)+ f.controller.dispose()+ const restored = f.make(); controllers.push(restored); await restored.connect()+ f.queue(); f.wake()+ await vi.waitFor(() => expect(f.navigate).toHaveBeenCalledOnce())+ expect(exchanges).toBe(2)+ expect(f.invoke.mock.calls.filter(([command]) => command === "native_oauth_reject_candidate")).toHaveLength(1)+ })+ it("does not claim durable retirement or exchange later codes when native rejection fails", async () => {+ const f = fixture(); await f.controller.connect(); await f.controller.start("github", "/c/me")+ const original = f.invoke.getMockImplementation()!+ f.invoke.mockImplementation((command, args) => command === "native_oauth_reject_candidate" ? Promise.reject("store_unavailable") : original(command, args))+ f.post.mockResolvedValue({ ok: false, data: { error: "invalid_handoff" } })+ f.queue("x".repeat(32)); f.queue(); f.wake()+ await vi.waitFor(() => expect(f.view().message).toBe("retry_required"))+ expect(f.snapshot()).not.toBeNull()+ expect(f.navigate).not.toHaveBeenCalled()+ f.wake(); await new Promise(resolve => setTimeout(resolve, 0))+ expect(f.post.mock.calls.filter(([endpoint]) => endpoint === "exchange")).toHaveLength(1)+ })+ it.each([false, true])("ignores an old rejection completion after cancel (replace=%s)", async replace => {+ const f = fixture(); await f.controller.connect(); await f.controller.start("github", "/c/me")+ const original = f.invoke.getMockImplementation()!+ const retired = deferred<void>()+ f.invoke.mockImplementation(async (command, args) => {+ const result = await original(command, args)+ if (command === "native_oauth_reject_candidate") await retired.promise+ return result+ })+ const normal = f.post.getMockImplementation()!+ f.post.mockImplementation(endpoint => endpoint === "exchange" ? Promise.resolve({ ok: false, data: { error: "invalid_handoff" } }) : normal(endpoint))+ f.queue(); f.wake()+ await vi.waitFor(() => expect(f.invoke).toHaveBeenCalledWith("native_oauth_reject_candidate", expect.anything()))+ await f.controller.cancel()+ if (replace) await f.controller.start("google", "/c/me")+ retired.resolve(); await new Promise(resolve => setTimeout(resolve, 0))+ expect(f.navigate).not.toHaveBeenCalled()+ expect(f.view().phase).toBe(replace ? "waiting" : "idle")+ expect(f.view().message).toBeUndefined()+ expect(f.snapshot()?.provider ?? null).toBe(replace ? "google" : null)+ })+ it("does not trust a status URL that disagrees with the proof-protected server", async () => {+ const f = fixture(); await f.controller.connect(); await f.controller.start("github", "/c/me")+ f.queue(null, "access_denied"); f.wake()+ await vi.waitFor(() => expect(f.view().message).toBe("invalid_callback"))+ expect(f.snapshot()).not.toBeNull()+ expect(f.invoke.mock.calls.some(([name]) => name === "native_oauth_finish")).toBe(false)+ f.post.mockResolvedValue({ ok: true, data: { status: "failed", failure: "access_denied" } })+ f.queue(null, "provider_error"); f.wake()+ await vi.waitFor(() => expect(f.view().message).toBe("denied"))+ expect(f.snapshot()).toBeNull()+ })+ it.each([true, false])("checks session after ambiguous exchange (session=%s) without replaying the code", async signedIn => {+ const f = fixture(); await f.controller.connect(); await f.controller.start("github", "/c/me")+ f.post.mockRejectedValue(new Error("network")); f.hasSession.mockResolvedValue(signedIn)+ f.queue(); f.wake()+ await vi.waitFor(() => expect(f.hasSession).toHaveBeenCalled())+ if (signedIn) await vi.waitFor(() => expect(f.navigate).toHaveBeenCalledOnce())+ else await vi.waitFor(() => expect(f.view().message).toBe("retry_required"))+ f.wake(); await new Promise(resolve => setTimeout(resolve, 0))+ expect(f.post.mock.calls.filter(([endpoint]) => endpoint === "exchange")).toHaveLength(1)+ })+ it("recovers a cold candidate after listener setup, and never replays an already-dispatched persisted code", async () => {+ const f = fixture(); await f.controller.connect(); await f.controller.start("github", "/c/me")+ f.queue("k".repeat(32), null, true); f.controller.dispose()+ const restored = f.make(); controllers.push(restored); await restored.connect()+ expect(f.hasSession).toHaveBeenCalledOnce()+ expect(f.post.mock.calls.some(([endpoint]) => endpoint === "exchange")).toBe(false)+ expect(f.view().message).toBe("retry_required")+ })+ it("clears natively before offline cancel, and prevents an old exchange from navigating a newer attempt", async () => {+ const f = fixture(); await f.controller.connect(); await f.controller.start("github", "/c/me")+ const exchange = deferred<{ ok: boolean; data: unknown }>()+ const normal = f.post.getMockImplementation()!+ f.post.mockImplementation(endpoint => endpoint === "exchange" ? exchange.promise : endpoint === "cancel" ? Promise.reject(new Error("offline")) : normal(endpoint))+ f.queue(); f.wake(); await vi.waitFor(() => expect(f.view().phase).toBe("exchanging"))+ await f.controller.cancel(); expect(f.snapshot()).toBeNull(); expect(f.view().phase).toBe("idle")+ await f.controller.start("google", "/c/me")+ exchange.resolve({ ok: true, data: { redirectPath: "/c/me" } })+ await new Promise(resolve => setTimeout(resolve, 0))+ expect(f.navigate).not.toHaveBeenCalled(); expect(f.snapshot()?.provider).toBe("google")+ })+ it("serializes registrations so the newest queued attempt commits last", async () => {+ const f = fixture(); await f.controller.connect()+ const response = deferred<{ ok: boolean; data: unknown }>()+ f.post.mockReturnValueOnce(response.promise)+ const first = f.controller.start("github", "/c/me")+ await vi.waitFor(() => expect(f.post).toHaveBeenCalled())+ const second = f.controller.start("google", "/c/me")+ expect(f.invoke.mock.calls.filter(([command]) => command === "native_oauth_prepare")).toHaveLength(1)+ response.resolve({ ok: true, data: { startUrl: "old" } }); await first; await second+ expect(f.snapshot()?.provider).toBe("google")+ expect(f.invoke.mock.calls.filter(([command]) => command === "native_oauth_open_start")).toHaveLength(1)+ })+ it("fails closed on unavailable native bridge, registration failure and unsafe redirect", async () => {+ const f = fixture(); f.listen.mockRejectedValue(new Error("unknown command")); await f.controller.connect()+ expect(f.view().phase).toBe("unsupported"); await f.controller.start("github", "/c/me"); expect(f.post).not.toHaveBeenCalled()+ const g = fixture(); await g.controller.connect(); await g.controller.start("google", "//evil.test"); expect(g.post).not.toHaveBeenCalled()+ g.post.mockResolvedValue({ ok: false, data: { error: "rate_limited" } }); await g.controller.start("google", "/c/me")+ expect(g.view().message).toBe("start_failed"); expect(g.snapshot()).toBeNull()+ expect(g.invoke.mock.calls.some(([name]) => name === "native_oauth_open_start")).toBe(false)+ })+ it("checks an already-dispatched cold callback against a successful session", async () => {+ const f = fixture(); await f.controller.connect(); await f.controller.start("google", "/c/me")+ f.queue("k".repeat(32), null, true); f.controller.dispose(); f.hasSession.mockResolvedValue(true)+ const restored = f.make(); controllers.push(restored); await restored.connect()+ expect(f.navigate).toHaveBeenCalledWith("/c/me")+ expect(f.post.mock.calls.some(([endpoint]) => endpoint === "exchange")).toBe(false)+ })+ it("keeps persistence failure bounded without claiming cancellation or opening a browser", async () => {+ const f = fixture(); f.listen.mockRejectedValue("store_unavailable"); await f.controller.connect()+ expect(f.view().message).toBe("unavailable")+ const g = fixture(); await g.controller.connect(); await g.controller.start("github", "/c/me")+ const original = g.invoke.getMockImplementation()!+ g.invoke.mockImplementation((command, args) => command === "native_oauth_cancel" ? Promise.reject("store_unavailable") : original(command, args))+ await g.controller.cancel(); expect(g.view().message).toBe("unavailable"); expect(g.snapshot()).not.toBeNull()+ })+ it("fails closed on malformed native proof and does not send it to the server", async () => {+ const f = fixture(); await f.controller.connect(); await f.controller.start("google", "/c/me")+ const original = f.invoke.getMockImplementation()!+ f.invoke.mockImplementation((command, args) => command === "native_oauth_pending_exchange" ? Promise.resolve({ state: "malformed" }) : original(command, args))+ f.wake(); await vi.waitFor(() => expect(f.view().message).toBe("unavailable"))+ expect(f.post.mock.calls.some(([endpoint]) => endpoint === "exchange")).toBe(false)+ })+ it("recovers a candidate arriving during registration of the new document listener", async () => {+ const f = fixture(); await f.controller.connect(); await f.controller.start("google", "/c/me"); f.controller.dispose()+ f.listen.mockImplementation(async ready => { f.queue(); ready(); return f.stop })+ const restored = f.make(); controllers.push(restored); await restored.connect()+ expect(f.navigate).toHaveBeenCalledOnce()+ expect(f.post.mock.calls.filter(([endpoint]) => endpoint === "exchange")).toHaveLength(1)+ })+ it("retires a late subscription after disposal and expires waiting UI", async () => {+ const f = fixture(); const listen = deferred<() => void>(); f.listen.mockReturnValue(listen.promise)+ const connected = f.controller.connect(); f.controller.dispose(); listen.resolve(f.stop); await connected+ expect(f.stop).toHaveBeenCalledOnce(); expect(f.invoke).not.toHaveBeenCalled()+ vi.useFakeTimers(); const g = fixture(); await g.controller.connect(); await g.controller.start("github", "/c/me")+ await vi.advanceTimersByTimeAsync(600_000); expect(g.view().message).toBe("expired")+ })+})++describe("native browser adapter", () => {+ it("navigates with the verified local destination", () => {+ const assign = vi.fn(); vi.stubGlobal("window", { location: { assign } })+ nativeOauthBrowserDeps.navigate("/c/me"); expect(assign).toHaveBeenCalledWith("/c/me")+ })+ it("uses a payload-free Channel with registration-scoped cleanup, not event/deep-link listeners", async () => {+ const invoke = vi.fn().mockResolvedValue(7)+ class Channel { onmessage = () => {} }+ vi.stubGlobal("window", { __TAURI__: { core: { Channel, invoke } } })+ const ready = vi.fn(); const stop = await nativeOauthBrowserDeps.listen(ready)+ const channel = invoke.mock.calls[0][1].channel as Channel+ channel.onmessage(); expect(ready).toHaveBeenCalledOnce(); stop()+ expect(invoke.mock.calls.map(([name]) => name)).toEqual(["native_oauth_listen", "native_oauth_unlisten"])+ expect(invoke.mock.calls[1][1]).toEqual({ registrationId: 7 })+ })+ it("posts proofs only to same-origin JSON and confirms ordinary session without exposing tokens", async () => {+ const fetcher = vi.fn().mockResolvedValue(new Response(JSON.stringify({ session: { id: "normal-session" } })))+ vi.stubGlobal("fetch", fetcher)+ expect(await nativeOauthBrowserDeps.hasSession()).toBe(true)+ expect(fetcher.mock.calls[0][0]).toBe("/api/auth/get-session?disableCookieCache=true")+ fetcher.mockResolvedValue(new Response(JSON.stringify({ status: "cancelled" })))+ await nativeOauthBrowserDeps.post("cancel", { attemptId: "id", state: "proof", verifier: "pkce" })+ expect(fetcher.mock.calls[1][1]).toMatchObject({ credentials: "same-origin", cache: "no-store", method: "POST", headers: { "Content-Type": "application/json" } })+ })+})diff --git a/src/web/src/lib/native-oauth-client.ts b/src/web/src/lib/native-oauth-client.tsnew file mode 100644index 000000000..d921688be--- /dev/null+++ b/src/web/src/lib/native-oauth-client.ts@@ -0,0 +1,241 @@+import { isSafeRedirectPath, nativeOauthRegistrationSchema, nativeOauthProofSchema, nativeOauthExchangeSchema, tauriInvoke } from "@alook/shared"+import { z } from "zod"+import { nativeOauthSnapshotSchema, type NativeOauthSnapshot } from "@/lib/native-oauth-schema"++const exchangeSchema = nativeOauthProofSchema.extend({+ candidateId: z.string(), code: z.string().nullable(), status: z.string().nullable(), wasDispatched: z.boolean(),+}).strict()+export type { NativeOauthSnapshot } from "@/lib/native-oauth-schema"+export type NativeOauthView = {+ phase: "initializing" | "idle" | "preparing" | "waiting" | "exchanging" | "checking_status" | "error" | "unsupported"+ message?: "start_failed" | "expired" | "denied" | "invalid_callback" | "retry_required" | "unavailable"+ attempt: NativeOauthSnapshot | null+}+export type NativeOauthDeps = {+ invoke: <T>(command: string, args?: Record<string, unknown>) => Promise<T>+ listen: (ready: () => void) => Promise<() => void>+ post: (endpoint: string, body: unknown) => Promise<{ ok: boolean; data: unknown }>+ hasSession: () => Promise<boolean>+ navigate: (path: string) => void+}++export function createNativeOauthController(deps: NativeOauthDeps, changed: (view: NativeOauthView) => void) {+ let view: NativeOauthView = { phase: "initializing", attempt: null }+ let generation = 0+ let disposed = false+ let connected = false+ let stopListening: (() => void) | undefined+ let processing = false+ let wakeAgain = false+ let startQueue = Promise.resolve()+ let expiry: ReturnType<typeof setTimeout> | undefined+ const publish = (next: NativeOauthView) => {+ view = next+ if (!disposed) { setAttempt(next.attempt); changed(next) }+ }+ const current = (version: number) => !disposed && generation === version+ const setAttempt = (attempt: NativeOauthSnapshot | null) => {+ clearTimeout(expiry)+ if (attempt) expiry = setTimeout(() => {+ if (!disposed && view.attempt?.attemptId === attempt.attemptId) {+ generation += 1+ publish({ phase: "error", message: "expired", attempt: null })+ void deps.invoke("native_oauth_snapshot").catch(() => {})+ }+ }, Math.max(0, attempt.expiresAt - Date.now()))+ }+ const readSnapshot = async () => {+ const result = nativeOauthSnapshotSchema.nullable().parse(await deps.invoke("native_oauth_snapshot"))+ return result+ }+ const finish = async (attemptId: string, candidateId: string) => {+ await deps.invoke("native_oauth_finish", { attemptId, candidateId })+ }+ const confirmSession = async () => {+ try { return await deps.hasSession() } catch { return false }+ }+ const drain = async () => {+ if (disposed || !connected) return+ if (processing) { wakeAgain = true; return }+ processing = true+ const version = generation+ try {+ do {+ wakeAgain = false+ const candidate = exchangeSchema.nullable().parse(await deps.invoke("native_oauth_pending_exchange"))+ if (!current(version)) return+ if (!candidate) return+ const snapshot = await readSnapshot()+ if (!current(version)) return+ if (!snapshot || snapshot.attemptId !== candidate.attemptId) continue+ const { attemptId, state, verifier, candidateId } = candidate+ const proof = { attemptId, state, verifier }+ if (candidate.wasDispatched && candidate.code) {+ if (await confirmSession()) {+ if (!current(version)) return+ await finish(attemptId, candidateId)+ if (current(version)) deps.navigate(snapshot.redirectPath)+ } else if (current(version)) {+ publish({ phase: "error", message: "retry_required", attempt: snapshot })+ }+ return+ }+ publish({ phase: candidate.code ? "exchanging" : "checking_status", attempt: snapshot })+ try {+ if (candidate.code) {+ const body = nativeOauthExchangeSchema.parse({ ...proof, code: candidate.code })+ const response = await deps.post("exchange", body)+ if (!current(version)) return+ const success = z.object({ redirectPath: z.string().refine(isSafeRedirectPath) }).strict().safeParse(response.data)+ if (response.ok && success.success) {+ await finish(attemptId, candidateId)+ if (current(version)) deps.navigate(success.data.redirectPath)+ return+ }+ const failure = z.object({ error: z.literal("invalid_handoff") }).strict().safeParse(response.data)+ if (!failure.success) throw new Error("exchange_unconfirmed")+ await deps.invoke("native_oauth_reject_candidate", { attemptId, candidateId })+ if (!current(version)) return+ publish({ phase: "waiting", message: "invalid_callback", attempt: snapshot })+ wakeAgain = true+ continue+ }+ const statusResponse = await deps.post("status", proof)+ if (!current(version)) return+ const status = z.object({ status: z.enum(["pending", "opened", "ready", "exchanging", "consumed", "failed", "cancelled", "replaced", "expired", "unknown"]), failure: z.string().optional() }).strict().parse(statusResponse.data)+ if (!statusResponse.ok) throw new Error("status_unavailable")+ if (["failed", "cancelled", "replaced", "expired", "unknown", "consumed"].includes(status.status)) {+ const signedIn = status.status === "consumed" && await confirmSession()+ if (!current(version)) return+ await finish(attemptId, candidateId)+ if (!current(version)) return+ setAttempt(null)+ if (signedIn) deps.navigate(snapshot.redirectPath)+ else publish({ phase: "error", message: status.failure === "access_denied" ? "denied" : "retry_required", attempt: null })+ return+ }+ await deps.invoke("native_oauth_reject_candidate", { attemptId, candidateId })+ if (!current(version)) return+ publish({ phase: "waiting", message: "invalid_callback", attempt: snapshot })+ wakeAgain = true+ } catch {+ const signedIn = !!candidate.code && await confirmSession()+ if (!current(version)) return+ if (signedIn) {+ await finish(attemptId, candidateId)+ if (current(version)) deps.navigate(snapshot.redirectPath)+ } else publish({ phase: "error", message: "retry_required", attempt: snapshot })+ return+ }+ } while (wakeAgain && current(version))+ } catch {+ if (current(version)) publish({ phase: "error", message: "unavailable", attempt: view.attempt })+ } finally {+ processing = false+ if (wakeAgain && !disposed) { wakeAgain = false; void drain() }+ }+ }+ return {+ async connect() {+ publish({ phase: "initializing", attempt: null })+ try {+ const unsubscribe = await deps.listen(() => { void drain() })+ if (disposed) { unsubscribe(); return }+ stopListening = unsubscribe+ const attempt = await readSnapshot()+ if (disposed) return+ connected = true+ publish({ phase: attempt?.waiting ? "waiting" : "idle", attempt })+ await drain()+ } catch (error) {+ if (!disposed) publish(error === "store_unavailable"+ ? { phase: "error", message: "unavailable", attempt: null }+ : { phase: "unsupported", attempt: null })+ }+ },+ start(provider: "github" | "google", redirectPath: string) {+ if (disposed || !connected || !isSafeRedirectPath(redirectPath)) return Promise.resolve()+ const version = ++generation+ publish({ phase: "preparing", attempt: view.attempt })+ const task = async () => {+ if (!current(version)) return+ let attemptId: string | undefined+ try {+ const registration = nativeOauthRegistrationSchema.parse(await deps.invoke("native_oauth_prepare", { provider, redirectPath }))+ attemptId = registration.attemptId+ if (!current(version)) return+ const attempt = await readSnapshot()+ if (!current(version)) return+ publish({ phase: "preparing", attempt })+ const response = await deps.post("attempt", registration)+ if (!current(version)) return+ const data = z.object({ startUrl: z.string() }).strict().parse(response.data)+ if (!response.ok) throw new Error("registration_failed")+ await deps.invoke("native_oauth_open_start", { attemptId, startUrl: data.startUrl })+ if (!current(version)) return+ const waiting = await readSnapshot()+ if (!current(version)) return+ publish({ phase: "waiting", attempt: waiting })+ void drain()+ } catch {+ if (!current(version)) return+ if (attemptId) {+ const proof = await deps.invoke("native_oauth_cancel", { attemptId }).catch(() => null)+ if (proof) await deps.post("cancel", nativeOauthProofSchema.parse(proof)).catch(() => {})+ }+ if (current(version)) { setAttempt(null); publish({ phase: "error", message: "start_failed", attempt: null }) }+ }+ }+ startQueue = startQueue.then(task, task)+ return startQueue+ },+ async cancel() {+ const version = ++generation+ const attempt = view.attempt+ try {+ const proof = await deps.invoke("native_oauth_cancel")+ if (current(version)) { setAttempt(null); publish({ phase: "idle", attempt: null }) }+ if (proof) await deps.post("cancel", nativeOauthProofSchema.parse(proof)).catch(() => {})+ } catch {+ if (current(version)) publish({ phase: "error", message: "unavailable", attempt })+ }+ },+ dispose() {+ disposed = true+ generation += 1+ clearTimeout(expiry)+ stopListening?.()+ },+ }+}++async function request(path: string, body?: unknown) {+ return fetch(path, {+ method: body === undefined ? "GET" : "POST", credentials: "same-origin", cache: "no-store",+ headers: body === undefined ? undefined : { "Content-Type": "application/json" },+ body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(15_000),+ })+}++export const nativeOauthBrowserDeps: NativeOauthDeps = {+ invoke: tauriInvoke,+ async listen(ready) {+ const bridge = (window as unknown as { __TAURI__?: { core?: { Channel?: new () => { onmessage: () => void } } } }).__TAURI__+ const Channel = bridge?.core?.Channel+ if (!Channel) throw new Error("native_bridge_unavailable")+ const channel = new Channel()+ channel.onmessage = ready+ const registrationId = await tauriInvoke<number>("native_oauth_listen", { channel })+ return () => { void tauriInvoke("native_oauth_unlisten", { registrationId }).catch(() => {}) }+ },+ async post(endpoint, body) {+ const response = await request(`/api/auth/native/${endpoint}`, body)+ return { ok: response.ok, data: await response.json() }+ },+ async hasSession() {+ const response = await request("/api/auth/get-session?disableCookieCache=true")+ const result = z.object({ session: z.object({ id: z.string() }).passthrough().nullable() }).passthrough().safeParse(await response.json())+ return response.ok && result.success && result.data.session !== null+ },+ navigate(path) { window.location.assign(path) },+}diff --git a/src/web/src/lib/native-oauth-schema.ts b/src/web/src/lib/native-oauth-schema.tsnew file mode 100644index 000000000..735eb17fb--- /dev/null+++ b/src/web/src/lib/native-oauth-schema.ts@@ -0,0 +1,12 @@+import { isSafeRedirectPath } from "@alook/shared"+import { z } from "zod"++export const nativeOauthSnapshotSchema = z.object({+ attemptId: z.string(),+ provider: z.enum(["github", "google"]),+ redirectPath: z.string().refine(isSafeRedirectPath),+ expiresAt: z.number(),+ waiting: z.boolean(),+}).strict()++export type NativeOauthSnapshot = z.infer<typeof nativeOauthSnapshotSchema>