Skip to content

Commit 633cce6

Browse files
fix(auth-ui): the forgot-password form sends one reset request at a time (#32788)
<!-- claude-projects-attribution: {"github_login":"os-sales"} --> _Requested by **Sales** · [project thread](https://claude.ai/code/project/chan_01D5bWFY3rFzgJcytD5gD4Uu?thread=cmsg_01D5bWFY3rFzgJcytD5gD4Uu2tNhjjZZAybyTGwcxZ2XAm)_ Part of #32645 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:「忘记密码」表单一次只发一个重置请求,连点只发一次;另加一条服务端突发测试,钉住同一地址并发重置请求只答 200 或 429、不出 5xx。 - 为什么改:生产上连点「发送重置链接」出现 500。客户端这半边是真的(表单从未在请求期间禁用按钮);服务端在框架自己的组合里实测复现不出 500,那半边留在卡上待云端读数。 - 风险与回滚:只动 `@object-ui/auth` 的一个表单与两个测试文件,单个 revert 即回滚;失败的请求会释放表单,不会把按钮锁死。 - 先看:`ui/packages/auth/src/ForgotPasswordForm.tsx` 的 `handleSubmit`;`packages/plugins/plugin-auth/src/reset-request-mail-after-response.test.ts` 末尾新 describe。 - 两分钟验证:`pnpm --dir ui exec vitest run packages/auth/src/__tests__/forgot-password-success-message.test.tsx`,预期 12 passed,其中「two synchronous submits send one reset request」为绿。 - 需要你做的:无,席位落地。 ## What changes - **`@object-ui/auth` — `ForgotPasswordForm`:** the email form's submit handler ignores a submit while its reset request is pending (a ref read and set synchronously in the handler, so a second submit fired before React re-renders is dropped), and the button and email field are disabled with the submitting label until the request answers. A request that fails, a 429 included, releases the form so the next submit is sent. The phone (SMS code) branch is unchanged. - **`@objectstack/plugin-auth` — test only:** the card's acceptance pin, as a new top-level describe in the reset harness file (`reset-request-mail-after-response.test.ts`): eight concurrent `POST /request-password-reset` for one address through `AuthManager.handleRequest`, counted by the storage `AuthPlugin` wires (`createLazyCacheRateLimitStorage` over `MemoryCacheAdapter`), under the reset endpoint's rule as the auth settings bind writes it (`customRules['/request-password-reset']`, 3 per 60 s). - Changeset: `@object-ui/auth` patch. `@objectstack/plugin-auth` ships no changed bytes (its `files` is `dist`, and only a test file changed), so it carries none. ## Why — what was measured **Client (the defect this PR fixes).** The form's only guard was the provider's `isLoading`. `AuthProvider`'s `forgotPassword` never raises it (that flag tracks the session read), so the button was never disabled during a reset request and every click sent its own `POST /request-password-reset`. That is the three XHRs in the card's DevTools capture. Before / after, the pin `two synchronous submits send one reset request`: - before (guard removed by ablation): `AssertionError: expected "vi.fn()" to be called 1 times, but got 2 times`; - after: one `forgotPassword` call, the button reads `Sending…` and is disabled, the success screen follows. **Server (not reproduced in the framework's own composition).** The card's expected 500 did not occur in any run below. Every run answered each request 200 (the uniform body) or 429 (`{"message":"Too many requests. Please try again later."}`), and the server logged no error. | Run (tree `objectstack@296e2ec`, this branch's base, after a full build) | Burst | Answers | |:---|:---|:---| | `AuthManager.handleRequest`, cache-backed storage over `MemoryCacheAdapter`, rule 3/60 s, address with an account | 8 | 3×200, 5×429 | | same, address with no account | 8 | 3×200, 5×429 | | real CRM backend, `os start`, `NODE_ENV=production` (the vendor's limiter on by default), better-sqlite3 | 6, unknown and known address | 3×200, 3×429 | | same backend on Postgres 16 | 6, 20 | 3×200, rest 429 | | Postgres, with a live session cookie, then with a signed-out (revoked) one | 3 each | 3×200 | On Postgres every admitted request for the account minted its reset token and recorded its identity mail (12 `sys_verification` reset rows and 12 `sys_identity_email` rows for the 12 admitted requests). The 500 the card shows has no top-level `message`, and in this code only two paths answer that shape. One is an exception inside a vendor endpoint, answered by the router with an empty-bodied 500. The other is an exception out of `handleRequest` (for example from the rate limiter's `consume`, which runs before any endpoint), answered by the host's catch. Both write a server-side error line. Between the production cloud pin (`c5758b0d`) and `main`, the rate limiter, its counter store, the reset endpoint and the reset mail are unchanged. What did change is how a forwarding host reaches the auth surface: PR #32707 routes `auth.handleRequest` through the plugin's own route table. Every run above is on `main`, after that change. The cause is therefore most likely in the hosted composition, not in this code. The card stays open for that reading. The new burst pin is green on `main`. Its sensitivity was checked once: a counter store that throws on the second write to one key turns both cases red. The throw escapes `handleRequest` as a rejection, which a host answers as exactly the message-less 500 above: ``` Error: ablation: the counter store refused a second write to one key ❯ incrementFixedWindowOnce src/rate-limit-storage.ts Tests 2 failed | 12 skipped (14) ``` Restored afterwards with blob equal to `HEAD` (`8bcd840c61fc`) and an empty `git diff HEAD`. ## Tests - `pnpm --dir ui exec vitest run packages/auth/` — Test Files 45 passed (45), Tests 461 passed (461). - `pnpm --filter @object-ui/auth type-check` — exit 0. - `pnpm --filter @objectstack/plugin-auth exec vitest run src/reset-request-mail-after-response.test.ts` — Tests 14 passed (14). - `pnpm --filter @objectstack/plugin-auth typecheck` — exit 0 (test layer: `check:test-typecheck: OK`). - `pnpm --filter @objectstack/plugin-auth exec vitest run --maxWorkers=2` (the whole package, on `3c28e4b5`, before the merge of `main`) — Test Files 265 passed (265), Tests 4943 passed, 10 skipped (4953). - After merging `main` (head `03979ba6`; the incoming commits touch none of these packages): the reset harness file with `rate-limit-concurrency.test.ts` and `rate-limit-storage.test.ts` — Test Files 3 passed (3), Tests 43 passed (43); `packages/auth/` under `ui/` — Tests 461 passed (461); both typechecks exit 0. ## Acceptance notes - The card's first acceptance item (the plugin-auth burst test) is met as a pin that holds on `main`; it does not show a defect in this code, because none was found here. - The card's second acceptance item (two synchronous submits, one `forgotPassword` call) is met. - The card's own reading says the client guard does not close the card, so this PR is `Part of`, not a fix of the whole card. What stays open is the production 500. The reading that would place it is the server log line written at that moment, which is one of `Auth request error:`, `# SERVER_ERROR:` or `better-auth returned error`, together with the `cache` service the hosted runtime registers. - Not changed: the reset rule, its budget, the uniform answer, or any check on the door. - The untranslated English fallback banner (`Auth request failed with status 500`) the card mentions is left as it is. It is the client's last-resort text for a body with no message. - Branch: the harness assigned `claude/project-thread-6kjsre` (not `claude/issue-32645-…`); the claim on the card names it. ## Verification All readings below are on head `03979ba6`. - `pnpm lint` — exit 0. - `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` derived 66 commands for this diff; each was run and recorded, and `--ran` reconciles: `66 derived, 66 run, 0 NOT-MEASURED, 0 UNRUN`. - `pnpm --filter @objectstack/spec check:generated` (spec moved on `main`): 13 of 14 artifacts current; `check:test-typecheck` first stopped with `tsc … failed without diagnostics` at the default heap, and re-run with `NODE_OPTIONS=--max-old-space-size=8192` it answers `check:test-typecheck: OK`. Not an artifact of this diff, which does not touch `packages/spec`. <details><summary>Derived gate commands and exit codes (66)</summary> ``` node scripts/check-adr-0087-registration.mjs --base origin/main :: exit 0 node scripts/check-adr-0087-registration.mjs --self-test :: exit 0 node scripts/check-changeset-no-major.mjs --base origin/main :: exit 0 node scripts/check-closing-keyword-parity.mjs :: exit 0 node scripts/check-closing-keyword-parity.mjs --self-test :: exit 0 node scripts/check-comment-mask-adoption.mjs :: exit 0 node scripts/check-comment-mask-adoption.mjs --self-test :: exit 0 node scripts/check-comment-mask-corpus.mjs :: exit 0 node scripts/check-dev-prereqs.mjs --self-test :: exit 0 node scripts/check-dts-emitted.mjs --self-test :: exit 0 node scripts/check-empty-changeset.mjs --base origin/main :: exit 0 node scripts/check-empty-changeset.mjs --self-test :: exit 0 node scripts/check-issue-citations.mjs :: exit 0 node scripts/check-plugin-teardown-shape.mjs :: exit 0 node scripts/check-plugin-teardown-shape.mjs --self-test :: exit 0 node scripts/check-sdui-manifest.mjs :: exit 0 node scripts/check-sdui-manifest.mjs --self-test :: exit 0 node scripts/check-tenant-audit-census.mjs :: exit 0 node scripts/check-tenant-audit-census.mjs --self-test :: exit 0 node scripts/ci/assert-turbo-remote-cache.mjs --self-test :: exit 0 node scripts/ci/plan-test-core-shards.mjs --self-test :: exit 0 node scripts/ci/prune-turbo-cache.mjs --self-test :: exit 0 node scripts/ci/snapshot-next.mjs --self-test :: exit 0 node scripts/docs-audit/check-affected-docs.mjs :: exit 0 node scripts/docs-audit/check-drift-comment.mjs :: exit 0 node scripts/pm/release-rehearsal-clone.mjs --self-test :: exit 0 node scripts/release-pending-publish.mjs --self-test :: exit 0 pnpm --dir ui exec vitest run scripts/ :: exit 0 pnpm --filter @objectstack/spec run check:duration-unit-keys :: exit 0 pnpm check:changeset-gate-self-tests :: exit 0 pnpm check:ci-filter-parity :: exit 0 pnpm check:closed-ceremony-text :: exit 0 pnpm check:cross-package-test-inputs :: exit 0 pnpm check:dispatcher-error-vocabulary :: exit 0 pnpm check:doc-authoring :: exit 0 pnpm check:driver-memory-census :: exit 0 pnpm check:dts-closure :: exit 0 pnpm check:dual-build-cjs-loads :: exit 0 pnpm check:engine-double-contract :: exit 0 pnpm check:gitlink-declared :: exit 0 pnpm check:issue-citations :: exit 0 pnpm check:keyed-text-bounds :: exit 0 pnpm check:lean-entry-closure :: exit 0 pnpm check:logger-receiver-detach :: exit 0 pnpm check:nul-bytes :: exit 0 pnpm check:objectql-double-limit :: exit 0 pnpm check:org-identifier :: exit 0 pnpm check:page-declaration-shape :: exit 0 pnpm check:platform-object-tenancy-census :: exit 0 pnpm check:published-files :: exit 0 pnpm check:query-options-erasure :: exit 0 pnpm check:refd-timer-probe :: exit 0 pnpm check:registry-log-declared :: exit 0 pnpm check:rest-log-spy-declared :: exit 0 pnpm check:skill-identifier-liveness :: exit 0 pnpm check:slot-lookup :: exit 0 pnpm check:sourcemap-no-sources-content :: exit 0 pnpm check:system-context-census :: exit 0 pnpm check:test-source-alias :: exit 0 pnpm check:tier-file-adoption :: exit 0 pnpm check:type-check-coverage :: exit 0 pnpm check:type-check-debt :: exit 0 pnpm check:undeclared-dep-imports :: exit 0 pnpm check:vouch-for-reference-callers :: exit 0 pnpm check:watch-hint-literal :: exit 0 pnpm check:where-matcher :: exit 0 ``` </details> ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. (not touched) - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed. (not touched) - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. - [x] The *Before Submitting* list in CONTRIBUTING.md is done. --- _Generated by [Claude Code](https://claude.ai/code/session_01L6bhgXjcwwHcA9BB8HRHe9)_ 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01L6bhgXjcwwHcA9BB8HRHe9 <!-- signed: domain:server#4 · os-sales · session_01L6bhgXjcwwHcA9BB8HRHe9 --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent c249611 commit 633cce6

4 files changed

Lines changed: 203 additions & 6 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@object-ui/auth': patch
3+
---
4+
5+
fix(auth): the forgot-password form sends one reset request at a time
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
- **`@object-ui/auth`:** `ForgotPasswordForm` ignores a submit while its reset request is pending, so a fast double or triple click on "Send reset link" sends one `POST /request-password-reset`, not one per click. The button shows its submitting label and, like the email field, is disabled until the request answers; a request that fails (a 429 included) releases the form, so the next submit is sent. Before, the form's only guard was the provider's `isLoading`, which tracks the session read and was never raised for this call. The phone (SMS code) branch is unchanged.

‎packages/plugins/plugin-auth/src/reset-request-mail-after-response.test.ts‎

Lines changed: 106 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,14 +34,24 @@
3434
* transport that reports itself unconfigured (the stock `log` one), true
3535
* with a configured one. It describes the deployment, not an address: in
3636
* all three a known and an unknown address get the same reset answer, and
37-
* that answer is the same one whether mail leaves or not.
37+
* that answer is the same one whether mail leaves or not;
38+
* - a burst of concurrent reset requests for one address, counted by the
39+
* cache-backed rate-limit storage `AuthPlugin` wires
40+
* (`createLazyCacheRateLimitStorage` over the kernel cache adapter) under
41+
* the per-endpoint rule the auth settings bind writes, answers each request
42+
* 200 or 429 and never 5xx: exactly the rule's `max` are admitted, every
43+
* admitted answer is the body an address with no account gets, every
44+
* refusal carries its message, nothing is logged at error, and each
45+
* admitted request for the account still sends its reset mail.
3846
*/
3947

4048
import { describe, it, expect, afterAll, afterEach, vi } from 'vitest';
4149
import { ObjectQL } from '@objectstack/objectql';
4250
import { SqlDriver } from '@objectstack/driver-sql';
51+
import { MemoryCacheAdapter } from '@objectstack/service-cache';
4352
import { AuthManager } from './auth-manager.js';
4453
import { authIdentityObjects } from './manifest.js';
54+
import { createLazyCacheRateLimitStorage } from './rate-limit-storage.js';
4555
import { runAfterResponse } from './run-after-response.js';
4656
import { memoizeScrypt } from './__tests__/scrypt-memo.testkit';
4757
import { sqliteEnginePool } from './__tests__/sqlite-engine-pool.testkit';
@@ -371,3 +381,98 @@ describe('runAfterResponse', () => {
371381
}
372382
});
373383
});
384+
385+
describe('a burst of reset requests for one address answers 200 or 429, never 5xx', () => {
386+
/** The per-endpoint rule the auth settings bind writes (`rate_limit_max` / `rate_limit_window_seconds`). */
387+
const RULE = { window: 60, max: 3 } as const;
388+
/** Requests in the burst: more than the rule admits, so both answers occur. */
389+
const BURST = 8;
390+
391+
/**
392+
* A deployment counting through the storage `AuthPlugin` hands better-auth
393+
* (`rateLimit.customStorage`), over the kernel cache adapter, with the
394+
* reset endpoint's rule as the settings bind writes it. Records every send,
395+
* every server-side error line, and every console error (better-call's own
396+
* unhandled-error line goes there).
397+
*/
398+
async function burstDeployment(withAccount: boolean) {
399+
vi.spyOn(console, 'warn').mockImplementation(() => {});
400+
const consoleErrors = vi.spyOn(console, 'error').mockImplementation(() => {});
401+
const engine = await engines.take();
402+
const logged: string[] = [];
403+
const cache = new MemoryCacheAdapter();
404+
const manager = new AuthManager({
405+
secret: SECRET,
406+
baseUrl: BASE,
407+
dataEngine: engine as never,
408+
rateLimit: {
409+
enabled: true,
410+
window: RULE.window,
411+
max: RULE.max,
412+
customRules: { '/request-password-reset': { ...RULE } },
413+
},
414+
rateLimitStorage: createLazyCacheRateLimitStorage({ resolveCache: async () => cache }),
415+
logger: { warn: () => {}, error: (message: string) => logged.push(message) },
416+
} as never);
417+
const sends: Mail[] = [];
418+
manager.setEmailService({
419+
sendTemplate: async (input: Mail) => {
420+
sends.push(input);
421+
return { status: 'sent' };
422+
},
423+
} as never);
424+
if (withAccount) {
425+
const signedUp = await post(manager, '/sign-up/email', { email: EMAIL, password: PASSWORD, name: 'Reset' });
426+
expect(signedUp.status, await signedUp.clone().text()).toBe(200);
427+
sends.length = 0;
428+
}
429+
return { manager, sends, logged, consoleErrors };
430+
}
431+
432+
/** Fire `BURST` reset requests for `email` at once; answer each status and body. */
433+
async function burst(manager: AuthManager, email: string): Promise<Array<{ status: number; body: string }>> {
434+
const answers = await Promise.all(
435+
Array.from({ length: BURST }, () => post(manager, '/request-password-reset', { email, redirectTo: `${BASE}/reset` })),
436+
);
437+
return Promise.all(answers.map(async (res) => ({ status: res.status, body: await res.text() })));
438+
}
439+
440+
it('an address with an account: the rule admits exactly max, refuses the rest with 429, and logs no error', async () => {
441+
const d = await burstDeployment(true);
442+
443+
const answers = await burst(d.manager, EMAIL);
444+
445+
expect(answers.map((a) => a.status).sort()).toEqual([
446+
...Array.from({ length: RULE.max }, () => 200),
447+
...Array.from({ length: BURST - RULE.max }, () => 429),
448+
]);
449+
const admitted = answers.filter((a) => a.status === 200);
450+
expect(new Set(admitted.map((a) => a.body)).size).toBe(1);
451+
for (const refused of answers.filter((a) => a.status === 429)) {
452+
expect(JSON.parse(refused.body)).toEqual({ message: expect.any(String) });
453+
}
454+
// Each admitted request still sends its reset mail, after the response.
455+
await vi.waitFor(() => expect(d.sends.map((m) => [m.template, m.to.address])).toEqual(
456+
Array.from({ length: RULE.max }, () => ['auth.password_reset', EMAIL]),
457+
));
458+
expect(d.logged).toEqual([]);
459+
expect(d.consoleErrors).not.toHaveBeenCalled();
460+
}, 60_000);
461+
462+
it('an address with no account answers the same burst the same way, with the same admitted body', async () => {
463+
const withAccount = await burstDeployment(true);
464+
const forAccount = await burst(withAccount.manager, EMAIL);
465+
const without = await burstDeployment(false);
466+
const forNobody = await burst(without.manager, NOBODY);
467+
468+
expect(forNobody.map((a) => a.status).sort()).toEqual(forAccount.map((a) => a.status).sort());
469+
const admittedBodies = new Set(
470+
[...forAccount, ...forNobody].filter((a) => a.status === 200).map((a) => a.body),
471+
);
472+
expect(admittedBodies.size).toBe(1);
473+
await vi.waitFor(() => expect(withAccount.sends).toHaveLength(RULE.max));
474+
expect(without.sends).toEqual([]);
475+
expect([...withAccount.logged, ...without.logged]).toEqual([]);
476+
expect(without.consoleErrors).not.toHaveBeenCalled();
477+
}, 60_000);
478+
});

