Skip to content

Commit 280cded

Browse files
committed
fix(console): profile password card maps the password-door refusal code; auth client keeps the code on three more doors
Co-authored-by: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Q4EjjQkY5yXZrN9BEA3rEK
1 parent 4af32b9 commit 280cded

4 files changed

Lines changed: 173 additions & 11 deletions

File tree

‎ui/apps/console/src/pages/system/ProfilePage.tsx‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ import {
3737
} from '@object-ui/components';
3838
import { useUpload } from '@object-ui/fields';
3939
import { toast } from 'sonner';
40-
import { ConsolePageHeader } from '@object-ui/app-shell';
40+
import { ConsolePageHeader, passwordDoorRefusalMessages } from '@object-ui/app-shell';
4141
import { resolveBuiltInLanguage, useAppContentLanguages, useDisplayLocale, useObjectTranslation, type TranslateFn } from '@object-ui/i18n';
4242
import { useAdapter, extractFieldErrors, extractWriteErrorMessage } from '@object-ui/react';
4343
import { usePermissions } from '@object-ui/permissions';
@@ -880,7 +880,15 @@ function PasswordCard({ changePassword, setInitialPassword, hasLocalPassword, hi
880880
}
881881
reset();
882882
} catch (err) {
883-
setError(err instanceof Error ? err.message : String(err));
883+
// A refusal's `code` picks the localized sentence, as on the set-password
884+
// and reset-password pages: a cloud-managed runtime, an SSO-only account
885+
// or a pending SSO person refuses both doors with 409
886+
// `RESOURCE_CONFLICT`, whose server text is English in every language.
887+
// Any other code keeps the server's own message.
888+
const code = err instanceof Error ? (err as Error & { code?: string }).code : undefined;
889+
const refusals = passwordDoorRefusalMessages(t);
890+
const localized = code && Object.prototype.hasOwnProperty.call(refusals, code) ? refusals[code] : undefined;
891+
setError(localized ?? (err instanceof Error ? err.message : String(err)));
884892
} finally {
885893
setSubmitting(false);
886894
}
Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* Profile — the password card draws a refusal's localized sentence, not the
5+
* server's English one.
6+
*
7+
* A cloud-managed runtime, an SSO-only account and a pending SSO person are
8+
* refused a local password with 409 `RESOURCE_CONFLICT`. The set-password and
9+
* reset-password pages map that code through `passwordDoorRefusalMessages`
10+
* (app-shell); the profile page's password card set the server's `message`
11+
* instead, which is English in every language. These cases render the REAL
12+
* page and the REAL map; only the page's data hooks are stubbed, as in the
13+
* sibling profile suites. The translator echoes each call site's
14+
* `defaultValue` and is a spy, so a case can name the pack key it read.
15+
*
16+
* CONTROL: another code (a wrong current password) and a rejection with no
17+
* code keep the server's own message.
18+
*/
19+
20+
import '@testing-library/jest-dom/vitest';
21+
import { afterEach, describe, expect, it, vi } from 'vitest';
22+
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
23+
24+
const { ADAPTER, translate, auth } = vi.hoisted(() => ({
25+
ADAPTER: { findOne: async () => ({ id: 'usr_1' }), update: async () => ({}) },
26+
translate: vi.fn((key: string, options?: Record<string, unknown>) =>
27+
String(options?.defaultValue ?? key).replace(/\{\{(\w+)\}\}/g, (_hole, name: string) =>
28+
String(options?.[name] ?? ''),
29+
),
30+
),
31+
auth: {
32+
hasPassword: true,
33+
changePassword: async (_current: string, _next: string): Promise<void> => {},
34+
setInitialPassword: async (_next: string): Promise<void> => {},
35+
},
36+
}));
37+
38+
vi.mock('@object-ui/auth', async (importOriginal) => ({
39+
...(await importOriginal<Record<string, unknown>>()),
40+
useAuth: () => ({
41+
user: { id: 'usr_1', name: 'Ada', email: 'ada@example.com' },
42+
updateUser: async () => {},
43+
isLoading: false,
44+
changePassword: (current: string, next: string) => auth.changePassword(current, next),
45+
setInitialPassword: (next: string) => auth.setInitialPassword(next),
46+
hasLocalPassword: async () => auth.hasPassword,
47+
}),
48+
}));
49+
50+
vi.mock('@object-ui/fields', async (importOriginal) => ({
51+
...(await importOriginal<Record<string, unknown>>()),
52+
useUpload: () => ({ upload: async () => ({ url: '' }) }),
53+
}));
54+
55+
vi.mock('@object-ui/i18n', async (importOriginal) => ({
56+
...(await importOriginal<Record<string, unknown>>()),
57+
useObjectTranslation: () => ({ t: translate, language: 'en', offerableLanguages: ['en'] }),
58+
}));
59+
60+
vi.mock('@object-ui/react', async (importOriginal) => ({
61+
...(await importOriginal<Record<string, unknown>>()),
62+
useAdapter: () => ADAPTER,
63+
}));
64+
65+
vi.mock('@object-ui/permissions', async (importOriginal) => ({
66+
...(await importOriginal<Record<string, unknown>>()),
67+
usePermissions: () => ({ isLoaded: true, checkField: () => true }),
68+
}));
69+
70+
// Imported after the mocks so the page picks them up.
71+
const { ProfilePage } = await import('../ProfilePage');
72+
73+
const SERVER_TEXT = 'This environment is cloud-managed: no local password is set or reset here.';
74+
const LOCALIZED =
75+
"This deployment signs you in through its identity provider, so no password is set or reset here. Sign in with the identity provider's button on the sign-in page.";
76+
77+
function refusal(message: string, code?: string): Error {
78+
const err = new Error(message) as Error & { code?: string; status?: number };
79+
if (code) err.code = code;
80+
err.status = 409;
81+
return err;
82+
}
83+
84+
afterEach(() => {
85+
cleanup();
86+
translate.mockClear();
87+
auth.hasPassword = true;
88+
auth.changePassword = async () => {};
89+
auth.setInitialPassword = async () => {};
90+
});
91+
92+
async function submit(kind: 'change' | 'set'): Promise<HTMLElement> {
93+
render(<ProfilePage />);
94+
const action = kind === 'change' ? 'Change password' : 'Set password';
95+
const button = await screen.findByRole('button', { name: action });
96+
await waitFor(() => expect(button).toBeEnabled());
97+
if (kind === 'change') {
98+
fireEvent.change(screen.getByLabelText('Current password'), { target: { value: 'old-password-1' } });
99+
}
100+
fireEvent.change(document.getElementById('new-password')!, { target: { value: 'new-password-1' } });
101+
fireEvent.change(document.getElementById('confirm-password')!, { target: { value: 'new-password-1' } });
102+
fireEvent.click(button);
103+
return button;
104+
}
105+
106+
describe('profile password card — RESOURCE_CONFLICT draws the password-door sentence', () => {
107+
it('set-password: the localized sentence, read from the password-door pack key', async () => {
108+
auth.hasPassword = false;
109+
auth.setInitialPassword = async () => { throw refusal(SERVER_TEXT, 'RESOURCE_CONFLICT'); };
110+
await submit('set');
111+
expect(await screen.findByText(LOCALIZED)).toBeInTheDocument();
112+
expect(screen.queryByText(SERVER_TEXT)).not.toBeInTheDocument();
113+
expect(translate).toHaveBeenCalledWith('auth.login.errors.managedPasswordReset', expect.anything());
114+
});
115+
116+
it('change-password: the localized sentence too', async () => {
117+
auth.changePassword = async () => { throw refusal(SERVER_TEXT, 'RESOURCE_CONFLICT'); };
118+
await submit('change');
119+
expect(await screen.findByText(LOCALIZED)).toBeInTheDocument();
120+
expect(screen.queryByText(SERVER_TEXT)).not.toBeInTheDocument();
121+
});
122+
123+
it('CONTROL: another code (a wrong current password) keeps the server message', async () => {
124+
auth.changePassword = async () => { throw refusal('Invalid password', 'INVALID_PASSWORD'); };
125+
await submit('change');
126+
expect(await screen.findByText('Invalid password')).toBeInTheDocument();
127+
expect(screen.queryByText(LOCALIZED)).not.toBeInTheDocument();
128+
});
129+
130+
it('CONTROL: a rejection without a code keeps its message', async () => {
131+
auth.hasPassword = false;
132+
auth.setInitialPassword = async () => { throw new Error('Set password failed with status 500'); };
133+
await submit('set');
134+
expect(await screen.findByText('Set password failed with status 500')).toBeInTheDocument();
135+
expect(screen.queryByText(LOCALIZED)).not.toBeInTheDocument();
136+
});
137+
});

