Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

Browser: sign in as real Chrome; Google's refused sign-in opens in a window (#549)

Oleksandr Ivanchenko3e65f1131ed3
diff --git a/docker/browser-entrypoint.sh b/docker/browser-entrypoint.sh
index 5e5175dd..981984cf 100644
--- a/docker/browser-entrypoint.sh
+++ b/docker/browser-entrypoint.sh
@@ -1,11 +1,12 @@
#!/bin/sh
# Keep Chromium and its private network proxy in the same supervised container.
set -eu
-# Windowless Chromium tells sites it is "HeadlessChrome"; send the user agent the windowed
-# Chromium of this version sends instead.
-major=$(chromium --version | grep -oE '[0-9]+\.[0-9.]+' | head -n1 | cut -d. -f1)
-agent="Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${major}.0.0.0 Safari/537.36"
-chromium --headless=new --no-sandbox --disable-dev-shm-usage --user-agent="$agent" \
+# Chromium keeps its own user agent: a --user-agent flag empties the client hints a real Chrome
+# fills, and Google refuses sign-in on that. kwant takes the headless token out over DevTools
+# with the browser's own client hints (src/sandbox/identity.rs). AutomationControlled off keeps
+# navigator.webdriver false while the debugging port is open.
+chromium --headless=new --no-sandbox --disable-dev-shm-usage \
+ --disable-blink-features=AutomationControlled \
--remote-debugging-port=9223 --remote-allow-origins='*' \
--window-size=1280,800 --user-data-dir=/tmp/kwnt-chromium about:blank &
chrome_pid=$!
diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh
index 91a07813..e4e509be 100755
--- a/docker/entrypoint.sh
+++ b/docker/entrypoint.sh
@@ -18,7 +18,7 @@ chromium \
--user-data-dir="$CHROME_DATA_DIR" \
--password-store=basic \
--enable-features=PasswordImport,AutofillServerCommunication \
- --enable-automation=false &
+ --disable-blink-features=AutomationControlled &
# Proxy incoming port 9222 from container network to local Chromium on 9223
socat TCP-LISTEN:9222,fork,reuseaddr TCP:127.0.0.1:9223 &
diff --git a/docs/browser-service.md b/docs/browser-service.md
index 587fd5b4..f068d791 100644
--- a/docs/browser-service.md
+++ b/docs/browser-service.md
@@ -51,7 +51,7 @@ The browser profile lives on the container's tmpfs, so stopping or removing it l
Prebuild images to avoid first-use latency:
```bash
-docker build -t kwnt-browser:v2 -f docker/browser.Dockerfile docker
+docker build -t kwnt-browser:v3 -f docker/browser.Dockerfile docker
docker build -t kwnt-executor:v1 -f docker/executor.Dockerfile docker
./target/release/kwnt serve --host 127.0.0.1 --port 8799
```
diff --git a/frontend/src/components/ComputerModeSwitch.tsx b/frontend/src/components/ComputerModeSwitch.tsx
index 34b315e2..45eb7f9a 100644
--- a/frontend/src/components/ComputerModeSwitch.tsx
+++ b/frontend/src/components/ComputerModeSwitch.tsx
@@ -28,7 +28,7 @@ export interface ComputerModeApi {
select: (mode: ComputerMode) => void;
dismissError: () => void;
/** Local mode: opens the bots' Chrome as a window, or brings it back into the app. */
- setWindow: (visible: boolean) => void;
+ setWindow: (visible: boolean, untilSignedIn?: boolean) => void;
/** True while a window switch restarts Chrome. */
windowPending: boolean;
/** "Run Claude inside the VM": saves at once; on failure the switch goes back and `isoError` says why. */
@@ -77,11 +77,11 @@ export function useComputerMode(enabled: boolean): ComputerModeApi {
}, []);
const [windowPending, setWindowPending] = useState(false);
- const setWindow = useCallback((visible: boolean) => {
+ const setWindow = useCallback((visible: boolean, untilSignedIn = false) => {
if (stateRef.current.pending) return;
playSfx('click');
setWindowPending(true);
- saveLocalWindow(visible).then((r) => {
+ saveLocalWindow(visible, untilSignedIn).then((r) => {
setWindowPending(false);
if (r.ok) {
dispatch({ type: 'saved', settings: r.settings });
@@ -290,6 +290,32 @@ export const OpenWindowButton: React.FC<{ api: ComputerModeApi; label?: boolean
);
};
+/**
+ * A sign-in page that refuses a windowless browser (Google's "This browser or app may not be
+ * secure"): one line, and on the desktop apps one button that opens the same Chrome as a real
+ * window for the sign-in. It comes back into the app by itself once the sign-in is over.
+ */
+export const SignInLine: React.FC<{ signIn: { text: string; action: string | null } | null; api?: ComputerModeApi }> = ({ signIn, api }) => {
+ if (!signIn) return null;
+ return (
+ <div role="status" data-signin-line className="flex flex-wrap items-center gap-x-2 gap-y-1 px-2.5 py-2 rounded-lg border border-amber-400/30 bg-amber-950/40 text-xs text-amber-200">
+ <span>{signIn.text}</span>
+ {signIn.action && api && (
+ <button
+ type="button"
+ onClick={() => api.setWindow(true, true)}
+ disabled={api.windowPending}
+ aria-busy={api.windowPending || undefined}
+ className="inline-flex items-center gap-1 font-semibold underline underline-offset-2 text-amber-100 enabled:hover:text-white disabled:opacity-60"
+ >
+ {api.windowPending ? <Loader2 size={12} className="animate-spin" aria-hidden="true" /> : <AppWindow size={12} aria-hidden="true" />}
+ {signIn.action}
+ </button>
+ )}
+ </div>
+ );
+};
+
/** Shown in place of the live view while the bots' Chrome is open as a window. */
export const LocalBrowserNote: React.FC<{ api?: ComputerModeApi }> = ({ api }) => (
<div className="flex-1 flex items-center justify-center p-6 rounded-xl border border-zinc-800 bg-zinc-950 text-center">
diff --git a/frontend/src/components/VirtualMachinePane.tsx b/frontend/src/components/VirtualMachinePane.tsx
index 447c392d..f40d5d69 100644
--- a/frontend/src/components/VirtualMachinePane.tsx
+++ b/frontend/src/components/VirtualMachinePane.tsx
@@ -18,7 +18,7 @@ import {
} from 'lucide-react';
import { playSfx } from '../audio/chiptune';
import { BOT_BUSY_TEXT, HELD_BY_PERSON_TEXT, useBrowserStream } from '../useBrowserStream';
-import { ComputerModeChip, ComputerModeError, LocalBrowserNote, OpenWindowButton, useComputerMode } from './ComputerModeSwitch';
+import { ComputerModeChip, ComputerModeError, LocalBrowserNote, OpenWindowButton, SignInLine, useComputerMode } from './ComputerModeSwitch';
import { browserFooterLabel, isBlankPage, showsLocalWindow } from '../computerMode';
import { loginMatchesPage } from '../savedPasswords';
import { PendingLoginPrompt, SavedPasswordsPanel, useSavedPasswords } from './SavedPasswordsPanel';
@@ -774,6 +774,7 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
{controlError}
</div>
)}
+ <SignInLine signIn={stream.signIn} api={computer} />
<div
data-browser-watch
data-watch-state={takeover ? 'stage' : waitingForBot ? 'busy' : needsYou ? 'needs-you' : 'watching'}
@@ -941,7 +942,7 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
return true;
}}
handBackQuiet={recording}
- belowBar={teamId ? <RecordingStrip stage={teamId} phone /> : null}
+ belowBar={<><SignInLine signIn={stream.signIn} api={computer} />{teamId ? <RecordingStrip stage={teamId} phone /> : null}</>}
stream={stream}
step={stepForStage}
controlling={stream.controlling}
@@ -971,7 +972,7 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
onRetryControl={takeOver}
extraAction={recordSteps}
handBackQuiet={recording}
- belowBar={teamId ? <RecordingStrip stage={teamId} /> : null}
+ belowBar={<><SignInLine signIn={stream.signIn} api={computer} />{teamId ? <RecordingStrip stage={teamId} /> : null}</>}
/>
)}
diff --git a/frontend/src/computerMode.ts b/frontend/src/computerMode.ts
index c158709f..65cf77b7 100644
--- a/frontend/src/computerMode.ts
+++ b/frontend/src/computerMode.ts
@@ -209,8 +209,13 @@ async function putSettings(path: string, body: unknown, failed: string): Promise
export const saveComputerMode = (mode: ComputerMode) => putSettings('/api/settings/computer', { mode }, 'Switching failed');
/** Opens the bots' Chrome as a window (`true`) or puts it back in the app (`false`). */
-export const saveLocalWindow = (visible: boolean) =>
- putSettings('/api/settings/computer/window', { visible }, visible ? 'Could not open the window' : 'Could not bring the browser back');
+/** `untilSignedIn`: the window is for a sign-in, and comes back into the app once it is over. */
+export const saveLocalWindow = (visible: boolean, untilSignedIn = false) =>
+ putSettings(
+ '/api/settings/computer/window',
+ untilSignedIn ? { visible, until_signed_in: true } : { visible },
+ visible ? 'Could not open the window' : 'Could not bring the browser back',
+ );
/** Turns "Run Claude inside the VM" on or off. A 400's code is put in people's words (fix 5). */
export async function saveIsolateClaude(on: boolean): Promise<SaveResult> {
diff --git a/frontend/src/useBrowserStream.ts b/frontend/src/useBrowserStream.ts
index c773445d..a9a133d0 100644
--- a/frontend/src/useBrowserStream.ts
+++ b/frontend/src/useBrowserStream.ts
@@ -53,6 +53,9 @@ export function useBrowserStream(id: string | undefined, visible: boolean, page?
const [cursor, setCursor] = useState<string>('default');
// The last resize was answered `ignored`: the page follows a real window and keeps its size
const [resizeIgnored, setResizeIgnored] = useState(false);
+ // A sign-in page that refuses a windowless browser: the line to show, and its button's label
+ // when a real Chrome window can be opened here
+ const [signIn, setSignIn] = useState<{ text: string; action: string | null } | null>(null);
// Actions the server answered "Invalid browser input" for (an older server): hide their buttons
const [unsupported, setUnsupported] = useState<ReadonlySet<string>>(new Set());
const actionsById = useRef(new Map<number, string>());
@@ -110,6 +113,11 @@ export function useBrowserStream(id: string | undefined, visible: boolean, page?
break;
}
case 'location': setLocation({ url: message.url || '', title: message.title || '' }); break;
+ case 'signin':
+ setSignIn(typeof message.text === 'string' && message.text
+ ? { text: message.text, action: typeof message.action === 'string' ? message.action : null }
+ : null);
+ break;
case 'control':
takingControl.current = false;
setControlling(!!message.active);
@@ -184,6 +192,7 @@ export function useBrowserStream(id: string | undefined, visible: boolean, page?
setBusy(false);
setFrame(null);
setLocation(null);
+ setSignIn(null);
setTapFocus(null);
setSelect(null);
setDialog(null);
@@ -254,7 +263,7 @@ export function useBrowserStream(id: string | undefined, visible: boolean, page?
return {
/** The page the connected stream shows, null for the server's default (meaningful while `connected`). */
page: livePage,
- connected, controlling, busy, error, frame, location, tapFocus, viewport, select, dialog, cursor, unsupported, resizeIgnored,
+ connected, controlling, busy, error, frame, location, tapFocus, viewport, select, dialog, cursor, unsupported, resizeIgnored, signIn,
send, request, acknowledgeFrame, restoreViewport, clearSelect, clearDialog, clearError,
};
}
diff --git a/frontend/tests/computerMode.test.mjs b/frontend/tests/computerMode.test.mjs
index d25fac04..defe0c0c 100644
--- a/frontend/tests/computerMode.test.mjs
+++ b/frontend/tests/computerMode.test.mjs
@@ -7,7 +7,7 @@ globalThis.localStorage ??= { getItem: () => null, setItem: () => {} };
const m = await loadBundled(`
export * from './src/computerMode';
- export { ComputerModeControl, ComputerModeChip, LocalBrowserNote, OpenWindowButton } from './src/components/ComputerModeSwitch';
+ export { ComputerModeControl, ComputerModeChip, LocalBrowserNote, OpenWindowButton, SignInLine } from './src/components/ComputerModeSwitch';
export { renderToStaticMarkup } from 'react-dom/server.browser';
export { createElement } from 'react';
`);
@@ -204,3 +204,22 @@ test('the note offers to bring the browser back, and saveLocalWindow sends the f
}
assert.equal(asked, null, 'rendering alone does not switch');
});
+
+test('a sign-in Google refuses gets one line, and on the desktop one button that opens Chrome until signed in', async () => {
+ const line = (signIn) => m.renderToStaticMarkup(m.createElement(m.SignInLine, { signIn, api: api(ready(settings('local'))) }));
+ assert.equal(line(null), '');
+ const desktop = line({ text: 'Google only allows sign-in in a normal Chrome window.', action: 'Sign in in Chrome' });
+ assert.match(desktop, /Google only allows sign-in in a normal Chrome window\./);
+ assert.match(desktop, /<button[^>]*>.*Sign in in Chrome<\/button>/);
+ const server = line({ text: "Google doesn't allow sign-in from a browser on a server. Sign in on this site with email instead, or connect Google in Apps &amp; accounts.", action: null });
+ assert.doesNotMatch(server, /<button/);
+ const realFetch = globalThis.fetch;
+ try {
+ let body;
+ globalThis.fetch = async (_url, init) => { body = init.body; return new Response(JSON.stringify(settings('local', true, true, {}, { visible: true, available: true })), { status: 200 }); };
+ assert.equal((await m.saveLocalWindow(true, true)).ok, true);
+ assert.equal(body, '{"visible":true,"until_signed_in":true}');
+ } finally {
+ globalThis.fetch = realFetch;
+ }
+});
diff --git a/site-src/docs-browser.html b/site-src/docs-browser.html
index a98aa3ce..12d16b54 100644
--- a/site-src/docs-browser.html
+++ b/site-src/docs-browser.html
@@ -147,7 +147,7 @@ card_art: avatar:user
<h2 id="vm">VM mode with Docker</h2>
<p>Install Docker and start kwant. The first browser request builds the browser image from a recipe embedded in the binary and starts a private container, so a VPS with only the binary works too. No desktop or display server is needed. Prebuild the images to skip the first-use wait:</p>
-<pre><code>docker build -t kwnt-browser:v2 -f docker/browser.Dockerfile docker
+<pre><code>docker build -t kwnt-browser:v3 -f docker/browser.Dockerfile docker
docker build -t kwnt-executor:v1 -f docker/executor.Dockerfile docker</code></pre>
<p>The browser shares a 1.5 GiB memory limit across all bots, rather than one Chromium per bot. Browser contexts keep cookies and local storage apart. They aren't OS isolation between users who don't trust each other.</p>
diff --git a/site/docs/browser.html b/site/docs/browser.html
index 4da82440..f6a9918f 100644
--- a/site/docs/browser.html
+++ b/site/docs/browser.html
@@ -198,7 +198,7 @@
<h2 id="vm">VM mode with Docker</h2>
<p>Install Docker and start kwant. The first browser request builds the browser image from a recipe embedded in the binary and starts a private container, so a VPS with only the binary works too. No desktop or display server is needed. Prebuild the images to skip the first-use wait:</p>
-<pre><code>docker build -t kwnt-browser:v2 -f docker/browser.Dockerfile docker
+<pre><code>docker build -t kwnt-browser:v3 -f docker/browser.Dockerfile docker
docker build -t kwnt-executor:v1 -f docker/executor.Dockerfile docker</code></pre>
<p>The browser shares a 1.5 GiB memory limit across all bots, rather than one Chromium per bot. Browser contexts keep cookies and local storage apart. They aren't OS isolation between users who don't trust each other.</p>
diff --git a/src/sandbox/browser.rs b/src/sandbox/browser.rs
index 083d297b..a343e110 100644
--- a/src/sandbox/browser.rs
+++ b/src/sandbox/browser.rs
@@ -1575,14 +1575,29 @@ impl BrowserController {
resp.json().await.map_err(http_error)
}
- /// Starts following the popups the bot's page opens, unless that is already running.
+ /// The browser-level DevTools address of this controller's browser.
+ async fn browser_ws(&self) -> Option<String> {
+ let version = self.devtools_json("/json/version").await.ok()?;
+ let advertised = version["webSocketDebuggerUrl"].as_str()?;
+ self.reachable_ws_url(advertised).ok()
+ }
+
+ /// Makes sure every page, popup and worker of this browser tells sites what it really is,
+ /// without the headless token ([`super::identity`]). Cheap once its keeper runs.
+ pub async fn keep_identity(&self) {
+ if let Some(browser_ws) = self.browser_ws().await {
+ super::identity::keep(browser_ws).await;
+ }
+ }
+
+ /// Starts following the popups the bot's page opens, unless that is already running. Also
+ /// starts the identity keeper again if the browser restarted under this controller.
async fn follow_popups(&self) {
if self.popups.is_watching() {
return;
}
- let Ok(version) = self.devtools_json("/json/version").await else { return };
- let Some(advertised) = version["webSocketDebuggerUrl"].as_str() else { return };
- let Ok(browser_ws) = self.reachable_ws_url(advertised) else { return };
+ let Some(browser_ws) = self.browser_ws().await else { return };
+ super::identity::keep(browser_ws.clone()).await;
self.popups.watch(browser_ws).await;
}
diff --git a/src/sandbox/computer.rs b/src/sandbox/computer.rs
index fb0791f8..08df7ce2 100644
--- a/src/sandbox/computer.rs
+++ b/src/sandbox/computer.rs
@@ -122,19 +122,40 @@ pub fn find_chrome(
}
}
}
+ if os == "windows" {
+ if let Some(found) = windows_chrome(&windows_roots()) {
+ return Some(found);
+ }
+ }
+ // by name first, then by folder: an installed Google Chrome anywhere on the path wins over a
+ // Chromium earlier on it, so sites see the same brand as on everyone else's Chrome
let on_path = path.and_then(|path| {
- std::env::split_paths(path).find_map(|dir| {
- CHROME_COMMANDS
- .iter()
- .map(|name| dir.join(name))
- .find(|candidate| candidate.is_file())
- })
+ let dirs: Vec<PathBuf> = std::env::split_paths(path).collect();
+ CHROME_COMMANDS
+ .iter()
+ .find_map(|name| dirs.iter().map(|dir| dir.join(name)).find(|candidate| candidate.is_file()))
});
on_path
.or_else(|| playwright_chromium(os, home?))
.or_else(|| super::chrome_download::downloaded_chrome(os, home?))
}
+/// Where Windows installs Chrome: per machine (`Program Files`, both) and per person
+/// (`%LOCALAPPDATA%`).
+fn windows_roots() -> Vec<PathBuf> {
+ ["ProgramFiles", "ProgramFiles(x86)", "LOCALAPPDATA"]
+ .iter()
+ .filter_map(|var| std::env::var_os(var).map(PathBuf::from))
+ .collect()
+}
+
+/// The installed Google Chrome under one of `roots`, else a Chromium there.
+pub fn windows_chrome(roots: &[PathBuf]) -> Option<PathBuf> {
+ const APPS: [&str; 2] = ["Google/Chrome/Application/chrome.exe", "Chromium/Application/chrome.exe"];
+ APPS.iter()
+ .find_map(|app| roots.iter().map(|root| root.join(app)).find(|candidate| candidate.is_file()))
+}
+
/// The newest Chromium Playwright downloaded into the person's cache (`kwnt setup` puts one there
/// when no Chrome is installed): `~/.cache/ms-playwright` on Linux,
/// `~/Library/Caches/ms-playwright` on a Mac.
@@ -259,27 +280,42 @@ pub fn read_devtools_port(profile: &Path) -> Option<u16> {
text.lines().next()?.trim().parse().ok().filter(|&p| p > 0)
}
+/// Chrome's switch that keeps `navigator.webdriver` false while a debugging port is open. A
+/// Chrome feature switch, not a script: the page sees the same browser a person uses.
+pub const NOT_AUTOMATED: &str = "--disable-blink-features=AutomationControlled";
+
+/// Whether the browser at `path` is Google Chrome (not Chromium or Chrome for Testing), whose
+/// pages name "Google Chrome" among their brands.
+pub fn is_google_chrome(path: &Path) -> bool {
+ let text = path.to_string_lossy().to_lowercase().replace('\\', "/");
+ (text.contains("google chrome") || text.contains("google-chrome") || text.contains("google/chrome/application"))
+ && !text.contains("for testing")
+}
+
/// The viewport of windowless local Chrome, matching the vm browser and the in-app viewer.
pub const HEADLESS_WINDOW_SIZE: &str = "1280,800";
/// Chrome's command line for local mode: its own profile, never the person's everyday one, and a
/// debugging port Chrome picks itself (it listens on 127.0.0.1). Without a window (`headless`)
-/// unless the person asked to see one. A windowless Chrome sends `user_agent` (see
-/// [`headed_user_agent`]) instead of its own, which tells every site it is "HeadlessChrome".
-pub fn chrome_args(profile: &Path, headless: bool, user_agent: Option<&str>) -> Vec<String> {
+/// unless the person asked to see one.
+///
+/// Chrome keeps its own user agent: a `--user-agent` flag empties the client hints a real Chrome
+/// fills, and Google refuses sign-in on that. The headless token is taken out over DevTools
+/// instead, with the browser's own client hints ([`super::identity`]). With a debugging port
+/// Chrome says `navigator.webdriver` is true; [`NOT_AUTOMATED`] turns that off. No
+/// `--enable-automation`, which adds the "controlled by automated software" bar.
+pub fn chrome_args(profile: &Path, headless: bool) -> Vec<String> {
let mut args = vec![
format!("--user-data-dir={}", profile.display()),
"--remote-debugging-port=0".into(),
"--remote-debugging-address=127.0.0.1".into(),
"--no-first-run".into(),
"--no-default-browser-check".into(),
+ NOT_AUTOMATED.into(),
];
if headless {
args.push("--headless=new".into());
args.push(format!("--window-size={HEADLESS_WINDOW_SIZE}"));
- if let Some(agent) = user_agent {
- args.push(format!("--user-agent={agent}"));
- }
}
args.push("about:blank".into());
args
@@ -358,11 +394,40 @@ pub fn launched_headless(profile: &Path) -> Option<bool> {
}
}
+/// The file kwant writes next to [`LAUNCH_MODE_FILE`] once it starts Chrome as Chrome
+/// ([`chrome_args`]: no `--user-agent`, not marked automated). Kwant 0.9.4 and older wrote none.
+const LAUNCH_IDENTITY_FILE: &str = "kwant-launch-identity";
+
+fn record_launch_identity(profile: &Path) -> std::io::Result<()> {
+ std::fs::write(profile.join(LAUNCH_IDENTITY_FILE), "chrome")
+}
+
+/// Whether the windowless Chrome on `profile` was started by an older kwant, with a made-up
+/// `--user-agent` and without [`NOT_AUTOMATED`]: sites read it as automated (Google refuses its
+/// sign-in), and what kwant sets over DevTools can't undo that, so it has to be started again.
+pub fn started_by_older_kwant(profile: &Path) -> bool {
+ let line = profile_owner(profile).and_then(command_line);
+ is_older_launch(line.as_deref(), profile.join(LAUNCH_IDENTITY_FILE).exists())
+}
+
+/// [`started_by_older_kwant`] from the Chrome's command line, else (no command line, as on
+/// Windows) from whether kwant left its launch mark. A Chrome kwant starts now always passes, so
+/// it is never restarted twice.
+pub fn is_older_launch(command_line: Option<&str>, marked: bool) -> bool {
+ match command_line {
+ Some(line) => {
+ let mut args = line.split(' ');
+ line.contains(" --user-agent=") || !args.any(|arg| arg == NOT_AUTOMATED)
+ }
+ None => !marked,
+ }
+}
+
/// Whether a running kwant Chrome is windowless: from its command line, else from the form kwant
-/// recorded when it started it, else from its user agent (only an older kwant's Chrome has
-/// neither, and that one still says "HeadlessChrome" when windowless). The user agent alone is
-/// wrong for kwant's own windowless Chrome, which reads like a windowed one: trusting it made
-/// every call see the wrong form and restart Chrome.
+/// recorded when it started it, else from its user agent (`/json/version` still says
+/// "HeadlessChrome" when windowless: the identity kwant gives pages doesn't change it). Its
+/// command line comes first, as a Chrome an older kwant started with `--user-agent` reads like a
+/// windowed one.
pub fn is_windowless(command_line: Option<&str>, launched_headless: Option<bool>, user_agent: &str) -> bool {
match (command_line, launched_headless) {
(Some(line), _) => is_headless_command_line(line),
@@ -371,8 +436,8 @@ pub fn is_windowless(command_line: Option<&str>, launched_headless: Option<bool>
}
}
-/// Whether a running Chrome is windowless, from its `/json/version` user agent. Only right for a
-/// Chrome started without kwant's user agent (see [`is_windowless`]).
+/// Whether a running Chrome is windowless, from its `/json/version` user agent. Wrong for a
+/// Chrome an older kwant started with `--user-agent` (see [`is_windowless`]).
pub fn is_headless_user_agent(user_agent: &str) -> bool {
user_agent.contains("HeadlessChrome")
}
@@ -399,8 +464,8 @@ async fn user_agent(endpoint: &str) -> Option<String> {
Some(version["User-Agent"].as_str().unwrap_or_default().to_string())
}
-/// The kwant Chrome running on `profile`: its CDP endpoint and whether it is windowless. That comes
-/// from [`is_windowless`], since its user agent reads like a windowed one.
+/// The kwant Chrome running on `profile`: its CDP endpoint and whether it is windowless (see
+/// [`is_windowless`]).
pub async fn running_local_chrome(profile: &Path) -> Option<(String, bool)> {
let port = read_devtools_port(profile)?;
let endpoint = format!("http://127.0.0.1:{port}");
@@ -409,12 +474,6 @@ pub async fn running_local_chrome(profile: &Path) -> Option<(String, bool)> {
Some((endpoint, is_windowless(line.as_deref(), launched_headless(profile), &agent)))
}
-/// Whether the Chrome at `endpoint` still tells sites it is "HeadlessChrome": one started before
-/// kwant set its user agent, which kwant restarts so sites see a normal Chrome.
-pub async fn says_headless(endpoint: &str) -> bool {
- user_agent(endpoint).await.is_some_and(|agent| is_headless_user_agent(&agent))
-}
-
/// The live Chrome holding `profile`, from the `SingletonLock` link Chrome keeps in it
/// ("<host>-<pid>"). `None` when no Chrome holds it, or on Windows, which has no such link.
///
@@ -659,10 +718,10 @@ fn launch_local_chrome(profile: &Path, headless: bool) -> Result<(), String> {
std::fs::create_dir_all(profile).map_err(|e| e.to_string())?;
// without it, a Chrome whose command line can't be read would be taken for the wrong form
record_launch_mode(profile, headless)
+ .and_then(|()| record_launch_identity(profile))
.map_err(|e| format!("Could not write to {}: {e}", profile.display()))?;
- let agent = if headless { chrome_user_agent(&chrome) } else { None };
let mut cmd = std::process::Command::new(&chrome);
- cmd.args(chrome_args(profile, headless, agent.as_deref()))
+ cmd.args(chrome_args(profile, headless))
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null());
@@ -855,7 +914,7 @@ mod tests {
#[test]
fn chrome_uses_its_own_profile_and_a_loopback_port() {
for headless in [true, false] {
- let args = chrome_args(Path::new("/data/local-chrome"), headless, None);
+ let args = chrome_args(Path::new("/data/local-chrome"), headless);
assert!(args.contains(&"--user-data-dir=/data/local-chrome".to_string()));
assert!(args.contains(&"--remote-debugging-port=0".to_string()));
assert!(args.contains(&"--remote-debugging-address=127.0.0.1".to_string()));
@@ -864,10 +923,10 @@ mod tests {
#[test]
fn chrome_is_windowless_unless_a_window_is_asked_for() {
- let args = chrome_args(Path::new("/p"), true, None);
+ let args = chrome_args(Path::new("/p"), true);
assert!(args.contains(&"--headless=new".to_string()));
assert!(args.contains(&"--window-size=1280,800".to_string()));
- let args = chrome_args(Path::new("/p"), false, None);
+ let args = chrome_args(Path::new("/p"), false);
assert!(!args.iter().any(|a| a.starts_with("--headless")));
assert!(!args.iter().any(|a| a.starts_with("--window-size")));
assert!(is_headless_user_agent("Mozilla/5.0 (X11; Linux x86_64) HeadlessChrome/131.0 Safari/537.36"));
@@ -875,7 +934,7 @@ mod tests {
}
#[test]
- fn windowless_chrome_sends_the_windowed_user_agent() {
+ fn web_fetch_sends_the_windowed_user_agent() {
assert_eq!(
headed_user_agent("Google Chrome 131.0.6778.86 \n", "macos").as_deref(),
Some("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36")
@@ -890,12 +949,50 @@ mod tests {
assert_eq!(headed_user_agent("", "linux"), None);
assert_eq!(headed_user_agent("Chromium version unknown", "linux"), None);
- let agent = headed_user_agent("Chromium 154.0.8037.92", "linux").unwrap();
- let args = chrome_args(Path::new("/p"), true, Some(&agent));
- assert!(args.contains(&format!("--user-agent={agent}")));
- assert!(!args.iter().any(|a| a.contains("Headless") && a.starts_with("--user-agent")));
- // a window already sends the normal one
- assert!(!chrome_args(Path::new("/p"), false, Some(&agent)).iter().any(|a| a.starts_with("--user-agent")));
+ }
+
+ #[test]
+ fn chrome_keeps_its_own_user_agent_and_is_not_marked_automated() {
+ for headless in [true, false] {
+ let args = chrome_args(Path::new("/p"), headless);
+ // the flag empties the client hints Google asks for; the identity is set over DevTools
+ assert!(!args.iter().any(|a| a.starts_with("--user-agent")), "{args:?}");
+ assert!(!args.iter().any(|a| a.starts_with("--enable-automation")), "{args:?}");
+ assert!(args.contains(&"--disable-blink-features=AutomationControlled".to_string()), "{args:?}");
+ }
+ }
+
+ #[test]
+ fn google_chrome_is_told_apart_from_chromium() {
+ assert!(is_google_chrome(Path::new("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome")));
+ assert!(is_google_chrome(Path::new("/usr/bin/google-chrome-stable")));
+ assert!(is_google_chrome(Path::new(r"C:\Program Files\Google\Chrome\Application\chrome.exe")));
+ assert!(!is_google_chrome(Path::new("/Applications/Chromium.app/Contents/MacOS/Chromium")));
+ assert!(!is_google_chrome(Path::new("/usr/bin/chromium")));
+ assert!(!is_google_chrome(Path::new("/home/me/.cache/kwant/chrome/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing")));
+ }
+
+ #[test]
+ fn an_installed_google_chrome_is_preferred_over_a_chromium_earlier_on_the_path() {
+ let early = tempfile::tempdir().unwrap();
+ let late = tempfile::tempdir().unwrap();
+ std::fs::write(early.path().join("chromium"), "").unwrap();
+ std::fs::write(late.path().join("google-chrome"), "").unwrap();
+ let path = std::env::join_paths([early.path(), late.path()]).unwrap();
+ assert_eq!(find_chrome(None, "linux", None, path.to_str()), Some(late.path().join("google-chrome")));
+
+ let machine = tempfile::tempdir().unwrap();
+ let person = tempfile::tempdir().unwrap();
+ let chromium = machine.path().join("Chromium/Application/chrome.exe");
+ std::fs::create_dir_all(chromium.parent().unwrap()).unwrap();
+ std::fs::write(&chromium, "").unwrap();
+ let roots = [machine.path().to_path_buf(), person.path().to_path_buf()];
+ assert_eq!(windows_chrome(&roots), Some(chromium));
+ let chrome = person.path().join("Google/Chrome/Application/chrome.exe");
+ std::fs::create_dir_all(chrome.parent().unwrap()).unwrap();
+ std::fs::write(&chrome, "").unwrap();
+ assert_eq!(windows_chrome(&roots), Some(chrome));
+ assert_eq!(windows_chrome(&[]), None);
}
#[tokio::test]
@@ -906,9 +1003,9 @@ mod tests {
#[test]
fn windowless_is_read_from_the_command_line() {
- let headless = chrome_args(Path::new("/p"), true, Some("Mozilla/5.0 (X11; Linux x86_64) Chrome/154.0.0.0"));
+ let headless = chrome_args(Path::new("/p"), true);
assert!(is_headless_command_line(&format!("/usr/lib/chromium/chromium {}", headless.join(" "))));
- let window = chrome_args(Path::new("/p"), false, None);
+ let window = chrome_args(Path::new("/p"), false);
assert!(!is_headless_command_line(&format!("/usr/lib/chromium/chromium {}", window.join(" "))));
assert!(is_headless_command_line("chrome --headless --user-data-dir=/p"));
// a profile or user agent that merely mentions it is not the flag
@@ -937,6 +1034,26 @@ mod tests {
assert_eq!(launched_headless(dir.path()), Some(false));
}
+ #[test]
+ fn a_windowless_chrome_an_older_kwant_started_is_started_again() {
+ let profile = Path::new("/p");
+ let now = format!("chromium {}", chrome_args(profile, true).join(" "));
+ assert!(!is_older_launch(Some(&now), false), "kwant's own launch, read from its command line");
+ let old = format!(
+ "chromium --user-data-dir=/p --remote-debugging-port=0 --headless=new --window-size={HEADLESS_WINDOW_SIZE} --user-agent=Mozilla/5.0 (X11; Linux x86_64) Chrome/141.0.0.0 Safari/537.36 about:blank"
+ );
+ assert!(is_older_launch(Some(&old), true), "0.9.4: a made-up user agent, marked automated");
+ assert!(is_older_launch(Some(&format!("{now} --user-agent=x")), false));
+ // no command line (Windows): kwant's mark decides
+ assert!(is_older_launch(None, false));
+ assert!(!is_older_launch(None, true));
+
+ let dir = tempfile::tempdir().unwrap();
+ assert!(!dir.path().join(LAUNCH_IDENTITY_FILE).exists());
+ record_launch_identity(dir.path()).unwrap();
+ assert!(dir.path().join(LAUNCH_IDENTITY_FILE).exists());
+ }
+
/// Rigel's finding on #22: kwant's windowless Chrome answers with a windowed user agent, and
/// when its command line can't be read (no `SingletonLock` here, so no owner) it was taken for
/// a window, so every call saw the wrong form and restarted it.
diff --git a/src/sandbox/identity.rs b/src/sandbox/identity.rs
new file mode 100644
index 00000000..7d0290bc
--- /dev/null
+++ b/src/sandbox/identity.rs
@@ -0,0 +1,511 @@
+//! What the bots' Chrome tells sites it is, on every page, popup and worker.
+//!
+//! Windowless Chrome says "HeadlessChrome" in its user agent. kwant used to replace the string
+//! with `--user-agent`, which also empties the high-entropy client hints a real Chrome always
+//! fills (`sec-ch-ua-full-version-list`, `navigator.userAgentData.getHighEntropyValues`): Google
+//! asks for them and refused the sign-in. Now Chrome starts with its own user agent, and a keeper
+//! on each browser sets `Network.setUserAgentOverride` with the same user agent minus the
+//! headless token **and** the browser's own client hints (read from the browser, so the version,
+//! platform version, architecture and bitness are the real ones), for every target as it is
+//! created, with auto-attach, before it runs. Nothing is injected into pages: it says what the
+//! browser really is. A Chrome with a window already says that, so it is left alone.
+use serde_json::{json, Value};
+use std::collections::HashMap;
+use std::sync::{LazyLock, Mutex};
+use std::time::Duration;
+
+/// The user agent and client hints a target is given.
+#[derive(Debug, Clone, PartialEq)]
+pub struct Identity {
+ pub user_agent: String,
+ /// CDP `Emulation.UserAgentMetadata`.
+ pub metadata: Value,
+}
+
+/// The user agent with the headless token gone: what the same Chrome sends with a window.
+pub fn headed(user_agent: &str) -> String {
+ user_agent.replace("HeadlessChrome/", "Chrome/")
+}
+
+/// Whether a user agent says the browser runs without a window.
+pub fn is_headless(user_agent: &str) -> bool {
+ user_agent.contains("HeadlessChrome")
+}
+
+/// The full version in a `Browser.getVersion` product ("Chrome/154.0.8037.92",
+/// "HeadlessChrome/131.0.6778.86").
+pub fn product_version(product: &str) -> Option<&str> {
+ let version = product.rsplit('/').next()?.trim();
+ let ok = version.split('.').count() == 4 && version.split('.').all(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()));
+ ok.then_some(version)
+}
+
+/// Chrome's GREASE brand for `major` (`GetGreasedUserAgentBrandVersion`): a made-up brand that
+/// changes with the version so sites don't match brand lists exactly.
+fn grease(major: u32) -> (String, &'static str) {
+ const CHARS: [&str; 11] = [" ", "(", ":", "-", ".", "/", ")", ";", "=", "?", "_"];
+ const VERSIONS: [&str; 3] = ["8", "99", "24"];
+ let brand = format!("Not{}A{}Brand", CHARS[major as usize % 11], CHARS[(major as usize + 1) % 11]);
+ (brand, VERSIONS[major as usize % 3])
+}
+
+/// The `brands` and `fullVersionList` Chrome `full_version` sends, in Chrome's order
+/// (`GenerateBrandVersionList`, seeded with the major version): the GREASE brand, "Chromium",
+/// and `product` ("Google Chrome") when there is one.
+pub fn brand_lists(full_version: &str, product: Option<&str>) -> Option<(Value, Value)> {
+ let major_text = full_version.split('.').next()?;
+ let major: u32 = major_text.parse().ok()?;
+ let (grease_brand, grease_major) = grease(major);
+ let mut entries = vec![(grease_brand, grease_major.to_string(), format!("{grease_major}.0.0.0"))];
+ entries.push(("Chromium".into(), major_text.into(), full_version.into()));
+ if let Some(product) = product {
+ entries.push((product.into(), major_text.into(), full_version.into()));
+ }
+ let order: &[usize] = if entries.len() == 3 {
+ const ORDERS: [[usize; 3]; 6] = [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]];
+ &ORDERS[major as usize % 6]
+ } else {
+ const ORDERS: [[usize; 2]; 2] = [[0, 1], [1, 0]];
+ &ORDERS[major as usize % 2]
+ };
+ // entry i goes to position order[i]
+ let mut placed = vec![None; entries.len()];
+ for (i, entry) in entries.into_iter().enumerate() {
+ placed[order[i]] = Some(entry);
+ }
+ let placed: Vec<_> = placed.into_iter().flatten().collect();
+ let brands = placed.iter().map(|(b, major, _)| json!({"brand": b, "version": major})).collect();
+ let full = placed.iter().map(|(b, _, full)| json!({"brand": b, "version": full})).collect();
+ Some((Value::Array(brands), Value::Array(full)))
+}
+
+/// The client-hint platform for a Rust `std::env::consts::OS`.
+pub fn hint_platform(os: &str) -> &'static str {
+ match os {
+ "macos" => "macOS",
+ "windows" => "Windows",
+ _ => "Linux",
+ }
+}
+
+/// The client-hint architecture and bitness for a Rust `std::env::consts::ARCH`.
+pub fn hint_arch(arch: &str) -> (&'static str, &'static str) {
+ match arch {
+ "aarch64" => ("arm", "64"),
+ "arm" => ("arm", "32"),
+ "x86" => ("x86", "32"),
+ _ => ("x86", "64"),
+ }
+}
+
+/// The identity of the Chrome that answered `Browser.getVersion` with `product` and
+/// `user_agent`, built from that and this computer: used when the browser's own client hints
+/// can't be read. `google` for a Google Chrome (brand "Google Chrome"), else Chromium.
+pub fn from_version(product: &str, user_agent: &str, google: bool, os: &str, arch: &str, platform_version: &str) -> Option<Identity> {
+ let full = product_version(product)?;
+ let (brands, full_list) = brand_lists(full, google.then_some("Google Chrome"))?;
+ let (architecture, bitness) = hint_arch(arch);
+ Some(Identity {
+ user_agent: headed(user_agent),
+ metadata: json!({
+ "brands": brands,
+ "fullVersionList": full_list,
+ "fullVersion": full,
+ "platform": hint_platform(os),
+ "platformVersion": platform_version,
+ "architecture": architecture,
+ "bitness": bitness,
+ "model": "",
+ "mobile": false,
+ "wow64": false,
+ }),
+ })
+}
+
+/// The identity from what the browser itself reports (`navigator.userAgentData` with its
+/// high-entropy values, read on a `chrome://` page): kept as it is, except that a "HeadlessChrome"
+/// brand is the product it stands for, and a list missing that product is rebuilt in Chrome's
+/// order. `google` says which product this Chrome is when the report doesn't.
+pub fn from_report(user_agent: &str, report: &Value, google: bool) -> Option<Identity> {
+ let list = |key: &str| report[key].as_array().cloned();
+ let (brands, full_list) = (list("brands")?, list("fullVersionList")?);
+ let names = |l: &[Value]| l.iter().filter_map(|b| b["brand"].as_str().map(str::to_string)).collect::<Vec<_>>();
+ let product = if google || names(&brands).iter().any(|b| b == "Google Chrome" || b == "HeadlessChrome") {
+ Some("Google Chrome")
+ } else {
+ None
+ };
+ let full = full_list
+ .iter()
+ .find(|b| b["brand"] == "Chromium" || b["brand"] == "Google Chrome" || b["brand"] == "HeadlessChrome")
+ .and_then(|b| b["version"].as_str())
+ .filter(|v| v.split('.').count() == 4)?
+ .to_string();
+ let rename = |l: Vec<Value>| -> Vec<Value> {
+ l.into_iter()
+ .map(|mut b| {
+ if b["brand"] == "HeadlessChrome" {
+ b["brand"] = json!(product.unwrap_or("Chromium"));
+ }
+ b
+ })
+ .collect()
+ };
+ let (mut brands, mut full_list) = (rename(brands), rename(full_list));
+ let complete = |l: &[Value]| {
+ let n = names(l);
+ n.iter().any(|b| b == "Chromium") && product.is_none_or(|p| n.iter().any(|b| b == p))
+ };
+ if !complete(&brands) || !complete(&full_list) {
+ let (b, f) = brand_lists(&full, product)?;
+ brands = b.as_array().cloned().unwrap_or_default();
+ full_list = f.as_array().cloned().unwrap_or_default();
+ }
+ let text = |key: &str| report[key].as_str().unwrap_or_default().to_string();
+ Some(Identity {
+ user_agent: headed(user_agent),
+ metadata: json!({
+ "brands": brands,
+ "fullVersionList": full_list,
+ "fullVersion": full,
+ "platform": text("platform"),
+ "platformVersion": text("platformVersion"),
+ "architecture": text("architecture"),
+ "bitness": text("bitness"),
+ "model": text("model"),
+ "mobile": report["mobile"].as_bool().unwrap_or(false),
+ "wow64": report["wow64"].as_bool().unwrap_or(false),
+ }),
+ })
+}
+
+/// This computer's OS version as Chrome reports it on a Mac ("15.1.0"). Elsewhere empty: Chrome
+/// on Linux sends "" too, and Windows' value can't be worked out from here.
+fn local_platform_version() -> String {
+ if !cfg!(target_os = "macos") {
+ return String::new();
+ }
+ let out = std::process::Command::new("sw_vers").arg("-productVersion").output();
+ let version = out.map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string()).unwrap_or_default();
+ let mut parts: Vec<&str> = version.split('.').filter(|p| !p.is_empty()).collect();
+ while !parts.is_empty() && parts.len() < 3 {
+ parts.push("0");
+ }
+ parts.join(".")
+}
+
+/// The target types given the identity: pages and frames, and every kind of worker, which send
+/// their own requests.
+fn takes_identity(kind: &str) -> bool {
+ matches!(kind, "page" | "iframe" | "worker" | "shared_worker" | "service_worker" | "other")
+}
+
+/// Targets that can have frames or workers of their own, which their own auto-attach reaches.
+fn has_children(kind: &str) -> bool {
+ matches!(kind, "page" | "iframe")
+}
+
+static KEEPERS: LazyLock<Mutex<HashMap<String, tokio::task::JoinHandle<()>>>> = LazyLock::new(Default::default);
+
+/// Keeps the identity on every target of the browser at `browser_ws` (its browser-level DevTools
+/// address), unless a keeper already runs for it, and waits briefly until the pages already open
+/// have it. Ends with the browser's connection; the next call starts it again.
+pub async fn keep(browser_ws: String) {
+ let ready = {
+ let mut keepers = KEEPERS.lock().unwrap_or_else(|e| e.into_inner());
+ keepers.retain(|_, task| !task.is_finished());
+ if keepers.contains_key(&browser_ws) {
+ return;
+ }
+ let (tx, rx) = tokio::sync::oneshot::channel();
+ keepers.insert(browser_ws.clone(), tokio::spawn(run(browser_ws, tx)));
+ rx
+ };
+ let _ = tokio::time::timeout(Duration::from_secs(8), ready).await;
+}
+
+/// One CDP connection, with replies picked out of the events it also carries.
+struct Conn {
+ ws: super::browser::WsStream,
+ next: u64,
+ /// events that arrived while waiting for a reply, handled afterwards
+ queued: Vec<Value>,
+}
+
+impl Conn {
+ async fn send(&mut self, method: &str, params: Value, session: Option<&str>) -> Option<u64> {
+ use futures::SinkExt;
+ self.next += 1;
+ let mut message = json!({"id": self.next, "method": method, "params": params});
+ if let Some(session) = session {
+ message["sessionId"] = json!(session);
+ }
+ let text = tokio_tungstenite::tungstenite::Message::Text(message.to_string());
+ self.ws.send(text).await.ok().map(|_| self.next)
+ }
+
+ async fn recv(&mut self) -> Option<Value> {
+ if !self.queued.is_empty() {
+ return Some(self.queued.remove(0));
+ }
+ self.recv_raw().await
+ }
+
+ /// Sends and waits up to `wait` for the reply's result. Events meanwhile are queued.
+ async fn call(&mut self, method: &str, params: Value, session: Option<&str>, wait: Duration) -> Option<Value> {
+ let id = self.send(method, params, session).await?;
+ let deadline = tokio::time::Instant::now() + wait;
+ let mut held = Vec::new();
+ let reply = loop {
+ let Ok(Some(message)) = tokio::time::timeout_at(deadline, self.recv_raw()).await else { break None };
+ if message["id"] == id {
+ break message.get("result").cloned();
+ }
+ if message.get("method").is_some() {
+ held.push(message);
+ }
+ };
+ self.queued.extend(held);
+ reply
+ }
+
+ async fn recv_raw(&mut self) -> Option<Value> {
+ use futures::StreamExt;
+ loop {
+ match self.ws.next().await? {
+ Ok(tokio_tungstenite::tungstenite::Message::Text(text)) => return serde_json::from_str(&text).ok(),
+ Ok(_) => continue,
+ Err(_) => return None,
+ }
+ }
+ }
+}
+
+const REPORT_SCRIPT: &str = r#"navigator.userAgentData ? navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList","wow64"]).then(v => JSON.stringify(v)) : """#;
+
+/// The browser's own client hints, read on a background `chrome://version` page (a secure page
+/// that runs no site's code), which is closed again.
+async fn read_report(conn: &mut Conn) -> Option<Value> {
+ let wait = Duration::from_secs(5);
+ let created = conn.call("Target.createTarget", json!({"url": "chrome://version", "background": true}), None, wait).await?;
+ let target = created["targetId"].as_str()?.to_string();
+ let report = async {
+ let attached = conn.call("Target.attachToTarget", json!({"targetId": target, "flatten": true}), None, wait).await?;
+ let session = attached["sessionId"].as_str()?.to_string();
+ for _ in 0..20 {
+ let params = json!({"expression": REPORT_SCRIPT, "awaitPromise": true, "returnByValue": true});
+ let result = conn.call("Runtime.evaluate", params, Some(&session), wait).await;
+ let text = result.as_ref().and_then(|r| r["result"]["value"].as_str()).unwrap_or_default().to_string();
+ if let Ok(report) = serde_json::from_str::<Value>(&text) {
+ return Some(report);
+ }
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ None
+ }
+ .await;
+ let _ = conn.call("Target.closeTarget", json!({"targetId": target}), None, wait).await;
+ report
+}
+
+/// Whether the Chrome kwant starts on this computer is a Google Chrome.
+fn local_is_google() -> bool {
+ super::computer::local_chrome_path().is_some_and(|p| super::computer::is_google_chrome(&p))
+}
+
+async fn identity(conn: &mut Conn, version: &Value) -> Option<Identity> {
+ let user_agent = version["userAgent"].as_str().unwrap_or_default().to_string();
+ if let Some(report) = read_report(conn).await {
+ if let Some(identity) = from_report(&user_agent, &report, false) {
+ return Some(identity);
+ }
+ }
+ tracing::debug!("identity: the browser's client hints couldn't be read; building them");
+ let google = tokio::task::spawn_blocking(local_is_google).await.unwrap_or(false);
+ let platform_version = tokio::task::spawn_blocking(local_platform_version).await.unwrap_or_default();
+ from_version(
+ version["product"].as_str().unwrap_or_default(),
+ &user_agent,
+ google,
+ std::env::consts::OS,
+ std::env::consts::ARCH,
+ &platform_version,
+ )
+}
+
+async fn run(browser_ws: String, ready: tokio::sync::oneshot::Sender<()>) {
+ let Ok(ws) = super::browser::connect_cdp(&browser_ws).await else {
+ tracing::debug!("identity: couldn't connect to the browser");
+ return;
+ };
+ let mut conn = Conn { ws, next: 0, queued: Vec::new() };
+ let Some(version) = conn.call("Browser.getVersion", json!({}), None, Duration::from_secs(5)).await else { return };
+ if !is_headless(version["userAgent"].as_str().unwrap_or_default()) {
+ // a Chrome with a window already says what it is: nothing to set. Held open, so this
+ // browser isn't asked again on every connect.
+ let _ = ready.send(());
+ while conn.recv().await.is_some() {}
+ return;
+ }
+ let Some(identity) = identity(&mut conn, &version).await else {
+ tracing::warn!("identity: no version from the browser; its pages keep Chrome's own user agent");
+ let _ = ready.send(());
+ while conn.recv().await.is_some() {}
+ return;
+ };
+ tracing::info!(user_agent = %identity.user_agent, "identity: every page gets the browser's own identity without the headless token");
+ let attach = json!({"autoAttach": true, "waitForDebuggerOnStart": true, "flatten": true});
+ let Some(attach_id) = conn.send("Target.setAutoAttach", attach.clone(), None).await else { return };
+ let override_params = json!({"userAgent": identity.user_agent, "userAgentMetadata": identity.metadata});
+ let mut ready = Some(ready);
+ let mut attached_all = false;
+ // overrides sent for the targets already open, not yet answered
+ let mut pending: std::collections::HashSet<u64> = Default::default();
+ while let Some(message) = conn.recv().await {
+ if let Some(id) = message["id"].as_u64() {
+ if id == attach_id {
+ attached_all = true;
+ }
+ pending.remove(&id);
+ if attached_all && pending.is_empty() {
+ if let Some(ready) = ready.take() {
+ let _ = ready.send(());
+ }
+ }
+ continue;
+ }
+ if message["method"] != "Target.attachedToTarget" {
+ continue;
+ }
+ let params = &message["params"];
+ let Some(session) = params["sessionId"].as_str() else { continue };
+ let kind = params["targetInfo"]["type"].as_str().unwrap_or_default();
+ if takes_identity(kind) {
+ if let Some(id) = conn.send("Network.setUserAgentOverride", override_params.clone(), Some(session)).await {
+ if !attached_all {
+ pending.insert(id);
+ }
+ }
+ }
+ if has_children(kind) {
+ let _ = conn.send("Target.setAutoAttach", attach.clone(), Some(session)).await;
+ }
+ if params["waitingForDebugger"].as_bool().unwrap_or(false) {
+ let _ = conn.send("Runtime.runIfWaitingForDebugger", json!({}), Some(session)).await;
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn names(list: &Value) -> Vec<String> {
+ list.as_array().unwrap().iter().map(|b| format!("{}={}", b["brand"].as_str().unwrap(), b["version"].as_str().unwrap())).collect()
+ }
+
+ const LINUX_HEADLESS_UA: &str = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/154.0.0.0 Safari/537.36";
+
+ #[test]
+ fn the_brand_lists_match_what_chromium_154_sends() {
+ // read from Chromium 154.0.8037.92 on the server (header echo and getHighEntropyValues)
+ let (brands, full) = brand_lists("154.0.8037.92", None).unwrap();
+ assert_eq!(names(&brands), ["Not A(Brand=99", "Chromium=154"]);
+ assert_eq!(names(&full), ["Not A(Brand=99.0.0.0", "Chromium=154.0.8037.92"]);
+ }
+
+ #[test]
+ fn google_chrome_has_three_brands_in_chromes_order() {
+ let (brands, full) = brand_lists("131.0.6778.86", Some("Google Chrome")).unwrap();
+ // Chrome 131's own header: "Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"
+ assert_eq!(names(&brands), ["Google Chrome=131", "Chromium=131", "Not_A Brand=24"]);
+ assert_eq!(names(&full)[0], "Google Chrome=131.0.6778.86");
+ let (brands, _) = brand_lists("154.0.8037.92", Some("Google Chrome")).unwrap();
+ assert!(names(&brands).contains(&"Google Chrome=154".to_string()));
+ assert!(!names(&brands).iter().any(|b| b.contains("Headless")));
+ }
+
+ #[test]
+ fn built_from_get_version_for_chrome_and_chromium_on_each_platform() {
+ let mac = from_version("Chrome/131.0.6778.86", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/131.0.0.0 Safari/537.36", true, "macos", "aarch64", "15.1.0").unwrap();
+ assert_eq!(mac.user_agent, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36");
+ assert_eq!(mac.metadata["platform"], "macOS");
+ assert_eq!(mac.metadata["platformVersion"], "15.1.0");
+ assert_eq!(mac.metadata["architecture"], "arm");
+ assert_eq!(mac.metadata["bitness"], "64");
+ assert!(names(&mac.metadata["brands"]).contains(&"Google Chrome=131".to_string()));
+
+ let win = from_version("Chrome/140.0.7339.80", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/140.0.0.0 Safari/537.36", true, "windows", "x86_64", "").unwrap();
+ assert_eq!(win.metadata["platform"], "Windows");
+ assert_eq!(win.metadata["architecture"], "x86");
+ assert!(!win.user_agent.contains("Headless"));
+ assert!(names(&win.metadata["fullVersionList"]).contains(&"Google Chrome=140.0.7339.80".to_string()));
+
+ let linux = from_version("Chrome/154.0.8037.92", LINUX_HEADLESS_UA, false, "linux", "aarch64", "").unwrap();
+ assert_eq!(linux.metadata["platform"], "Linux");
+ assert_eq!(names(&linux.metadata["brands"]), ["Not A(Brand=99", "Chromium=154"]);
+ for identity in [&mac, &win, &linux] {
+ assert_eq!(identity.metadata["mobile"], false);
+ assert_eq!(identity.metadata["model"], "");
+ assert!(!identity.metadata.to_string().contains("Headless"));
+ }
+ assert_eq!(from_version("HeadlessChrome", LINUX_HEADLESS_UA, false, "linux", "x86_64", ""), None);
+ }
+
+ #[test]
+ fn a_report_from_the_browser_is_kept_as_it_is() {
+ // Chromium 154 windowless on the server, read on chrome://version
+ let report = json!({"architecture":"arm","bitness":"64","brands":[{"brand":"Not A(Brand","version":"99"},{"brand":"Chromium","version":"154"}],"fullVersionList":[{"brand":"Not A(Brand","version":"99.0.0.0"},{"brand":"Chromium","version":"154.0.8037.92"}],"mobile":false,"model":"","platform":"Linux","platformVersion":"","wow64":false});
+ let identity = from_report(LINUX_HEADLESS_UA, &report, false).unwrap();
+ assert_eq!(identity.user_agent, "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/154.0.0.0 Safari/537.36");
+ assert_eq!(identity.metadata["brands"], report["brands"]);
+ assert_eq!(identity.metadata["fullVersionList"], report["fullVersionList"]);
+ assert_eq!(identity.metadata["architecture"], "arm");
+ assert_eq!(identity.metadata["fullVersion"], "154.0.8037.92");
+ }
+
+ #[test]
+ fn a_headless_brand_in_the_report_becomes_google_chrome() {
+ let report = json!({"architecture":"arm","bitness":"64","brands":[{"brand":"HeadlessChrome","version":"131"},{"brand":"Chromium","version":"131"},{"brand":"Not_A Brand","version":"24"}],"fullVersionList":[{"brand":"HeadlessChrome","version":"131.0.6778.86"},{"brand":"Chromium","version":"131.0.6778.86"},{"brand":"Not_A Brand","version":"24.0.0.0"}],"mobile":false,"model":"","platform":"macOS","platformVersion":"15.1.0","wow64":false});
+ let identity = from_report("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/131.0.0.0 Safari/537.36", &report, false).unwrap();
+ assert_eq!(names(&identity.metadata["brands"]), ["Google Chrome=131", "Chromium=131", "Not_A Brand=24"]);
+ assert_eq!(identity.metadata["platformVersion"], "15.1.0");
+ assert!(!identity.metadata.to_string().contains("Headless"));
+ // a report missing the product it should name is rebuilt in Chrome's order
+ let partial = json!({"brands":[{"brand":"Chromium","version":"131"}],"fullVersionList":[{"brand":"Chromium","version":"131.0.6778.86"}],"platform":"macOS"});
+ let identity = from_report("HeadlessChrome/131.0.0.0", &partial, true).unwrap();
+ assert_eq!(names(&identity.metadata["brands"]), ["Google Chrome=131", "Chromium=131", "Not_A Brand=24"]);
+ // no version anywhere: nothing to build from
+ assert_eq!(from_report("x", &json!({"brands":[],"fullVersionList":[]}), false), None);
+ }
+
+ #[test]
+ fn product_versions() {
+ assert_eq!(product_version("Chrome/154.0.8037.92"), Some("154.0.8037.92"));
+ assert_eq!(product_version("HeadlessChrome/131.0.6778.86"), Some("131.0.6778.86"));
+ assert_eq!(product_version("Chrome/154"), None);
+ assert!(is_headless(LINUX_HEADLESS_UA));
+ assert!(!is_headless(&headed(LINUX_HEADLESS_UA)));
+ }
+
+ /// Real check, opt-in: starts Chrome the way local mode does (windowless unless
+ /// `KWNT_REAL_HEADED` is set, which needs a display), keeps its identity as a live view's
+ /// connection does, then runs `KWNT_REAL_IDENTITY_DRIVER` with the browser's DevTools address
+ /// as its last argument, which checks the pages, popups and workers.
+ #[tokio::test]
+ #[ignore]
+ async fn real_chrome_keeps_its_identity() {
+ let Ok(driver) = std::env::var("KWNT_REAL_IDENTITY_DRIVER") else { return };
+ let headless = std::env::var("KWNT_REAL_HEADED").is_err();
+ let profile = tempfile::tempdir().unwrap();
+ let (endpoint, windowless) = super::super::computer::ensure_local_chrome(profile.path(), headless).await.unwrap();
+ assert_eq!(windowless, headless);
+ let browser = super::super::browser::BrowserController::at_endpoint(&endpoint, None, true);
+ browser.keep_identity().await;
+ let version: Value = reqwest::get(format!("{endpoint}/json/version")).await.unwrap().json().await.unwrap();
+ let ws = version["webSocketDebuggerUrl"].as_str().unwrap().to_string();
+ let status = tokio::process::Command::new("sh").arg("-c").arg(format!("{driver} '{ws}'")).status().await.unwrap();
+ let _ = browser.send_cdp_command("Browser.close", json!({})).await;
+ assert!(status.success(), "the driver failed");
+ }
+}
diff --git a/src/sandbox/mod.rs b/src/sandbox/mod.rs
index 6e52fc8b..8a97b3cd 100644
--- a/src/sandbox/mod.rs
+++ b/src/sandbox/mod.rs
@@ -6,6 +6,7 @@ pub mod browser_history;
pub mod chrome_download;
pub mod computer;
pub mod credentials;
+pub mod identity;
pub mod manager;
pub mod popups;
pub mod cite;
@@ -13,6 +14,7 @@ pub mod progress;
pub mod reads;
pub mod safe_fs;
pub mod service;
+pub mod signin_gate;
pub mod site_guard;
pub mod vault;
diff --git a/src/sandbox/service.rs b/src/sandbox/service.rs
index bf94169f..0c649f6b 100644
--- a/src/sandbox/service.rs
+++ b/src/sandbox/service.rs
@@ -11,7 +11,7 @@ use tokio::{process::Command, sync::Mutex, time::{sleep, timeout}};
/// The VM browser's image. Bump it whenever `docker/browser.Dockerfile` or
/// `docker/browser-entrypoint.sh` change: kwant builds an image only when its tag is missing, and
/// replaces a browser container made from another tag, so the bump is what ships the change.
-pub const BROWSER_IMAGE: &str = "kwnt-browser:v2";
+pub const BROWSER_IMAGE: &str = "kwnt-browser:v3";
const BROWSER_DOCKERFILE: &str = include_str!("../../docker/browser.Dockerfile");
const BROWSER_ENTRYPOINT: &str = include_str!("../../docker/browser-entrypoint.sh");
@@ -66,6 +66,14 @@ struct SessionTarget {
target: String,
}
+/// The page before the current one in the tab `target` of the browser at `endpoint`.
+async fn previous_entry(endpoint: &str, target: &str) -> Option<String> {
+ let page = BrowserController::at_endpoint(endpoint, Some(target.to_string()), false);
+ let history = page.send_cdp_command("Page.getNavigationHistory", json!({})).await.ok()?;
+ let index = history["currentIndex"].as_u64()? as usize;
+ history["entries"].as_array()?.get(index.checked_sub(1)?)?["url"].as_str().map(str::to_string)
+}
+
pub struct BrowserService {
root: PathBuf,
endpoint: Option<String>,
@@ -146,6 +154,17 @@ impl BrowserService {
fn local_profile(&self) -> PathBuf { self.root.join("local-chrome") }
+ /// The addresses of the local Chrome's pages, or `None` when it isn't running.
+ pub async fn local_page_urls(&self) -> Option<Vec<String>> {
+ let (endpoint, _) = computer::running_local_chrome(&self.local_profile()).await?;
+ let browser = BrowserController::at_endpoint(&endpoint, None, true);
+ let targets = browser.send_cdp_command("Target.getTargets", json!({})).await.ok()?;
+ Some(targets["targetInfos"].as_array().into_iter().flatten()
+ .filter(|t| t["type"] == "page")
+ .filter_map(|t| t["url"].as_str().map(str::to_string))
+ .collect())
+ }
+
/// Shows the local Chrome as a real window (`visible`) or runs it without one, streamed into
/// the app. One profile cannot be open twice, so the running Chrome is closed and started
/// again in the other form; each bot's open page is reopened there, and sign-ins saved in the
@@ -162,7 +181,15 @@ impl BrowserService {
if let Ok(targets) = browser.send_cdp_command("Target.getTargets", json!({})).await {
for info in targets["targetInfos"].as_array().into_iter().flatten() {
if let (Some(id), Some(url)) = (info["targetId"].as_str(), info["url"].as_str()) {
- urls.insert(id.to_string(), url.to_string());
+ // a sign-in Google refused opens again at the sign-in, not at the refusal
+ let previous = if super::signin_gate::is_rejected(url) {
+ previous_entry(&endpoint, id).await
+ } else {
+ None
+ };
+ if let Some(url) = super::signin_gate::reopen_url(url, previous.as_deref()) {
+ urls.insert(id.to_string(), url);
+ }
}
}
}
@@ -209,13 +236,10 @@ impl BrowserService {
// at most one kwant Chrome per profile: reuse it, or wait for the one starting
let (endpoint, running_headless) = computer::ensure_local_chrome(&profile, headless).await
.map_err(BrowserError::Http)?;
- // a windowless Chrome started by an older kwant tells sites it is headless. Only that one,
- // which left no launch record: one kwant started itself is never restarted for it, so a
- // Chrome that ignores the user agent can't be restarted on every call
- let stale = running_headless && headless && computer::launched_headless(&profile).is_none()
- && computer::says_headless(&endpoint).await
- && computer::local_chrome_user_agent().await.is_some();
- if running_headless == headless && !stale { return Ok(endpoint); }
+ // what pages tell sites is set over DevTools (`identity`), so a Chrome in the right form
+ // will do, unless an older kwant started it marked as automated, which that can't undo
+ let older = running_headless && headless && computer::started_by_older_kwant(&profile);
+ if running_headless == headless && !older { return Ok(endpoint); }
// the other form (or that older one) is running on this profile: close it first
let _ = BrowserController::at_endpoint(&endpoint, None, true)
.send_cdp_command("Browser.close", json!({})).await;
@@ -414,6 +438,8 @@ impl BrowserService {
sleep(Duration::from_millis(250)).await;
}
}).await.map_err(|_| BrowserError::Timeout)?; }
+ // every page, popup and worker tells sites what this Chrome is, before any page loads
+ browser.keep_identity().await;
let sessions = tokio::fs::read(self.sessions_file()).await.ok()
.and_then(|bytes| serde_json::from_slice(&bytes).ok()).unwrap_or_default();
Ok(ServiceState { browser, endpoint, sessions })
@@ -869,7 +895,7 @@ mod image_tests {
use super::{BROWSER_DOCKERFILE, BROWSER_ENTRYPOINT, BROWSER_IMAGE};
use sha2::{Digest, Sha256};
- /// The browser files `kwnt-browser:v2` was built from. A change to them without a new
+ /// The browser files `kwnt-browser:v3` was built from. A change to them without a new
/// [`BROWSER_IMAGE`] would never reach a computer that already has the old tag.
#[test]
fn the_browser_image_tag_moves_with_its_files() {
@@ -879,7 +905,7 @@ mod image_tests {
let hash: String = files.finalize().iter().take(8).map(|b| format!("{b:02x}")).collect();
assert_eq!(
(BROWSER_IMAGE, hash.as_str()),
- ("kwnt-browser:v2", "52d86739629ce24f"),
+ ("kwnt-browser:v3", "8176b39255827329"),
"docker/browser files changed: bump BROWSER_IMAGE, then record the new hash here"
);
}
diff --git a/src/sandbox/signin_gate.rs b/src/sandbox/signin_gate.rs
new file mode 100644
index 00000000..6530e54b
--- /dev/null
+++ b/src/sandbox/signin_gate.rs
@@ -0,0 +1,206 @@
+//! Sign-in pages that refuse a browser run by a program, and what kwant does about them.
+//!
+//! Google (and Microsoft and Apple) judge more than the user agent before they let anyone sign in,
+//! and refuse a windowless Chrome however it introduces itself: "Couldn't sign you in. This
+//! browser or app may not be secure." A Chrome with a window, on the person's own computer, is
+//! Chrome's normal mode, so on the desktop apps the sign-in moves there (`set_local_window`), and
+//! comes back into the app once it is done. A server has no screen to open one on: the person is
+//! told the ways that do work.
+use reqwest::Url;
+
+/// Who runs a sign-in page that refuses automated browsers.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Provider {
+ Google,
+ Microsoft,
+ Apple,
+}
+
+impl Provider {
+ pub fn name(self) -> &'static str {
+ match self {
+ Provider::Google => "Google",
+ Provider::Microsoft => "Microsoft",
+ Provider::Apple => "Apple",
+ }
+ }
+}
+
+fn parse(url: &str) -> Option<Url> {
+ Url::parse(url).ok().filter(|u| u.scheme() == "https" || u.scheme() == "http")
+}
+
+/// The provider whose sign-in host `url` is on.
+pub fn provider(url: &str) -> Option<Provider> {
+ let url = parse(url)?;
+ match url.host_str()? {
+ "accounts.google.com" => Some(Provider::Google),
+ "login.microsoftonline.com" | "login.live.com" => Some(Provider::Microsoft),
+ "appleid.apple.com" | "idmsa.apple.com" => Some(Provider::Apple),
+ _ => None,
+ }
+}
+
+/// Whether `url` is a sign-in page of one of those providers (Google's account pages that aren't
+/// sign-in, such as its help, don't count).
+pub fn is_signin(url: &str) -> bool {
+ let Some(provider) = provider(url) else { return false };
+ if provider != Provider::Google {
+ return true;
+ }
+ let path = parse(url).map(|u| u.path().to_string()).unwrap_or_default();
+ ["/signin", "/v3/signin", "/o/oauth2", "/ServiceLogin", "/AccountChooser", "/InteractiveLogin"]
+ .iter()
+ .any(|prefix| path.starts_with(prefix))
+}
+
+/// Whether `url` is the page Google shows when it refused the browser: "Couldn't sign you in.
+/// This browser or app may not be secure."
+pub fn is_rejected(url: &str) -> bool {
+ provider(url) == Some(Provider::Google)
+ && parse(url).is_some_and(|u| u.path().starts_with("/v3/signin/rejected") || u.path().starts_with("/signin/rejected"))
+}
+
+/// When the live view says something about a sign-in: always on the refused page, and on any
+/// sign-in page of those providers once the person has taken control of it to sign in.
+pub fn needs_window(url: &str, person_in_control: bool) -> bool {
+ is_rejected(url) || (person_in_control && is_signin(url))
+}
+
+/// Where to open the sign-in again in a real window. Not the refused page itself, which only
+/// says no: the sign-in it came from, from its `continue` (Google puts the address it was signing
+/// in for there), else the page before it in the tab's history. Any other page opens as it is.
+pub fn reopen_url(url: &str, previous: Option<&str>) -> Option<String> {
+ if !is_rejected(url) {
+ return parse(url).map(|_| url.to_string());
+ }
+ let url = parse(url)?;
+ let next = url.query_pairs().find(|(key, _)| key == "continue").map(|(_, value)| value.to_string());
+ next.filter(|n| parse(n).is_some())
+ .or_else(|| previous.filter(|p| parse(p).is_some() && !is_rejected(p)).map(str::to_string))
+}
+
+/// The line the live view shows on such a page. `window` when a real Chrome window can be opened
+/// here (the desktop apps); else the plain way out on a server.
+pub fn notice(provider: Provider, window: bool) -> String {
+ let name = provider.name();
+ if window {
+ format!("{name} only allows sign-in in a normal Chrome window.")
+ } else {
+ format!(
+ "{name} doesn't allow sign-in from a browser on a server. Sign in on this site with email instead, or connect {name} in Apps & accounts."
+ )
+ }
+}
+
+/// The action next to [`notice`] when a window can be opened.
+pub const WINDOW_ACTION: &str = "Sign in in Chrome";
+
+/// What a live view has been told about a sign-in page, so it hears each change once.
+#[derive(Debug)]
+pub struct LiveNotice {
+ /// Whether a real Chrome window can be opened here; `None` when Chrome already is one.
+ window: Option<bool>,
+ shown: bool,
+}
+
+impl LiveNotice {
+ pub fn new(window: Option<bool>) -> Self {
+ LiveNotice { window, shown: false }
+ }
+
+ /// The message for the live view after the page moved to `url` (or the person took control
+ /// of it): `{"type":"signin","text":…,"action":…}` on such a sign-in page, `{"type":"signin",
+ /// "text":null}` once the page left the sign-in host, else nothing.
+ pub fn update(&mut self, url: &str, person_in_control: bool) -> Option<serde_json::Value> {
+ let window = self.window?;
+ let provider = provider(url);
+ if let Some(provider) = provider.filter(|_| needs_window(url, person_in_control)) {
+ if self.shown { return None; }
+ self.shown = true;
+ let action = window.then_some(WINDOW_ACTION);
+ return Some(serde_json::json!({"type":"signin","text":notice(provider, window),"action":action}));
+ }
+ if self.shown && provider.is_none() {
+ self.shown = false;
+ return Some(serde_json::json!({"type":"signin","text":null}));
+ }
+ None
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const REJECTED: &str = "https://accounts.google.com/v3/signin/rejected?app_domain=https://elevenlabs.io&continue=https://accounts.google.com/o/oauth2/auth?client_id%3Dabc%26redirect_uri%3Dhttps://elevenlabs.io/__/auth/handler&flowName=GeneralOAuthLite";
+
+ #[test]
+ fn the_refused_page_is_recognised() {
+ assert!(is_rejected(REJECTED));
+ assert!(needs_window(REJECTED, false), "a bot reaching it is enough");
+ assert!(!is_rejected("https://accounts.google.com/v3/signin/identifier?flowName=GlifWebSignIn"));
+ assert!(!is_rejected("https://example.com/v3/signin/rejected"));
+ assert!(!is_rejected("not a url"));
+ }
+
+ #[test]
+ fn other_sign_in_pages_count_once_the_person_takes_control() {
+ let identifier = "https://accounts.google.com/v3/signin/identifier?flowName=GlifWebSignIn";
+ assert!(!needs_window(identifier, false), "a bot on it may still get through");
+ assert!(needs_window(identifier, true));
+ assert!(needs_window("https://accounts.google.com/o/oauth2/v2/auth?client_id=x", true));
+ assert!(needs_window("https://login.microsoftonline.com/common/oauth2/v2.0/authorize", true));
+ assert!(needs_window("https://appleid.apple.com/auth/authorize?client_id=x", true));
+ assert!(!needs_window("https://accounts.google.com/TOS", true), "not a sign-in");
+ assert!(!needs_window("https://elevenlabs.io/sign-in", true));
+ assert!(!needs_window("https://accounts.google.com.evil.example/signin", true));
+ assert_eq!(provider("https://login.live.com/x"), Some(Provider::Microsoft));
+ }
+
+ #[test]
+ fn the_window_opens_at_the_sign_in_before_the_refusal() {
+ assert_eq!(
+ reopen_url(REJECTED, Some("https://accounts.google.com/v3/signin/identifier")).as_deref(),
+ Some("https://accounts.google.com/o/oauth2/auth?client_id=abc&redirect_uri=https://elevenlabs.io/__/auth/handler")
+ );
+ let no_continue = "https://accounts.google.com/v3/signin/rejected?app_domain=https://elevenlabs.io";
+ assert_eq!(reopen_url(no_continue, Some("https://elevenlabs.io/sign-in")).as_deref(), Some("https://elevenlabs.io/sign-in"));
+ assert_eq!(reopen_url(no_continue, Some(no_continue)), None);
+ assert_eq!(reopen_url(no_continue, None), None);
+ let bad_continue = "https://accounts.google.com/v3/signin/rejected?continue=javascript:alert(1)";
+ assert_eq!(reopen_url(bad_continue, None), None, "only a web address is opened");
+ assert_eq!(reopen_url("https://elevenlabs.io/app", None).as_deref(), Some("https://elevenlabs.io/app"));
+ }
+
+ #[test]
+ fn the_lines_say_what_to_do() {
+ assert_eq!(notice(Provider::Google, true), "Google only allows sign-in in a normal Chrome window.");
+ assert_eq!(
+ notice(Provider::Google, false),
+ "Google doesn't allow sign-in from a browser on a server. Sign in on this site with email instead, or connect Google in Apps & accounts."
+ );
+ assert!(notice(Provider::Microsoft, true).starts_with("Microsoft only allows"));
+ }
+
+ #[test]
+ fn a_live_view_hears_each_change_once() {
+ let mut live = LiveNotice::new(Some(true));
+ assert_eq!(live.update("https://elevenlabs.io/sign-in", false), None);
+ let shown = live.update(REJECTED, false).unwrap();
+ assert_eq!(shown["text"], "Google only allows sign-in in a normal Chrome window.");
+ assert_eq!(shown["action"], "Sign in in Chrome");
+ assert_eq!(live.update(REJECTED, true), None, "once");
+ assert_eq!(live.update("https://accounts.google.com/v3/signin/identifier", true), None, "still the sign-in");
+ assert_eq!(live.update("https://elevenlabs.io/app", false).unwrap()["text"], serde_json::Value::Null);
+ assert_eq!(live.update("https://elevenlabs.io/app/home", false), None);
+
+ let mut server = LiveNotice::new(Some(false));
+ let shown = server.update("https://accounts.google.com/v3/signin/identifier", true).unwrap();
+ assert!(shown["text"].as_str().unwrap().contains("from a browser on a server"));
+ assert_eq!(shown["action"], serde_json::Value::Null);
+
+ let mut windowed = LiveNotice::new(None);
+ assert_eq!(windowed.update(REJECTED, true), None, "a real window needs no line");
+ }
+}
diff --git a/src/server/browser_stream.rs b/src/server/browser_stream.rs
index 41c94fd2..55cbf1dc 100644
--- a/src/server/browser_stream.rs
+++ b/src/server/browser_stream.rs
@@ -1323,7 +1323,13 @@ async fn serve(mut socket: WebSocket, state: AppState, id: String) -> Result<(),
// Show it once records on the team's stage, whichever of its pages is shown
let mut rec = StageRecorder::new(state.clone(), super::browser_pages::page_team(&id).to_string(), shared.socket);
let pointer = Pointer::new(state.clone(), cdp.clone(), client_tx.clone());
- let result = stream(&mut socket, &ctrl, &cdp, &mut events, &mut page, &shared, &client_tx, &mut client_rx, &jobs, &mut rec, &pointer).await;
+ // a sign-in page that refuses a windowless browser: a real window on the desktop apps, the
+ // ways that work on a server, nothing when Chrome already is a window
+ let service = &state.browser_service;
+ let local = service.mode() == crate::sandbox::computer::ComputerMode::Local;
+ let window = if local && service.local_window() { None } else { Some(local && crate::sandbox::computer::window_reason().is_none()) };
+ let mut signin = crate::sandbox::signin_gate::LiveNotice::new(window);
+ let result = stream(&mut socket, &ctrl, &cdp, &mut events, &mut page, &shared, &client_tx, &mut client_rx, &jobs, &mut rec, &pointer, &mut signin).await;
// a recording live on this socket stops here (Show it once: `closed`), its steps kept, after
// the edit still pending in the page, if the page can still be reached
if rec.is_live() {
@@ -1355,12 +1361,16 @@ async fn stream(
jobs: &mpsc::UnboundedSender<Job>,
rec: &mut StageRecorder,
pointer: &Arc<Pointer>,
+ signin: &mut crate::sandbox::signin_gate::LiveNotice,
) -> (Result<(), BrowserError>, Option<PersonLease>) {
let mut lease: Option<PersonLease> = None;
// the Show it once recorder's script on new documents, while a recording is live
let mut recorder_script: Option<String> = None;
let result = async {
watch_page(cdp, shared).await?;
+ // the view may open on a sign-in that was already refused
+ let url = ctrl.current_url.lock().await.clone().unwrap_or_default();
+ if let Some(notice) = signin.update(&url, ctrl.is_held_for_person()) { send(socket, notice).await?; }
// a link to another app may have fired before the view opened, with nobody to close
// Chrome's prompt: check the page still gets input, off the loop. Not while a button is
// held, where a move would be part of someone's drag.
@@ -1391,7 +1401,12 @@ async fn stream(
// page (the opener once its popup closed) draws that picture once, and a client
// must know whose it is. Its frames wait in `events` until the loop reads them.
match read_location(cdp, ctrl).await {
- Some(location) => send(socket, location).await?,
+ Some(location) => {
+ // a "Continue with Google" popup in front
+ let url = location["url"].as_str().unwrap_or_default().to_string();
+ send(socket, location).await?;
+ if let Some(notice) = signin.update(&url, lease.is_some() || ctrl.is_held_for_person()) { send(socket, notice).await?; }
+ }
// a dialog open on the new page: the address follows when it answers
None => refresh_location(cdp, ctrl, shared, client_tx),
}
@@ -1455,6 +1470,9 @@ async fn stream(
if let Some(url) = navigated_to(method, params) {
pointer.forget_world();
let _ = client_tx.send(json!({"type":"location","url":url,"title":""}));
+ if let Some(notice) = signin.update(&url, lease.is_some() || ctrl.is_held_for_person()) {
+ let _ = client_tx.send(notice);
+ }
if rec.is_live() {
let acts = rec.on_navigated(&url).await;
recorder_acts(socket, ctrl, cdp, shared, rec, acts, &mut recorder_script).await?;
@@ -1535,6 +1553,9 @@ async fn stream(
}
let (vw, vh) = shared.view();
send(socket, json!({"type":"control","active":true,"viewport":{"width":vw,"height":vh}})).await?;
+ // taking control of a sign-in page: the person is about to sign in
+ let url = ctrl.current_url.lock().await.clone().unwrap_or_default();
+ if let Some(notice) = signin.update(&url, true) { send(socket, notice).await?; }
}
"release_control" => {
// Show it once: the edit still pending in the page is a step first
diff --git a/src/server/computer.rs b/src/server/computer.rs
index ff31e442..c661b6df 100644
--- a/src/server/computer.rs
+++ b/src/server/computer.rs
@@ -172,18 +172,24 @@ pub async fn put_computer(
#[derive(Deserialize)]
pub struct WindowPayload {
pub visible: bool,
+ /// With `visible`: the window is for a sign-in that refuses windowless browsers (the live
+ /// view's "Sign in in Chrome"), so kwant puts Chrome back in the app once the pages have left
+ /// the sign-in.
+ #[serde(default)]
+ pub until_signed_in: bool,
}
/// `PUT /api/settings/computer/window` with `{"visible":bool}`: in local mode, shows the bots'
/// Chrome as a real window (for a sign-in or CAPTCHA) or puts it back in the app. Each bot's open
/// page is reopened in the other form. 400 outside local mode or with no display for a window;
-/// 502 if Chrome could not be restarted (the previous form is kept).
+/// 502 if Chrome could not be restarted (the previous form is kept). `until_signed_in` puts it
+/// back by itself when the sign-in is over (see [`back_after_signin`]).
pub async fn put_window(
State(state): State<AppState>,
payload: Result<Json<WindowPayload>, axum::extract::rejection::JsonRejection>,
) -> Result<Json<Value>, (StatusCode, Json<Value>)> {
let fail = |status, m: String| (status, Json(json!({ "error": m })));
- let Json(WindowPayload { visible }) = payload
+ let Json(WindowPayload { visible, until_signed_in }) = payload
.map_err(|_| fail(StatusCode::BAD_REQUEST, "visible must be true or false".into()))?;
if apply_mode(&state).await != ComputerMode::Local {
return Err(fail(
@@ -196,27 +202,64 @@ pub async fn put_window(
return Err(fail(StatusCode::BAD_REQUEST, reason));
}
}
- {
- // the restarted Chrome has new pages: every controller must reconnect
- let mut controllers = state.browser_controllers.lock().await;
- if let Err(error) = state.browser_service.set_local_window(visible).await {
- tracing::warn!("Could not restart local Chrome: {}", error);
- return Err(fail(
- StatusCode::BAD_GATEWAY,
- format!("Could not restart Chrome: {error}"),
- ));
- }
- for team_id in controllers.drain().map(|(id, _)| super::browser_pages::page_team(&id).to_string()).collect::<std::collections::BTreeSet<_>>() {
- let _ = state.event_sender.send(RuntimeEvent::SandboxStatusChanged {
- team_id,
- container_name: "browser-service".into(),
- is_running: false,
- });
- }
+ // a newer switch, either way, ends the wait of an earlier sign-in
+ let generation = WINDOW_SWITCHES.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1;
+ if let Err(error) = switch_window(&state, visible).await {
+ tracing::warn!("Could not restart local Chrome: {}", error);
+ return Err(fail(StatusCode::BAD_GATEWAY, format!("Could not restart Chrome: {error}")));
+ }
+ if visible && until_signed_in {
+ tokio::spawn(back_after_signin(state.clone(), generation));
}
Ok(Json(view(&state).await))
}
+/// Counts window switches, so a sign-in wait can tell a newer switch happened.
+static WINDOW_SWITCHES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
+
+/// Restarts the local Chrome with or without a window. The restarted Chrome has new pages: every
+/// controller must reconnect, and each live view is told.
+async fn switch_window(state: &AppState, visible: bool) -> Result<(), crate::sandbox::browser::BrowserError> {
+ let mut controllers = state.browser_controllers.lock().await;
+ state.browser_service.set_local_window(visible).await?;
+ for team_id in controllers.drain().map(|(id, _)| super::browser_pages::page_team(&id).to_string()).collect::<std::collections::BTreeSet<_>>() {
+ let _ = state.event_sender.send(RuntimeEvent::SandboxStatusChanged {
+ team_id,
+ container_name: "browser-service".into(),
+ is_running: false,
+ });
+ }
+ Ok(())
+}
+
+/// After "Sign in in Chrome": puts Chrome back in the app once no page is on a sign-in host any
+/// more (two checks 2 s apart, after one was seen there). Stops waiting when the person put it
+/// back themselves, another switch happened, Chrome closed, or after 30 minutes.
+async fn back_after_signin(state: AppState, generation: u64) {
+ use crate::sandbox::signin_gate;
+ let current = || WINDOW_SWITCHES.load(std::sync::atomic::Ordering::SeqCst) == generation;
+ let started = std::time::Instant::now();
+ let mut seen = false;
+ let mut gone = 0;
+ while started.elapsed() < std::time::Duration::from_secs(30 * 60) {
+ tokio::time::sleep(std::time::Duration::from_secs(2)).await;
+ if !current() || !state.browser_service.local_window() { return; }
+ let Some(urls) = state.browser_service.local_page_urls().await else { return };
+ let on_signin = urls.iter().any(|url| signin_gate::provider(url).is_some());
+ seen |= on_signin;
+ gone = if seen && !on_signin { gone + 1 } else { 0 };
+ if gone >= 2 {
+ if !current() { return; }
+ WINDOW_SWITCHES.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ match switch_window(&state, false).await {
+ Ok(()) => tracing::info!("the sign-in in the Chrome window is over: back in the app"),
+ Err(error) => tracing::warn!("Could not put Chrome back in the app after a sign-in: {}", error),
+ }
+ return;
+ }
+ }
+}
+
/// The approvals the person set for the bot or team a local command runs for: a bot's own
/// setting, else the space of the bot or team. An unreadable setting asks.
async fn local_shell_approvals(state: &AppState, target_id: &str) -> String {
diff --git a/tests/browser_container_test.rs b/tests/browser_container_test.rs
index 8f1d59d4..6f77448b 100644
--- a/tests/browser_container_test.rs
+++ b/tests/browser_container_test.rs
@@ -1,6 +1,6 @@
//! The VM browser container's lifecycle against real Docker: run with
//! `cargo test --test browser_container_test -- --ignored` on a host with Docker and the
-//! `kwnt-browser:v2` image. Ignored by default so CI and ordinary test runs never start a container.
+//! `kwnt-browser:v3` image. Ignored by default so CI and ordinary test runs never start a container.
use kwnt::sandbox::service::{managed_container_name, BrowserService};
use std::process::Command;
use std::time::Duration;
@@ -17,7 +17,7 @@ impl Drop for Cleanup {
}
#[tokio::test]
-#[ignore = "needs Docker and the kwnt-browser:v2 image; starts a real container"]
+#[ignore = "needs Docker and the kwnt-browser:v3 image; starts a real container"]
async fn a_fresh_kwants_container_has_no_restart_and_labels_stops_at_shutdown_and_is_reaped_once_its_folder_is_gone() {
std::env::set_var(kwnt::sandbox::computer::MODE_ENV, "vm");
let tmp = tempfile::tempdir().unwrap();
diff --git a/tests/browser_stream_test.rs b/tests/browser_stream_test.rs
index fa9a3bb7..96b98820 100644
--- a/tests/browser_stream_test.rs
+++ b/tests/browser_stream_test.rs
@@ -768,7 +768,7 @@ async fn a_link_to_another_app_is_stopped_or_its_prompt_closed_so_the_tab_keeps_
/// Opt in after building docker/browser.Dockerfile. Uses disposable data and a local HTML page.
#[tokio::test]
-#[ignore = "requires Docker and the kwnt-browser:v2 image"]
+#[ignore = "requires Docker and the kwnt-browser:v3 image"]
async fn live_chromium_stream_and_isolated_sessions() {
let _ = tracing_subscriber::fmt().with_max_level(tracing::Level::WARN).try_init();
let tmp = tempfile::tempdir().unwrap();
diff --git a/tests/docker_packaging_test.rs b/tests/docker_packaging_test.rs
index 9dd4f16a..5f887dc6 100644
--- a/tests/docker_packaging_test.rs
+++ b/tests/docker_packaging_test.rs
@@ -31,3 +31,17 @@ fn test_copied_entrypoints_are_world_readable() {
assert!(!content.contains("chmod +x"), "{dockerfile} must not rely on chmod +x alone");
}
}
+
+/// The browser images start Chromium as a normal browser: no `--user-agent` (it empties the client
+/// hints Google checks before a sign-in), no `--enable-automation` in any form (Chrome reads
+/// `--enable-automation=false` as the switch being on), and `navigator.webdriver` kept false.
+#[test]
+fn test_browser_images_start_chromium_as_a_normal_browser() {
+ for script in ["docker/browser-entrypoint.sh", "docker/entrypoint.sh"] {
+ let content = std::fs::read_to_string(script).unwrap();
+ let command: String = content.lines().filter(|l| !l.trim_start().starts_with('#')).collect::<Vec<_>>().join("\n");
+ assert!(!command.contains("--user-agent"), "{script} must not set --user-agent");
+ assert!(!command.contains("--enable-automation"), "{script} must not pass --enable-automation");
+ assert!(command.contains("--disable-blink-features=AutomationControlled"), "{script} must keep navigator.webdriver false");
+ }
+}
diff --git a/tests/local_chrome_test.rs b/tests/local_chrome_test.rs
index de210bdb..69fad284 100644
--- a/tests/local_chrome_test.rs
+++ b/tests/local_chrome_test.rs
@@ -88,6 +88,11 @@ async fn local_chrome_runs_windowless_and_can_open_as_a_window() {
assert!(page_agent.contains(" Chrome/"), "page user agent: {page_agent}");
assert!(!request_agent.contains("Headless") && !page_agent.contains("Headless"),
"windowless Chrome must not say so: {request_agent} / {page_agent}");
+ // and not one a program drives: Google refuses its sign-in when this is true
+ let webdriver = ctrl.send_cdp_command("Runtime.evaluate", serde_json::json!({
+ "expression": "navigator.webdriver", "returnByValue": true,
+ })).await.unwrap();
+ assert_eq!(webdriver["result"]["value"], serde_json::json!(false), "navigator.webdriver");
// the same input path the in-app viewer uses
ctrl.dispatch_input(BrowserInput::Click { x: 100.0, y: 100.0 }).await.unwrap();
assert_eq!(title_becomes(&ctrl, "clicked 1280x800").await, "clicked 1280x800");
diff --git a/tests/local_chrome_upgrade_test.rs b/tests/local_chrome_upgrade_test.rs
index 4ba4e449..27a938e6 100644
--- a/tests/local_chrome_upgrade_test.rs
+++ b/tests/local_chrome_upgrade_test.rs
@@ -1,6 +1,6 @@
-//! Upgrading kwant with its windowless Chrome still running: that Chrome was started without
-//! kwant's user agent and tells sites it is "HeadlessChrome", so kwant restarts it once, and never
-//! again after. Skipped when no Chrome is installed.
+//! Upgrading kwant with its windowless Chrome still running: kwant 0.9.4 started it with a made-up
+//! `--user-agent` and marked automated (`navigator.webdriver`), which Google refuses to sign in,
+//! so kwant restarts it once as Chrome, and never again after. Skipped when no Chrome is installed.
#[path = "support/chrome_guard.rs"]
mod chrome_guard;
use chrome_guard::ChromeGuard;
@@ -10,11 +10,6 @@ use kwnt::sandbox::{
};
use std::time::Duration;
-async fn page_agent(endpoint: &str) -> String {
- let version: serde_json::Value = reqwest::get(format!("{endpoint}/json/version")).await.unwrap().json().await.unwrap();
- version["User-Agent"].as_str().unwrap_or_default().to_string()
-}
-
#[tokio::test]
async fn an_older_kwants_headless_chrome_is_restarted_once() {
std::env::remove_var("DISPLAY");
@@ -28,9 +23,19 @@ async fn an_older_kwants_headless_chrome_is_restarted_once() {
std::fs::create_dir_all(&profile).unwrap();
let _chrome = ChromeGuard(profile.clone());
- // what an older kwant left running: windowless, its own user agent, no launch record
+ // what kwant 0.9.4 left running: windowless, a made-up user agent, no launch record
+ let old_args = [
+ format!("--user-data-dir={}", profile.display()),
+ "--remote-debugging-port=0".into(),
+ "--remote-debugging-address=127.0.0.1".into(),
+ "--no-first-run".into(),
+ "--no-default-browser-check".into(),
+ "--headless=new".into(),
+ "--user-agent=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36".into(),
+ "about:blank".into(),
+ ];
let mut old = std::process::Command::new(&chrome)
- .args(computer::chrome_args(&profile, true, None))
+ .args(old_args)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
@@ -42,18 +47,18 @@ async fn an_older_kwants_headless_chrome_is_restarted_once() {
if let Some((e, _)) = computer::running_local_chrome(&profile).await { endpoint = Some(e); break; }
tokio::time::sleep(Duration::from_millis(250)).await;
}
- let endpoint = endpoint.expect("the older Chrome answers");
- assert!(page_agent(&endpoint).await.contains("HeadlessChrome"));
+ assert!(endpoint.is_some(), "the older Chrome answers");
assert_eq!(computer::launched_headless(&profile), None);
+ assert!(computer::started_by_older_kwant(&profile));
let service = BrowserService::new(tmp.path().to_path_buf(), None);
service.set_mode(ComputerMode::Local).await;
service.session("bot", tmp.path()).await.expect("local session");
let new_pid = computer::profile_owner(&profile).expect("a Chrome holds the profile");
assert_ne!(new_pid, old_pid, "the older Chrome is restarted");
- let (endpoint, headless) = computer::running_local_chrome(&profile).await.expect("chrome running");
+ let (_, headless) = computer::running_local_chrome(&profile).await.expect("chrome running");
assert!(headless);
- assert!(!page_agent(&endpoint).await.contains("Headless"));
+ assert!(!computer::started_by_older_kwant(&profile), "started as Chrome now");
assert_eq!(computer::launched_headless(&profile), Some(true));
// later calls keep it