feat: Allow Passkey logins on desktop (#12749)

* feat: Allow Passkey logins on desktop

* Refactor, address PR feedback
This commit is contained in:
Tom Moor authored and GitHub committed 2026-06-19 11:16:00 -04:00
1 parent b4dbfc269e
commit d7ebae60d1
6 files changed
+237 -98

No files matched your search

+5 -1
View File
@@ -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 <Redirect to={postLoginPath} />;
@@ -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<typeof ButtonLarge> & {
id: string;
@@ -32,7 +27,6 @@ function AuthenticationProvider(props: Props) {
const [authState, setAuthState] = React.useState<AuthState>("initial");
const [isSubmitting, setSubmitting] = React.useState(false);
const [email, setEmail] = React.useState("");
const formRef = React.useRef<HTMLFormElement>(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<HTMLFormElement>
) => {
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<string, unknown>, 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<string, unknown>, 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 = (
<ButtonLarge
type="submit"
icon={<PluginIcon id={id} color="currentColor" />}
fullwidth
disabled={isDesktop}
{...rest}
>
{t("Continue with Passkey")}
</ButtonLarge>
);
return (
<Wrapper>
<Form
ref={formRef}
method="POST"
action="/auth/passkeys.verifyAuthentication"
onSubmit={handleSubmitPasskey}
>
{isDesktop ? (
<Tooltip
content={t("Passkeys are not supported in the desktop app")}
>
{button}
</Tooltip>
) : (
button
)}
</Form>
</Wrapper>
);
return <PasskeyAuthenticationProvider {...rest} />;
}
if (id === "email") {
@@ -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<typeof ButtonLarge>;
/**
* 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<string, unknown>,
prefix = "",
out: Record<string, string> = {}
): Record<string, string> {
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<string, unknown>, 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<HTMLFormElement>(null);
const hasAutoStarted = React.useRef(false);
const [fields, setFields] = React.useState<Record<string, string> | 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<HTMLFormElement>) => {
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 (
<Wrapper>
<Form
ref={formRef}
method="POST"
action="/auth/passkeys.verifyAuthentication"
onSubmit={handleSubmit}
>
{fields &&
Object.entries(fields).map(([fieldName, value]) => (
<input
key={fieldName}
type="hidden"
name={fieldName}
value={value}
readOnly
/>
))}
<ButtonLarge
type="submit"
icon={<PluginIcon id="passkeys" color="currentColor" />}
fullwidth
{...props}
disabled={isAuthenticating}
>
{t("Continue with Passkey")}
</ButtonLarge>
</Form>
</Wrapper>
);
}
const Wrapper = styled.div`
width: 100%;
`;
const Form = styled.form`
width: 100%;
display: flex;
justify-content: space-between;
`;
+27 -1
View File
@@ -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"
);
});
});
+25
View File
@@ -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),
+1 -2
View File
@@ -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></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></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",