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): return to invites and deep links after sign-in (#9885)

Jacob Beckerman5e137670368a
diff --git a/apps/web/src/features/auth/auth.tsx b/apps/web/src/features/auth/auth.tsx
index ac6521e4b0..cab57f9378 100644
--- a/apps/web/src/features/auth/auth.tsx
+++ b/apps/web/src/features/auth/auth.tsx
@@ -8,12 +8,19 @@ import { LoadingBlock } from '@core/component/LoadingBlock';
import { isMobile } from '@core/mobile/isMobile';
import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';
import { virtualKeyboardVisible } from '@core/mobile/virtualKeyboard';
+import { deepEqual } from '@core/util/compareUtils';
import { getNativeMobilePlatform } from '@core/util/platform';
import { getWebOrigin } from '@core/util/webOrigin';
import { useNavigate, useSearchParams } from '@solidjs/router';
-import { onMount, Show } from 'solid-js';
+import { createMemo, onMount } from 'solid-js';
+import { match } from 'ts-pattern';
import { AuthProvider, type AuthUser } from './context/auth-context';
import { sessionTokenParam } from './core/email-code';
+import {
+ AGENT_SETUP_PATH,
+ postAuthTarget,
+ readRedirectParam,
+} from './core/post-auth-target';
import { createAppAuthContext } from './create-app-auth-context';
import { AuthView } from './views/auth-view';
import { MobileWebSignupView } from './views/mobile-web-signup-view';
@@ -53,7 +60,12 @@ export function Login(props: { signupMode?: boolean }) {
onAgentSignup={() => navigate('/signup/agent')}
// Desktop sign-up resolves into onboarding's frame either way.
pending={desktopSignup() ? () => <OnboardingPending /> : undefined}
- signedIn={(user) => <PostAuthGate user={user()} />}
+ signedIn={(user) => (
+ <PostAuthGate
+ user={user()}
+ redirect={readRedirectParam(params.redirect)}
+ />
+ )}
/>
</AuthProvider>
);
@@ -91,29 +103,35 @@ function agentSignupDestination(user: AuthUser, teamInvite?: string) {
return '/';
}
-const AGENT_SETUP_PATH = '/agent-setup';
-
function needsAgentSetup(user: AuthUser) {
return user.isAgent && !user.tutorialComplete;
}
-function PostAuthGate(props: { user: AuthUser }) {
- const needsOnboarding = () =>
- !isMobile() &&
- !isNativeMobilePlatform() &&
- !props.user.tutorialComplete &&
- !props.user.isAgent;
+/**
+ * Pages that need an account (team and channel invites, meetings) link to
+ * `/login?redirect=`; honor it once signed in, opening an invite before
+ * onboarding so the invitee joins first.
+ */
+function PostAuthGate(props: { user: AuthUser; redirect: unknown }) {
+ // Compared by value so a refreshed user object never remounts onboarding.
+ const target = createMemo(
+ () =>
+ postAuthTarget({
+ tutorialComplete: props.user.tutorialComplete,
+ isAgent: props.user.isAgent,
+ onboardsOnThisDevice: !isMobile() && !isNativeMobilePlatform(),
+ redirect: props.redirect,
+ }),
+ undefined,
+ { equals: deepEqual }
+ );
return (
- <Show
- when={needsOnboarding()}
- fallback={
- <PostLoginRedirect
- target={needsAgentSetup(props.user) ? AGENT_SETUP_PATH : '/'}
- />
- }
- >
- <Onboarding />
- </Show>
+ <>
+ {match(target())
+ .with({ t: 'onboarding' }, ({ next }) => <Onboarding next={next} />)
+ .with({ t: 'navigate' }, ({ to }) => <PostLoginRedirect target={to} />)
+ .exhaustive()}
+ </>
);
}
diff --git a/apps/web/src/features/auth/core/post-auth-target.test.ts b/apps/web/src/features/auth/core/post-auth-target.test.ts
new file mode 100644
index 0000000000..32c21972e3
--- /dev/null
+++ b/apps/web/src/features/auth/core/post-auth-target.test.ts
@@ -0,0 +1,141 @@
+import { describe, expect, it } from 'vitest';
+import {
+ AGENT_SETUP_PATH,
+ desktopAuthCallbackUrl,
+ postAuthTarget,
+ readRedirectParam,
+} from './post-auth-target';
+
+const newUser = {
+ tutorialComplete: false,
+ isAgent: false,
+ onboardsOnThisDevice: true,
+};
+const returningUser = { ...newUser, tutorialComplete: true };
+
+describe('postAuthTarget', () => {
+ it('sends a new invitee to the team invite before onboarding', () => {
+ expect(
+ postAuthTarget({ ...newUser, redirect: '/team-invite?id=abc' })
+ ).toEqual({ t: 'navigate', to: '/team-invite?id=abc' });
+ });
+
+ it('sends a new invitee to a channel invite before onboarding', () => {
+ expect(
+ postAuthTarget({ ...newUser, redirect: '/channel-invite?id=abc' })
+ ).toEqual({ t: 'navigate', to: '/channel-invite?id=abc' });
+ });
+
+ it('carries any other deep link through onboarding as next', () => {
+ expect(postAuthTarget({ ...newUser, redirect: '/meet/new' })).toEqual({
+ t: 'onboarding',
+ next: '/meet/new',
+ });
+ });
+
+ it('onboards without a deep link', () => {
+ expect(postAuthTarget({ ...newUser, redirect: undefined })).toEqual({
+ t: 'onboarding',
+ next: undefined,
+ });
+ });
+
+ it('returns an onboarded user to the deep link', () => {
+ expect(
+ postAuthTarget({ ...returningUser, redirect: '/team-invite?id=abc' })
+ ).toEqual({ t: 'navigate', to: '/team-invite?id=abc' });
+ });
+
+ it('lands an onboarded user on Home without a deep link', () => {
+ expect(postAuthTarget({ ...returningUser, redirect: undefined })).toEqual({
+ t: 'navigate',
+ to: '/',
+ });
+ });
+
+ it.each<[unknown]>([
+ ['https://evil.example/team-invite'],
+ ['//evil.example/team-invite'],
+ ['/\\evil.example'],
+ ['team-invite?id=abc'],
+ [['/team-invite?id=abc']],
+ ])('ignores an unsafe redirect %o', (redirect) => {
+ expect(postAuthTarget({ ...returningUser, redirect })).toEqual({
+ t: 'navigate',
+ to: '/',
+ });
+ });
+
+ it('does not treat a lookalike path as an invite', () => {
+ expect(
+ postAuthTarget({ ...newUser, redirect: '/team-invites-archive' })
+ ).toEqual({ t: 'onboarding', next: '/team-invites-archive' });
+ });
+
+ it('skips desktop onboarding on mobile and honors the deep link', () => {
+ expect(
+ postAuthTarget({
+ ...newUser,
+ onboardsOnThisDevice: false,
+ redirect: '/meet/new',
+ })
+ ).toEqual({ t: 'navigate', to: '/meet/new' });
+ });
+
+ it('sends an agent that has not finished setup to agent setup', () => {
+ expect(
+ postAuthTarget({
+ ...newUser,
+ isAgent: true,
+ redirect: '/team-invite?id=abc',
+ })
+ ).toEqual({ t: 'navigate', to: AGENT_SETUP_PATH });
+ });
+});
+
+/** What the app sees after the auth service reads `original_url` from its
+ * query and, when `doubleDecode`, decodes it once more (`UrlEncoded<Url>`). */
+function redirectAfterAuthService(callback: string, doubleDecode: boolean) {
+ const returned = doubleDecode ? decodeURIComponent(callback) : callback;
+ const url = new URL(`${returned}&token=code`);
+ return readRedirectParam(url.searchParams.get('redirect'));
+}
+
+describe('desktopAuthCallbackUrl', () => {
+ it.each([true, false])(
+ 'carries a redirect through the auth service (double decode: %o)',
+ (doubleDecode) => {
+ const redirect = '/team-invite?id=abc&source=email';
+ const callback = desktopAuthCallbackUrl('macro:///login', redirect);
+ expect(callback.startsWith('macro:///login?redirect=')).toBe(true);
+ expect(redirectAfterAuthService(callback, doubleDecode)).toBe(redirect);
+ }
+ );
+
+ it.each<[unknown]>([[null], ['https://evil.example'], ['//evil.example']])(
+ 'leaves the callback alone for %o',
+ (redirect) => {
+ expect(desktopAuthCallbackUrl('macro:///login', redirect)).toBe(
+ 'macro:///login'
+ );
+ }
+ );
+});
+
+describe('readRedirectParam', () => {
+ it('passes a decoded redirect through', () => {
+ expect(readRedirectParam('/team-invite?id=abc')).toBe(
+ '/team-invite?id=abc'
+ );
+ });
+
+ it('decodes a redirect that arrives still encoded', () => {
+ expect(readRedirectParam('%2Fteam-invite%3Fid%3Dabc')).toBe(
+ '/team-invite?id=abc'
+ );
+ });
+
+ it('drops a malformed encoding', () => {
+ expect(readRedirectParam('%2F%E0%A4%A')).toBeUndefined();
+ });
+});
diff --git a/apps/web/src/features/auth/core/post-auth-target.ts b/apps/web/src/features/auth/core/post-auth-target.ts
new file mode 100644
index 0000000000..f483acfc65
--- /dev/null
+++ b/apps/web/src/features/auth/core/post-auth-target.ts
@@ -0,0 +1,75 @@
+import { sanitizeNext } from '@app/features/onboarding/core/next-target';
+
+export const AGENT_SETUP_PATH = '/agent-setup';
+
+/** Where a freshly signed-in user goes: into onboarding, or straight to a path. */
+export type PostAuthTarget =
+ | { t: 'onboarding'; next: string | undefined }
+ | { t: 'navigate'; to: string };
+
+/**
+ * Invite pages answer before onboarding. Joining first means onboarding opens
+ * already on the team, instead of burying the invite six steps in, where
+ * most invitees quit before reaching it.
+ */
+function isInvitePath(path: string): boolean {
+ return /^\/(team|channel)-invite(\?|$)/.test(path);
+}
+
+/**
+ * Resolves the `/login?redirect=` deep link after sign-in. Pages that need an
+ * account (team and channel invites, meetings) send people here with the page
+ * to come back to; without this the link was dropped and everyone landed on
+ * Home or in onboarding.
+ */
+export function postAuthTarget(input: {
+ tutorialComplete: boolean;
+ isAgent: boolean;
+ /** Mobile and native apps skip desktop onboarding. */
+ onboardsOnThisDevice: boolean;
+ redirect: unknown;
+}): PostAuthTarget {
+ if (input.isAgent && !input.tutorialComplete) {
+ return { t: 'navigate', to: AGENT_SETUP_PATH };
+ }
+ const redirect = sanitizeNext(input.redirect);
+ const needsOnboarding =
+ input.onboardsOnThisDevice && !input.tutorialComplete && !input.isAgent;
+ if (needsOnboarding && !(redirect && isInvitePath(redirect))) {
+ return { t: 'onboarding', next: redirect };
+ }
+ return { t: 'navigate', to: redirect ?? '/' };
+}
+
+/**
+ * The desktop sign-in callback, carrying the page's `redirect`. Desktop SSO
+ * returns through a pinned `macro:///login` deep link rather than the page
+ * sign-in started on, so the deep link would otherwise be lost; the auth
+ * service keeps the query and appends the session code.
+ *
+ * The auth service URL-decodes `original_url` once more after reading it from
+ * the query (`UrlEncoded<Url>`), so the redirect is encoded twice here: a
+ * redirect with its own `&` would otherwise split into separate parameters.
+ * {@link readRedirectParam} accepts it whether or not that extra decode runs.
+ */
+export function desktopAuthCallbackUrl(
+ callbackUrl: string,
+ redirect: unknown
+): string {
+ const next = sanitizeNext(redirect);
+ if (!next) return callbackUrl;
+ return `${callbackUrl}?redirect=${encodeURIComponent(encodeURIComponent(next))}`;
+}
+
+/**
+ * The login page's `redirect` parameter, decoded once more when it arrives
+ * still encoded (a desktop callback the auth service did not decode twice).
+ */
+export function readRedirectParam(value: unknown): unknown {
+ if (typeof value !== 'string' || !value.startsWith('%2F')) return value;
+ try {
+ return decodeURIComponent(value);
+ } catch {
+ return undefined;
+ }
+}
diff --git a/apps/web/src/features/auth/useSsoLogin.ts b/apps/web/src/features/auth/useSsoLogin.ts
index 64d9b84b35..baf913193a 100644
--- a/apps/web/src/features/auth/useSsoLogin.ts
+++ b/apps/web/src/features/auth/useSsoLogin.ts
@@ -18,6 +18,7 @@ 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';
+import { desktopAuthCallbackUrl } from './core/post-auth-target';
/**
* Run the hosted flow in the system browser and return through the `macro://`
@@ -34,7 +35,16 @@ async function startDesktopSso(
authUrl: URL,
originalLocation: RedirectLocation['originalLocation'] | undefined
) {
- authUrl.searchParams.set('original_url', DESKTOP_AUTH_CALLBACK_URL);
+ // `/login?redirect=` deep links (invites, meetings) ride the callback, so
+ // the login page can open them once signed in, before onboarding for an
+ // invite.
+ authUrl.searchParams.set(
+ 'original_url',
+ desktopAuthCallbackUrl(
+ DESKTOP_AUTH_CALLBACK_URL,
+ new URL(window.location.href).searchParams.get('redirect')
+ )
+ );
// The callback route sends the user home, so park the destination they were
// headed for; BasePathComponent restores it after sign-in.
diff --git a/apps/web/src/features/onboarding/onboarding.tsx b/apps/web/src/features/onboarding/onboarding.tsx
index 40a257ee64..37ac6b4ae1 100644
--- a/apps/web/src/features/onboarding/onboarding.tsx
+++ b/apps/web/src/features/onboarding/onboarding.tsx
@@ -10,8 +10,12 @@ import { createAppOnboardingContext } from './create-app-onboarding-context';
import { OnboardingFlowView } from './views/onboarding-flow-view';
import { SignupJourneyView } from './views/signup-journey-view';
-/** The signed-in onboarding flow, wired to the app's services and router. */
-export function Onboarding() {
+/**
+ * The signed-in onboarding flow, wired to the app's services and router.
+ * `next` overrides the page's own `?next`, for hosts (sign-in) whose deep
+ * link arrives under another name.
+ */
+export function Onboarding(props: { next?: string }) {
const context = createAppOnboardingContext();
const navigate = useNavigate();
const userInfoQuery = useUserInfoQuery();
@@ -30,7 +34,10 @@ export function Onboarding() {
return (
<OnboardingProvider value={context}>
<OnboardingFlowView
- next={typeof params.next === 'string' ? params.next : undefined}
+ next={
+ props.next ??
+ (typeof params.next === 'string' ? params.next : undefined)
+ }
step={requestedStep}
checkoutReturn={parseCheckoutReturn(params)}
onNavigate={(target) => navigate(target, { replace: true })}
diff --git a/docs/agent-guide/settings.md b/docs/agent-guide/settings.md
index f1a68590f8..85f9a3b281 100644
--- a/docs/agent-guide/settings.md
+++ b/docs/agent-guide/settings.md
@@ -205,6 +205,13 @@ and its email and **Copy link** go to `/app/signup/agent?team_invite=<id>` (see
grants a Pro seat (an enterprise team, or one with a subscription), otherwise
**Free to join**. Examples: [desktop](media/team-invite-email/desktop.png) and
[mobile](media/team-invite-email/mobile.png).
+A signed-out invitee who opens an emailed or link invite is sent to
+`/app/login?redirect=/team-invite?…`; once signed in or signed up (including
+desktop Google sign-in, whose `macro:///login` callback carries the redirect)
+they return to the invite before onboarding, so they join first and onboarding
+opens on the team. Channel invites (`/channel-invite`) also open before
+onboarding. Other `?redirect=` deep links, such as meetings, return there after
+sign-in, or after onboarding for a new account.
An unanswered invite gets up to two reminder emails, with subjects starting
**Reminder:**, 3 days after the last email and 4 days after that. Invites more
than 14 days old, already-members, and invites whose sender left the team get none.