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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,12 @@ The page now renders a handoff panel in the ordinary login card:
the switch makes a transfer that resolves afterwards discard its code instead of
producing a handoff, and the short-lived `better-auth.electron` cookie is cleared
around each transfer so a stale code cannot be read back as this attempt's.
- "Continue in browser" is a third exit: the session stays in this browser instead of
being handed to the desktop app. It bumps the same generation counter, so a
transfer in flight is discarded rather than opening the desktop app after the
choice, then follows the page's ordinary authenticated redirect (the validated
`redirect` target or the app root) through `window.location.replace`, which keeps
the handoff page out of history.
- Only a *confirmed* sign-out releases the handoff. `signOutWithoutRedirect` used to
swallow both failure shapes — Better Auth throws on transport failures and reports
API failures in `response.error` — so a failed sign-out was indistinguishable from
Expand Down Expand Up @@ -87,7 +93,9 @@ an intended build difference, not part of this defect.
no transfer without a choice; the link's decoded `identifier`/`state` payload
matching the URL the page navigates to; a late transfer after a switch producing
no link and no navigation; the `state`/`code_challenge` surviving the switch into
the next provider sign-in; and a failed transfer leaving an enabled retry.
the next provider sign-in; a failed transfer leaving an enabled retry; and the
web-browser exit navigating to the app's authenticated target while discarding
an in-flight transfer.
- That suite found the switch button disabled while a transfer was in flight, which
is the state the escape hatch exists for; the gate was removed.
- The failed-sign-out cases (a rejected request and an `error` response) assert the
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@ Translation: current
- 换账号按钮不受页面加载态限制:交接正为错误账号进行中,恰恰是最需要这个出口的时刻。
切换会递增一个代次计数,使之后才返回的交接结果丢弃其授权码而不生成交接链接;每次
交接前后都会清除短时效的 `better-auth.electron` cookie,避免把陈旧授权码读成本次结果。
- “在 Web 浏览器中使用”是第三个出口:会话留在当前浏览器而不交给桌面端。它同样递增
代次计数,进行中的交接会被丢弃而不会在选择之后拉起桌面应用;随后经
`window.location.replace` 走页面既有的已登录跳转(校验过的 `redirect` 目标或应用
根路径),回退不会重返交接页。
- 只有**确认成功**的退出才会放行交接。`signOutWithoutRedirect` 此前会吞掉两种失败形态
—— Better Auth 传输失败靠抛出、API 失败写在 `response.error` —— 于是退出失败与成功
无法区分,而此时浏览器的会话 cookie(正是交接会交出去的东西)仍然认证着上一个账号。
Expand Down Expand Up @@ -68,7 +72,8 @@ Translation: current
在 jsdom 中渲染真实的 `LoginPage`,配合桩 auth client,覆盖:未选择前不发起交接;链接
解码出的 `identifier`/`state` 与页面跳转的 URL 一致;切换账号后才返回的交接既不生成
链接也不触发跳转;`state`/`code_challenge` 跨越切换进入下一次 provider 登录;交接失败
后重试入口仍然可用。
后重试入口仍然可用;“在 Web 浏览器中使用”跳转已登录目标、不发起交接并丢弃进行中的
交接。
- 该测试发现交接进行中时换账号按钮被禁用,而这正是该出口存在的场景,随后移除了这一限制。
- 退出失败的两种形态(请求被拒、返回 `error`)各有用例,断言交接被阻止,并在重试成功后
恢复。把 `signOutWithoutRedirect` 改回原先吞掉失败的写法,恰好使这三个用例失败,说明
Expand Down
1 change: 1 addition & 0 deletions locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -1690,6 +1690,7 @@
"login.desktopHandoff.switchFailed": "Could not sign out of this browser. It is still signed in as the account above — try again.",
"login.desktopHandoff.switching": "Signing out of this browser...",
"login.desktopHandoff.title": "Continue to Lody Desktop",
"login.desktopHandoff.useWeb": "Continue in browser",
"login.desktopRedirect.browser.description": "Completing sign-in and opening Lody desktop.",
"login.desktopRedirect.browser.title": "Redirecting to desktop app",
"login.desktopRedirect.electron.description": "Loading your workspace...",
Expand Down
1 change: 1 addition & 0 deletions locales/zh_CN.json
Original file line number Diff line number Diff line change
Expand Up @@ -1690,6 +1690,7 @@
"login.desktopHandoff.switchFailed": "无法退出当前浏览器账号,它仍以上方账号登录,请重试。",
"login.desktopHandoff.switching": "正在退出当前浏览器账号…",
"login.desktopHandoff.title": "继续登录 Lody 桌面版",
"login.desktopHandoff.useWeb": "在 Web 浏览器中使用",
"login.desktopRedirect.browser.description": "正在完成登录并打开 Lody 桌面应用...",
"login.desktopRedirect.browser.title": "正在跳转到桌面应用",
"login.desktopRedirect.electron.description": "正在加载你的工作区...",
Expand Down
36 changes: 36 additions & 0 deletions packages/components/src/components/login-page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1377,6 +1377,29 @@ export function LoginPage({
}
}, [authClient, isElectronRenderer, loginSurface, postHog, t]);

