Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions .changeset/37973-profile-password-refusal.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
---
'@object-ui/auth': patch
'@object-ui/console': patch
---

fix(console): the profile page's password card shows a password refusal in the session's language

Clause-②: no
Metadata-protocol: none

The profile page's password card (set a local password, change password) now maps a refusal's `code` through `passwordDoorRefusalMessages`, as the set-password and reset-password pages do: a 409 `RESOURCE_CONFLICT` (a cloud-managed runtime, an SSO-only account, a pending SSO person) shows the localized sentence instead of the server's English one. Any other code keeps the server's message.

`@object-ui/auth`: `sendVerificationEmail`, `signOut` and `signInWithProvider` now reject through the same error builder as the other doors, so the thrown error carries the refusal's `code` and HTTP `status`, read from better-auth's flat body or from the ADR-0112 envelope. The `message` is unchanged.
12 changes: 10 additions & 2 deletions ui/apps/console/src/pages/system/ProfilePage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ import {
} from '@object-ui/components';
import { useUpload } from '@object-ui/fields';
import { toast } from 'sonner';
import { ConsolePageHeader } from '@object-ui/app-shell';
import { ConsolePageHeader, passwordDoorRefusalMessages } from '@object-ui/app-shell';
import { resolveBuiltInLanguage, useAppContentLanguages, useDisplayLocale, useObjectTranslation, type TranslateFn } from '@object-ui/i18n';
import { useAdapter, extractFieldErrors, extractWriteErrorMessage } from '@object-ui/react';
import { usePermissions } from '@object-ui/permissions';
Expand Down Expand Up @@ -880,7 +880,15 @@ function PasswordCard({ changePassword, setInitialPassword, hasLocalPassword, hi
}
reset();
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
// A refusal's `code` picks the localized sentence, as on the set-password
// and reset-password pages: a cloud-managed runtime, an SSO-only account
// or a pending SSO person refuses both doors with 409
// `RESOURCE_CONFLICT`, whose server text is English in every language.
// Any other code keeps the server's own message.
const code = err instanceof Error ? (err as Error & { code?: string }).code : undefined;
const refusals = passwordDoorRefusalMessages(t);
const localized = code && Object.prototype.hasOwnProperty.call(refusals, code) ? refusals[code] : undefined;
setError(localized ?? (err instanceof Error ? err.message : String(err)));
} finally {
setSubmitting(false);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* Profile — the password card draws a refusal's localized sentence, not the
* server's English one.
*
* A cloud-managed runtime, an SSO-only account and a pending SSO person are
* refused a local password with 409 `RESOURCE_CONFLICT`. The set-password and
* reset-password pages map that code through `passwordDoorRefusalMessages`
* (app-shell); the profile page's password card set the server's `message`
* instead, which is English in every language. These cases render the REAL
* page and the REAL map; only the page's data hooks are stubbed, as in the
* sibling profile suites. The translator echoes each call site's
* `defaultValue` and is a spy, so a case can name the pack key it read.
*
* CONTROL: another code (a wrong current password) and a rejection with no
* code keep the server's own message.
*/

import '@testing-library/jest-dom/vitest';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';

const { ADAPTER, translate, auth } = vi.hoisted(() => ({
ADAPTER: { findOne: async () => ({ id: 'usr_1' }), update: async () => ({}) },
translate: vi.fn((key: string, options?: Record<string, unknown>) =>
String(options?.defaultValue ?? key).replace(/\{\{(\w+)\}\}/g, (_hole, name: string) =>
String(options?.[name] ?? ''),
),
),
auth: {
hasPassword: true,
changePassword: async (_current: string, _next: string): Promise<void> => {},
setInitialPassword: async (_next: string): Promise<void> => {},
},
}));

vi.mock('@object-ui/auth', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
useAuth: () => ({
user: { id: 'usr_1', name: 'Ada', email: 'ada@example.com' },
updateUser: async () => {},
isLoading: false,
changePassword: (current: string, next: string) => auth.changePassword(current, next),
setInitialPassword: (next: string) => auth.setInitialPassword(next),
hasLocalPassword: async () => auth.hasPassword,
}),
}));

vi.mock('@object-ui/fields', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
useUpload: () => ({ upload: async () => ({ url: '' }) }),
}));

vi.mock('@object-ui/i18n', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
useObjectTranslation: () => ({ t: translate, language: 'en', offerableLanguages: ['en'] }),
}));

vi.mock('@object-ui/react', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
useAdapter: () => ADAPTER,
}));

vi.mock('@object-ui/permissions', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
usePermissions: () => ({ isLoaded: true, checkField: () => true }),
}));

// Imported after the mocks so the page picks them up.
const { ProfilePage } = await import('../ProfilePage');

const SERVER_TEXT = 'This environment is cloud-managed: no local password is set or reset here.';
const LOCALIZED =
"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.";

function refusal(message: string, code?: string): Error {
const err = new Error(message) as Error & { code?: string; status?: number };
if (code) err.code = code;
err.status = 409;
return err;
}

afterEach(() => {
cleanup();
translate.mockClear();
auth.hasPassword = true;
auth.changePassword = async () => {};
auth.setInitialPassword = async () => {};
});