‎ui/packages/auth/src/__tests__/managedRefusalEnvelope-34171.test.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,3 +92,25 @@ describe('#34171 — an ADR-0112 envelope refusal keeps its code on every passwo
9292
expect(err.message).toBe('Auth request failed with status 500');
9393
});
9494
});
95+
96+
describe('the remaining client doors keep the refusal code too (verification mail, sign-out, social sign-in)', () => {
97+
const doors: Array<[string, string, (c: ReturnType<typeof createAuthClient>) => Promise<unknown>]> = [
98+
['sendVerificationEmail', '/send-verification-email', (c) => c.sendVerificationEmail('a@example.com')],
99+
['signOut', '/sign-out', (c) => c.signOut()],
100+
['signInWithProvider', '/sign-in/social', (c) => c.signInWithProvider('google')],
101+
];
102+
103+
it.each(doors)('%s: an ADR-0112 envelope answers code RESOURCE_CONFLICT, its message, status 409', async (_name, path, call) => {
104+
const err = await rejectionOf(call(clientFor(path, 409, ENVELOPE)));
105+
expect(err.code).toBe('RESOURCE_CONFLICT');
106+
expect(err.status).toBe(409);
107+
expect(err.message).toBe(MANAGED);
108+
});
109+
110+
it.each(doors)('%s CONTROL: a flat better-auth refusal keeps its own code and message', async (_name, path, call) => {
111+
const err = await rejectionOf(call(clientFor(path, 400, { code: 'SOME_FLAT_CODE', message: 'Flat message' })));
112+
expect(err.code).toBe('SOME_FLAT_CODE');
113+
expect(err.status).toBe(400);
114+
expect(err.message).toBe('Flat message');
115+
});
116+
});