‎ui/packages/auth/src/ForgotPasswordForm.tsx‎

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
* LICENSE file in the root directory of this source tree.
77
*/
88

9-
import React, { useEffect, useState } from 'react';
9+
import React, { useEffect, useRef, useState } from 'react';
1010
import { useAuth } from './useAuth.js';
1111
import type { AuthLinkComponentProps } from './types.js';
1212
import {
@@ -145,6 +145,13 @@ export function ForgotPasswordForm({
145145
const [email, setEmail] = useState('');
146146
const [error, setError] = useState<string | null>(null);
147147
const [submitted, setSubmitted] = useState(false);
148+
// One reset request at a time. The ref is read and set synchronously in the
149+
// handler, so a second submit that fires before React re-renders (a fast
150+
// double or triple click) sees the first one still pending and is ignored;
151+
// `sending` is the same fact for the render (button and input disabled).
152+
// The provider's `isLoading` is the session read and never covers this call.
153+
const resetRequestPending = useRef(false);
154+
const [sending, setSending] = useState(false);
148155
// Phone (SMS OTP) reset branch (framework#2780). Only offered when the
149156
// server reports `features.phoneNumberOtp` — the phoneNumber plugin plus a
150157
// deliverable SMS service — so the link never leads to codes that can't
@@ -226,6 +233,9 @@ export function ForgotPasswordForm({
226233

227234
const handleSubmit = async (e: React.FormEvent) => {
228235
e.preventDefault();
236+
if (resetRequestPending.current) return;
237+
resetRequestPending.current = true;
238+
setSending(true);
229239
setError(null);
230240

231241
try {
@@ -237,6 +247,9 @@ export function ForgotPasswordForm({
237247
const authError = err instanceof Error ? err : new Error(String(err));
238248
setError(authError.message);
239249
onError?.(authError);
250+
} finally {
251+
resetRequestPending.current = false;
252+
setSending(false);
240253
}
241254
};
242255

@@ -457,14 +470,14 @@ export function ForgotPasswordForm({
457470
onChange={(e) => setEmail(e.target.value)}
458471
required
459472
autoComplete="email"
460-
disabled={isLoading}
473+
disabled={isLoading || sending}
461474
className={AUTH_INPUT_CLASS}
462475
/>
463476
</div>
464477

465-
<button type="submit" disabled={isLoading} className={AUTH_PRIMARY_BUTTON_CLASS}>
466-
{isLoading && <AuthSpinner />}
467-
{isLoading ? l.submittingButton : l.submitButton}
478+
<button type="submit" disabled={isLoading || sending} className={AUTH_PRIMARY_BUTTON_CLASS}>
479+
{(isLoading || sending) && <AuthSpinner />}
480+
{isLoading || sending ? l.submittingButton : l.submitButton}
468481
</button>
469482

470483
{phoneOtpEnabled && (

‎ui/packages/auth/src/__tests__/forgot-password-success-message.test.tsx‎

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,3 +194,72 @@ describe('ForgotPasswordForm — success screen on a deployment that sends no ma
194194
expect(screen.queryByText("A reset link can't be emailed here")).toBeNull();
195195
});
196196
});
197+
198+
/**
199+
* objectstack#32645 — one reset request at a time. A fast double click fires
200+
* the form's submit twice before React re-renders, so a disabled button alone
201+
* cannot stop the second request; the handler ignores a submit while one is
202+
* pending, and takes the next one once that request has answered.
203+
*/
204+
describe('ForgotPasswordForm — a submit while a reset request is pending is ignored (objectstack#32645)', () => {
205+
/** A reset request the case answers by hand. */
206+
function pendingReset() {
207+
let settle!: { resolve: () => void; reject: (error: Error) => void };
208+
const forgotPassword = vi.fn(
209+
() =>
210+
new Promise<void>((resolve, reject) => {
211+
settle = { resolve, reject };
212+
}),
213+
);
214+
return { forgotPassword, settle: () => settle };
215+
}
216+
217+
function renderWith(forgotPassword: AuthClient['forgotPassword']) {
218+
const client = createMockClient({ forgotPassword });
219+
const view = render(
220+
<AuthProvider authUrl="/api/auth" client={client}>
221+
<ForgotPasswordForm />
222+
</AuthProvider>,
223+
);
224+
return { client, view };
225+
}
226+
227+
it('two synchronous submits send one reset request', async () => {
228+
const reset = pendingReset();
229+
renderWith(reset.forgotPassword);
230+
fireEvent.change(await screen.findByLabelText('Email'), { target: { value: 'twice@example.com' } });
231+
const button = screen.getByRole('button', { name: 'Send Reset Link' });
232+
const form = button.closest('form') as HTMLFormElement;
233+
234+
// Both in one synchronous turn: no render happens between them.
235+
fireEvent.submit(form);
236+
fireEvent.submit(form);
237+
238+
expect(reset.forgotPassword).toHaveBeenCalledTimes(1);
239+
expect(reset.forgotPassword).toHaveBeenCalledWith('twice@example.com');
240+
241+
// While it is pending the button says so and cannot be pressed.
242+
const pendingButton = await screen.findByRole('button', { name: 'Sending…' });
243+
expect((pendingButton as HTMLButtonElement).disabled).toBe(true);
244+
245+
reset.settle().resolve();
246+
expect(await screen.findByText('Check your email')).toBeTruthy();
247+
expect(reset.forgotPassword).toHaveBeenCalledTimes(1);
248+
});
249+
250+
it('takes the next submit once the pending request has failed', async () => {
251+
const reset = pendingReset();
252+
renderWith(reset.forgotPassword);
253+
fireEvent.change(await screen.findByLabelText('Email'), { target: { value: 'retry@example.com' } });
254+
const form = screen.getByRole('button', { name: 'Send Reset Link' }).closest('form') as HTMLFormElement;
255+
256+
fireEvent.submit(form);
257+
reset.settle().reject(new Error('Too many requests. Please try again later.'));
258+
expect(await screen.findByText('Too many requests. Please try again later.')).toBeTruthy();
259+
260+
const button = screen.getByRole('button', { name: 'Send Reset Link' }) as HTMLButtonElement;
261+
expect(button.disabled).toBe(false);
262+
fireEvent.submit(form);
263+
expect(reset.forgotPassword).toHaveBeenCalledTimes(2);
264+
});
265+
});

0 commit comments

Comments
 (0)