Skip to content

Commit be72183

Browse files
Merge branch 'main' into claude/project-thread-ddyc2k
2 parents 91cc0b2 + c92b887 commit be72183

13 files changed

Lines changed: 345 additions & 35 deletions
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
---
2+
'@object-ui/app-shell': patch
3+
'@object-ui/i18n': patch
4+
---
5+
6+
fix(app-shell): the metadata editor's save-status chip says "Not saved" while a save is held, instead of promising an auto-save that never comes (#29901)
7+
8+
Clause-②: no
9+
Metadata-protocol: none
10+
11+
On the metadata editor page (Studio's All metadata item page, Setup's metadata pages) with auto-save on, a draft the server refused with `422 INVALID_METADATA` stays dirty, and the chip beside Save kept reading "Auto-saving…" although the auto-save is held until the refused part changes and no further save is sent. The same happened while the inspector holds a fault it reports (a CEL predicate that does not parse), which holds the auto-save the same way.
12+
13+
The chip now has a held state: while either hold stands on a dirty draft it reads "Not saved — fix the errors to save" in the destructive tone, with the Save button's own explanation as its tooltip. It returns to the usual states as soon as the hold lifts: editing the part the server named, or fixing the inspector fault, lets the auto-save run and the chip reads "Auto-saving…", then "Saved". Nothing about when a save is sent or held changes. New string: `engine.edit.notSavedHeld` (en, zh).
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@objectstack/plugin-auth': patch
3+
---
4+
5+
fix(plugin-auth): the phone-number password-reset request answers without waiting for the SMS send, as the emailed reset does
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
- **The rule.** `POST /api/v1/auth/phone-number/request-password-reset` answers at once, the same way for any number: the reset text is built and sent after the response, as the emailed reset (`POST /api/v1/auth/request-password-reset`) already sends its mail.
11+
- **A send that fails is logged on the server**, at error (`phone password-reset text was not delivered`), and never reaches the caller, who is answered `{ status: true }` either way, as before. The one-time code is in the text only, never in that line.
12+
- **Unchanged.** The answer's status and body; the per-number cooldown and hourly cap and the per-IP limit on the route; the text itself; and a server-side `auth.api.requestPasswordResetPhoneNumber` call, which carries no request and still awaits its send.

‎docs/adr/0012-notification-platform.md‎

Lines changed: 22 additions & 9 deletions
Large diffs are not rendered by default.

‎packages/plugins/plugin-auth/src/auth-manager-auth-instance.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -500,7 +500,7 @@ export async function createAuthInstance(this: AuthInstanceHost): Promise<Auth<a
500500
`${invitation ? 'Account-invitation' : 'Password-reset'} email could not be sent to ${user.email}: ${result.error ?? 'delivery failed'}`,
501501
);
502502
}
503-
}), (error) => logAfterResponseSendFailure(this.config.logger, 'password-reset', error)),
503+
}), (error) => logAfterResponseSendFailure(this.config.logger, 'password-reset email', error)),
504504
// [#25060, ruling 1B on #25040] The mail half of "a sign-up for an
505505
// address that already has an account answers like a success". The
506506
// vendor calls this only when the address already has a row AND its

