From 1e1ea35ae1e78491b7b1b5c88e0a78518b52d0fd Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 05:11:11 +0000 Subject: [PATCH 1/4] fix(console): invitation refusals read in the console's language get-invitation's code-less not-found answer (a 400 with no code) now reads as the localized not-found sentence, keyed on the route, the status and the missing code, never on the vendor's English. The auth client carries the HTTP status on the thrown error so the page can see it. USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION joins the org error map with a sentence in every locale pack, and the not-found sentence now names the used, expired and revoked states and where an accepted invitation's organization is. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5nwxuShQ1A7T6jAiLn --- .../invitationVendorRefusals-33650.test.tsx | 291 ++++++++++++++++++ .../manage/AcceptInvitationPage.tsx | 11 +- .../console/organizations/orgErrorMessage.ts | 62 +++- .../__tests__/authErrorStatus-33650.test.ts | 57 ++++ ui/packages/auth/src/createAuthClient.ts | 13 + ui/packages/i18n/src/locales/ar.ts | 3 +- ui/packages/i18n/src/locales/de.ts | 3 +- ui/packages/i18n/src/locales/en.ts | 3 +- ui/packages/i18n/src/locales/es.ts | 3 +- ui/packages/i18n/src/locales/fr.ts | 3 +- ui/packages/i18n/src/locales/ja.ts | 3 +- ui/packages/i18n/src/locales/ko.ts | 3 +- ui/packages/i18n/src/locales/pt-BR.ts | 3 +- ui/packages/i18n/src/locales/ru.ts | 3 +- ui/packages/i18n/src/locales/zh-Hans.ts | 3 +- ui/packages/i18n/src/locales/zh-Hant.ts | 3 +- 16 files changed, 447 insertions(+), 20 deletions(-) create mode 100644 ui/packages/app-shell/src/console/organizations/__tests__/invitationVendorRefusals-33650.test.tsx create mode 100644 ui/packages/auth/src/__tests__/authErrorStatus-33650.test.ts diff --git a/ui/packages/app-shell/src/console/organizations/__tests__/invitationVendorRefusals-33650.test.tsx b/ui/packages/app-shell/src/console/organizations/__tests__/invitationVendorRefusals-33650.test.tsx new file mode 100644 index 00000000000..d63a037c127 --- /dev/null +++ b/ui/packages/app-shell/src/console/organizations/__tests__/invitationVendorRefusals-33650.test.tsx @@ -0,0 +1,291 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#33650 — two invitation refusals drew better-auth's raw English, + * and an invitation the invitee had already accepted read as an error. + * + * ## Why the auth client is real here + * + * The sibling holdouts file (`org-i18n-holdouts-4474.test.tsx`) mocks `useAuth` + * with hand-built coded errors. This card is exactly the case such a mock + * cannot see: better-auth's `get-invitation` answers its not-found with a 400 + * and NO code, and the thrown value carried no status either, so nothing a + * hand-made `code` stands for was ever on the wire. So `useAuth` here forwards + * to the REAL `createAuthClient` over a stubbed `fetch` that answers with + * better-auth 1.7.12's own bodies (`crud-invites.mjs`), and the page, the + * dialog and the i18n provider are the real ones. + * + * ## The three faces, as `origin/main` drew them in zh + * + * 1. `/accept-invitation/ID`, get-invitation 400 `{ message: "Invitation not found!" }` + * .......... 邀请不可用 + `Invitation not found!` + * 2. invite dialog, invite-member 400 `USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION` + * .......... `User is already a member of this organization` + * 3. the invitee re-opens an invitation they accepted: get-invitation answers + * the SAME code-less 400 (the route refuses any status but `pending`), so + * the page cannot tell it from an unknown id. The sentence now names the + * used / expired / revoked states and where an accepted invitation's + * organization is, beside the page's "Go to organizations" button. + */ + +import '@testing-library/jest-dom/vitest'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { render, screen, waitFor, fireEvent, cleanup } from '@testing-library/react'; +import React from 'react'; +import { I18nProvider } from '@object-ui/i18n'; +import { builtInLocales } from '@object-ui/i18n/locales'; +import { createAuthClient } from '@object-ui/auth'; + +// ── The vendor's answers, per route ────────────────────────────────────────── + +type Answer = { status: number; body: unknown }; +const answers = new Map(); + +const PENDING = { + id: 'inv-1', + organizationId: 'org-42', + organizationName: 'Acme', + organizationSlug: 'acme', + email: 'zhang.wei@example.com', + role: 'member', + status: 'pending', + expiresAt: '2099-03-04T12:00:00.000Z', + inviterId: 'u-0', + inviterEmail: 'grace@example.com', +}; + +/** better-auth 1.7.12 `getInvitation`: the not-found throw, verbatim — no `code`. */ +const GET_INVITATION_NOT_FOUND: Answer = { status: 400, body: { message: 'Invitation not found!' } }; + +const fetchFn = vi.fn(async (input: string | URL | Request) => { + const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url; + for (const [path, answer] of answers) { + if (url.includes(path)) { + return new Response(JSON.stringify(answer.body), { + status: answer.status, + headers: { 'Content-Type': 'application/json' }, + }); + } + } + return new Response(JSON.stringify({}), { status: 200, headers: { 'Content-Type': 'application/json' } }); +}); + +const client = createAuthClient({ + baseURL: 'http://localhost/api/auth', + fetchFn: fetchFn as unknown as typeof fetch, +}); + +// ⚠️ STABLE identities: the accept page keys its fetch effect on `getInvitation`. +const auth = { + isAuthenticated: true, + isLoading: false, + activeMember: { role: 'owner' }, + getInvitation: (id: string) => client.getInvitation(id), + acceptInvitation: (id: string) => client.acceptInvitation(id), + rejectInvitation: (id: string) => client.rejectInvitation(id), + switchOrganization: async () => undefined, + inviteMember: (args: Parameters[0]) => client.inviteMember(args), + describeDelegableScope: async () => null, +}; + +vi.mock('@object-ui/auth', async (importActual) => ({ + ...(await importActual()), + useAuth: () => auth, +})); + +const toastError = vi.fn(); +vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: (m: string) => toastError(m) } })); + +vi.mock('react-router-dom', async (importActual) => { + const navigate = () => {}; + const location = { pathname: '/accept-invitation/inv-1', search: '' }; + const params = { invitationId: 'inv-1' }; + return { + ...(await importActual()), + useNavigate: () => navigate, + useLocation: () => location, + useParams: () => params, + }; +}); + +// The component kit is not the subject: the dialog's portal and the select's +// popover are swapped for plain elements, as the sibling i18n tests do. +vi.mock('@object-ui/components', async (importOriginal) => { + const actual = await importOriginal>(); + const passthrough = (tag: string) => (p: any) => React.createElement(tag, p, p.children); + return { + ...actual, + Dialog: ({ open, children }: any) => (open ?
{children}
: null), + DialogContent: passthrough('div'), + DialogDescription: passthrough('p'), + DialogFooter: passthrough('div'), + DialogHeader: passthrough('div'), + DialogTitle: passthrough('h2'), + Select: ({ value, onValueChange, children }: any) => ( + + ), + SelectContent: ({ children }: any) => <>{children}, + SelectItem: ({ value, children, ...rest }: any) => ( + + ), + SelectTrigger: ({ children }: any) => <>{children}, + SelectValue: () => null, + }; +}); + +import { AcceptInvitationPage } from '../manage/AcceptInvitationPage'; +import { InviteMemberDialog } from '../manage/InviteMemberDialog'; + +const zh = builtInLocales['zh-Hans'] as any; +const en = builtInLocales.en as any; + +const renderIn = (lang: 'en' | 'zh', ui: React.ReactElement) => + render( + + {ui} + , + ); + +/** The error card's sentence, once the page has drawn it. */ +async function acceptPageError(): Promise { + const page = await screen.findByTestId('accept-invitation-page'); + await waitFor(() => expect(page.querySelector('p.text-muted-foreground')).not.toBeNull()); + return page.querySelector('p.text-muted-foreground') as HTMLElement; +} + +beforeEach(() => { + answers.clear(); + fetchFn.mockClear(); + toastError.mockClear(); +}); + +afterEach(() => cleanup()); + +describe('#33650 face 1 — get-invitation\'s code-less not-found', () => { + it('zh: draws the localized not-found sentence, not the vendor\'s English', async () => { + answers.set('/organization/get-invitation', GET_INVITATION_NOT_FOUND); + renderIn('zh', ); + + const sentence = await acceptPageError(); + expect(sentence).toHaveTextContent(zh.organization.errors.invitationNotFound); + expect(screen.getByTestId('accept-invitation-page')).not.toHaveTextContent('Invitation not found!'); + expect(screen.getByText(zh.organization.accept.errorTitle)).toBeInTheDocument(); + // The answer really came over the wire from the vendor route. + expect(fetchFn.mock.calls.some(([u]) => String(u instanceof Request ? u.url : u).includes('/organization/get-invitation'))).toBe(true); + }); + + it('en: draws the console\'s own English sentence, not the vendor\'s', async () => { + answers.set('/organization/get-invitation', GET_INVITATION_NOT_FOUND); + renderIn('en', ); + + const sentence = await acceptPageError(); + expect(sentence).toHaveTextContent(en.organization.errors.invitationNotFound); + expect(screen.getByTestId('accept-invitation-page')).not.toHaveTextContent('Invitation not found!'); + }); + + it('CONTROL: a coded 400 from the same route still shows its own message', async () => { + // better-auth 1.7.12 `getInvitation`: the inviter left the organization. + // Not a not-found; unmapped, so it keeps the server's sentence. + answers.set('/organization/get-invitation', { + status: 400, + body: { + code: 'INVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION', + message: 'Inviter is no longer a member of the organization', + }, + }); + renderIn('zh', ); + + const sentence = await acceptPageError(); + expect(sentence).toHaveTextContent('Inviter is no longer a member of the organization'); + }); + + it('CONTROL: a code-less answer with another status keeps its own message', async () => { + // better-auth's session check on the same route: 401, no code. + answers.set('/organization/get-invitation', { status: 401, body: { message: 'Not authenticated' } }); + renderIn('zh', ); + + const sentence = await acceptPageError(); + expect(sentence).toHaveTextContent('Not authenticated'); + expect(sentence).not.toHaveTextContent(zh.organization.errors.invitationNotFound); + }); + + it('CONTROL: accept-invitation\'s coded INVITATION_NOT_FOUND still maps as before', async () => { + answers.set('/organization/get-invitation', { status: 200, body: PENDING }); + answers.set('/organization/accept-invitation', { + status: 400, + body: { code: 'INVITATION_NOT_FOUND', message: 'Invitation not found' }, + }); + renderIn('zh', ); + + await screen.findByTestId('accept-invitation-role'); + fireEvent.click(screen.getByText(zh.organization.accept.accept)); + await waitFor(() => expect(toastError).toHaveBeenCalled()); + expect(toastError).toHaveBeenLastCalledWith(zh.organization.errors.invitationNotFound); + }); +}); + +describe('#33650 face 3 — the invitee re-opens an invitation they accepted', () => { + it('reads as used / expired / revoked and points to the organization list, with the way in', async () => { + // An accepted row is no longer `pending`, so get-invitation answers the + // same code-less 400 as for an unknown id: the id alone cannot tell. + answers.set('/organization/get-invitation', GET_INVITATION_NOT_FOUND); + renderIn('zh', ); + + const sentence = await acceptPageError(); + expect(sentence.textContent).toContain('已被使用'); + expect(sentence.textContent).toContain('组织列表'); + expect(screen.getByRole('button', { name: zh.organization.accept.goToOrgs })).toBeInTheDocument(); + }); +}); + +describe('#33650 face 2 — inviting someone who is already a member', () => { + it('zh: the invite dialog draws the localized sentence', async () => { + // better-auth 1.7.12 `createInvitation` (`crud-invites.mjs`), verbatim. + answers.set('/organization/invite-member', { + status: 400, + body: { + code: 'USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION', + message: 'User is already a member of this organization', + }, + }); + renderIn('zh', {}} />); + await waitFor(() => expect(screen.getByTestId('invite-email-input')).toBeInTheDocument()); + fireEvent.change(screen.getByTestId('invite-email-input'), { target: { value: 'zhang.wei@example.com' } }); + fireEvent.submit(document.querySelector('form')!); + + await waitFor(() => expect(screen.getByTestId('invite-error')).toBeInTheDocument()); + expect(screen.getByTestId('invite-error')).toHaveTextContent(zh.organization.errors.alreadyMember); + expect(screen.getByTestId('invite-error')).not.toHaveTextContent('User is already a member'); + }); + + it('CONTROL: an unmapped coded refusal still shows the server\'s own message', async () => { + answers.set('/organization/invite-member', { + status: 400, + body: { code: 'ORGANIZATION_NOT_FOUND', message: 'Organization not found' }, + }); + renderIn('zh', {}} />); + await waitFor(() => expect(screen.getByTestId('invite-email-input')).toBeInTheDocument()); + fireEvent.change(screen.getByTestId('invite-email-input'), { target: { value: 'p@example.com' } }); + fireEvent.submit(document.querySelector('form')!); + + await waitFor(() => expect(screen.getByTestId('invite-error')).toBeInTheDocument()); + expect(screen.getByTestId('invite-error')).toHaveTextContent('Organization not found'); + }); +}); + +describe('#33650 — every shipped pack carries the new sentence', () => { + it('organization.errors.alreadyMember is a translated string in each pack', () => { + const packs = Object.keys(builtInLocales) as Array; + expect(packs.length).toBeGreaterThanOrEqual(11); + for (const lang of packs) { + const value = (builtInLocales[lang] as any).organization?.errors?.alreadyMember; + expect(typeof value, `${lang}.organization.errors.alreadyMember`).toBe('string'); + if (lang !== 'en') expect(value, `${lang} echoes the English`).not.toBe(en.organization.errors.alreadyMember); + } + }); +}); diff --git a/ui/packages/app-shell/src/console/organizations/manage/AcceptInvitationPage.tsx b/ui/packages/app-shell/src/console/organizations/manage/AcceptInvitationPage.tsx index 6882c542a22..0468383b792 100644 --- a/ui/packages/app-shell/src/console/organizations/manage/AcceptInvitationPage.tsx +++ b/ui/packages/app-shell/src/console/organizations/manage/AcceptInvitationPage.tsx @@ -18,7 +18,7 @@ import { useDisplayLocale, useObjectTranslation } from '@object-ui/i18n'; import { Loader2, Building2, CheckCircle, XCircle } from 'lucide-react'; import { toast } from 'sonner'; import { resolveOrgRoleLabel } from '../orgRoleLabel.js'; -import { resolveOrgErrorMessage } from '../orgErrorMessage.js'; +import { resolveInvitationLookupMessage, resolveOrgErrorMessage } from '../orgErrorMessage.js'; import { resolveRootUrl } from '../resolveHomeUrl.js'; type InvitationWithOrg = AuthInvitation & { @@ -80,12 +80,9 @@ export function AcceptInvitationPage() { }) .catch((err) => { if (!cancelled) - setError( - resolveOrgErrorMessage(err, t, { - key: 'organization.errors.invitationNotFound', - defaultValue: 'This invitation no longer exists or has expired', - }), - ); + // objectstack#33650 — the lookup's own not-found answer carries no + // code; read by route, status and the missing code, never the text. + setError(resolveInvitationLookupMessage(err, t)); }) .finally(() => { if (!cancelled) setIsLoading(false); diff --git a/ui/packages/app-shell/src/console/organizations/orgErrorMessage.ts b/ui/packages/app-shell/src/console/organizations/orgErrorMessage.ts index 7a59f2f6e94..ec5a7e26a09 100644 --- a/ui/packages/app-shell/src/console/organizations/orgErrorMessage.ts +++ b/ui/packages/app-shell/src/console/organizations/orgErrorMessage.ts @@ -45,6 +45,7 @@ * `console/organizations/` can actually provoke — the three the card measured, * plus siblings on the same three call paths (the role-cap refusal that * `invitableOrgRoles` narrows for but the server re-checks; a duplicate invite; + * an invite to someone already in the organization (objectstack#33650); * the slug collision that is the create dialog's other outcome; the * multi-org-disabled refusal `CreateWorkspaceDialog` already comments about; and * the expired link `AcceptInvitationPage` already has a hand-written fallback @@ -75,6 +76,13 @@ export interface OrgErrorEntry { defaultValue: string; } +/** The not-found sentence, shared by the code row and the invitation lookup below. */ +const INVITATION_NOT_FOUND_ENTRY: OrgErrorEntry = { + key: 'organization.errors.invitationNotFound', + defaultValue: + 'This invitation has already been used, has expired, or was revoked. If you accepted it, the organization is in your organization list.', +}; + /** * Organization error code (better-auth's, or an objectstack registered code) * -> the console's own i18n key. @@ -98,6 +106,13 @@ export const ORG_ERROR_MESSAGE_KEYS: Record = { key: 'organization.errors.alreadyInvited', defaultValue: 'This user has already been invited to this organization', }, + // Inviting an address that already holds a membership: better-auth 1.7.12 + // `create-invitation` (`crud-invites.mjs`) refuses it with this code before + // it looks for a pending invitation (objectstack#33650). + USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION: { + key: 'organization.errors.alreadyMember', + defaultValue: 'This user is already a member of this organization', + }, // --- create-workspace path (CreateWorkspaceDialog) --- ORGANIZATION_ALREADY_EXISTS: { @@ -138,9 +153,14 @@ export const ORG_ERROR_MESSAGE_KEYS: Record = { key: 'organization.errors.notTheRecipient', defaultValue: 'You are not the recipient of the invitation', }, + // One sentence for every state the server folds into "not found": an + // unknown id, an invitation already accepted, declined or cancelled, and one + // past its expiry. The server answers all of them alike, so the sentence + // names them all, and tells the invitee who already accepted where the + // organization is (objectstack#33650). INVITATION_NOT_FOUND: { - key: 'organization.errors.invitationNotFound', - defaultValue: 'This invitation no longer exists or has expired', + key: INVITATION_NOT_FOUND_ENTRY.key, + defaultValue: INVITATION_NOT_FOUND_ENTRY.defaultValue, }, }; @@ -193,6 +213,44 @@ export function resolveOrgErrorMessage( return t(UNKNOWN_ERROR.key, { defaultValue: UNKNOWN_ERROR.defaultValue }); } +/** Read the HTTP status off a thrown value, if it carries one. */ +function errorStatus(err: unknown): number | undefined { + if (typeof err !== 'object' || err === null) return undefined; + const status = (err as { status?: unknown }).status; + return typeof status === 'number' ? status : undefined; +} + +/** + * Resolve a rejected invitation LOOKUP (`getInvitation`, better-auth's + * `GET /organization/get-invitation`) into the message to show the invitee. + * + * That route is the one organization route whose not-found answer carries no + * code: better-auth 1.7.12 (`crud-invites.mjs`, `getInvitation`) throws + * `APIError.fromStatus("BAD_REQUEST", { message: "Invitation not found!" })` + * for an unknown id and for an invitation that is accepted, rejected, + * canceled or expired, where `accept-invitation` throws the coded + * `INVITATION_NOT_FOUND` for the same states. Every other 400 the route can + * answer names its code (`ORGANIZATION_NOT_FOUND`, + * `INVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION`, better-call's + * `VALIDATION_ERROR`). So a 400 with NO code, from this route only, is that + * answer, and it reads as the not-found sentence. The English text is never + * read, for the reason the header gives. + * + * Everything else goes through {@link resolveOrgErrorMessage} unchanged: a + * coded refusal maps by its code, and a code-less answer with another status + * (a 401 from a session that ended, a 5xx) keeps its own message. + * + * Only the caller knows which route it called, so this is a separate entry + * point rather than a status rule inside {@link resolveOrgErrorMessage}: a + * code-less 400 from any other organization route is not a not-found. + */ +export function resolveInvitationLookupMessage(err: unknown, t: OrgTranslate): string { + if (errorCode(err) === undefined && errorStatus(err) === 400) { + return t(INVITATION_NOT_FOUND_ENTRY.key, { defaultValue: INVITATION_NOT_FOUND_ENTRY.defaultValue }); + } + return resolveOrgErrorMessage(err, t, INVITATION_NOT_FOUND_ENTRY); +} + // --------------------------------------------------------------------------- // The organization delete that the server refuses (objectstack#32648) // --------------------------------------------------------------------------- diff --git a/ui/packages/auth/src/__tests__/authErrorStatus-33650.test.ts b/ui/packages/auth/src/__tests__/authErrorStatus-33650.test.ts new file mode 100644 index 00000000000..d70fc933760 --- /dev/null +++ b/ui/packages/auth/src/__tests__/authErrorStatus-33650.test.ts @@ -0,0 +1,57 @@ +/** + * objectstack#33650 — the HTTP status survives the client boundary. + * + * better-auth 1.7.12's `GET /organization/get-invitation` answers an unknown, + * used, expired or revoked invitation with a 400 whose body is + * `{ message: "Invitation not found!" }` and no `code`. The console tells that + * answer apart by route, status and the missing code (never the English), so + * the thrown error has to carry the status. This drives the REAL client over a + * mocked `fetch`, like `org-error-code-4474.test.ts` next door. + */ + +import { describe, it, expect, vi } from 'vitest'; +import { createAuthClient } from '../createAuthClient'; + +function answering(pathFragment: string, status: number, body: unknown) { + return vi.fn(async (input: string | URL | Request) => { + const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url; + return new Response(JSON.stringify(url.includes(pathFragment) ? body : {}), { + status: url.includes(pathFragment) ? status : 200, + headers: { 'Content-Type': 'application/json' }, + }); + }); +} + +async function rejectionOf(promise: Promise): Promise { + try { + await promise; + } catch (err) { + return err as Error & { code?: string; status?: number }; + } + throw new Error('expected the call to reject, but it resolved'); +} + +describe('#33650 — organization rejections carry the HTTP status', () => { + it('getInvitation: the code-less not-found carries status 400 and no code', async () => { + const fetchFn = answering('/organization/get-invitation', 400, { message: 'Invitation not found!' }); + const client = createAuthClient({ baseURL: 'http://localhost/api/auth', fetchFn: fetchFn as unknown as typeof fetch }); + + const err = await rejectionOf(client.getInvitation('inv-1')); + expect(err.status).toBe(400); + expect(err.code).toBeUndefined(); + // MUST NOT CHANGE: the message is what it was before. + expect(err.message).toBe('Invitation not found!'); + }); + + it('inviteMember: a coded refusal carries its status beside the code', async () => { + const fetchFn = answering('/organization/invite-member', 400, { + code: 'USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION', + message: 'User is already a member of this organization', + }); + const client = createAuthClient({ baseURL: 'http://localhost/api/auth', fetchFn: fetchFn as unknown as typeof fetch }); + + const err = await rejectionOf(client.inviteMember({ organizationId: 'org-1', email: 'p@x.test', role: 'member' })); + expect(err.code).toBe('USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION'); + expect(err.status).toBe(400); + }); +}); diff --git a/ui/packages/auth/src/createAuthClient.ts b/ui/packages/auth/src/createAuthClient.ts index 94f57bc8fcd..0a7015632f3 100644 --- a/ui/packages/auth/src/createAuthClient.ts +++ b/ui/packages/auth/src/createAuthClient.ts @@ -118,6 +118,7 @@ interface AuthErrorDependent { /** The thrown value of every auth-client rejection that goes through {@link toAuthError}. */ type AuthClientError = Error & { code?: string; + status?: number; dependents?: AuthErrorDependent[]; userMessage?: string; details?: Record; @@ -184,6 +185,17 @@ function readDependents(raw: unknown): AuthErrorDependent[] | undefined { * `details.cause`, never on the message, so the body's `details` object is * carried on the thrown error as the server sent it. A `details` that is not a * plain object is not carried. + * + * ## And so is the HTTP `status` (objectstack#33650) + * + * Not every refusal carries a code. better-auth 1.7.12's `GET + * /organization/get-invitation` answers an unknown, used, expired or revoked + * invitation with a 400 whose body is `{ message: "Invitation not found!" }` + * and nothing else, while every other 400 on that route names its code. The + * console can tell that answer apart only by the route it called, the status + * and the absence of a code, never by the English sentence, so the status is + * carried as well. The two-factor and invitation-preview errors in this file + * already carry theirs. */ function toAuthError( error: BetterAuthErrorLike, @@ -193,6 +205,7 @@ function toAuthError( error.message ?? fallbackMessage ?? `Auth request failed with status ${error.status}`, ) as AuthClientError; if (error.code) err.code = error.code; + if (typeof error.status === 'number') err.status = error.status; const dependents = readDependents(error.dependents); if (dependents) err.dependents = dependents; if (typeof error.userMessage === 'string' && error.userMessage.trim()) err.userMessage = error.userMessage; diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index ac25601f30b..69866a5d609 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -3893,12 +3893,13 @@ const ar = { notAllowedToInvite: 'لا يُسمح لك بدعوة مستخدمين إلى هذه المؤسسة.', notAllowedToInviteWithRole: 'لا يُسمح لك بدعوة مستخدم بهذا الدور.', alreadyInvited: 'تمت دعوة هذا المستخدم إلى هذه المؤسسة بالفعل.', + alreadyMember: 'هذا المستخدم عضو بالفعل في هذه المؤسسة.', organizationExists: 'هذه المؤسسة موجودة بالفعل.', slugTaken: 'هذا المُعرِّف مستخدَم بالفعل.', notAllowedToCreate: 'لا يُسمح لك بإنشاء مؤسسة جديدة.', organizationLimitReached: 'لقد بلغت الحد الأقصى لعدد المؤسسات التي يمكنك إنشاؤها. لا تُحتسب المؤسسات التي دُعيت إليها ضمن هذا الحد.', notTheRecipient: 'لست المستلم المقصود بهذه الدعوة.', - invitationNotFound: 'لم تعد هذه الدعوة موجودة أو أنها منتهية الصلاحية.', + invitationNotFound: 'تم استخدام هذه الدعوة بالفعل أو انتهت صلاحيتها أو تم إلغاؤها. إذا كنت قد قبلتها، فستجد المؤسسة في قائمة مؤسساتك.', unknown: 'حدث خطأ ما. يرجى المحاولة مرة أخرى.', }, backToList: "العودة إلى المؤسسات", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 14aa2b815ed..d7e9301757b 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -3584,12 +3584,13 @@ const de = { notAllowedToInvite: 'Sie dürfen keine Benutzer in diese Organisation einladen.', notAllowedToInviteWithRole: 'Sie dürfen keine Benutzer mit dieser Rolle einladen.', alreadyInvited: 'Dieser Benutzer wurde bereits in diese Organisation eingeladen.', + alreadyMember: 'Dieser Benutzer ist bereits Mitglied dieser Organisation.', organizationExists: 'Diese Organisation existiert bereits.', slugTaken: 'Dieser URL-Slug ist bereits vergeben.', notAllowedToCreate: 'Sie dürfen keine neue Organisation erstellen.', organizationLimitReached: 'Sie haben die maximale Anzahl an Organisationen erreicht, die Sie erstellen können. Organisationen, zu denen Sie eingeladen wurden, zählen nicht dazu.', notTheRecipient: 'Sie sind nicht der Empfänger dieser Einladung.', - invitationNotFound: 'Diese Einladung existiert nicht mehr oder ist abgelaufen.', + invitationNotFound: 'Diese Einladung wurde bereits verwendet, ist abgelaufen oder wurde widerrufen. Wenn Sie sie angenommen haben, finden Sie die Organisation in Ihrer Organisationsliste.', unknown: 'Etwas ist schiefgelaufen. Bitte versuchen Sie es erneut.', }, backToList: "Zurück zu den Organisationen", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 4b79da50fba..44a37492d3b 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -4467,12 +4467,13 @@ const en = { notAllowedToInvite: 'You are not allowed to invite users to this organization', notAllowedToInviteWithRole: 'You are not allowed to invite a user with this role', alreadyInvited: 'This user has already been invited to this organization', + alreadyMember: 'This user is already a member of this organization', organizationExists: 'Organization already exists', slugTaken: 'That URL slug is already taken', notAllowedToCreate: 'You are not allowed to create a new organization', organizationLimitReached: 'You have reached the limit on organizations you can create. Organizations you were invited to do not count toward it.', notTheRecipient: 'You are not the recipient of the invitation', - invitationNotFound: 'This invitation no longer exists or has expired', + invitationNotFound: 'This invitation has already been used, has expired, or was revoked. If you accepted it, the organization is in your organization list.', unknown: 'Something went wrong. Please try again.', }, backToList: 'Back to organizations', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index c7a355c0f06..3e314ac017a 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -3662,12 +3662,13 @@ const es = { notAllowedToInvite: 'No tiene permiso para invitar usuarios a esta organización.', notAllowedToInviteWithRole: 'No tiene permiso para invitar a un usuario con este rol.', alreadyInvited: 'Este usuario ya ha sido invitado a esta organización.', + alreadyMember: 'Este usuario ya es miembro de esta organización.', organizationExists: 'Esa organización ya existe.', slugTaken: 'Ese slug ya está en uso.', notAllowedToCreate: 'No tiene permiso para crear una organización nueva.', organizationLimitReached: 'Ha alcanzado el número máximo de organizaciones que puede crear. Las organizaciones a las que se le ha invitado no cuentan para este límite.', notTheRecipient: 'No es el destinatario de esta invitación.', - invitationNotFound: 'Esta invitación ya no existe o ha caducado.', + invitationNotFound: 'Esta invitación ya se utilizó, caducó o fue revocada. Si ya la aceptó, encontrará la organización en su lista de organizaciones.', unknown: 'Algo salió mal. Inténtelo de nuevo.', }, backToList: "Volver a las organizaciones", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 750cd29e6aa..4f69562ddaf 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -3658,12 +3658,13 @@ const fr = { notAllowedToInvite: "Vous n'êtes pas autorisé à inviter des utilisateurs dans cette organisation.", notAllowedToInviteWithRole: "Vous n'êtes pas autorisé à inviter un utilisateur avec ce rôle.", alreadyInvited: 'Cet utilisateur a déjà été invité dans cette organisation.', + alreadyMember: 'Cet utilisateur est déjà membre de cette organisation.', organizationExists: 'Cette organisation existe déjà.', slugTaken: 'Ce slug est déjà utilisé.', notAllowedToCreate: "Vous n'êtes pas autorisé à créer une nouvelle organisation.", organizationLimitReached: "Vous avez atteint le nombre maximal d'organisations que vous pouvez créer. Les organisations auxquelles vous avez été invité ne sont pas comptées.", notTheRecipient: "Vous n'êtes pas le destinataire de cette invitation.", - invitationNotFound: "Cette invitation n'existe plus ou a expiré.", + invitationNotFound: "Cette invitation a déjà été utilisée, a expiré ou a été révoquée. Si vous l'avez acceptée, vous trouverez l'organisation dans votre liste d'organisations.", unknown: 'Une erreur est survenue. Veuillez réessayer.', }, backToList: "Retour aux organisations", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 508cc31f6ec..c6eec3e9aff 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -3586,12 +3586,13 @@ const ja = { notAllowedToInvite: 'この組織にユーザーを招待する権限がありません。', notAllowedToInviteWithRole: 'このロールでユーザーを招待する権限がありません。', alreadyInvited: 'このユーザーはすでにこの組織に招待されています。', + alreadyMember: 'このユーザーはすでにこの組織のメンバーです。', organizationExists: 'その組織はすでに存在します。', slugTaken: 'そのスラッグはすでに使用されています。', notAllowedToCreate: '新しい組織を作成する権限がありません。', organizationLimitReached: '作成できる組織の数が上限に達しました。招待されて参加した組織は上限に含まれません。', notTheRecipient: 'この招待の宛先はあなたではありません。', - invitationNotFound: 'この招待は存在しないか、有効期限が切れています。', + invitationNotFound: 'この招待はすでに使用済みか、有効期限切れか、取り消されています。承認済みの場合は、組織一覧にその組織があります。', unknown: '問題が発生しました。もう一度お試しください。', }, backToList: "組織一覧に戻る", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 7c3094c118b..748816a60c1 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -3583,12 +3583,13 @@ const ko = { notAllowedToInvite: '이 조직에 사용자를 초대할 권한이 없습니다.', notAllowedToInviteWithRole: '이 역할로 사용자를 초대할 권한이 없습니다.', alreadyInvited: '이 사용자는 이미 이 조직에 초대되었습니다.', + alreadyMember: '이 사용자는 이미 이 조직의 구성원입니다.', organizationExists: '해당 조직이 이미 존재합니다.', slugTaken: '해당 슬러그는 이미 사용 중입니다.', notAllowedToCreate: '새 조직을 만들 권한이 없습니다.', organizationLimitReached: '만들 수 있는 조직 수의 한도에 도달했습니다. 초대받아 참여한 조직은 한도에 포함되지 않습니다.', notTheRecipient: '이 초대의 수신자가 아닙니다.', - invitationNotFound: '이 초대는 더 이상 존재하지 않거나 만료되었습니다.', + invitationNotFound: '이 초대는 이미 사용되었거나 만료되었거나 취소되었습니다. 이미 수락했다면 조직 목록에서 해당 조직을 찾을 수 있습니다.', unknown: '문제가 발생했습니다. 다시 시도해 주세요.', }, backToList: "조직 목록으로 돌아가기", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index ebd6ed46e7e..c6d03ea6e72 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -3657,12 +3657,13 @@ const pt = { notAllowedToInvite: 'Você não tem permissão para convidar usuários para esta organização.', notAllowedToInviteWithRole: 'Você não tem permissão para convidar um usuário com esta função.', alreadyInvited: 'Este usuário já foi convidado para esta organização.', + alreadyMember: 'Este usuário já é membro desta organização.', organizationExists: 'Essa organização já existe.', slugTaken: 'Esse slug já está em uso.', notAllowedToCreate: 'Você não tem permissão para criar uma nova organização.', organizationLimitReached: 'Você atingiu o número máximo de organizações que pode criar. Organizações para as quais você foi convidado não contam para esse limite.', notTheRecipient: 'Você não é o destinatário deste convite.', - invitationNotFound: 'Este convite não existe mais ou expirou.', + invitationNotFound: 'Este convite já foi usado, expirou ou foi revogado. Se você já o aceitou, encontrará a organização na sua lista de organizações.', unknown: 'Algo deu errado. Tente novamente.', }, backToList: "Voltar para as organizações", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 0da1727dc75..be1fc286152 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -3749,12 +3749,13 @@ const ru = { notAllowedToInvite: 'У вас нет прав приглашать пользователей в эту организацию.', notAllowedToInviteWithRole: 'У вас нет прав приглашать пользователя с этой ролью.', alreadyInvited: 'Этот пользователь уже приглашён в эту организацию.', + alreadyMember: 'Этот пользователь уже является участником этой организации.', organizationExists: 'Такая организация уже существует.', slugTaken: 'Этот идентификатор уже занят.', notAllowedToCreate: 'У вас нет прав создавать новую организацию.', organizationLimitReached: 'Вы достигли максимального числа организаций, которые можете создать. Организации, в которые вас пригласили, не учитываются.', notTheRecipient: 'Вы не являетесь получателем этого приглашения.', - invitationNotFound: 'Это приглашение больше не существует или истекло.', + invitationNotFound: 'Это приглашение уже использовано, истекло или было отозвано. Если вы его приняли, организация есть в вашем списке организаций.', unknown: 'Что-то пошло не так. Попробуйте ещё раз.', }, backToList: "Назад к организациям", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index a76d57d9797..c614d0f6411 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -3832,12 +3832,13 @@ const zh = { notAllowedToInvite: '您无权邀请用户加入该组织。', notAllowedToInviteWithRole: '您无权以该角色邀请用户。', alreadyInvited: '该用户已被邀请加入本组织。', + alreadyMember: '该用户已是本组织成员。', organizationExists: '该组织已存在。', slugTaken: '该标识已被占用。', notAllowedToCreate: '您无权创建新组织。', organizationLimitReached: '您创建的组织数量已达上限。被邀请加入的组织不计入此上限。', notTheRecipient: '您不是该邀请的收件人。', - invitationNotFound: '该邀请已失效或已过期。', + invitationNotFound: '该邀请已被使用、已过期或已撤销。如果您已接受过该邀请,可在组织列表中找到该组织。', unknown: '出了点问题,请重试。', }, backToList: '返回组织列表', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index d1b6b15409c..5549f146f1f 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -3832,12 +3832,13 @@ const zhHant = { notAllowedToInvite: '您無權邀請使用者加入該組織。', notAllowedToInviteWithRole: '您無權以該角色邀請使用者。', alreadyInvited: '該使用者已被邀請加入本組織。', + alreadyMember: '該使用者已是本組織成員。', organizationExists: '該組織已存在。', slugTaken: '該標識已被佔用。', notAllowedToCreate: '您無權建立新組織。', organizationLimitReached: '您建立的組織數量已達上限。被邀請加入的組織不計入此上限。', notTheRecipient: '您不是該邀請的收件人。', - invitationNotFound: '該邀請已失效或已過期。', + invitationNotFound: '該邀請已被使用、已過期或已撤銷。如果您已接受過該邀請,可在組織列表中找到該組織。', unknown: '出了點問題,請重試。', }, backToList: '返回組織列表', From bfdc4f89a6830054c10c98470aea1e3318d477ae Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 05:14:46 +0000 Subject: [PATCH 2/4] chore(changeset): invitation refusal copy Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5nwxuShQ1A7T6jAiLn --- .changeset/33650-invitation-refusal-copy.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 .changeset/33650-invitation-refusal-copy.md diff --git a/.changeset/33650-invitation-refusal-copy.md b/.changeset/33650-invitation-refusal-copy.md new file mode 100644 index 00000000000..80b33ac907e --- /dev/null +++ b/.changeset/33650-invitation-refusal-copy.md @@ -0,0 +1,18 @@ +--- +'@object-ui/console': patch +'@object-ui/auth': patch +'@object-ui/i18n': patch +--- + +Clause-②: no +Metadata-protocol: none + +Organization invitation refusals now read in the console's language. Opening an +invitation link that is unknown, already used, expired or revoked shows the +console's own sentence instead of better-auth's "Invitation not found!" (the +lookup's not-found answer carries no code, so it is read by its route, its 400 +status and the missing code, never by its English text), and that sentence now +says the invitation may already have been used and where an accepted +invitation's organization is. Inviting someone who is already a member shows a +translated sentence instead of "User is already a member of this organization". +Errors thrown by `@object-ui/auth` now also carry the HTTP `status`. From 2c55521747afa488bda183ec83b45e0a1876ad1c Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 05:21:03 +0000 Subject: [PATCH 3/4] test(console): the org error map census names the already-member code Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5nwxuShQ1A7T6jAiLn --- .../organizations/__tests__/orgErrorMessage-4474.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/ui/packages/app-shell/src/console/organizations/__tests__/orgErrorMessage-4474.test.ts b/ui/packages/app-shell/src/console/organizations/__tests__/orgErrorMessage-4474.test.ts index 3c3e1e6e90b..1921ccc96fe 100644 --- a/ui/packages/app-shell/src/console/organizations/__tests__/orgErrorMessage-4474.test.ts +++ b/ui/packages/app-shell/src/console/organizations/__tests__/orgErrorMessage-4474.test.ts @@ -243,6 +243,8 @@ describe('#4474 — the mapping table itself', () => { 'ORGANIZATION_ALREADY_EXISTS', 'ORGANIZATION_CREATION_DISABLED', 'ORGANIZATION_SLUG_ALREADY_TAKEN', + // objectstack#33650: better-auth 1.7.12 `create-invitation` refuses an address that already holds a membership. + 'USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION', 'USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION', 'YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION', 'YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS', From 0c5eed2cb925bb868f69ac77a1fdca44a4a3d331 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 06:04:12 +0000 Subject: [PATCH 4/4] chore(changeset): declare the added locale key and error status as widening Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5nwxuShQ1A7T6jAiLn --- .changeset/33650-invitation-refusal-copy.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/.changeset/33650-invitation-refusal-copy.md b/.changeset/33650-invitation-refusal-copy.md index 80b33ac907e..57e5f532588 100644 --- a/.changeset/33650-invitation-refusal-copy.md +++ b/.changeset/33650-invitation-refusal-copy.md @@ -4,7 +4,7 @@ '@object-ui/i18n': patch --- -Clause-②: no +Clause-②: yes (widening) Metadata-protocol: none Organization invitation refusals now read in the console's language. Opening an @@ -16,3 +16,9 @@ says the invitation may already have been used and where an accepted invitation's organization is. Inviting someone who is already a member shows a translated sentence instead of "User is already a member of this organization". Errors thrown by `@object-ui/auth` now also carry the HTTP `status`. + +Widening, nothing removed or narrowed: `@object-ui/i18n` gains the key +`organization.errors.alreadyMember` in all eleven locale packs (and rewords +`organization.errors.invitationNotFound`), and errors thrown by +`@object-ui/auth` gain a numeric `status` property beside the existing +`message` and `code`.