Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(auth): sign the desktop app in instead of the browser (#7775)

Eric Hayesf7af35bf6f49
diff --git a/apps/web/src/features/auth/primitives/session.ts b/apps/web/src/features/auth/primitives/session.ts
index defc95cbe1..01387190ee 100644
--- a/apps/web/src/features/auth/primitives/session.ts
+++ b/apps/web/src/features/auth/primitives/session.ts
@@ -1,15 +1,36 @@
-import { createEffect, on } from 'solid-js';
+import { type Accessor, createEffect, on } from 'solid-js';
import type { AuthContext } from '../context/auth-context';
-/** Redeem the session code an SSO return put on the URL. */
+/**
+ * Redeem the session code an SSO return put on the URL.
+ *
+ * The code does not always arrive with the first render. The desktop app is
+ * already parked on the signed-out route when the hosted flow hands back
+ * `macro:///welcome?token=...`, so the deep link is a query-only navigation
+ * that leaves this view mounted — reading the code once at setup would miss
+ * it and leave the app signed out. Each code is redeemed at most once.
+ */
export function redeemSessionToken(
context: Pick<AuthContext, 'redeemSessionToken' | 'notifyFailure'>,
- token: string | undefined
+ token: Accessor<string | undefined>
) {
- if (!token) return;
- void context.redeemSessionToken(token).then((ok) => {
- if (!ok) context.notifyFailure('Sign-in failed. Please try again.');
- });
+ const attempted = new Set<string>();
+ createEffect(
+ on(token, async (code) => {
+ if (!code || attempted.has(code)) return;
+ attempted.add(code);
+ // Redemption reaches the network and then re-primes the session, so it
+ // can reject as well as answer false. Both leave the user signed out
+ // and both have to say so.
+ let redeemed = false;
+ try {
+ redeemed = await context.redeemSessionToken(code);
+ } catch (error) {
+ console.error('Failed to redeem session code', error);
+ }
+ if (!redeemed) context.notifyFailure('Sign-in failed. Please try again.');
+ })
+ );
}
/** Tell analytics who signed in, once per user. */
diff --git a/apps/web/src/features/auth/useSsoLogin.test.ts b/apps/web/src/features/auth/useSsoLogin.test.ts
index 9bd83c4fe3..c0cc34126b 100644
--- a/apps/web/src/features/auth/useSsoLogin.test.ts
+++ b/apps/web/src/features/auth/useSsoLogin.test.ts
@@ -4,15 +4,19 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
nativeMobile: false,
+ platform: 'web' as 'web' | 'desktop' | 'ios' | 'android',
servers: { 'auth-service': '' },
location: { state: undefined as RedirectLocation | undefined },
track: vi.fn(),
createNativeAuthSession: vi.fn(),
+ openDesktopAuthSession: vi.fn(),
authenticate: vi.fn(),
sessionLogin: vi.fn(),
unsetTokenPromise: vi.fn(),
invalidateAllAfterLogin: vi.fn(),
initEmailLink: vi.fn(),
+ setPostLoginRedirect: vi.fn(),
+ toastFailure: vi.fn(),
}));
vi.mock('@app/lib/analytics/analytics-context', () => ({
@@ -25,9 +29,17 @@ vi.mock('@core/mobile/isNativeMobilePlatform', () => ({
}));
vi.mock('@core/auth/native-auth', () => ({
createNativeAuthSession: mocks.createNativeAuthSession,
+ openDesktopAuthSession: mocks.openDesktopAuthSession,
+ DESKTOP_AUTH_CALLBACK_URL: 'macro:///login',
+}));
+vi.mock('@core/util/platform', () => ({
+ isPlatform: (target: string) => mocks.platform === target,
+}));
+vi.mock('@core/util/postLoginRedirect', () => ({
+ setPostLoginRedirect: mocks.setPostLoginRedirect,
}));
vi.mock('@core/component/Toast/Toast', () => ({
- toast: { failure: vi.fn() },
+ toast: { failure: mocks.toastFailure },
}));
vi.mock('@core/email-link', () => ({
useEmailLinks: () => ({ initEmailLink: mocks.initEmailLink }),
@@ -53,6 +65,8 @@ beforeEach(() => {
location: { href: loginUrl, origin: new URL(loginUrl).origin },
});
mocks.nativeMobile = false;
+ mocks.platform = 'web';
+ mocks.openDesktopAuthSession.mockResolvedValue({ success: true });
mocks.servers['auth-service'] = proxyAuthHost;
mocks.location.state = undefined;
mocks.createNativeAuthSession.mockReturnValue({
@@ -119,6 +133,70 @@ describe('useSsoLogin', () => {
);
});
+ // The desktop shell must not depend on the native navigation plugin
+ // rewriting this URL: that only happens for navigations it classifies as
+ // external, which the development proxy's same-origin auth host is not.
+ it.each([proxyAuthHost, 'https://gateway.macro.com/auth'])(
+ 'sends desktop SSO to the system browser with a deep-link callback through %s',
+ async (host) => {
+ mocks.platform = 'desktop';
+ mocks.servers['auth-service'] = host;
+
+ await useSsoLogin()('google');
+
+ const authUrl = new URL(mocks.openDesktopAuthSession.mock.calls[0][0]);
+ expect(`${authUrl.origin}${authUrl.pathname}`).toBe(`${host}/login/sso`);
+ expect(authUrl.searchParams.get('original_url')).toBe('macro:///login');
+ expect(authUrl.searchParams.get('is_mobile')).toBe('true');
+ expect(authUrl.searchParams.get('idp_name')).toBe('google');
+ expect(authUrl.searchParams.get('referral_code')).toBe('invite');
+ // The webview must stay on the SPA; navigating it away is what used to
+ // hand the flow to the navigation plugin.
+ expect(window.location.href).toBe(loginUrl);
+ expect(mocks.createNativeAuthSession).not.toHaveBeenCalled();
+ expect(mocks.sessionLogin).not.toHaveBeenCalled();
+ expect(mocks.track).toHaveBeenCalledWith('login', { method: 'google' }, [
+ 'posthog',
+ ]);
+ }
+ );
+
+ it('parks the desktop destination for after sign-in', async () => {
+ mocks.platform = 'desktop';
+ mocks.location.state = {
+ originalLocation: {
+ state: null,
+ key: '',
+ query: {},
+ pathname: '/doc/document-id',
+ search: '?referral_code=original-invite',
+ hash: '#comment',
+ },
+ };
+
+ await useSsoLogin()('google');
+
+ expect(mocks.setPostLoginRedirect).toHaveBeenCalledWith(
+ '/doc/document-id?referral_code=original-invite#comment'
+ );
+ const authUrl = new URL(mocks.openDesktopAuthSession.mock.calls[0][0]);
+ expect(authUrl.searchParams.get('original_url')).toBe('macro:///login');
+ });
+
+ it('reports a desktop browser that will not open', async () => {
+ mocks.platform = 'desktop';
+ mocks.openDesktopAuthSession.mockResolvedValue({
+ success: false,
+ error: 'Unable to start authentication',
+ });
+
+ await useSsoLogin()('google');
+
+ expect(mocks.toastFailure).toHaveBeenCalledWith(
+ 'Sign-in failed. Please try again.'
+ );
+ });
+
it.each([proxyAuthHost, 'https://gateway.macro.com/auth'])(
'uses native authentication and redeems the session code through %s',
async (host) => {
diff --git a/apps/web/src/features/auth/useSsoLogin.ts b/apps/web/src/features/auth/useSsoLogin.ts
index 7aef34fe1d..3063f92029 100644
--- a/apps/web/src/features/auth/useSsoLogin.ts
+++ b/apps/web/src/features/auth/useSsoLogin.ts
@@ -1,17 +1,54 @@
import type { AnalyticsProvider } from '@app/lib/analytics';
import { useAnalytics } from '@app/lib/analytics/analytics-context';
-import { createNativeAuthSession } from '@core/auth/native-auth';
+import {
+ createNativeAuthSession,
+ DESKTOP_AUTH_CALLBACK_URL,
+ openDesktopAuthSession,
+} from '@core/auth/native-auth';
import { toast } from '@core/component/Toast/Toast';
import { SERVER_HOSTS } from '@core/constant/servers';
import { useEmailLinks } from '@core/email-link';
import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';
import type { RedirectLocation } from '@core/util/authRedirect';
import { unsetTokenPromise } from '@core/util/fetchWithToken';
+import { isPlatform } from '@core/util/platform';
+import { setPostLoginRedirect } from '@core/util/postLoginRedirect';
import { invalidateAllAfterLogin } from '@queries/auth/user-info';
import { authServiceClient } from '@service-auth/client';
import { useLocation } from '@solidjs/router';
import { DEVELOPMENT_PROXY_PREFIX } from '../../lib/core/constant/developmentProxy';
+/**
+ * Run the hosted flow in the system browser and return through the `macro://`
+ * deep link.
+ *
+ * The callback is pinned rather than derived from the current page by the
+ * native navigation plugin: that rewrite only runs for a navigation it
+ * classifies as external, so behind the development proxy's same-origin auth
+ * host it never fires and the callback lands back in the browser. It also
+ * derives the callback from whatever page sign-in started on — normally
+ * `/welcome`, which does not redeem session codes.
+ */
+async function startDesktopSso(
+ authUrl: URL,
+ originalLocation: RedirectLocation['originalLocation'] | undefined
+) {
+ authUrl.searchParams.set('original_url', DESKTOP_AUTH_CALLBACK_URL);
+
+ // The callback route sends the user home, so park the destination they were
+ // headed for; BasePathComponent restores it after sign-in.
+ if (originalLocation) {
+ const { pathname, search, hash } = originalLocation;
+ setPostLoginRedirect(`${pathname}${search}${hash}`);
+ }
+
+ const result = await openDesktopAuthSession(authUrl.toString());
+ if (!result.success) {
+ console.error('Failed to open the browser for sign-in', result.error);
+ toast.failure('Sign-in failed. Please try again.');
+ }
+}
+
export function useSsoLogin(opts?: { signupMode?: boolean }) {
const analytics = useAnalytics();
const location = useLocation<RedirectLocation>();
@@ -35,10 +72,14 @@ export function useSsoLogin(opts?: { signupMode?: boolean }) {
if (referral_code) authUrl.searchParams.set('referral_code', referral_code);
- // The hosted OAuth callback sets cookies on macro.com. A proxied browser
- // needs the existing session-code handoff to establish cookies locally.
+ const desktop = isPlatform('desktop');
+
+ // The hosted OAuth callback sets cookies on macro.com. A proxied browser,
+ // and every native shell, needs the session-code handoff to establish
+ // cookies locally instead.
if (
isNativeMobilePlatform() ||
+ desktop ||
authUrl.pathname.startsWith(`${DEVELOPMENT_PROXY_PREFIX}/`)
) {
authUrl.searchParams.set('is_mobile', 'true');
@@ -86,6 +127,12 @@ export function useSsoLogin(opts?: { signupMode?: boolean }) {
return;
}
+ if (desktop) {
+ analytics.track(analyticsEvent, { method: idp_name }, analyticsProviders);
+ await startDesktopSso(authUrl, location.state?.originalLocation);
+ return;
+ }
+
if (location.state?.originalLocation) {
const { pathname, search, hash } = location.state.originalLocation;
diff --git a/apps/web/src/features/auth/views/auth-view.test.tsx b/apps/web/src/features/auth/views/auth-view.test.tsx
index deb780d2e1..1fe46f6c1a 100644
--- a/apps/web/src/features/auth/views/auth-view.test.tsx
+++ b/apps/web/src/features/auth/views/auth-view.test.tsx
@@ -1,4 +1,5 @@
import { cleanup, fireEvent, screen, waitFor } from '@solidjs/testing-library';
+import { createSignal } from 'solid-js';
import { afterEach, describe, expect, it, vi } from 'vitest';
import type { AuthIntent } from '../context/auth-context';
import type { FakeAuthWorld } from '../tests/fake-auth-context';
@@ -46,6 +47,37 @@ function setup(
return { fake, verified, signIn };
}
+/** As `setup`, but the session code can arrive after the view has mounted. */
+function setupWithTokenSignal(
+ options: {
+ world?: Partial<FakeAuthWorld>;
+ /** Replaces the fake backend's redemption, e.g. to make it reject. */
+ redeem?: (token: string) => Promise<boolean>;
+ } = {}
+) {
+ const [token, setToken] = createSignal<string | undefined>(undefined);
+ const { fake } = renderWithFakeAuth(
+ () => (
+ <AuthView
+ intent="login"
+ showApple={false}
+ compact={false}
+ token={token()}
+ signedIn={(user) => (
+ <p data-testid="signed-in">
+ {user().email} {user().tutorialComplete ? 'returning' : 'new'}
+ </p>
+ )}
+ />
+ ),
+ options.world
+ );
+ // Safe after render: the effect's first run sees no code and returns early,
+ // so nothing redeems until setToken.
+ if (options.redeem) fake.context.redeemSessionToken = options.redeem;
+ return { fake, setToken };
+}
+
const click = (name: string | RegExp) =>
fireEvent.click(screen.getByRole('button', { name }));
// Stepper swaps steps on the next frame, so each step is awaited.
@@ -218,6 +250,56 @@ describe('single sign-on', () => {
await screen.findByText('[email protected] new');
});
+ // The desktop app is already parked on the signed-out route when the
+ // `macro://` auth callback comes back, so the session code arrives as a
+ // query-only navigation that never remounts this view.
+ it('redeems a session code that arrives after mount', async () => {
+ const { setToken } = setupWithTokenSignal({
+ world: { sessionTokens: { 'tok-deep-link': '[email protected]' } },
+ });
+ await screen.findByRole('button', { name: 'Continue with Google' });
+
+ setToken('tok-deep-link');
+
+ await screen.findByText('[email protected] new');
+ });
+
+ it('redeems a late session code only once', async () => {
+ const { fake, setToken } = setupWithTokenSignal({
+ world: { sessionTokens: { 'tok-deep-link': '[email protected]' } },
+ });
+ setToken('tok-deep-link');
+ await screen.findByText('[email protected] new');
+
+ setToken('tok-deep-link');
+
+ await waitFor(() =>
+ expect(
+ fake.calls().filter((call) => call === 'redeem:tok-deep-link')
+ ).toHaveLength(1)
+ );
+ });
+
+ // Redemption re-primes the session after the network call, so it can reject
+ // rather than answer false — that must still tell the user.
+ it('reports a session code whose redemption throws', async () => {
+ const consoleError = vi
+ .spyOn(console, 'error')
+ .mockImplementation(() => {});
+ const { fake, setToken } = setupWithTokenSignal({
+ redeem: () => Promise.reject(new Error('network down')),
+ });
+
+ setToken('tok-deep-link');
+
+ await waitFor(() =>
+ expect(fake.notifications()).toEqual([
+ 'Sign-in failed. Please try again.',
+ ])
+ );
+ consoleError.mockRestore();
+ });
+
it('reports a session code that cannot be redeemed', async () => {
const { fake } = setup({ token: 'expired' });
await waitFor(() =>
diff --git a/apps/web/src/features/auth/views/auth-view.tsx b/apps/web/src/features/auth/views/auth-view.tsx
index bfa2a3d1e8..d1d7ebdcf8 100644
--- a/apps/web/src/features/auth/views/auth-view.tsx
+++ b/apps/web/src/features/auth/views/auth-view.tsx
@@ -62,7 +62,7 @@ export function AuthView(props: {
onVerified: props.onVerified,
});
createSessionIdentity(context);
- redeemSessionToken(context, props.token);
+ redeemSessionToken(context, () => props.token);
onMount(() => context.pageView(props.intent));
const user = () => {
diff --git a/apps/web/src/lib/core/auth/native-auth.test.ts b/apps/web/src/lib/core/auth/native-auth.test.ts
index 445ef8c669..8a65f388c6 100644
--- a/apps/web/src/lib/core/auth/native-auth.test.ts
+++ b/apps/web/src/lib/core/auth/native-auth.test.ts
@@ -9,7 +9,11 @@ vi.mock('@core/util/platform', () => ({
}));
vi.mock('@tauri-apps/api/core', () => ({ invoke: mocks.invoke }));
-import { createNativeAuthSession } from './native-auth';
+import {
+ createNativeAuthSession,
+ DESKTOP_AUTH_CALLBACK_URL,
+ openDesktopAuthSession,
+} from './native-auth';
beforeEach(() => {
vi.resetAllMocks();
@@ -71,6 +75,35 @@ describe('native browser authentication', () => {
});
});
+ it('hands the desktop flow to the system browser', async () => {
+ mocks.invoke.mockResolvedValue(undefined);
+ await expect(
+ openDesktopAuthSession('https://gateway.macro.com/auth/login/sso')
+ ).resolves.toEqual({ success: true });
+ expect(mocks.invoke).toHaveBeenCalledWith('plugin:opener|open_url', {
+ url: 'https://gateway.macro.com/auth/login/sso',
+ });
+ });
+
+ it('settles a desktop browser that will not open', async () => {
+ mocks.invoke.mockRejectedValueOnce(new Error('no opener'));
+ await expect(
+ openDesktopAuthSession('https://gateway.macro.com/auth/login/sso')
+ ).resolves.toEqual({
+ success: false,
+ error: 'Unable to start authentication',
+ });
+ });
+
+ // The deep-link bridge maps this to a `/login` router navigation, and only
+ // an empty host parses that way — `macro://login` would arrive as a host.
+ it('points the desktop callback at a route that redeems a session code', () => {
+ const callback = new URL(DESKTOP_AUTH_CALLBACK_URL);
+ expect(callback.protocol).toBe('macro:');
+ expect(callback.host).toBe('');
+ expect(callback.pathname).toBe('/login');
+ });
+
it('accepts account-link callbacks without a login session token', async () => {
mocks.invoke.mockResolvedValue({ success: true });
await expect(
diff --git a/apps/web/src/lib/core/auth/native-auth.ts b/apps/web/src/lib/core/auth/native-auth.ts
index 73152b35f8..47a87a3cd5 100644
--- a/apps/web/src/lib/core/auth/native-auth.ts
+++ b/apps/web/src/lib/core/auth/native-auth.ts
@@ -7,6 +7,34 @@ export type NativeAuthResult = {
error?: string;
};
+/**
+ * Where the hosted flow sends the desktop app's session code. The deep-link
+ * bridge turns `macro:///login?token=...` into a `/login` router navigation,
+ * and that route redeems the code — so it is pinned here rather than derived
+ * from the page the user signed in from, which is usually `/welcome` and
+ * ignores the code entirely.
+ */
+export const DESKTOP_AUTH_CALLBACK_URL = 'macro:///login';
+
+/**
+ * Hand the hosted flow to the system browser. Unlike the mobile sheet this
+ * never resolves with a token: the desktop shell has no in-app browser, so
+ * the session code comes back out-of-band through the `macro://` deep link.
+ * Success here only means the browser was launched.
+ */
+export async function openDesktopAuthSession(
+ authUrl: string
+): Promise<NativeAuthResult> {
+ try {
+ await invoke('plugin:opener|open_url', { url: authUrl });
+ return { success: true };
+ } catch {
+ // Mirrors createNativeAuthSession: a bridge failure settles the caller
+ // instead of leaving the sign-in button spinning.
+ return { success: false, error: 'Unable to start authentication' };
+ }
+}
+
/** Create the callback before asking the backend to construct OAuth state. */
export function createNativeAuthSession(iosCallbackHost: string) {
const android = getNativeMobilePlatform() === 'android';