// The third way out of the handoff: keep the session in this browser instead
// of transferring it to the desktop app. The bail-out is the same as an
// account switch — a transfer already in flight must not mint a handoff link
// (or its automatic `lody://` open) after the user chose the web — then the
// page's ordinary authenticated redirect carries the existing session into
// the app: the validated `redirect` target, or the app root.
const handleUseInWebBrowser = useCallback(async () => {
electronAccountGenerationRef.current += 1;
autoOpenedElectronHandoffRef.current = null;
setElectronHandoffUrl(null);
setIsPreparingElectronHandoff(false);
setError('');
clearElectronAuthorizationCode();
capturePostHogEvent(postHog, 'auth/electron_handoff_use_web', {
login_surface: loginSurface,
launch_mode: detectAppLaunchMode(isElectronRenderer),
device_class: detectAppDeviceClass(),
});
if (await prepareAuthenticatedRedirect()) {
replaceLocation(getRedirectTarget());
}
}, [isElectronRenderer, loginSurface, postHog, prepareAuthenticatedRedirect, replaceLocation]);

const handleLegalLinkClick = useCallback(
async (event: React.MouseEvent<HTMLAnchorElement>, url: string) => {
if (!isNativeApp) {
Expand Down Expand Up @@ -1806,6 +1829,19 @@ export function LoginPage({
</Button>
)}

{/* Not gated on `isButtonsDisabled` either: during an in-flight transfer
this is the exit that cancels it. Disabled only while signing out,
when the session this path relies on is being torn down. */}
<Button
type="button"
variant="secondary"
onClick={() => void handleUseInWebBrowser()}
className="h-10 w-full"
disabled={isSwitchingElectronAccount}
>
{t('login.desktopHandoff.useWeb', 'Continue in browser')}
</Button>

{/* Deliberately not gated on `isButtonsDisabled`: a transfer in flight for
the wrong account is exactly when the user needs this way out, and its
late result is discarded by the account generation. */}
Expand Down
84 changes: 81 additions & 3 deletions packages/components/tests/electron-browser-login-handoff.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,8 @@ describe('electron browser sign-in handoff', () => {
authClient: LodyAuthClient,
sessionValue: StableSessionValue = createSessionValue(true),
desktop = false,
standaloneClient?: ConvexReactClient
standaloneClient?: ConvexReactClient,
replaceLocation: (path: string) => void = () => undefined
) => {
await act(async () => {
root.render(
Expand All @@ -118,11 +119,11 @@ describe('electron browser sign-in handoff', () => {
{standaloneClient ? (
<ConvexProvider client={standaloneClient}>
<CloudPlatformProvider>
<LoginPage replaceLocation={() => undefined} isElectronRenderer={desktop} />
<LoginPage replaceLocation={replaceLocation} isElectronRenderer={desktop} />
</CloudPlatformProvider>
</ConvexProvider>
) : (
<LoginPage replaceLocation={() => undefined} isElectronRenderer={desktop} />
<LoginPage replaceLocation={replaceLocation} isElectronRenderer={desktop} />
)}
</StableSessionContext.Provider>
</AuthProvider>
Expand Down Expand Up @@ -245,6 +246,83 @@ describe('electron browser sign-in handoff', () => {
expect(findButton(/Use a different account/i)).toBeDefined();
});

it('offers continuing in the web browser instead of a desktop handoff', async () => {
const transferUser = vi.fn<TransferUser>(async () => ({
data: { electron_authorization_code: 'code-123' },
}));
const replaceLocation = vi.fn();
await renderLoginPage(
createAuthClient({ transferUser }),
undefined,
false,
undefined,
replaceLocation
);

await clickButton(/Continue in browser/i);

// The browser session is already good for the web app, so nothing is
// transferred and the page's normal authenticated target is used.
expect(transferUser).not.toHaveBeenCalled();
expect(replaceLocation).toHaveBeenCalledWith('/');
expect(deepLinkNavigations).toEqual([]);
});

it('still leaves for the web app after the handoff link exists', async () => {
const replaceLocation = vi.fn();
await renderLoginPage(
createAuthClient({
transferUser: async () => ({ data: { electron_authorization_code: 'code-123' } }),
}),
undefined,
false,
undefined,
replaceLocation
);
await clickButton(/Continue with this account/i);
expect(handoffLink()).not.toBeNull();

await clickButton(/Continue in browser/i);

expect(replaceLocation).toHaveBeenCalledWith('/');
// The mock leaves the page mounted; the panel must no longer offer the
// handoff link it just retracted.
expect(handoffLink()).toBeNull();
});

it('drops a transfer that lands after the user left for the web app', async () => {
let resolveTransfer: ((code: string) => void) | undefined;
const transferUser = vi.fn<TransferUser>(
() =>
new Promise((resolve) => {
resolveTransfer = (code) => resolve({ data: { electron_authorization_code: code } });
})
);
const replaceLocation = vi.fn();
await renderLoginPage(
createAuthClient({ transferUser }),
undefined,
false,
undefined,
replaceLocation
);

await clickButton(/Continue with this account/i);
expect(transferUser).toHaveBeenCalledTimes(1);

await clickButton(/Continue in browser/i);
expect(replaceLocation).toHaveBeenCalledWith('/');

await act(async () => {
resolveTransfer?.('code-from-old-account');
});

// The code minted for the desktop app must not open it after the user
// chose the web.
expect(handoffLink()).toBeNull();
expect(deepLinkNavigations).toEqual([]);
});

it('returns Nightly authorization to Nightly and preserves its PKCE state', async () => {
window.history.replaceState({}, '', `/login${ELECTRON_QUERY}&desktop_channel=nightly`);
await renderLoginPage(
Expand Down
Loading