‎ui/packages/auth/src/createAuthClient.ts‎

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -825,9 +825,8 @@ export function createAuthClient(config: AuthClientConfig): AuthClient {
825825
sendVerificationEmail: (args: { email: string; callbackURL?: string }) => Promise<{ error?: { message?: string; status?: number } | null }>;
826826
};
827827
const { error } = await baseAuth.sendVerificationEmail({ email, callbackURL });
828-
if (error) {
829-
throw new Error(error.message ?? `Auth request failed with status ${error.status}`);
830-
}
828+
// `toAuthError` keeps the refusal's code, flat or in the ADR-0112 envelope.
829+
if (error) throw toAuthError(error);
831830
},
832831

833832
async signOut() {
@@ -848,9 +847,7 @@ export function createAuthClient(config: AuthClientConfig): AuthClient {
848847
forgetConfig();
849848
const { data, error } = await betterAuth.signOut({ callbackURL });
850849
TokenStorage.clear();
851-
if (error) {
852-
throw new Error(error.message ?? `Auth request failed with status ${error.status}`);
853-
}
850+
if (error) throw toAuthError(error);
854851
// `disableDefaultFetchPlugins: true` drops better-auth's `redirectPlugin`,
855852
// so the provider-logout redirect is followed here, the same way
856853
// `signInWithProvider` follows its `{ url, redirect }`. Without it the
@@ -1240,9 +1237,7 @@ export function createAuthClient(config: AuthClientConfig): AuthClient {
12401237
result = await signInSocial();
12411238
}
12421239
const { data, error } = result;
1243-
if (error) {
1244-
throw new Error(error.message ?? `Auth request failed with status ${error.status}`);
1245-
}
1240+
if (error) throw toAuthError(error);
12461241
// A missing redirect URL means the flow CANNOT continue — surface it
12471242
// instead of resolving silently (the user would see a dead button).
12481243
if (!data?.url) {

0 commit comments

Comments
 (0)