async function submit(kind: 'change' | 'set'): Promise<HTMLElement> {
render(<ProfilePage />);
const action = kind === 'change' ? 'Change password' : 'Set password';
const button = await screen.findByRole('button', { name: action });
await waitFor(() => expect(button).toBeEnabled());
if (kind === 'change') {
fireEvent.change(screen.getByLabelText('Current password'), { target: { value: 'old-password-1' } });
}
fireEvent.change(document.getElementById('new-password')!, { target: { value: 'new-password-1' } });
fireEvent.change(document.getElementById('confirm-password')!, { target: { value: 'new-password-1' } });
fireEvent.click(button);
return button;
}

describe('profile password card — RESOURCE_CONFLICT draws the password-door sentence', () => {
it('set-password: the localized sentence, read from the password-door pack key', async () => {
auth.hasPassword = false;
auth.setInitialPassword = async () => { throw refusal(SERVER_TEXT, 'RESOURCE_CONFLICT'); };
await submit('set');
expect(await screen.findByText(LOCALIZED)).toBeInTheDocument();
expect(screen.queryByText(SERVER_TEXT)).not.toBeInTheDocument();
expect(translate).toHaveBeenCalledWith('auth.login.errors.managedPasswordReset', expect.anything());
});

it('change-password: the localized sentence too', async () => {
auth.changePassword = async () => { throw refusal(SERVER_TEXT, 'RESOURCE_CONFLICT'); };
await submit('change');
expect(await screen.findByText(LOCALIZED)).toBeInTheDocument();
expect(screen.queryByText(SERVER_TEXT)).not.toBeInTheDocument();
});

it('CONTROL: another code (a wrong current password) keeps the server message', async () => {
auth.changePassword = async () => { throw refusal('Invalid password', 'INVALID_PASSWORD'); };
await submit('change');
expect(await screen.findByText('Invalid password')).toBeInTheDocument();
expect(screen.queryByText(LOCALIZED)).not.toBeInTheDocument();
});

it('CONTROL: a rejection without a code keeps its message', async () => {
auth.hasPassword = false;
auth.setInitialPassword = async () => { throw new Error('Set password failed with status 500'); };
await submit('set');
expect(await screen.findByText('Set password failed with status 500')).toBeInTheDocument();
expect(screen.queryByText(LOCALIZED)).not.toBeInTheDocument();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -92,3 +92,25 @@ describe('#34171 — an ADR-0112 envelope refusal keeps its code on every passwo
expect(err.message).toBe('Auth request failed with status 500');
});
});

describe('the remaining client doors keep the refusal code too (verification mail, sign-out, social sign-in)', () => {
const doors: Array<[string, string, (c: ReturnType<typeof createAuthClient>) => Promise<unknown>]> = [
['sendVerificationEmail', '/send-verification-email', (c) => c.sendVerificationEmail('a@example.com')],
['signOut', '/sign-out', (c) => c.signOut()],
['signInWithProvider', '/sign-in/social', (c) => c.signInWithProvider('google')],
];

it.each(doors)('%s: an ADR-0112 envelope answers code RESOURCE_CONFLICT, its message, status 409', async (_name, path, call) => {
const err = await rejectionOf(call(clientFor(path, 409, ENVELOPE)));
expect(err.code).toBe('RESOURCE_CONFLICT');
expect(err.status).toBe(409);
expect(err.message).toBe(MANAGED);
});

it.each(doors)('%s CONTROL: a flat better-auth refusal keeps its own code and message', async (_name, path, call) => {
const err = await rejectionOf(call(clientFor(path, 400, { code: 'SOME_FLAT_CODE', message: 'Flat message' })));
expect(err.code).toBe('SOME_FLAT_CODE');
expect(err.status).toBe(400);
expect(err.message).toBe('Flat message');
});
});
13 changes: 4 additions & 9 deletions ui/packages/auth/src/createAuthClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -825,9 +825,8 @@ export function createAuthClient(config: AuthClientConfig): AuthClient {
sendVerificationEmail: (args: { email: string; callbackURL?: string }) => Promise<{ error?: { message?: string; status?: number } | null }>;
};
const { error } = await baseAuth.sendVerificationEmail({ email, callbackURL });
if (error) {
throw new Error(error.message ?? `Auth request failed with status ${error.status}`);
}
// `toAuthError` keeps the refusal's code, flat or in the ADR-0112 envelope.
if (error) throw toAuthError(error);
},

async signOut() {
Expand All @@ -848,9 +847,7 @@ export function createAuthClient(config: AuthClientConfig): AuthClient {
forgetConfig();
const { data, error } = await betterAuth.signOut({ callbackURL });
TokenStorage.clear();
if (error) {
throw new Error(error.message ?? `Auth request failed with status ${error.status}`);
}
if (error) throw toAuthError(error);
// `disableDefaultFetchPlugins: true` drops better-auth's `redirectPlugin`,
// so the provider-logout redirect is followed here, the same way
// `signInWithProvider` follows its `{ url, redirect }`. Without it the
Expand Down Expand Up @@ -1240,9 +1237,7 @@ export function createAuthClient(config: AuthClientConfig): AuthClient {
result = await signInSocial();
}
const { data, error } = result;
if (error) {
throw new Error(error.message ?? `Auth request failed with status ${error.status}`);
}
if (error) throw toAuthError(error);
// A missing redirect URL means the flow CANNOT continue — surface it
// instead of resolving silently (the user would see a dead button).
if (!data?.url) {
Expand Down
Loading