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): stop mobile sign-in code lockouts reading as "Invalid code." (#7947)

teo1aa689a06975
diff --git a/apps/web/src/features/auth/browser-test/README.md b/apps/web/src/features/auth/browser-test/README.md
index 442caa04b9..727f6f332c 100644
--- a/apps/web/src/features/auth/browser-test/README.md
+++ b/apps/web/src/features/auth/browser-test/README.md
@@ -25,3 +25,4 @@ To click through by hand, run
other address signs up as a first-time user.
- `/?page=signup` is the desktop sign-up through onboarding's opening slides.
- `/?page=mobile-signup` is the mobile-web email capture.
+- Add `&verifyLatency=300` to make code checks take a network round trip.
diff --git a/apps/web/src/features/auth/browser-test/auth.browser.e2e.ts b/apps/web/src/features/auth/browser-test/auth.browser.e2e.ts
index a975958756..fbc5c2b1d8 100644
--- a/apps/web/src/features/auth/browser-test/auth.browser.e2e.ts
+++ b/apps/web/src/features/auth/browser-test/auth.browser.e2e.ts
@@ -17,14 +17,37 @@ test('a returning user signs in with an emailed code', async ({ page }) => {
test('a wrong code can be corrected without starting over', async ({
page,
}) => {
- await openFixture(page, '/?page=login');
+ await openFixture(page, '/?page=login&verifyLatency=300');
await page.getByRole('button', { name: 'Continue with email' }).click();
await signInWithCode(page, '[email protected]', '111111');
await expect(page.getByRole('alert')).toHaveText('Invalid code.');
- await page.getByLabel('One-time code').fill('424242');
+ const code = page.getByLabel('One-time code');
+ await expect(code).toHaveValue('');
+ await expect(code).toBeFocused();
+ await expect(page.getByRole('button', { name: 'Verify' })).toBeDisabled();
+ await page.keyboard.press('Enter');
+ expect(
+ (await fakeCalls(page)).filter((call) => call.startsWith('verify:'))
+ ).toEqual(['verify:[email protected]:111111']);
+ await page.keyboard.type('424242');
await expectLanded(page, '/');
});
+test('a rate-limited code check says to wait instead of calling the code invalid', async ({
+ page,
+}) => {
+ await openFixture(page, '/?page=login', {
+ codeAttempts: { '[email protected]': 5 },
+ });
+ await page.getByRole('button', { name: 'Continue with email' }).click();
+ await signInWithCode(page, '[email protected]', '424242');
+ await expect(page.getByRole('alert')).toHaveText(
+ 'Too many attempts. Wait a minute, then try again.'
+ );
+ await expect(page.getByLabel('One-time code')).toHaveValue('424242');
+ await expect(page.getByRole('button', { name: 'Verify' })).toBeEnabled();
+});
+
test('Google sign-in comes back with a session code the page redeems', async ({
page,
}) => {
diff --git a/apps/web/src/features/auth/browser-test/fixture.tsx b/apps/web/src/features/auth/browser-test/fixture.tsx
index 0ae04eee0a..1af4d02c29 100644
--- a/apps/web/src/features/auth/browser-test/fixture.tsx
+++ b/apps/web/src/features/auth/browser-test/fixture.tsx
@@ -29,6 +29,8 @@ const params = Object.fromEntries(new URLSearchParams(location.search));
const page = params.page ?? 'login';
/** `?latency=ms`: both backends load like a cold page instead of instantly. */
const latencyMs = Number(params.latency ?? 0);
+/** `?verifyLatency=ms`: code checks take a network round trip. */
+const verifyLatencyMs = Number(params.verifyLatency ?? 0);
const read = <T,>(key: string): T | undefined => {
const raw = sessionStorage.getItem(key);
return raw ? (JSON.parse(raw) as T) : undefined;
@@ -71,6 +73,7 @@ const auth = createFakeAuth(
await new Promise(() => {});
},
sessionLatencyMs: latencyMs,
+ verifyLatencyMs,
}
);
write(FIXTURE_KEYS.auth, structuredClone(unwrap(auth.world)));
diff --git a/apps/web/src/features/auth/components/otp-input.tsx b/apps/web/src/features/auth/components/otp-input.tsx
index 1d935b1dd6..1bb0a82845 100644
--- a/apps/web/src/features/auth/components/otp-input.tsx
+++ b/apps/web/src/features/auth/components/otp-input.tsx
@@ -1,5 +1,12 @@
import { cn } from '@ui';
-import { createSignal, Index, onCleanup, onMount } from 'solid-js';
+import {
+ createEffect,
+ createSignal,
+ Index,
+ on,
+ onCleanup,
+ onMount,
+} from 'solid-js';
/**
* Segmented one-time-code input: one visible box per digit, backed by a
@@ -35,6 +42,18 @@ export function OtpInput(props: {
focusWhenConnected();
});
+ // Disabling the input while a code is checked drops its focus, and with it
+ // the phone keyboard; take it back so a rejected code can be retyped.
+ createEffect(
+ on(
+ () => props.disabled,
+ (disabled, wasDisabled) => {
+ if (wasDisabled && !disabled) inputEl?.focus({ preventScroll: true });
+ },
+ { defer: true }
+ )
+ );
+
const activeIndex = () => Math.min(props.value.length, length() - 1);
// No native maxLength: it counts raw pasted characters, so "123 456"
diff --git a/apps/web/src/features/auth/context/auth-context.tsx b/apps/web/src/features/auth/context/auth-context.tsx
index b6911f088f..bf4d08a543 100644
--- a/apps/web/src/features/auth/context/auth-context.tsx
+++ b/apps/web/src/features/auth/context/auth-context.tsx
@@ -30,6 +30,8 @@ export type SendCodeResult =
export type VerifyCodeResult =
| { t: 'verified' }
| { t: 'invalid-code' }
+ /** Too many attempts for this address; the code itself may be right. */
+ | { t: 'rate-limited' }
| { t: 'failed' };
type AuthEventName =
diff --git a/apps/web/src/features/auth/primitives/email-login.ts b/apps/web/src/features/auth/primitives/email-login.ts
index c4ad4d6f01..1b2e3fcc4f 100644
--- a/apps/web/src/features/auth/primitives/email-login.ts
+++ b/apps/web/src/features/auth/primitives/email-login.ts
@@ -1,9 +1,19 @@
import { createSignal, onCleanup } from 'solid-js';
-import type { AuthContext, AuthIntent } from '../context/auth-context';
+import type {
+ AuthContext,
+ AuthIntent,
+ VerifyCodeResult,
+} from '../context/auth-context';
import { isCompleteCode, RESEND_AFTER_SECONDS } from '../core/email-code';
export type LoginStep = 'choose' | 'email' | 'verify';
+const VERIFY_ERRORS = {
+ 'invalid-code': 'Invalid code.',
+ 'rate-limited': 'Too many attempts. Wait a minute, then try again.',
+ failed: 'Unable to perform verification.',
+} satisfies Record<Exclude<VerifyCodeResult['t'], 'verified'>, string>;
+
type EmailLoginCapabilities = Pick<
AuthContext,
| 'session'
@@ -77,11 +87,10 @@ export function createEmailLogin(
return;
}
setVerifying(false);
- setVerifyError(
- result.t === 'invalid-code'
- ? 'Invalid code.'
- : 'Unable to perform verification.'
- );
+ // The auth service allows only a few attempts a minute per address, and
+ // a rejected code left in the boxes would spend another on Verify.
+ if (result.t === 'invalid-code') setCode('');
+ setVerifyError(VERIFY_ERRORS[result.t]);
};
/** Send (or resend) the code; reports whether a code went out. */
diff --git a/apps/web/src/features/auth/queries/auth-requests.ts b/apps/web/src/features/auth/queries/auth-requests.ts
index 5702ee889d..4952119841 100644
--- a/apps/web/src/features/auth/queries/auth-requests.ts
+++ b/apps/web/src/features/auth/queries/auth-requests.ts
@@ -96,9 +96,10 @@ export async function verifyEmailCode(input: {
}): Promise<VerifyCodeResult> {
const result = await authServiceClient.passwordlessCallback(input);
if (result.isOk()) return { t: 'verified' };
- return result.error.some((error) => error.code === 'UNAUTHORIZED')
- ? { t: 'invalid-code' }
- : { t: 'failed' };
+ const code = result.error[0]?.code;
+ if (code === 'UNAUTHORIZED') return { t: 'invalid-code' };
+ if (code === 'RATE_LIMITED') return { t: 'rate-limited' };
+ return { t: 'failed' };
}
/** Exchanges the session code an SSO return carries for session cookies. */
diff --git a/apps/web/src/features/auth/tests/fake-auth-context.ts b/apps/web/src/features/auth/tests/fake-auth-context.ts
index 6d18a52368..5eb24e139a 100644
--- a/apps/web/src/features/auth/tests/fake-auth-context.ts
+++ b/apps/web/src/features/auth/tests/fake-auth-context.ts
@@ -16,6 +16,13 @@ export type FakeAuthWorld = {
accounts: Record<string, { tutorialComplete: boolean }>;
/** The code the fake mailer "sends". */
code: string;
+ /**
+ * Code checks allowed per address before verification is rate-limited, as
+ * on the auth service. Its window is a minute; here it lasts until a test
+ * clears `codeAttempts`.
+ */
+ codeAttemptLimit: number;
+ codeAttempts: Record<string, number>;
/** Addresses that sign in with a password instead of a code. */
passwordAccounts: Record<string, string>;
/** Addresses whose organization signs in through its own identity provider. */
@@ -37,6 +44,8 @@ export function defaultFakeAuthWorld(): FakeAuthWorld {
user: null,
accounts: { '[email protected]': { tutorialComplete: true } },
code: '424242',
+ codeAttemptLimit: 5,
+ codeAttempts: {},
passwordAccounts: {},
ssoDomains: [],
autoCode: false,
@@ -73,6 +82,8 @@ export function createFakeAuth(
) => Promise<void>;
/** Report the session as loading this long, like a cold page load. */
sessionLatencyMs?: number;
+ /** Answer code checks this late, like a round trip to the auth service. */
+ verifyLatencyMs?: number;
} = {}
) {
const [world, setWorld] = createStore<FakeAuthWorld>({
@@ -141,7 +152,16 @@ export function createFakeAuth(
},
verifyEmailCode: async ({ email, code }) => {
call(`verify:${email}:${code}`);
+ if (options.verifyLatencyMs)
+ await new Promise((resolve) =>
+ setTimeout(resolve, options.verifyLatencyMs)
+ );
if (world.failures.verify !== undefined) return { t: 'failed' };
+ const attempts = world.codeAttempts[email] ?? 0;
+ if (attempts >= world.codeAttemptLimit) return { t: 'rate-limited' };
+ update((draft) => {
+ draft.codeAttempts[email] = attempts + 1;
+ });
if (code !== world.code) return { t: 'invalid-code' };
signIn(email);
return { t: 'verified' };
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 1fe46f6c1a..a3568ec168 100644
--- a/apps/web/src/features/auth/views/auth-view.test.tsx
+++ b/apps/web/src/features/auth/views/auth-view.test.tsx
@@ -162,6 +162,51 @@ describe('email sign-in', () => {
await screen.findByTestId('signed-in');
});
+ // Every check counts against the auth service's per-address attempt limit.
+ it('checks each entered code once, even when Verify is tapped after a miss', async () => {
+ const { fake } = setup();
+ click('Continue with email');
+ await typeEmail('[email protected]');
+ click('Continue');
+ await screen.findByText('[email protected]');
+ for (const wrong of ['000000', '111111', '222222']) {
+ await typeCode(wrong);
+ await screen.findByText('Invalid code.');
+ expect(screen.getByLabelText(/code/i)).toHaveProperty('value', '');
+ click(/^Verify/);
+ }
+ await typeCode('424242');
+ await screen.findByTestId('signed-in');
+ expect(fake.calls().filter((call) => call.startsWith('verify:'))).toEqual([
+ 'verify:[email protected]:000000',
+ 'verify:[email protected]:111111',
+ 'verify:[email protected]:222222',
+ 'verify:[email protected]:424242',
+ ]);
+ });
+
+ it('says to wait when code checks are rate-limited, and keeps the code to retry', async () => {
+ const { fake } = setup({
+ world: { codeAttempts: { '[email protected]': 5 } },
+ });
+ click('Continue with email');
+ await typeEmail('[email protected]');
+ click('Continue');
+ await screen.findByText('[email protected]');
+ await typeCode('424242');
+ await screen.findByText(
+ 'Too many attempts. Wait a minute, then try again.'
+ );
+ expect(screen.queryByText('Invalid code.')).toBeNull();
+ expect(screen.getByLabelText(/code/i)).toHaveProperty('value', '424242');
+
+ fake.update((draft) => {
+ draft.codeAttempts = {};
+ });
+ click(/^Verify/);
+ await screen.findByTestId('signed-in');
+ });
+
it('asks for a password only for password accounts', async () => {
setup({ world: { passwordAccounts: { '[email protected]': 'hunter2' } } });
click('Continue with email');
diff --git a/apps/web/src/lib/service-clients/service-auth/client.test.ts b/apps/web/src/lib/service-clients/service-auth/client.test.ts
index 5d72a1fb4f..f0e2201ce4 100644
--- a/apps/web/src/lib/service-clients/service-auth/client.test.ts
+++ b/apps/web/src/lib/service-clients/service-auth/client.test.ts
@@ -32,6 +32,25 @@ describe('getExpiresAt', () => {
});
});
+describe('passwordless code check', () => {
+ test.each([
+ [401, 'UNAUTHORIZED'],
+ [429, 'RATE_LIMITED'],
+ [400, 'HTTP_ERROR'],
+ [500, 'SERVER_ERROR'],
+ ])('reports a %i response as %s', async (status, code) => {
+ const fetch = vi
+ .spyOn(window, 'fetch')
+ .mockResolvedValueOnce(new Response('rejected', { status }));
+ const result = await authServiceClient.passwordlessCallback({
+ code: '424242',
+ email: '[email protected]',
+ });
+ expect(result._unsafeUnwrapErr()[0].code).toBe(code);
+ fetch.mockRestore();
+ });
+});
+
describe('credit checkout', () => {
const args = {
amountCents: 2_500,
diff --git a/apps/web/src/lib/service-clients/service-auth/client.ts b/apps/web/src/lib/service-clients/service-auth/client.ts
index 85020b123b..fbf0d6073d 100644
--- a/apps/web/src/lib/service-clients/service-auth/client.ts
+++ b/apps/web/src/lib/service-clients/service-auth/client.ts
@@ -372,12 +372,17 @@ export const authServiceClient = {
});
},
async passwordlessCallback({ code, email }: { code: string; email: string }) {
- const result = await safeFetch<UserTokensResponse>(
+ const result = await safeFetch<UserTokensResponse, 'RATE_LIMITED'>(
`${authHost}/oauth/passwordless/${code}?email=${encodeURIComponent(email)}&disable_redirect=true`,
{ cache: 'no-store', credentials: 'include' },
async (response) => {
- const message = await response.text();
- return { code: 'UNAUTHORIZED' as const, message };
+ if (response.status === 401) {
+ return { code: 'UNAUTHORIZED', message: await response.text() };
+ }
+ if (response.status === 429) {
+ return { code: 'RATE_LIMITED', message: 'Rate limit exceeded' };
+ }
+ return statusError(response.status);
}
);
if (result.isOk()) {
diff --git a/docs/AGENT_GUIDE/login.md b/docs/AGENT_GUIDE/login.md
index bf55f3cf17..88ae91f346 100644
--- a/docs/AGENT_GUIDE/login.md
+++ b/docs/AGENT_GUIDE/login.md
@@ -10,7 +10,10 @@
response carries the one-time code and the frontend auto-verifies it, so you are logged in
immediately — no code entry step ever appears. A code email is still sent and visible in
Mailpit. Against a real deployment, expect a code-entry step instead: fetch the code from
- the user's inbox (locally: Mailpit).
+ the user's inbox (locally: Mailpit). The sixth digit submits the code. A rejected code
+ clears the boxes and refocuses them for retyping. The auth service allows five code
+ checks a minute per address; past that the step shows "Too many attempts. Wait a minute,
+ then try again." and keeps the code. Requesting a new code does not lift that wait.
5. First login auto-creates the user, seeds onboarding content (a "Macro Support x <name>"
channel, a "Macro how to guide" doc favorite, three sample tasks), and lands on
`/app/home`. The starter documents share a personal `docs` tag; the