Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions src-tauri/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 4 additions & 5 deletions src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,11 @@ tauri-plugin-opener = "2"
# hosted CSRF guard expects.
tauri-plugin-http = { version = "2", features = ["rustls-tls", "unsafe-headers"] }
# dev-ledger:// handoff from the system-browser OAuth flow.
# Pinned to 2.6.1: 2.6.2's load_desktop_ini does not compile against
# rust-ini 0.21.3 on Linux (ParseOption gained required fields).
# Fixed upstream in plugins-workspace#3711 — unpin once 2.6.3+ lands.
tauri-plugin-deep-link = "=2.6.1"
# Pin the upstream patch fixing rust-ini 0.21.3 build compatibility
# (plugins-workspace#3711). Single-instance deep-link forwarding requires >=2.6.2.
tauri-plugin-deep-link = "=2.6.3"
# Route a second process launch (deep-link activation) back to one window.
tauri-plugin-single-instance = "2"
tauri-plugin-single-instance = { version = "2", features = ["deep-link"] }
# OS-backed credential storage: Windows Credential Manager, macOS Keychain,
# Linux Secret Service (pure-Rust zbus + rust crypto — no libdbus/openssl).
keyring = { version = "3", features = [
Expand Down
35 changes: 18 additions & 17 deletions src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,24 @@ fn is_dev_origin(_url: &tauri::Url) -> bool {

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default()
// Windows/Linux deliver dev-ledger:// URLs by launching a second process.
// Tauri requires single-instance to be the FIRST registered plugin, with
// its "deep-link" feature enabled, to forward URLs to the running app.
// Registering it later in setup() cannot reliably intercept that launch.
let builder = tauri::Builder::default();

#[cfg(desktop)]
let builder = builder.plugin(tauri_plugin_single_instance::init(|app, _argv, _cwd| {
// The plugin's deep-link feature forwards the URL automatically
// before calling this callback. Do not parse or log credential-bearing
// URLs from argv; the JS handler performs flow+PKCE validation.
if let Some(w) = app.get_webview_window("main") {
let _ = w.unminimize();
let _ = w.set_focus();
}
}));

builder
.plugin(tauri_plugin_opener::init())
.plugin(tauri_plugin_http::init())
.plugin(tauri_plugin_deep_link::init())
Expand All @@ -91,22 +108,6 @@ pub fn run() {
sha256_hex
])
.setup(|app| {
#[cfg(desktop)]
{
// Single instance must be registered before other plugin work: a
// second launch (e.g. a dev-ledger:// deep-link activation while the
// app is already running) focuses the existing window and the
// deep-link plugin forwards the URL to it.
let _ =
app.handle()
.plugin(tauri_plugin_single_instance::init(|app, _argv, _cwd| {
if let Some(w) = app.get_webview_window("main") {
let _ = w.unminimize();
let _ = w.set_focus();
}
}));
}

// The main window is created in code (not tauri.conf.json) so the
// on_navigation guard can be attached: only bundled-app origins may
// navigate inside the webview.
Expand Down
100 changes: 82 additions & 18 deletions src/desktop/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,15 +32,34 @@ let pendingFlow: string | null = null;
let pendingVerifier: string | null = null;
let pendingRemember = false;
let noticeHandler: ((msg: string | null) => void) | null = null;
// Invoked after the bearer is available to the transport shim, without
// reloading the webview (which would erase unchecked memory-only sessions).
let completedHandler: (() => void) | null = null;
// In-memory duplicate suppression: a delivered single-use link may be
// activated again by the browser after its successful exchange.
let lastHandledFlow: string | null = null;

export function onDesktopAuthCompleted(cb: () => void): () => void {
completedHandler = cb;
return () => {
if (completedHandler === cb) completedHandler = null;
};
}
// Deep links may arrive before the React login gate mounts. Keep only a
// non-sensitive status message in memory; never retain URLs, codes or state.
let lastNotice: string | null = null;
let exchangeInProgress = false;

export function onDesktopAuthNotice(cb: (msg: string | null) => void): () => void {
noticeHandler = cb;
cb(lastNotice);
return () => {
if (noticeHandler === cb) noticeHandler = null;
};
}

function notice(msg: string | null) {
lastNotice = msg;
try {
noticeHandler?.(msg);
} catch {
Expand All @@ -50,6 +69,7 @@ function notice(msg: string | null) {

export function startDesktopLogin(remember: boolean): void {
notice(null);
lastHandledFlow = null;
pendingFlow = crypto.randomUUID();
pendingRemember = remember;
// 64 hex chars of CSPRNG entropy — the PKCE verifier. The server only
Expand All @@ -76,31 +96,66 @@ export function startDesktopLogin(remember: boolean): void {
});
}

// True when the URL is our registered deep link — anything else is ignored.
// Parse the complete registered scheme and host. Prefix matching would
// mistakenly accept dev-ledger://auth-foreign, etc. Never log URLs or codes.
export function isAuthDeepLink(url: string): boolean {
return url.startsWith(`${DESKTOP_SCHEME}://auth`);
try {
const parsed = new URL(url);
return parsed.protocol === `${DESKTOP_SCHEME}:`
&& parsed.hostname === 'auth'
&& (parsed.pathname === '' || parsed.pathname === '/')
&& !parsed.username && !parsed.password && !parsed.hash;
} catch {
return false;
}
}

async function handleAuthUrl(url: string): Promise<void> {
let parsed: URL;
// A harmless probe lets us distinguish native window activation from an
// event that actually reached the JavaScript listener. It never exchanges
// credentials or changes authentication state.
function isDiagnosticLink(url: string): boolean {
try {
parsed = new URL(url);
const parsed = new URL(url);
return parsed.protocol === `${DESKTOP_SCHEME}:`
&& parsed.hostname === 'diagnostic'
&& !parsed.search && !parsed.hash
&& (parsed.pathname === '' || parsed.pathname === '/');
} catch {
return false;
}
}

async function handleAuthUrl(url: string): Promise<void> {
if (exchangeInProgress) return; // Ignore repeated delivery of the same URL.
if (!isAuthDeepLink(url)) return;
const parsed = new URL(url);
const flows = parsed.searchParams.getAll('flow');
const codes = parsed.searchParams.getAll('code');
// Duplicate parameters or an unsolicited link must never reach the API.
if (flows.length !== 1 || codes.length !== 1 || !codes[0]) {
notice('An invalid sign-in link was received. Start a new sign-in from Dev Ledger.');
return;
}
const flow = parsed.searchParams.get('flow') ?? '';
const code = parsed.searchParams.get('code') ?? '';
const flow = flows[0];
const code = codes[0];
// Re-delivered links are inert: the first exchange already consumed the
// one-use credential, so replay must not overwrite a successful status.
if (flow === lastHandledFlow) return;
// A stale/foreign deep link (old browser attempt, another app's spoof)
// must never drive an exchange — the flow id is the binding between
// THIS app instance's login intent and the server's handoff.
if (!pendingFlow || flow !== pendingFlow || !code || !pendingVerifier) {
if (!pendingFlow || flow !== pendingFlow || !pendingVerifier) {
notice('A sign-in link reached Dev Ledger, but does not match an active login. Start again.');
return;
}
const verifier = pendingVerifier;
const remember = pendingRemember;
lastHandledFlow = flow;
pendingFlow = null;
pendingVerifier = null;
pendingRemember = false;
exchangeInProgress = true;
notice('Sign-in link received. Completing secure handoff...');
try {
// Relative path — routed through the transport shim (plugin-http), so
// the exchange needs no CORS accommodation on the server.
Expand All @@ -121,11 +176,15 @@ async function handleAuthUrl(url: string): Promise<void> {
// KEEP ME SIGNED IN: checked → OS keychain (restored on next launch);
// unchecked → memory only for this app session (keychain cleared).
await storeToken(body.token, { persistent: remember });
// Authenticated — a reload re-runs the standard boot gate, which now
// resolves through the bearer token exactly like a cookie session.
window.location.reload();
// Notify React to recheck /api/user INSIDE this webview. A reload
// destroys memoryToken for unchecked logins; no token may be written
// to sessionStorage/localStorage/cookies as a workaround.
notice('Sign-in completed. Loading your dashboard...');
completedHandler?.();
} catch {
notice('The Dev Ledger service is unreachable — sign-in could not finish.');
} finally {
exchangeInProgress = false;
}
}

Expand All @@ -136,15 +195,20 @@ async function handleAuthUrl(url: string): Promise<void> {
// registered.
export async function initDesktopAuth(): Promise<void> {
await loadToken();
await onOpenUrl((urls) => {
for (const u of urls) {
if (isAuthDeepLink(u)) void handleAuthUrl(u);
const accept = (u: string) => {
if (isDiagnosticLink(u)) {
notice('Windows protocol link reached the Dev Ledger JavaScript listener.');
return;
}
}).catch(() => {});
const current = await getCurrent().catch(() => null);
for (const u of current ?? []) {
if (isAuthDeepLink(u)) void handleAuthUrl(u);
}
};
await onOpenUrl((urls) => {
for (const u of urls) accept(u);
}).catch(() => {
notice('The desktop sign-in listener could not start. Restart Dev Ledger.');
});
const current = await getCurrent().catch(() => null);
for (const u of current ?? []) accept(u);
}

// Sign out: revoke the server-side token + session, clear the keychain,
Expand Down
2 changes: 1 addition & 1 deletion src/desktop/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { initDesktopAuth } from './auth';

export { isDesktop, API_BASE, DESKTOP_SCHEME } from './runtime';
export { openExternalUrl } from './links';
export { startDesktopLogin, desktopLogout, onDesktopAuthNotice } from './auth';
export { startDesktopLogin, desktopLogout, onDesktopAuthNotice, onDesktopAuthCompleted } from './auth';

export async function initDesktop(): Promise<void> {
if (!isDesktop()) return;
Expand Down
26 changes: 23 additions & 3 deletions src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {
initDesktop,
isDesktop,
onDesktopAuthNotice,
onDesktopAuthCompleted,
startDesktopLogin,
} from "./desktop";
import type { Identity } from "./store/live";
Expand Down Expand Up @@ -68,12 +69,20 @@ function Gate() {
// Desktop sign-in status line — a rejected/expired handoff surfaces here
// on the login screen instead of failing silently.
const [deskNotice, setDeskNotice] = useState<string | null>(null);
// A successful desktop handoff must revalidate the bearer in this SAME
// webview. Never reload: unchecked sign-ins live exclusively in memory.
const [authGeneration, setAuthGeneration] = useState(0);

useEffect(() => {
if (!DESKTOP) return;
return onDesktopAuthNotice(setDeskNotice);
}, []);

useEffect(() => {
if (!DESKTOP) return;
return onDesktopAuthCompleted(() => setAuthGeneration((n) => n + 1));
}, []);

useEffect(() => {
let live = true;
void desktopReady.then(() =>
Expand All @@ -90,7 +99,12 @@ function Gate() {
setPersistent(body?.persistent === true);
setMe(ok ? (body as Identity) : null);
setAuth(ok ? "in" : "out");
if (ok) setBooting(true);
if (ok) {
setDeskNotice(null);
setBooting(true);
} else if (DESKTOP && authGeneration > 0) {
setDeskNotice('Desktop token received, but /api/user did not authenticate it.');
}
// Analytics only: when this session was created by an initiated
// login this tab session, emit the funnel-completing event once.
// Auth state itself is untouched — consume only reads a flag.
Expand All @@ -99,12 +113,18 @@ function Gate() {
captureGoogleEvent("login", { method: "github" });
}
})
.catch(() => live && setAuth("out"))
.catch(() => {
if (!live) return;
setAuth("out");
if (DESKTOP && authGeneration > 0) {
setDeskNotice('Desktop token received, but the service could not verify it.');
}
})
);
return () => {
live = false;
};
}, []);
}, [authGeneration]);

// Inactivity heartbeat: while authenticated WITHOUT "keep me signed in",
// renew the server-side lease every 60s (plus immediately on focus/visible
Expand Down
Loading
Loading