From d7ebae60d1c19caa23a07a2e1c82905ad20e7240 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 19 Jun 2026 11:16:00 -0400 Subject: [PATCH] feat: Allow Passkey logins on desktop (#12749) * feat: Allow Passkey logins on desktop * Refactor, address PR feedback --- app/scenes/Login/Login.tsx | 6 +- .../components/AuthenticationProvider.tsx | 96 +--------- .../PasskeyAuthenticationProvider.tsx | 177 ++++++++++++++++++ plugins/passkeys/server/auth/passkeys.test.ts | 28 ++- plugins/passkeys/server/auth/passkeys.ts | 25 +++ shared/i18n/locales/en_US/translation.json | 3 +- 6 files changed, 237 insertions(+), 98 deletions(-) create mode 100644 app/scenes/Login/components/PasskeyAuthenticationProvider.tsx diff --git a/app/scenes/Login/Login.tsx b/app/scenes/Login/Login.tsx index ffab0fda0c..4b0426b54c 100644 --- a/app/scenes/Login/Login.tsx +++ b/app/scenes/Login/Login.tsx @@ -118,7 +118,11 @@ function Login({ children, onBack }: Props) { } }, [query]); - if (auth.authenticated) { + // A passkey login initiated from the desktop app must complete the login + // ceremony even when this browser already has a session. + const isPasskeyLogin = query.get("method") === "passkey"; + + if (auth.authenticated && !isPasskeyLogin) { const postLoginPath = spendPostLoginPath(); if (postLoginPath) { return ; diff --git a/app/scenes/Login/components/AuthenticationProvider.tsx b/app/scenes/Login/components/AuthenticationProvider.tsx index 4a1c67de10..d6824fd79f 100644 --- a/app/scenes/Login/components/AuthenticationProvider.tsx +++ b/app/scenes/Login/components/AuthenticationProvider.tsx @@ -1,20 +1,15 @@ -import { startAuthentication } from "@simplewebauthn/browser"; import { EmailIcon } from "outline-icons"; import * as React from "react"; import { useTranslation } from "react-i18next"; -import { toast } from "sonner"; import styled from "styled-components"; -import { errToString } from "@shared/utils/error"; import { Client } from "@shared/types"; import ButtonLarge from "~/components/ButtonLarge"; import InputLarge from "~/components/InputLarge"; import PluginIcon from "~/components/PluginIcon"; -import Tooltip from "~/components/Tooltip"; import { client } from "~/utils/ApiClient"; import Desktop from "~/utils/Desktop"; import { getRedirectUrl } from "~/utils/urls"; -import { CSRF } from "@shared/constants"; -import { getCookie } from "tiny-cookie"; +import { PasskeyAuthenticationProvider } from "./PasskeyAuthenticationProvider"; type Props = React.ComponentProps & { id: string; @@ -32,7 +27,6 @@ function AuthenticationProvider(props: Props) { const [authState, setAuthState] = React.useState("initial"); const [isSubmitting, setSubmitting] = React.useState(false); const [email, setEmail] = React.useState(""); - const formRef = React.useRef(null); const { isCreate, id, name, authUrl, onEmailSuccess, preferOTP, ...rest } = props; const clientType = Desktop.isElectron() ? Client.Desktop : Client.Web; @@ -73,93 +67,7 @@ function AuthenticationProvider(props: Props) { const href = getRedirectUrl(authUrl); if (id === "passkeys") { - const handleSubmitPasskey = async ( - event: React.SyntheticEvent - ) => { - event.preventDefault(); - - try { - const resp = await client.post( - "/passkeys.generateAuthenticationOptions", - undefined, - { - baseUrl: "/auth", - } - ); - const { challengeId, ...optionsData } = resp.data; - const authResp = await startAuthentication(optionsData); - - // Populate hidden form fields with authentication data - if (formRef.current) { - const createInputs = (obj: Record, prefix = "") => { - Object.entries(obj).forEach(([key, value]) => { - if (value === undefined || value === null) { - return; - } - - const fieldName = prefix ? `${prefix}[${key}]` : key; - - if (typeof value === "object" && !Array.isArray(value)) { - createInputs(value as Record, fieldName); - } else { - // Create hidden input for primitive values - const input = document.createElement("input"); - input.type = "hidden"; - input.name = fieldName; - input.value = String(value as string | number | boolean); - formRef.current?.appendChild(input); - } - }); - }; - - createInputs({ - ...authResp, - challengeId, - [CSRF.fieldName]: getCookie(CSRF.cookieName), - client: clientType, - }); - } - - // Submit form natively to let browser handle redirect and cookies - formRef.current?.submit(); - } catch (err) { - toast.error(errToString(err)); - } - }; - - const isDesktop = Desktop.isElectron(); - const button = ( - } - fullwidth - disabled={isDesktop} - {...rest} - > - {t("Continue with Passkey")} - - ); - - return ( - -
- {isDesktop ? ( - - {button} - - ) : ( - button - )} -
-
- ); + return ; } if (id === "email") { diff --git a/app/scenes/Login/components/PasskeyAuthenticationProvider.tsx b/app/scenes/Login/components/PasskeyAuthenticationProvider.tsx new file mode 100644 index 0000000000..58a5389364 --- /dev/null +++ b/app/scenes/Login/components/PasskeyAuthenticationProvider.tsx @@ -0,0 +1,177 @@ +import { startAuthentication } from "@simplewebauthn/browser"; +import * as React from "react"; +import { useTranslation } from "react-i18next"; +import { toast } from "sonner"; +import styled from "styled-components"; +import { getCookie } from "tiny-cookie"; +import { CSRF } from "@shared/constants"; +import { Client } from "@shared/types"; +import { errToString } from "@shared/utils/error"; +import ButtonLarge from "~/components/ButtonLarge"; +import PluginIcon from "~/components/PluginIcon"; +import useQuery from "~/hooks/useQuery"; +import { client } from "~/utils/ApiClient"; +import Desktop from "~/utils/Desktop"; + +type Props = React.ComponentProps; + +/** + * Flattens a nested object into form field entries using bracket notation + * (e.g. `response[authenticatorData]`) so the values can be rendered as hidden + * inputs and submitted as a regular form. + * + * @param obj The object to flatten. + * @param prefix Internal accumulator for nested field names. + * @param out Internal accumulator for the flattened result. + * @returns A flat map of field name to string value. + */ +function flattenFormFields( + obj: Record, + prefix = "", + out: Record = {} +): Record { + Object.entries(obj).forEach(([key, value]) => { + if (value === undefined || value === null) { + return; + } + + const fieldName = prefix ? `${prefix}[${key}]` : key; + + if (typeof value === "object" && !Array.isArray(value)) { + flattenFormFields(value as Record, fieldName, out); + } else { + out[fieldName] = String(value as string | number | boolean); + } + }); + + return out; +} + +/** + * Renders the "Continue with Passkey" login option and runs the WebAuthn + * authentication ceremony. + * + * In the desktop app the ceremony cannot run inside Electron's Chromium, so the + * flow is opened in the system browser and the resulting session is returned to + * the app via the outline:// deep link, mirroring the SSO desktop flow. + */ +export function PasskeyAuthenticationProvider(props: Props) { + const { t } = useTranslation(); + const query = useQuery(); + const formRef = React.useRef(null); + const hasAutoStarted = React.useRef(false); + const [fields, setFields] = React.useState | null>( + null + ); + const [isAuthenticating, setIsAuthenticating] = React.useState(false); + + // True when this page was opened in the system browser from the desktop app + // to complete a passkey login (see the /auth/passkey route). In that case the + // resulting session must be handed back to the desktop app rather than the + // browser. + const isDesktopRedirect = + query.get("method") === "passkey" && query.get("client") === Client.Desktop; + + const runAuthentication = React.useCallback(async (verifyClient: Client) => { + setIsAuthenticating(true); + try { + const resp = await client.post( + "/passkeys.generateAuthenticationOptions", + undefined, + { + baseUrl: "/auth", + } + ); + const { challengeId, ...optionsData } = resp.data; + const authResp = await startAuthentication(optionsData); + + // Render the authentication response as hidden inputs; the effect below + // submits the form natively once they're in the DOM so the browser + // follows the redirect and applies cookies. + setFields( + flattenFormFields({ + ...authResp, + challengeId, + [CSRF.fieldName]: getCookie(CSRF.cookieName), + client: verifyClient, + }) + ); + } catch (err) { + toast.error(errToString(err)); + // Re-enable the button so the user can retry; on success the form submits + // and navigates away, so there's no need to reset there. + setIsAuthenticating(false); + } + }, []); + + // Submit the form once the hidden fields from the ceremony have rendered. + React.useEffect(() => { + if (fields) { + formRef.current?.submit(); + } + }, [fields]); + + // When returning from the desktop app to complete passkey login, start the + // ceremony automatically once. + React.useEffect(() => { + if (isDesktopRedirect && !Desktop.isElectron() && !hasAutoStarted.current) { + hasAutoStarted.current = true; + void runAuthentication(Client.Desktop); + } + }, [isDesktopRedirect, runAuthentication]); + + const handleSubmit = (event: React.SyntheticEvent) => { + event.preventDefault(); + + // The WebAuthn ceremony cannot run inside Electron's Chromium as it lacks + // platform authenticator support. Open the flow in the system browser, + // which returns to the app via the outline:// deep link like SSO login. + if (Desktop.isElectron()) { + window.location.href = `/auth/passkey?client=${Client.Desktop}`; + return; + } + + void runAuthentication(isDesktopRedirect ? Client.Desktop : Client.Web); + }; + + return ( + +
+ {fields && + Object.entries(fields).map(([fieldName, value]) => ( + + ))} + } + fullwidth + {...props} + disabled={isAuthenticating} + > + {t("Continue with Passkey")} + +
+
+ ); +} + +const Wrapper = styled.div` + width: 100%; +`; + +const Form = styled.form` + width: 100%; + display: flex; + justify-content: space-between; +`; diff --git a/plugins/passkeys/server/auth/passkeys.test.ts b/plugins/passkeys/server/auth/passkeys.test.ts index 9adb78d6cf..1fad053090 100644 --- a/plugins/passkeys/server/auth/passkeys.test.ts +++ b/plugins/passkeys/server/auth/passkeys.test.ts @@ -1,5 +1,5 @@ import type { APIContext } from "@server/types"; -import { getExpectedOrigin } from "./passkeys"; +import { getExpectedOrigin, getPasskeyLoginRedirect } from "./passkeys"; describe("getExpectedOrigin", () => { // Helper to mock APIContext for testing @@ -87,3 +87,29 @@ describe("getExpectedOrigin", () => { expect(getExpectedOrigin(ctx)).toBe("http://outline.example.com:8080"); }); }); + +describe("getPasskeyLoginRedirect", () => { + it("should redirect to the desktop passkey flow when client=desktop", () => { + expect(getPasskeyLoginRedirect("desktop")).toBe( + "/?method=passkey&client=desktop" + ); + }); + + it("should default to the web client when client is missing", () => { + expect(getPasskeyLoginRedirect(undefined)).toBe( + "/?method=passkey&client=web" + ); + }); + + it("should default to the web client when client is invalid", () => { + expect(getPasskeyLoginRedirect("bogus")).toBe( + "/?method=passkey&client=web" + ); + }); + + it("should default to the web client when client is an array", () => { + expect(getPasskeyLoginRedirect(["desktop", "web"])).toBe( + "/?method=passkey&client=web" + ); + }); +}); diff --git a/plugins/passkeys/server/auth/passkeys.ts b/plugins/passkeys/server/auth/passkeys.ts index 621326987f..6a4a904a65 100644 --- a/plugins/passkeys/server/auth/passkeys.ts +++ b/plugins/passkeys/server/auth/passkeys.ts @@ -225,6 +225,31 @@ router.post( } ); +/** + * Resolves the login screen redirect for the desktop passkey entrypoint, + * normalizing an untrusted client query parameter to a known value. + * + * @param client - the raw client value from the request query. + * @returns the relative path to redirect the browser to. + */ +export const getPasskeyLoginRedirect = ( + client: string | string[] | undefined +): string => { + const normalized = client === Client.Desktop ? Client.Desktop : Client.Web; + return `/?method=passkey&client=${normalized}`; +}; + +/** + * Entry point for passkey login from the desktop app. The WebAuthn ceremony + * cannot run inside Electron's Chromium, so the desktop client opens this URL + * in the system browser. We forward to the login screen, which auto-starts the + * ceremony and returns the authenticated session via the outline:// deep link, + * mirroring the existing SSO desktop flow. + */ +router.get("passkey", (ctx: APIContext) => { + ctx.redirect(getPasskeyLoginRedirect(ctx.query.client)); +}); + router.post( "passkeys.generateAuthenticationOptions", validate(T.PasskeysGenerateAuthenticationOptionsSchema), diff --git a/shared/i18n/locales/en_US/translation.json b/shared/i18n/locales/en_US/translation.json index ec7197004a..0f5789643b 100644 --- a/shared/i18n/locales/en_US/translation.json +++ b/shared/i18n/locales/en_US/translation.json @@ -978,8 +978,6 @@ "Triggers": "Triggers", "Mention users and more": "Mention users and more", "Insert block": "Insert block", - "Continue with Passkey": "Continue with Passkey", - "Passkeys are not supported in the desktop app": "Passkeys are not supported in the desktop app", "Sign In": "Sign In", "Continue with Email": "Continue with Email", "Continue with {{ authProviderName }}": "Continue with {{ authProviderName }}", @@ -1005,6 +1003,7 @@ "Authentication failed – this login method was disabled by a workspace admin.": "Authentication failed – this login method was disabled by a workspace admin.", "The workspace you are trying to join requires an invite before you can create an account.<1>Please request an invite from your workspace admin and try again.": "The workspace you are trying to join requires an invite before you can create an account.<1>Please request an invite from your workspace admin and try again.", "Sorry, an unknown error occurred.": "Sorry, an unknown error occurred.", + "Continue with Passkey": "Continue with Passkey", "Choose installation": "Choose installation", "Enter the address of an Outline install to connect to": "Enter the address of an Outline install to connect to", "This doesn’t appear to be a valid installation": "This doesn’t appear to be a valid installation",