‎packages/plugins/plugin-auth/src/auth-manager-plugin-list.ts‎

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,7 @@ import {
8181
buildTwoFactorPluginSchema,
8282
} from './auth-schema-config.js';
8383
import { isPlaceholderEmail } from './placeholder-email.js';
84+
import { logAfterResponseSendFailure, sendAfterResponseOnPublicDoor } from './run-after-response.js';
8485
import {
8586
ONE_TIME_TOKEN_EXPIRES_IN_MINUTES,
8687
oneTimeTokenStoreHasher,
@@ -354,6 +355,15 @@ export async function buildPluginList(this: PluginListHost): Promise<any[]> {
354355
// by the admin create-user/import routes with a placeholder email
355356
// (see placeholder-email.ts), never by OTP self-signup.
356357
const otpCfg = this.config.phoneOtp ?? {};
358+
// The reset text, sent the way the emailed reset sends its mail
359+
// (`sendResetPassword`, `auth-manager-auth-instance.ts`): on the public
360+
// door after the response, its failure logged on the server.
361+
const sendPasswordResetText = sendAfterResponseOnPublicDoor(
362+
async ({ phoneNumber: phone, code }: { phoneNumber: string; code: string }) => {
363+
await this.deliverPhoneOtp(phone, code);
364+
},
365+
(error) => logAfterResponseSendFailure(this.config.logger, 'phone password-reset text', error),
366+
);
357367
return phoneNumber({
358368
schema: buildPhoneNumberPluginSchema(),
359369
// Wrong-code attempts before the stored OTP is invalidated. Explicit
@@ -373,13 +383,19 @@ export async function buildPluginList(this: PluginListHost): Promise<any[]> {
373383
await this.deliverPhoneOtp(phone, code);
374384
},
375385
// Self-service password reset OTP (`/phone-number/request-password-
376-
// reset`). better-auth invokes this via runInBackgroundOrAwait —
377-
// errors are logged, the route still answers {status:true} — so a
378-
// throw here can neither 500 the request nor leak whether the number
379-
// is registered.
380-
sendPasswordResetOTP: async ({ phoneNumber: phone, code }) => {
381-
await this.deliverPhoneOtp(phone, code);
382-
},
386+
// reset`). The request answers the same way for any number, answers
387+
// at once and does not wait on the SMS send, as the emailed reset
388+
// does: a call that carries a `Request` — the public door — resolves
389+
// immediately and the text is built and sent after the response
390+
// (`sendAfterResponseOnPublicDoor`); what the send does is logged on
391+
// the server and never reaches the caller, who is answered
392+
// `{ status: true }` either way. better-auth hands this callback the
393+
// endpoint context, not the `Request` the emailed reset is handed
394+
// (`sendPasswordResetOTP(data, ctx)`, better-auth 1.7.12
395+
// `plugins/phone-number/routes.mjs`), so the context's own `request`
396+
// is what decides: a server-side `auth.api.*` call carries none and
397+
// still awaits its send.
398+
sendPasswordResetOTP: (data, ctx) => sendPasswordResetText(data, ctx?.request),
383399
});
384400
});
385401
}

‎packages/plugins/plugin-auth/src/phone-otp-no-sms-service-refusal.test.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -267,12 +267,12 @@ describe('POST /phone-number/send-otp without a deliverable SMS service', () =>
267267
}),
268268
);
269269

