diff --git a/.changeset/34706-accept-invitation-followups.md b/.changeset/34706-accept-invitation-followups.md new file mode 100644 index 00000000000..65e7d0cb3a8 --- /dev/null +++ b/.changeset/34706-accept-invitation-followups.md @@ -0,0 +1,19 @@ +--- +'@objectstack/platform-objects': patch +'@object-ui/app-shell': patch +'@object-ui/console': patch +'@object-ui/i18n': patch +--- + +fix(app-shell,console): the invitation inbox's accept routes an unverified address to verification, and the verify screen no longer says a link was sent before it was + +Clause-②: no +Metadata-protocol: none + +Follow-ups to the rule that, while a deployment delivers mail, accepting an invitation needs a verified address (`403 EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION`). + +- **The invitation inbox's Accept** (`@object-ui/app-shell`). When the `sys_invitation` `accept_invitation` action is refused with that code, the console's `type: 'api'` action handlers (`useConsoleActionRuntime` and `RecordDetailView`, through the action door or the direct call alike) now open the verification-mail screen, `/verify-email-prompt`, for the account's address, with the mail's link returning to that invitation's accept page, instead of showing the vendor's sentence in a toast. Every other refusal still reads as before. The rule is keyed on the code alone; no action metadata key, spec field or server route changes. +- **The action's AI description** (`@objectstack/platform-objects`). `sys_invitation.accept_invitation`'s `ai.description` now states the condition: while the deployment delivers email, the caller's address must be verified, and an unverified caller is refused with that code and nothing is written. The text is the agent-facing description only; no translated bundle carries it. +- **The verify screen's copy** (`@object-ui/console`, `@object-ui/i18n`). `/verify-email-prompt` said "We sent a verification link" on every arrival, but only the sign-up sends a mail before arriving there. The sign-in arrival (refused `EMAIL_NOT_VERIFIED`, which sends nothing unless the deployment sets `emailVerification.sendOnSignIn`) and both accept-invitation arrivals send nothing. The sign-up arrival now marks itself with `?sent=1` and keeps its copy; every other arrival reads "Your email address has not been verified yet. Send a verification link to ADDRESS…", offers "Send verification email", and shows "Sent to:" and the spam hint only once the button has sent the mail. Two keys are added to the `auth.verifyEmail` namespace in every built-in locale: `sendDescription` and `sendButton`. + +**A host that embeds the accept page or the console action runtime declares `/verify-email-prompt`.** `DefaultAcceptInvitationPage` and the action handlers above navigate there with `email` and `redirect` query keys; `apps/console` mounts its own `VerifyEmailPromptPage` at that route, and a host without it sends the person to a route that does not exist. The `@object-ui/app-shell` README states the route and its query keys ("Hosting the invitation pages"). diff --git a/packages/platform-objects/src/identity/sys-invitation.object.ts b/packages/platform-objects/src/identity/sys-invitation.object.ts index 4a46d3758c8..f73d9962d33 100644 --- a/packages/platform-objects/src/identity/sys-invitation.object.ts +++ b/packages/platform-objects/src/identity/sys-invitation.object.ts @@ -261,7 +261,8 @@ export const SysInvitation = ObjectSchema.create({ ai: { exposed: true, description: - 'Accept an invitation addressed to the current user (the record), joining its organization with the invited role. Works only on a pending invitation sent to the caller\'s own email address.', + 'Accept an invitation addressed to the current user (the record), joining its organization with the invited role. Works only on a pending invitation sent to the caller\'s own email address. ' + + 'While this deployment delivers email, the caller\'s address must also be verified: an unverified caller is refused with EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION and nothing is written, so ask the human to verify their email address first, then accept.', }, }, { diff --git a/ui/apps/console/src/pages/auth/RegisterPage.tsx b/ui/apps/console/src/pages/auth/RegisterPage.tsx index c0546a58889..acf3ea3a958 100644 --- a/ui/apps/console/src/pages/auth/RegisterPage.tsx +++ b/ui/apps/console/src/pages/auth/RegisterPage.tsx @@ -69,6 +69,7 @@ import { import { AuthLayout } from './AuthLayout'; import { followOauthAuthorize } from './followAuthorize'; import { handoffMarkQuery, useHandoffRedirect, verificationCallbackURL } from './handoffRedirect'; +import { VERIFICATION_SENT_PARAM } from './verifyEmailPromptQuery'; // Was a second module-private copy of LoginPage's helper; both now share one // implementation — objectui#4181. Behaviour here is unchanged. import { withConsoleBase } from '../../utils/consoleBase'; @@ -423,6 +424,8 @@ export function RegisterPage() { const sp = new URLSearchParams(); sp.set('email', email); if (redirect) sp.set('redirect', redirect); + // The sign-up has sent the verification mail (objectstack#34706). + sp.set(VERIFICATION_SENT_PARAM, '1'); navigate(`/verify-email-prompt?${sp.toString()}${handoffMarkQuery(redirect)}`, { replace: true }); }} labels={{ diff --git a/ui/apps/console/src/pages/auth/VerifyEmailPromptPage.tsx b/ui/apps/console/src/pages/auth/VerifyEmailPromptPage.tsx index 457b9987737..ed456602beb 100644 --- a/ui/apps/console/src/pages/auth/VerifyEmailPromptPage.tsx +++ b/ui/apps/console/src/pages/auth/VerifyEmailPromptPage.tsx @@ -1,6 +1,12 @@ /** - * VerifyEmailPromptPage — "we sent you a link" page shown after sign-up - * or after a sign-in attempt was blocked by `EMAIL_NOT_VERIFIED`. + * VerifyEmailPromptPage — the verification-mail page shown after sign-up, + * after a sign-in attempt was blocked by `EMAIL_NOT_VERIFIED`, and after an + * invitation accept was refused for an unverified address. + * + * Only the sign-up arrival has had a mail sent for it, and only it says so + * (`?sent=1`, `./verifyEmailPromptQuery`). Every other arrival asks the person + * to send the link and reads "sent" only once the button has sent it + * (objectstack#34706). * * Ported from `framework/apps/account/src/routes/verify-email-prompt.tsx`. * Calls `useAuth().sendVerificationEmail(email, callbackURL)` on resend. @@ -22,6 +28,7 @@ import { } from '@object-ui/components'; import { AuthLayout } from './AuthLayout'; import { handoffMarkQuery, verificationCallbackURL } from './handoffRedirect'; +import { VERIFICATION_SENT_PARAM } from './verifyEmailPromptQuery'; export function VerifyEmailPromptPage() { const { t } = useObjectTranslation(); @@ -29,6 +36,8 @@ export function VerifyEmailPromptPage() { const [params] = useSearchParams(); const email = params.get('email') ?? ''; const redirect = params.get('redirect') ?? ''; + // Did this arrival's server call already send the mail? Only the sign-up's. + const sentOnArrival = params.get(VERIFICATION_SENT_PARAM) === '1'; const { sendVerificationEmail } = useAuth(); const [resending, setResending] = useState(false); @@ -112,15 +121,23 @@ export function VerifyEmailPromptPage() { {t('auth.verifyEmail.title', { defaultValue: 'Verify your email address' })} - {t('auth.verifyEmail.description', { - defaultValue: - 'We sent a verification link to your email address. Please click the link to verify your account.', - })} + {sentOnArrival + ? t('auth.verifyEmail.description', { + defaultValue: + 'We sent a verification link to your email address. Please click the link to verify your account.', + }) + : email + ? t('auth.verifyEmail.sendDescription', { + email, + defaultValue: + 'Your email address has not been verified yet. Send a verification link to {{email}}, then click the link to verify your account.', + }) + : t('auth.verifyEmail.emailMissing', { defaultValue: 'Email address is missing' })}
- {email ? ( + {email && (sentOnArrival || resent) ? (

{t('auth.verifyEmail.sentTo', { defaultValue: 'Sent to:' })}{' '} {email} @@ -159,9 +176,13 @@ export function VerifyEmailPromptPage() { ) : ( <> - {t('auth.verifyEmail.resendButton', { - defaultValue: 'Resend verification email', - })} + {sentOnArrival + ? t('auth.verifyEmail.resendButton', { + defaultValue: 'Resend verification email', + }) + : t('auth.verifyEmail.sendButton', { + defaultValue: 'Send verification email', + })} )} @@ -181,12 +202,14 @@ export function VerifyEmailPromptPage() { {t('auth.verifyEmail.backToLogin', { defaultValue: 'Back to login' })} -

- {t('auth.verifyEmail.checkSpam', { - defaultValue: - "Didn't receive the email? Check your spam folder or contact support.", - })} -

+ {sentOnArrival || resent ? ( +

+ {t('auth.verifyEmail.checkSpam', { + defaultValue: + "Didn't receive the email? Check your spam folder or contact support.", + })} +

+ ) : null}
diff --git a/ui/apps/console/src/pages/auth/__tests__/handoffVerificationMail-30157.test.tsx b/ui/apps/console/src/pages/auth/__tests__/handoffVerificationMail-30157.test.tsx index 7d9cbba76ec..2d1982bd0f8 100644 --- a/ui/apps/console/src/pages/auth/__tests__/handoffVerificationMail-30157.test.tsx +++ b/ui/apps/console/src/pages/auth/__tests__/handoffVerificationMail-30157.test.tsx @@ -114,11 +114,16 @@ function renderPage(page: keyof typeof PAGES, client: AuthClient, search: string const withRedirect = (redirect: string) => `?redirect=${encodeURIComponent(redirect)}`; const routerLocation = () => screen.getByTestId('router-location').textContent; -/** The prompt's query as `/login` and `/register` build it today: `email`, then `redirect`. */ -const promptAt = (redirect: string) => { +/** + * The prompt's query as `/login` and `/register` build it today: `email`, then + * `redirect`, then — from `/register` alone, whose sign-up sent the mail — + * `sent` (objectstack#34706). + */ +const promptAt = (redirect: string, sent = false) => { const sp = new URLSearchParams(); sp.set('email', EMAIL); sp.set('redirect', redirect); + if (sent) sp.set('sent', '1'); return `/verify-email-prompt?${sp.toString()}`; }; @@ -151,7 +156,7 @@ describe('the verification mail returns a hand-off sign-up to "go back to the ap it('/verify-email-prompt: the resent mail', async () => { const client = createMockClient(); - renderPage('verify-email-prompt', client, `?email=${encodeURIComponent(EMAIL)}&redirect=${encodeURIComponent(HANDOFF)}`); + renderPage('verify-email-prompt', client, `?email=${encodeURIComponent(EMAIL)}&redirect=${encodeURIComponent(HANDOFF)}&sent=1`); await userEvent.click(await screen.findByRole('button', { name: /Resend verification email/ })); await waitFor(() => expect(client.sendVerificationEmail).toHaveBeenCalledTimes(1)); expect(client.sendVerificationEmail.mock.calls[0]).toEqual([EMAIL, '/_console/verify-email?handoff=verified']); @@ -162,7 +167,7 @@ describe('the verification mail returns a hand-off sign-up to "go back to the ap await signUpUnverified(client, INVITE, MARK); expect(client.signUp.mock.calls[0][0].callbackURL).toBe('/_console/accept-invitation/inv_1'); cleanup(); - renderPage('verify-email-prompt', client, `?email=${encodeURIComponent(EMAIL)}&redirect=${encodeURIComponent(INVITE)}`); + renderPage('verify-email-prompt', client, `?email=${encodeURIComponent(EMAIL)}&redirect=${encodeURIComponent(INVITE)}&sent=1`); await userEvent.click(await screen.findByRole('button', { name: /Resend verification email/ })); await waitFor(() => expect(client.sendVerificationEmail).toHaveBeenCalledTimes(1)); expect(client.sendVerificationEmail.mock.calls[0]).toEqual([EMAIL, '/_console/accept-invitation/inv_1']); @@ -177,7 +182,7 @@ describe('the route\'s refusal time survives the hops through /verify-email-prom it('/register: verification required carries it to the prompt', async () => { await signUpUnverified(createMockClient(), HANDOFF, MARK); - expect(routerLocation()).toBe(`${promptAt(HANDOFF)}${MARK}`); + expect(routerLocation()).toBe(`${promptAt(HANDOFF, true)}${MARK}`); }); it('/verify-email-prompt: "Back to login" carries it', async () => { @@ -191,7 +196,7 @@ describe('the route\'s refusal time survives the hops through /verify-email-prom expect(routerLocation()).toBe(promptAt(INVITE)); cleanup(); await signUpUnverified(createMockClient(), INVITE, MARK); - expect(routerLocation()).toBe(promptAt(INVITE)); + expect(routerLocation()).toBe(promptAt(INVITE, true)); cleanup(); renderPage('verify-email-prompt', createMockClient(), `?redirect=${encodeURIComponent(INVITE)}${MARK}`); await userEvent.click(await screen.findByRole('button', { name: 'Back to login' })); diff --git a/ui/apps/console/src/pages/auth/__tests__/verificationCallback-10893.test.tsx b/ui/apps/console/src/pages/auth/__tests__/verificationCallback-10893.test.tsx index 0727b9fc107..b1824bb3de3 100644 --- a/ui/apps/console/src/pages/auth/__tests__/verificationCallback-10893.test.tsx +++ b/ui/apps/console/src/pages/auth/__tests__/verificationCallback-10893.test.tsx @@ -177,12 +177,15 @@ describe('RegisterPage — the verification mail carries ?redirect= (objectui#10 const sp = new URLSearchParams(window.location.search); expect(sp.get('email')).toBe('wangwei@example.com'); expect(sp.get('redirect')).toBe('/accept-invitation/inv_1'); + // objectstack#34706 — the sign-up sent the mail, and says so to the prompt. + expect(sp.get('sent')).toBe('1'); }); }); describe('VerifyEmailPromptPage — the resent mail carries ?redirect= too (objectui#10893)', () => { async function resendCallback(name: MountName, search: string): Promise<[unknown, unknown]> { - const mount = mountConsole(name, `/verify-email-prompt${search}`); + // The resend after a sign-up, which marks its arrival as sent (objectstack#34706). + const mount = mountConsole(name, `/verify-email-prompt${search}&sent=1`); renderAt(mount.basename, ); await userEvent.click(await screen.findByRole('button', { name: /Resend verification email/ })); await waitFor(() => expect(wire.resend).toHaveLength(1)); @@ -208,3 +211,48 @@ describe('VerifyEmailPromptPage — the resent mail carries ?redirect= too (obje expect(Object.keys(wire.resend[0])).not.toContain('callbackURL'); }); }); + +describe('VerifyEmailPromptPage — the standing copy says a link was sent only when one was (objectstack#34706)', () => { + const SENT_COPY = 'We sent a verification link to your email address. Please click the link to verify your account.'; + const ADDRESS = 'wangwei@example.com'; + + function arriveAt(search: string) { + const mount = mountConsole('standalone', `/verify-email-prompt${search}`); + renderAt(mount.basename, ); + } + + // The sign-in arrival (`/login` on EMAIL_NOT_VERIFIED) and the accept-invitation + // arrivals carry `email` and `redirect` and no `sent`: nothing was mailed. + it('an arrival that sent nothing asks the person to send the link, and claims no mail before the button is pressed', async () => { + arriveAt(`?email=wangwei%40example.com&${INVITE.slice(1)}`); + + expect(await screen.findByText( + `Your email address has not been verified yet. Send a verification link to ${ADDRESS}, then click the link to verify your account.`, + )).toBeTruthy(); + expect(screen.getByRole('button', { name: /^Send verification email$/ })).toBeTruthy(); + expect(screen.queryByText(SENT_COPY)).toBeNull(); + expect(screen.queryByText(/Sent to:/)).toBeNull(); + expect(screen.queryByText(/Didn't receive the email/)).toBeNull(); + expect(wire.resend).toHaveLength(0); + }); + + it('pressing the button sends the mail, and only then does the page say it was sent', async () => { + arriveAt(`?email=wangwei%40example.com&${INVITE.slice(1)}`); + await userEvent.click(await screen.findByRole('button', { name: /^Send verification email$/ })); + + await waitFor(() => expect(wire.resend).toHaveLength(1)); + expect(wire.resend[0].email).toBe(ADDRESS); + expect(await screen.findByText(/Sent to:/)).toBeTruthy(); + expect(screen.getByText(/Didn't receive the email/)).toBeTruthy(); + expect(screen.getByRole('button', { name: 'Email sent! Check your inbox' })).toBeTruthy(); + }); + + it('CONTROL: the sign-up arrival (`sent=1`) keeps its "we sent" copy and offers a resend', async () => { + arriveAt(`?email=wangwei%40example.com&${INVITE.slice(1)}&sent=1`); + + expect(await screen.findByText(SENT_COPY)).toBeTruthy(); + expect(screen.getByText(/Sent to:/)).toBeTruthy(); + expect(screen.getByRole('button', { name: /^Resend verification email$/ })).toBeTruthy(); + expect(screen.getByText(/Didn't receive the email/)).toBeTruthy(); + }); +}); diff --git a/ui/apps/console/src/pages/auth/verifyEmailPromptQuery.ts b/ui/apps/console/src/pages/auth/verifyEmailPromptQuery.ts new file mode 100644 index 00000000000..2b0f824d4c2 --- /dev/null +++ b/ui/apps/console/src/pages/auth/verifyEmailPromptQuery.ts @@ -0,0 +1,14 @@ +/** + * The query key an arrival at `/verify-email-prompt` sets when the server has + * already sent the verification mail (objectstack#34706). + * + * Only the sign-up arrival sets it: the sign-up sends the mail itself when it + * answers that verification is required. The sign-in arrival (a refused + * `EMAIL_NOT_VERIFIED`, which sends nothing unless the deployment opts into + * `emailVerification.sendOnSignIn`) and the accept-invitation arrivals (a + * refused accept, which sends nothing) leave it out, so the prompt's standing + * copy asks the person to send the link rather than saying it was sent. + * Absent is the default on purpose: a page that cannot tell must not claim a + * mail went out. + */ +export const VERIFICATION_SENT_PARAM = 'sent'; diff --git a/ui/packages/app-shell/README.md b/ui/packages/app-shell/README.md index 18b3210f03e..9d7c1fd08f3 100644 --- a/ui/packages/app-shell/README.md +++ b/ui/packages/app-shell/README.md @@ -293,6 +293,28 @@ invitation redirect is an affordance, not an authorization: the server still refuses a non-invitee's sign-up. +### Hosting the invitation pages: declare `/verify-email-prompt` + +While a deployment delivers mail, the server refuses to let an account whose +address is not verified accept an invitation +(`EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION`). Two +surfaces of this package answer that refusal by navigating to the +verification-mail screen at `/verify-email-prompt`, a route this package does +not mount: + +- `DefaultAcceptInvitationPage` (`/accept-invitation/:invitationId`), with + `redirect` set to the accept page itself; +- the console's `type: 'api'` action handlers (`useConsoleActionRuntime` and + `RecordDetailView`), when the invitation inbox's `accept_invitation` action + is refused, with `redirect` set to the accept page for that invitation. + +A host that mounts either one declares `/verify-email-prompt` too, or the +person is sent to a route that does not exist. The route reads two query keys, +each absent when unknown: `email`, the account's address, and `redirect`, the +basename-stripped router path the verification mail's link returns to. Nothing +has been sent when either surface arrives there, so the screen offers to send +the link. `apps/console` mounts its own `VerifyEmailPromptPage` there. + ## Unsaved edits A page that keeps edits in component state registers them while it holds them, diff --git a/ui/packages/app-shell/src/console/organizations/orgErrorMessage.ts b/ui/packages/app-shell/src/console/organizations/orgErrorMessage.ts index cc660f4cd65..1374b4cb005 100644 --- a/ui/packages/app-shell/src/console/organizations/orgErrorMessage.ts +++ b/ui/packages/app-shell/src/console/organizations/orgErrorMessage.ts @@ -195,6 +195,42 @@ export function isAcceptNeedsVerifiedEmail(err: unknown): boolean { return errorCode(err) === ACCEPT_NEEDS_VERIFIED_EMAIL_CODE; } +/** + * The verification screen that answers {@link isAcceptNeedsVerifiedEmail}, as a + * router path: `/verify-email-prompt` with the account's address (`email`) and + * the router path the verification mail's link returns to (`redirect`). Each + * is left out when absent. + * + * The route is the host's: the console declares it, and a host that mounts + * the accept page or the console's action runtime without it sends the person + * nowhere (the package README, "Hosting the invitation pages"). + */ +export function verifyEmailPromptPath( + email: string | null | undefined, + redirect: string | null | undefined, +): string { + const sp = new URLSearchParams(); + if (email) sp.set('email', email); + if (redirect) sp.set('redirect', redirect); + return `/verify-email-prompt?${sp.toString()}`; +} + +/** + * {@link verifyEmailPromptPath} for a refusal that did not come from the accept + * page — the invitation inbox's `accept_invitation` action: the mail's link + * returns to the accept page for that invitation, where the person accepts + * once verified. No invitation id, no `redirect`. + */ +export function invitationVerifyEmailPromptPath( + email: string | null | undefined, + invitationId: unknown, +): string { + const redirect = typeof invitationId === 'string' && invitationId + ? `/accept-invitation/${encodeURIComponent(invitationId)}` + : undefined; + return verifyEmailPromptPath(email, redirect); +} + /** * Resolve a rejected organization call into the message to show the user. * diff --git a/ui/packages/app-shell/src/hooks/__tests__/useConsoleActionRuntime.apiActionDoor-27611.test.tsx b/ui/packages/app-shell/src/hooks/__tests__/useConsoleActionRuntime.apiActionDoor-27611.test.tsx index 763bd832d8e..406a257d6e4 100644 --- a/ui/packages/app-shell/src/hooks/__tests__/useConsoleActionRuntime.apiActionDoor-27611.test.tsx +++ b/ui/packages/app-shell/src/hooks/__tests__/useConsoleActionRuntime.apiActionDoor-27611.test.tsx @@ -29,12 +29,13 @@ import { render, screen, renderHook, act } from '@testing-library/react'; import React from 'react'; import { builtInLocales, registerBuiltInLocales } from '@object-ui/i18n/locales'; -vi.mock('react-router-dom', () => ({ useNavigate: () => vi.fn() })); +const { navigateSpy } = vi.hoisted(() => ({ navigateSpy: vi.fn() })); +vi.mock('react-router-dom', () => ({ useNavigate: () => navigateSpy })); const authFetchSpy = vi.fn(); vi.mock('@object-ui/auth', async (importOriginal) => ({ ...(await importOriginal>()), - useAuth: () => ({ user: { id: 'u1', name: 'User', image: null }, activeOrganization: null }), + useAuth: () => ({ user: { id: 'u1', name: 'User', email: 'user@example.test', image: null }, activeOrganization: null }), createAuthenticatedFetch: () => authFetchSpy, })); @@ -114,8 +115,19 @@ const APPROVE = { params: [{ name: 'comment', label: 'Comment', type: 'textarea' }], }; +/** The invitation inbox's accept, as `sys_invitation` declares it. */ +const ACCEPT = { + name: 'accept_invitation', + label: 'Accept Invitation', + type: 'api', + target: '/api/v1/auth/organization/accept-invitation', + recordIdParam: 'invitationId', + refreshAfter: true, +}; + const OBJECTS = [ { name: 'sys_user', actions: [BAN, PING, NOTE] }, + { name: 'sys_invitation', actions: [ACCEPT] }, { name: 'sys_environment', actions: [CREATE_ENV] }, { name: 'showcase_task', actions: [RECALC] }, { name: 'sys_approval_request', actions: [APPROVE] }, @@ -152,6 +164,7 @@ function sent(): { url: string; method: string; body: any } { beforeEach(() => { authFetchSpy.mockReset(); + navigateSpy.mockReset(); }); describe('objectstack#27611 — a declared same-origin api click goes through the action door', () => { @@ -301,3 +314,49 @@ describe('objectstack#27611 — what the door answers once objectstack#27738 lan expect(out).toEqual({ success: true, data: { request: { id: 'req_1', record_title: 'Q4 budget' } }, reload: true }); }); }); + +describe('objectstack#34706 — the invitation inbox accept, refused for an unverified address, opens the verification screen', () => { + // better-auth's flat refusal body, relayed by the door as the target answered it. + const UNVERIFIED = { + code: 'EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION', + message: 'Email verification required before accepting or rejecting invitation', + }; + const VERIFY = '/verify-email-prompt?email=user%40example.test&redirect=%2Faccept-invitation%2Finv_1'; + + it('through the door: navigates to the prompt for the account, returning to that invitation, with no toast and no refresh', async () => { + answer(403, UNVERIFIED); + const { result, onRefresh } = mount('sys_invitation'); + + const out = await click(result, { ...ACCEPT, params: { _rowRecord: { id: 'inv_1' } } }); + + expect(sent().url.endsWith(`${DOOR}sys_invitation/accept_invitation`)).toBe(true); + expect(navigateSpy).toHaveBeenCalledTimes(1); + expect(navigateSpy).toHaveBeenCalledWith(VERIFY); + expect(out).toEqual({ success: false }); + expect(onRefresh).not.toHaveBeenCalled(); + }); + + it('through the direct call (no declaration in this host\'s objects): the same hand-over', async () => { + answer(403, UNVERIFIED); + const { result } = mount('sys_invitation', []); + + const out = await click(result, { ...ACCEPT, params: { _rowRecord: { id: 'inv_1' } } }); + + expect(sent().url).toBe(ACCEPT.target); + expect(navigateSpy).toHaveBeenCalledWith(VERIFY); + expect(out).toEqual({ success: false }); + }); + + it('CONTROL: another refusal of the same door keeps its sentence and navigates nowhere', async () => { + answer(403, { + code: 'YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION', + message: 'You are not the recipient of the invitation', + }); + const { result } = mount('sys_invitation'); + + const out = await click(result, { ...ACCEPT, params: { _rowRecord: { id: 'inv_1' } } }); + + expect(navigateSpy).not.toHaveBeenCalled(); + expect(out).toEqual({ success: false, error: 'You are not the recipient of the invitation' }); + }); +}); diff --git a/ui/packages/app-shell/src/hooks/useConsoleActionRuntime.tsx b/ui/packages/app-shell/src/hooks/useConsoleActionRuntime.tsx index 8b4693b010d..3e465b73d2c 100644 --- a/ui/packages/app-shell/src/hooks/useConsoleActionRuntime.tsx +++ b/ui/packages/app-shell/src/hooks/useConsoleActionRuntime.tsx @@ -55,6 +55,7 @@ import { resolvePageVarTokens } from '../utils/resolvePageVarTokens.js'; import { launchConsoleFlow } from '../utils/flowLaunch.js'; import type { TranslateFn } from '@object-ui/i18n'; import { apiActionRefusalResult } from '../utils/flowResponse.js'; +import { invitationVerifyEmailPromptPath, isAcceptNeedsVerifiedEmail } from '../console/organizations/orgErrorMessage.js'; import { findDeclaredApiAction, isSameOriginApiTarget, @@ -480,6 +481,16 @@ export function useConsoleActionRuntime(opts: ConsoleActionRuntimeOptions): Cons openEntitlementDialog(entitlementSpec); return { success: false }; } + // objectstack#34706 — an invitation accept refused because the + // caller's address is unverified (the invitation inbox's + // `accept_invitation`): the next step is to verify, so hand over to + // the verification-mail screen as the accept page does, its link + // returning to that invitation's accept page. The screen owns the + // messaging, so no toast. + if (isAcceptNeedsVerifiedEmail(body)) { + navigate(invitationVerifyEmailPromptPath(user?.email, rowRecord?.id)); + return { success: false }; + } // A flow-backed endpoint's refused run reads its inner refusal, not // the node chain (objectstack#27487); a refusal naming fields carries // them for the param dialog to mark (objectstack#28289). @@ -699,7 +710,7 @@ export function useConsoleActionRuntime(opts: ConsoleActionRuntimeOptions): Cons } catch (error) { return { success: false, error: (error as Error).message }; } - }, [dataSource, objApiName, objects, metadata, authFetch, activeOrganization, refresh, openEntitlementDialog, t, language]); + }, [dataSource, objApiName, objects, metadata, authFetch, activeOrganization, refresh, openEntitlementDialog, t, language, navigate, user?.email]); /** * Flow action handler — starts the flow through one of two doors diff --git a/ui/packages/app-shell/src/views/RecordDetailView.apiActionDoor-27611.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.apiActionDoor-27611.test.tsx index e7f524cd07c..014c0b46657 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.apiActionDoor-27611.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.apiActionDoor-27611.test.tsx @@ -22,7 +22,7 @@ import * as React from 'react'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { render, waitFor, act, cleanup } from '@testing-library/react'; -import { MemoryRouter } from 'react-router-dom'; +import { MemoryRouter, useLocation } from 'react-router-dom'; import { builtInLocales } from '@object-ui/i18n/locales'; const authFetchSpy = vi.fn(async (..._args: unknown[]) => @@ -33,7 +33,7 @@ const authFetchSpy = vi.fn(async (..._args: unknown[]) => ); vi.mock('@object-ui/auth', async (importOriginal) => ({ ...(await importOriginal>()), - useAuth: () => ({ user: { id: 'u1', name: 'Ada', image: null }, activeOrganization: null }), + useAuth: () => ({ user: { id: 'u1', name: 'Ada', email: 'ada@example.test', image: null }, activeOrganization: null }), createAuthenticatedFetch: () => authFetchSpy, })); @@ -119,6 +119,21 @@ const CLOSE_SUBTASK = { target: '/api/v1/subtasks/{id}/close', }; +/** The invitation inbox's accept, as `sys_invitation` declares it. */ +const ACCEPT = { + name: 'accept_invitation', + label: 'Accept Invitation', + type: 'api', + target: '/api/v1/auth/organization/accept-invitation', + recordIdParam: 'invitationId', +}; + +/** Where the router is, drawn so a test can read a navigation off the page. */ +function LocationProbe() { + const location = useLocation(); + return {location.pathname + location.search}; +} + const OBJECTS = [ { name: OBJECT_NAME, @@ -127,7 +142,7 @@ const OBJECTS = [ id: { type: 'text', label: 'Id' }, title: { type: 'text', label: 'Title' }, }, - actions: [RECALC, PING, ROTATE], + actions: [RECALC, PING, ROTATE, ACCEPT], }, { name: 'showcase_subtask', label: 'Subtask', fields: { id: { type: 'text', label: 'Id' } }, actions: [CLOSE_SUBTASK] }, ]; @@ -172,6 +187,7 @@ async function clickOnPage(action: any, status: number, body: unknown) { recordIdOverride={RECORD_ID} embedded /> + , ); @@ -278,3 +294,38 @@ describe('RecordDetailView api handler — a declared same-origin click goes thr expect(out).toEqual({ success: false, error: builtInLocales.en.form.noPermissionToSave }); }); }); + +describe('objectstack#34706 — RecordDetailView: an invitation accept refused for an unverified address opens the verification screen', () => { + const UNVERIFIED = { + code: 'EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION', + message: 'Email verification required before accepting or rejecting invitation', + }; + const VERIFY = `/verify-email-prompt?email=ada%40example.test&redirect=%2Faccept-invitation%2F${RECORD_ID}`; + const location = () => document.querySelector('[data-testid="router-location"]')?.textContent; + + it('a header click through the door navigates to the prompt, returning to this record\'s accept page, with no toast', async () => { + const { out, url } = await clickOnPage(ACCEPT, 403, UNVERIFIED); + + expect(url.endsWith(`${DOOR}${OBJECT_NAME}/${ACCEPT.name}`)).toBe(true); + expect(out).toEqual({ success: false }); + await waitFor(() => expect(location()).toBe(VERIFY)); + }); + + it('the direct call (an undeclared action name) hands over the same way', async () => { + const { out, url } = await clickOnPage({ ...ACCEPT, name: 'accept_elsewhere' }, 403, UNVERIFIED); + + expect(url).toBe(ACCEPT.target); + expect(out).toEqual({ success: false }); + await waitFor(() => expect(location()).toBe(VERIFY)); + }); + + it('CONTROL: another refusal keeps its sentence and the page stays put', async () => { + const { out } = await clickOnPage(ACCEPT, 403, { + code: 'YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION', + message: 'You are not the recipient of the invitation', + }); + + expect(out).toEqual({ success: false, error: 'You are not the recipient of the invitation' }); + expect(location()).toBe(`/app/demo/${OBJECT_NAME}/${RECORD_ID}`); + }); +}); diff --git a/ui/packages/app-shell/src/views/RecordDetailView.tsx b/ui/packages/app-shell/src/views/RecordDetailView.tsx index 6b09872e4f4..3de87b0fa5c 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.tsx @@ -67,6 +67,7 @@ import { recycleBinRefusalLabelsOf, recycleBinRestoreOf } from '../utils/recycle import { launchConsoleFlow } from '../utils/flowLaunch.js'; import type { TranslateFn } from '@object-ui/i18n'; import { apiActionRefusalResult } from '../utils/flowResponse.js'; +import { invitationVerifyEmailPromptPath, isAcceptNeedsVerifiedEmail } from '../console/organizations/orgErrorMessage.js'; import { findDeclaredApiAction, isSameOriginApiTarget, readApiActionDoorSuccess, sendApiActionThroughDoor } from '../utils/apiActionDoor.js'; import { useNavigationContext, useRecordBreadcrumbTitle } from '../context/NavigationContext.js'; // Audit provenance renders as the one-line ; the other @@ -75,7 +76,7 @@ import { useNavigationContext, useRecordBreadcrumbTitle } from '../context/Navig import { deriveRecordDetailSections } from './recordDetailSections.js'; import type { DataSource, FeedItem, Reaction, RecordPageOperation, RecordPagePayload } from '@object-ui/types'; import { placedHeaderActions } from '@object-ui/types'; -import type { ActionDef, ActionParamDef, ConfirmationHandler, ParamCollectionHandler } from '@object-ui/core'; +import type { ActionDef, ActionParamDef, ActionResult, ConfirmationHandler, ParamCollectionHandler } from '@object-ui/core'; import type { ConsoleActionDispatch } from '../consoleActionDispatch.js'; import { useRecordApprovals, openApprovalOf, isSubmitterOf } from '../hooks/useRecordApprovals.js'; import { RecordAttachmentsPanel } from './RecordAttachmentsPanel.js'; @@ -1799,6 +1800,20 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri // row's, else a related-list row's explicit `recordId`, else this // page's own for an action on this page's object — and the params bag. const doorObject = action.objectName ?? objectName; + const subjectId = rowRecord?.id + ?? (action as { recordId?: unknown }).recordId + ?? (doorObject === objectName ? pureRecordId : undefined); + // A non-2xx answer, from the door or from the target. objectstack#34706 — + // an invitation accept refused for an unverified address hands over to + // the verification-mail screen, as `useConsoleActionRuntime`'s api + // handler does; the screen owns the messaging, so no toast. + const refused = (res: { status: number }, json: unknown): ActionResult => { + if (isAcceptNeedsVerifiedEmail(json)) { + navigate(invitationVerifyEmailPromptPath(user?.email, subjectId)); + return { success: false }; + } + return apiActionRefusalResult(res, json, `HTTP ${res.status}`, language); + }; if (isSameOriginApiTarget(targetStr) && action.name && findDeclaredApiAction(objects, doorObject, action.name, targetStr)) { const door = await sendApiActionThroughDoor({ @@ -1806,13 +1821,11 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri baseUrl, action, objectName: doorObject!, - recordId: rowRecord?.id - ?? (action as { recordId?: unknown }).recordId - ?? (doorObject === objectName ? pureRecordId : undefined), + recordId: subjectId, params, }); if (!door.answered) return door.result; - if (!door.res.ok) return apiActionRefusalResult(door.res, door.json, `HTTP ${door.res.status}`, language); + if (!door.res.ok) return refused(door.res, door.json); const answer = readApiActionDoorSuccess(door, `Action "${action.name}"`); if (!answer.ok) return { success: false, error: answer.error }; if (action.refreshAfter === true) notifyViewChanged(); @@ -1919,7 +1932,7 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri if (!res.ok) { let errBody: any = null; try { errBody = await res.json(); } catch { /* response body not JSON */ } - return apiActionRefusalResult(res, errBody, `HTTP ${res.status}`, language); + return refused(res, errBody); } const data = await res.json().catch(() => ({})); if (action.refreshAfter === true) notifyViewChanged(); @@ -2028,7 +2041,7 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri } catch (error) { return { success: false, error: (error as Error).message }; } - }, [dataSource, objectName, objectDef, objects, pureRecordId, pageRecord, authFetch, activeOrganization, language]); + }, [dataSource, objectName, objectDef, objects, pureRecordId, pageRecord, authFetch, activeOrganization, language, navigate, user?.email]); // Client-side modal transport: `type:'modal'` actions open here (Dialog / // Sheet / Drawer by `placement`) and render arbitrary SchemaNode content. diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index b8e2d76ac5a..e816fdb5767 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -3231,6 +3231,10 @@ const ar = { missingToken: "رابط التحقق لا يحتوي على رمز.", emailMissing: "عنوان البريد الإلكتروني مفقود", resendButton: "إعادة إرسال بريد التحقق", + // objectstack#34706 — the prompt's copy on an arrival that sent no mail. + sendDescription: + "لم يتم التحقق من بريدك الإلكتروني بعد. أرسل رابط التحقق إلى {{email}}، ثم انقر على الرابط للتحقق من حسابك.", + sendButton: "إرسال بريد التحقق", resending: "جارٍ الإرسال…", resent: "تم إرسال البريد! تحقق من صندوق الوارد", resentSuccess: "تم إرسال بريد التحقق!", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 19e4ef1d927..a4d799eb2c7 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -2949,6 +2949,10 @@ const de = { missingToken: "Im Bestätigungslink fehlt ein Token.", emailMissing: "E-Mail-Adresse fehlt", resendButton: "Bestätigungs-E-Mail erneut senden", + // objectstack#34706 — the prompt's copy on an arrival that sent no mail. + sendDescription: + "Ihre E-Mail-Adresse ist noch nicht bestätigt. Senden Sie einen Bestätigungslink an {{email}} und klicken Sie dann auf den Link, um Ihr Konto zu bestätigen.", + sendButton: "Bestätigungs-E-Mail senden", resending: "Sende…", resent: "E-Mail gesendet! Überprüfen Sie Ihren Posteingang", resentSuccess: "Bestätigungs-E-Mail gesendet!", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 05dc3eac472..c9a22ac8836 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -3565,6 +3565,10 @@ const en = { missingToken: 'Verification link is missing a token.', emailMissing: 'Email address is missing', resendButton: 'Resend verification email', + // objectstack#34706 — the prompt's copy on an arrival that sent no mail. + sendDescription: + 'Your email address has not been verified yet. Send a verification link to {{email}}, then click the link to verify your account.', + sendButton: 'Send verification email', resending: 'Sending…', resent: 'Email sent! Check your inbox', resentSuccess: 'Verification email sent!', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 18596c01fb4..6172ca5cd7a 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -3021,6 +3021,10 @@ const es = { missingToken: "Falta un token en el enlace de verificación.", emailMissing: "Falta la dirección de correo", resendButton: "Reenviar correo de verificación", + // objectstack#34706 — the prompt's copy on an arrival that sent no mail. + sendDescription: + "Su correo aún no está verificado. Envíe un enlace de verificación a {{email}} y luego haga clic en el enlace para verificar su cuenta.", + sendButton: "Enviar correo de verificación", resending: "Enviando…", resent: "¡Correo enviado! Revise su bandeja de entrada", resentSuccess: "¡Correo de verificación enviado!", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 008363ecffa..33db2276136 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -3017,6 +3017,10 @@ const fr = { missingToken: "Il manque un token dans le lien de vérification.", emailMissing: "Adresse e-mail manquante", resendButton: "Renvoyer l'e-mail de vérification", + // objectstack#34706 — the prompt's copy on an arrival that sent no mail. + sendDescription: + "Votre adresse e-mail n'est pas encore vérifiée. Envoyez un lien de vérification à {{email}}, puis cliquez sur le lien pour vérifier votre compte.", + sendButton: "Envoyer l'e-mail de vérification", resending: "Envoi…", resent: "E-mail envoyé ! Vérifiez votre boîte de réception", resentSuccess: "E-mail de vérification envoyé !", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 42ea9c925b3..85f64692c80 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -2951,6 +2951,10 @@ const ja = { missingToken: "確認リンクにトークンがありません。", emailMissing: "メールアドレスがありません", resendButton: "確認メールを再送信", + // objectstack#34706 — the prompt's copy on an arrival that sent no mail. + sendDescription: + "メールアドレスはまだ確認されていません。{{email}} に確認リンクを送信し、リンクをクリックしてアカウントを確認してください。", + sendButton: "確認メールを送信", resending: "送信中…", resent: "メールが送信されました!受信箱を確認してください", resentSuccess: "確認メールが送信されました!", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 6bb204167d0..34e18704ad4 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -2949,6 +2949,10 @@ const ko = { missingToken: "확인 링크에 토큰이 없습니다.", emailMissing: "이메일 주소 누락", resendButton: "확인 이메일 다시 보내기", + // objectstack#34706 — the prompt's copy on an arrival that sent no mail. + sendDescription: + "이메일 주소가 아직 확인되지 않았습니다. {{email}}(으)로 확인 링크를 보낸 후 링크를 클릭하여 계정을 확인하세요.", + sendButton: "확인 이메일 보내기", resending: "전송 중…", resent: "이메일이 전송되었습니다! 받은 편지함을 확인하세요", resentSuccess: "확인 이메일이 전송되었습니다!", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index b4a7a70058a..860e9ecd0d1 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -3016,6 +3016,10 @@ const pt = { missingToken: "Falta um token no link de verificação.", emailMissing: "Endereço de e-mail ausente", resendButton: "Reenviar e-mail de verificação", + // objectstack#34706 — the prompt's copy on an arrival that sent no mail. + sendDescription: + "Seu endereço de e-mail ainda não foi verificado. Envie um link de verificação para {{email}} e depois clique no link para verificar sua conta.", + sendButton: "Enviar e-mail de verificação", resending: "Enviando…", resent: "E-mail enviado! Verifique sua caixa de entrada", resentSuccess: "E-mail de verificação enviado!", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index ff3b4d5b044..a7ab3dc6207 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -3098,6 +3098,10 @@ const ru = { missingToken: "В ссылке подтверждения отсутствует токен.", emailMissing: "Email не указан", resendButton: "Отправить письмо повторно", + // objectstack#34706 — the prompt's copy on an arrival that sent no mail. + sendDescription: + "Ваш email ещё не подтверждён. Отправьте ссылку подтверждения на {{email}}, затем нажмите на ссылку для подтверждения аккаунта.", + sendButton: "Отправить письмо подтверждения", resending: "Отправка…", resent: "Письмо отправлено! Проверьте входящие", resentSuccess: "Письмо с подтверждением отправлено!", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 094504a6ffb..c4aa11a69e5 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -3031,6 +3031,10 @@ const zh = { missingToken: '验证链接缺少令牌。', emailMissing: '缺少邮箱地址', resendButton: '重新发送验证邮件', + // objectstack#34706 — the prompt's copy on an arrival that sent no mail. + sendDescription: + '您的邮箱地址尚未验证。请向 {{email}} 发送一封验证邮件,然后点击邮件中的链接以验证您的账户。', + sendButton: '发送验证邮件', resending: '发送中…', resent: '邮件已发送!请查看收件箱', resentSuccess: '验证邮件已发送!', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 993f6f4677a..cba02aa168d 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -3031,6 +3031,10 @@ const zhHant = { missingToken: '驗證連結缺少令牌。', emailMissing: '缺少郵箱地址', resendButton: '重新發送驗證郵件', + // objectstack#34706 — the prompt's copy on an arrival that sent no mail. + sendDescription: + '您的郵箱地址尚未驗證。請向 {{email}} 傳送一封驗證郵件,然後點選郵件中的連結以驗證您的賬戶。', + sendButton: '傳送驗證郵件', resending: '傳送中…', resent: '郵件已傳送!請檢視收件箱', resentSuccess: '驗證郵件已傳送!',