270-
// better-auth runs this send through `runInBackgroundOrAwait`, which logs a
271-
// throw and answers success — so the refusal cannot leak, by status or
272-
// body, whether the number belongs to an account.
270+
// On this public door the send runs after the response
271+
// (`sendAfterResponseOnPublicDoor`) and what it throws is logged on the
272+
// server — so the refusal cannot change the answer, by status or body.
273273
expect(response.status, await response.clone().text()).toBe(200);
274274
expect(await response.json()).toEqual({ status: true });
275-
expect(deliver).toHaveBeenCalledTimes(1);
275+
await vi.waitFor(() => expect(deliver).toHaveBeenCalledTimes(1));
276276
await expect(deliver.mock.results[0]?.value).rejects.toMatchObject({
277277
statusCode: 400,
278278
body: { code: 'SMS_SERVICE_REQUIRED' },

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

Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,14 @@
1919
* answer is the one a succeeding send gets;
2020
* - the server-side reset call (no `Request` — the identity import's) still
2121
* awaits its send, because it reads the delivery receipt the send settles;
22+
* - the phone-number reset request (`plugins.phoneNumber` with an SMS
23+
* service) answers without waiting for the SMS send, as the emailed reset
24+
* does: a number with an account and a number without one get the same
25+
* answer while the reset text's send is still open, and the text still
26+
* goes out after the response; a text whose send fails is logged on the
27+
* server at error, without its code, and the answer is the one a sent text
28+
* gets; the server-side phone reset call (no `Request`) still awaits its
29+
* send;
2230
* - `runAfterResponse` hands a task's synchronous throw to `onFailure` and
2331
* survives an `onFailure` that throws.
2432
*/
@@ -177,6 +185,118 @@ describe('a reset request answers without waiting on the reset mail', () => {
177185
}, 60_000);
178186
});
179187

188+
describe('the phone-number reset request answers without waiting on the reset text', () => {
189+
const PHONE = '+15550161';
190+
const NO_ACCOUNT_PHONE = '+15550162';
191+
const SYS = { context: { isSystem: true } } as never;
192+
193+
type Text = { to: string; templateParams?: { code?: string } };
194+
195+
/** A promise the case settles by hand. */
196+
function deferred(): { promise: Promise<void>; resolve: () => void } {
197+
let resolve!: () => void;
198+
const promise = new Promise<void>((r) => {
199+
resolve = r;
200+
});
201+
return { promise, resolve };
202+
}
203+
204+
/**
205+
* A deployment with phone-number sign-in and one account holding `PHONE`,
206+
* whose SMS service hands each send to `answer`, and records every text it
207+
* was handed (`texts`) and the number of every send that has settled
208+
* (`settled`).
209+
*/
210+
async function phoneDeployment(answer: () => Promise<unknown>) {
211+
vi.spyOn(console, 'warn').mockImplementation(() => {});
212+
const engine = await engines.take();
213+
const logged: string[] = [];
214+
const manager = new AuthManager({
215+
secret: SECRET,
216+
baseUrl: BASE,
217+
dataEngine: engine as never,
218+
plugins: { phoneNumber: true },
219+
logger: { warn: () => {}, error: (message: string) => logged.push(message) },
220+
} as never);
221+
manager.setEmailService({ sendTemplate: async () => ({ status: 'sent' }) } as never);
222+
const texts: Text[] = [];
223+
const settled: string[] = [];
224+
manager.setSmsService({
225+
async send(input: Text) {
226+
texts.push(input);
227+
try {
228+
return await answer();
229+
} finally {
230+
settled.push(input.to);
231+
}
232+
},
233+
isConfigured: () => true,
234+
} as never);
235+
const signedUp = await post(manager, '/sign-up/email', { email: EMAIL, password: PASSWORD, name: 'Reset' });
236+
expect(signedUp.status, await signedUp.clone().text()).toBe(200);
237+
const [user] = (await engine.find('sys_user', { where: { email: EMAIL }, limit: 1 }, SYS)) as Array<{ id: string }>;
238+
await engine.update('sys_user', { id: user.id, phone_number: PHONE, phone_number_verified: true }, SYS);
239+
return { manager, texts, settled, logged };
240+
}
241+
242+
async function requestPhoneReset(manager: AuthManager, phoneNumber: string): Promise<{ status: number; body: string }> {
243+
const res = await post(manager, '/phone-number/request-password-reset', { phoneNumber });
244+
return { status: res.status, body: await res.text() };
245+
}
246+
247+
it('answers a number with an account and a number without one alike, while the reset text is still being sent', async () => {
248+
const send = deferred();
249+
const d = await phoneDeployment(async () => {
250+
await send.promise;
251+
return { id: 'sms1', status: 'sent' };
252+
});
253+
254+
const forAccount = await requestPhoneReset(d.manager, PHONE);
255+
const forNobody = await requestPhoneReset(d.manager, NO_ACCOUNT_PHONE);
256+
257+
expect(forAccount.status).toBe(200);
258+
expect(forAccount).toEqual(forNobody);
259+
// Both answers arrived while the text's send was still open.
260+
expect(d.settled).toEqual([]);
261+
262+
// The control: the text still goes to the number, after the response.
263+
send.resolve();
264+
await vi.waitFor(() => expect(d.settled).toEqual([PHONE]));
265+
expect(d.texts.map((t) => t.to)).toEqual([PHONE]);
266+
expect(d.logged).toEqual([]);
267+
}, 60_000);
268+
269+
it('logs a reset text whose send fails on the server, without its code, and answers as for a text that is sent', async () => {
270+
const failing = await phoneDeployment(async () => ({ status: 'failed', error: 'carrier unavailable' }));
271+
const sending = await phoneDeployment(async () => ({ id: 'sms1', status: 'sent' }));
272+
273+
const throughFailing = await requestPhoneReset(failing.manager, PHONE);
274+
const throughSending = await requestPhoneReset(sending.manager, PHONE);
275+
276+
expect(throughFailing).toEqual(throughSending);
277+
await vi.waitFor(() => expect(failing.logged).toHaveLength(1));
278+
expect(failing.logged[0]).toContain('phone password-reset text was not delivered');
279+
expect(failing.logged[0]).toContain('carrier unavailable');
280+
const code = String(failing.texts[0]?.templateParams?.code ?? '');
281+
expect(code, 'the text carries its code').not.toBe('');
282+
expect(failing.logged[0]).not.toContain(code);
283+
}, 60_000);
284+
285+
it('the server-side phone reset call (no Request) still awaits its send', async () => {
286+
const d = await phoneDeployment(async () => {
287+
await new Promise((resolve) => setImmediate(resolve));
288+
return { id: 'sms1', status: 'sent' };
289+
});
290+
const api = (await d.manager.getApi()) as unknown as {
291+
requestPasswordResetPhoneNumber(input: { body: { phoneNumber: string } }): Promise<unknown>;
292+
};
293+
294+
await api.requestPasswordResetPhoneNumber({ body: { phoneNumber: PHONE } });
295+
296+
expect(d.settled).toEqual([PHONE]);
297+
}, 60_000);
298+
});
299+
180300
describe('runAfterResponse', () => {
181301
it("hands a task's synchronous throw to onFailure", async () => {
182302
const failures: unknown[] = [];

‎packages/plugins/plugin-auth/src/run-after-response.ts‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@
1212
* (`auth-manager-auth-instance.ts`, `sendResetPassword`), and what the send
1313
* does is the server's to log, never the caller's to see — which it already
1414
* never was: better-auth answers `{ status: true }` whatever the send does.
15+
* The phone-number reset request answers the same way, and its reset text is
16+
* sent after the response on the same terms (`auth-manager-plugin-list.ts`,
17+
* `sendPasswordResetOTP`).
1518
*
1619
* ## How
1720
*
@@ -44,12 +47,14 @@ export function runAfterResponse(task: () => Promise<unknown>, onFailure: (error
4447
}
4548

4649
/**
47-
* Wrap a better-auth mail callback — called as `(data, request)` — so that a
50+
* Wrap a better-auth send callback — called as `(data, request)` — so that a
4851
* call carrying its `Request` (every HTTP request: the public door) resolves at
4952
* once and the send runs after the response ({@link runAfterResponse}), its
5053
* failure going to `onFailure`. A call without one (a server-side `auth.api.*`
5154
* call, such as the identity import's) is handed straight to `send` — the same
52-
* promise — and awaited by its caller exactly as before.
55+
* promise — and awaited by its caller exactly as before. A callback better-auth
56+
* hands the endpoint context instead (the phone-number reset's) is called
57+
* with that context's `request`, the value the emailed reset is handed.
5358
*/
5459
export function sendAfterResponseOnPublicDoor<D>(
5560
send: (data: D, request?: unknown) => Promise<unknown>,
@@ -76,11 +81,12 @@ type FailureLogger = {
7681
* `error` when the host logger carries it, else its guaranteed `warn`, else —
7782
* no host logger at all — the console: the level better-auth's own
7883
* background-task log used for the same failure while the send ran inside the
79-
* request. Called through the property, never an extracted reference (a
80-
* class-based logger needs its receiver).
84+
* request. `what` names the send, its medium included (`password-reset
85+
* email`, `phone password-reset text`). Called through the property, never an
86+
* extracted reference (a class-based logger needs its receiver).
8187
*/
8288
export function logAfterResponseSendFailure(logger: unknown, what: string, error: unknown): void {
83-
const message = `[AuthManager] ${what} email was not delivered: ${
89+
const message = `[AuthManager] ${what} was not delivered: ${
8490
error instanceof Error ? error.message : String(error)
8591
}`;
8692
const sink = logger as FailureLogger | undefined;

‎ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.celGate.test.tsx‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,3 +152,27 @@ describe('MetadataResourceEditPage — Save is gated on the block inspector’s
152152
await waitFor(() => expect(saveButton()).toBeEnabled(), { timeout: 4000 });
153153
});
154154
});
155+
156+
describe('MetadataResourceEditPage — the save-status chip while the inspector holds auto-save (#29901)', () => {
157+
// `inspectorBlocking` returns the auto-save effect early exactly as a server
158+
// refusal does, so the chip must not promise an auto-save then either.
159+
const chipState = () => screen.queryByTestId('save-status')?.getAttribute('data-state') ?? null;
160+
161+
it('reads the held state on a dangling operator, and the auto-save state once it parses', async () => {
162+
const box = await openBlockCel();
163+
164+
// CONTROL first: a good predicate dirties the draft and reads auto-save.
165+
fireEvent.change(box, { target: { value: 'record.amount > 20' } });
166+
await waitFor(() => expect(chipState()).toBe('autosave-pending'), { timeout: 4000 });
167+
168+
fireEvent.change(box, { target: { value: 'record.amount >' } });
169+
await waitFor(() => expect(chipState()).toBe('held'), { timeout: 4000 });
170+
expect(screen.getByTestId('save-status')).toHaveAttribute(
171+
'title',
172+
'Fix the issues shown in the inspector before saving.',
173+
);
174+
175+
fireEvent.change(box, { target: { value: 'record.amount > 21' } });
176+
await waitFor(() => expect(chipState()).toBe('autosave-pending'), { timeout: 4000 });
177+
});
178+
});

‎ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.serverRefusalGate.test.tsx‎

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -505,3 +505,72 @@ describe('MetadataResourceEditPage — a refusal is read off the parsed error on
505505
expect(saveButton()).toBeEnabled();
506506
}, 20000);
507507
});
508+
509+
/**
510+
* The toolbar's save-status chip tells the truth while a refusal holds the
511+
* auto-save (objectstack#29901).
512+
*
513+
* The auto-save effect returns early on `refusalBlocking`, so after a 422 no
514+
* save is coming — yet the chip used to keep its "auto-saving" state for as
515+
* long as the page stayed dirty, beside banners saying the opposite. These
516+
* pins read the chip's KIND (`data-state`), never its copy.
517+
*
518+
* Every "held" assertion is paired with the CONTROL below: the same edit on the
519+
* same harness, with no refusal, reads the auto-save state and saves.
520+
*/
521+
describe('MetadataResourceEditPage — the save-status chip while a refusal holds auto-save (#29901)', () => {
522+
const chipState = () => screen.queryByTestId('save-status')?.getAttribute('data-state') ?? null;
523+
524+
it('CONTROL: an ordinary dirty edit reads the auto-save state, then saves', async () => {
525+
openEditor();
526+
const box = await selectAndOpenCel('bystander');
527+
fireEvent.change(box, { target: { value: 'record.amount > 11' } });
528+
529+
await waitFor(() => expect(chipState()).toBe('autosave-pending'), { timeout: 6000 });
530+
await waitFor(() => expect(mockClient.save).toHaveBeenCalledTimes(1), { timeout: 6000 });
531+
await waitFor(() => expect(chipState()).toBe('saved'), { timeout: 6000 });
532+
}, 20000);
533+
534+
it("the card's path: after a 422 the chip reads the refused state and no second save is sent", async () => {
535+
mockClient.save.mockRejectedValueOnce(await refusal(REFUSED_PATH));
536+
537+
openEditor();
538+
const offenderBox = await selectAndOpenCel('offender');
539+
fireEvent.change(offenderBox, { target: { value: 'record.amount > 21' } });
540+
await waitFor(() => expect(mockClient.save).toHaveBeenCalledTimes(1), { timeout: 6000 });
541+
542+
await waitFor(() => expect(chipState()).toBe('held'), { timeout: 6000 });
543+
// The chip carries the reason Save is withheld, the button's own words.
544+
expect(screen.getByTestId('save-status')).toHaveAttribute(
545+
'title',
546+
expect.stringContaining('The server refused this draft'),
547+
);
548+
549+
// Past the debounce, and again after an UNRELATED edit: still held, and
550+
// still the one save — the chip promised nothing that did not come.
551+
await pastAutoSaveWindow();
552+
expect(chipState()).toBe('held');
553+
const bystanderBox = await selectAndOpenCel('bystander');
554+
fireEvent.change(bystanderBox, { target: { value: 'record.amount > 12' } });
555+
await pastAutoSaveWindow();
556+
expect(chipState()).toBe('held');
557+
expect(mockClient.save).toHaveBeenCalledTimes(1);
558+
}, 25000);
559+
560+
it('recovers: an edit the server accepts returns the chip to saving / saved', async () => {
561+
mockClient.save.mockRejectedValueOnce(await refusal(REFUSED_PATH));
562+
563+
openEditor();
564+
let offenderBox = await selectAndOpenCel('offender');
565+
fireEvent.change(offenderBox, { target: { value: 'record.amount > 21' } });
566+
await waitFor(() => expect(chipState()).toBe('held'), { timeout: 6000 });
567+
568+
// Editing the slice the server named releases the hold; the next save is
569+
// accepted.
570+
offenderBox = await selectAndOpenCel('offender');
571+
fireEvent.change(offenderBox, { target: { value: 'record.amount > 22' } });
572+
await waitFor(() => expect(chipState()).not.toBe('held'), { timeout: 6000 });
573+
await waitFor(() => expect(mockClient.save).toHaveBeenCalledTimes(2), { timeout: 6000 });
574+
await waitFor(() => expect(chipState()).toBe('saved'), { timeout: 6000 });
575+
}, 25000);
576+
});

0 commit comments

Comments
 (0)