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
12 changes: 12 additions & 0 deletions .changeset/30125-invitation-sign-up-joins.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
'@object-ui/app-shell': patch
'@object-ui/console': patch
---

feat(console,app-shell): registering from an invitation link joins that invitation's organization and enters the app in one step

Clause-②: yes (widening)
Metadata-protocol: none

- **`@object-ui/console`: `/register`** opened from an invitation link (`?redirect=/accept-invitation/ID`) now accepts THAT invitation as the account the sign-up just created, switches the session to its organization and enters the console root. A new member used to pass three screens: the sign-up, the accept page ("Accept invitation"), and "Invitation accepted … Continue". The server still decides: an address that is not the invited one is refused, nothing is accepted, and the page goes on to the accept page as before, which shows the refusal. A person who opens the page already signed in accepts nothing there, and a sign-up that waits for email verification is accepted from the accept page the verification mail returns to.
- **`@object-ui/app-shell`: `DefaultRegisterPage`** does the same; it used to go to `/` after the sign-up and leave the invitation behind. New export **`useInvitationSignUpJoin(redirect)`**, the one hook both register pages call, answering `none`, `joining`, `joined` or `refused` (type `InvitationSignUpJoin`).
23 changes: 23 additions & 0 deletions ui/apps/console/src/pages/auth/RegisterPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@
* `SELF_REGISTRATION_CLOSED` re-reads the preview, so an invitation that
* went away meanwhile ends the same way and a live one names the address
* it was sent to (#27509).
* - Registered from an invitation link, accepts THAT invitation as the new
* account and enters its organization, instead of stopping on the accept
* page and then on "Invitation accepted" (#30125, app-shell's
* `useInvitationSignUpJoin`). An address the server refuses goes on to the
* accept page as before, which shows the refusal.
*/

import { useEffect, useLayoutEffect, useRef, useState } from 'react';
Expand All @@ -51,6 +56,7 @@ import {
InvitationGoneNotice,
invitationArrivalCopy,
useInvitationArrival,
useInvitationSignUpJoin,
} from '@object-ui/app-shell';
import { AuthLayout } from './AuthLayout';
import { followOauthAuthorize } from './followAuthorize';
Expand Down Expand Up @@ -116,6 +122,8 @@ export function RegisterPage() {
const ssoHandoffStartedRef = useRef(false);
// And the mobile sign-in hand-off navigation.
const mobileHandoffStartedRef = useRef(false);
// And the entry into the organization an invitation sign-up joined (#30125).
const invitationEntryStartedRef = useRef(false);

// See LoginPage: `isLoading` is overloaded (initial session check + every
// in-flight signUp). Latch once the first check resolves so a failed
Expand Down Expand Up @@ -164,6 +172,8 @@ export function RegisterPage() {
const invitationCopy = invitationRedirect
? invitationArrivalCopy('register', invitationArrival.preview, t)
: null;
// #30125 — the sign-up made on this page from an invitation link accepts it.
const invitationJoin = useInvitationSignUpJoin(redirect);

// Sign-up switched off — bounce to /login.
useEffect(() => {
Expand Down Expand Up @@ -198,6 +208,18 @@ export function RegisterPage() {
return;
}

// #30125 — registered from an invitation link: hold while the acceptance
// is in flight, then enter the organization it joined. A refusal falls
// through to the steps below, which open the accept page as before.
if (invitationJoin === 'joining') return;
if (invitationJoin === 'joined') {
if (!invitationEntryStartedRef.current) {
invitationEntryStartedRef.current = true;
window.location.assign(withConsoleBase('/'));
}
return;
}

if (!activeOrganization) {
if (isOrganizationsLoading || autoSelectingOrg) return;
if (organizations.length === 1) {
Expand Down Expand Up @@ -227,6 +249,7 @@ export function RegisterPage() {
switchOrganization,
handoff.target,
handoff.holdForSignIn,
invitationJoin,
]);

// The first session check has answered and nobody is signed in: the page is
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
/**
* #30125 — registering from an invitation link joins that invitation's
* organization and enters the console, instead of stopping on the accept page
* ("Accept invitation") and then on "Invitation accepted … Continue".
*
* Pinned on the console's own `/register`, the page the console routes:
*
* - the sign-up accepts the invitation its `?redirect=` names, switches the
* session to that organization, and leaves for the console root once;
* - the server refusing the read (an address that is not the invited one):
* nothing is accepted and the page opens the accept page, as before;
* - a person already signed in when the page opens accepts nothing here.
*
* The real `AuthProvider` runs over a mock client, so the session appears the
* way a sign-up makes it appear. The Console is mounted as the shipped build
* is (`<base href="/_console/">`), so "the root" is read where the browser
* would land. The package's `DefaultRegisterPage` carries the same pins in
* `packages/app-shell/src/console/auth/__tests__/invitationSignUpJoin-30125.test.tsx`.
*/

import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, cleanup, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter } from 'react-router-dom';
import { AuthProvider } from '@object-ui/auth';
import type { AuthClient } from '@object-ui/auth';
import { RegisterPage } from '../RegisterPage';

const INVITATION_ID = 'inv_30125';
const ACCEPT_PATH = `/accept-invitation/${INVITATION_ID}`;
const ORG = { id: 'org_acme', name: 'Acme', slug: 'acme' };
const USER = { id: 'u_new', name: 'Zhang', email: 'zhang@example.com' };

let baseEl: HTMLBaseElement | null = null;
let assign: ReturnType<typeof vi.fn>;

beforeEach(() => {
window.localStorage.clear();
baseEl = document.createElement('base');
baseEl.setAttribute('href', '/_console/');
document.head.appendChild(baseEl);
vi.stubEnv('BASE_URL', './');
assign = vi.fn();
vi.spyOn(window.location, 'assign').mockImplementation(assign as never);
vi.spyOn(console, 'warn').mockImplementation(() => {});
});

afterEach(() => {
cleanup();
baseEl?.remove();
baseEl = null;
vi.unstubAllEnvs();
vi.restoreAllMocks();
});

interface ServerOptions {
/** Signed in already when the page opens. */
signedInOnArrival?: boolean;
/** `get-invitation` refuses this account (better-auth's recipient check). */
refuseRecipient?: boolean;
}

function createMockClient({ signedInOnArrival = false, refuseRecipient = false }: ServerOptions = {}) {
let signedIn = signedInOnArrival;
let member = false;
let active: typeof ORG | null = null;
const session = () => ({ user: USER, session: { token: 't', createdAt: new Date() } });
const client = {
getSession: vi.fn(async () => (signedIn ? session() : null)),
getConfig: vi.fn().mockResolvedValue({
emailPassword: { enabled: true, disableSignUp: false, requireEmailVerification: false },
features: { audiencePosture: 'invite_only' },
}),
getInvitationPreview: vi.fn().mockResolvedValue({
organizationName: ORG.name,
inviterName: 'Lin',
email: 'z***@example.com',
}),
signUp: vi.fn(async () => {
signedIn = true;
return { user: USER, session: undefined, requiresVerification: false };
}),
getInvitation: vi.fn(async (id: string) => {
if (refuseRecipient) {
throw Object.assign(new Error('You are not the recipient of the invitation'), {
code: 'YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION',
status: 403,
});
}
return { id, organizationId: ORG.id, email: USER.email, role: 'member', status: 'pending' };
}),
acceptInvitation: vi.fn(async () => {
member = true;
}),
listOrganizations: vi.fn(async () => (member ? [ORG] : [])),
getActiveOrganization: vi.fn(async () => active),
getActiveMember: vi.fn().mockResolvedValue(null),
setActiveOrganization: vi.fn(async (id: string) => {
active = id === ORG.id ? ORG : null;
return active;
}),
};
return client as typeof client & AuthClient;
}

function renderRegister(client: AuthClient) {
const search = `?redirect=${encodeURIComponent(ACCEPT_PATH)}`;
window.history.replaceState({}, '', `/_console/register${search}`);
return render(
<AuthProvider authUrl="/api/v1/auth" client={client}>
<MemoryRouter initialEntries={[`/register${search}`]}>
<RegisterPage />
</MemoryRouter>
</AuthProvider>,
);
}

async function signUpOnTheForm() {
const user = userEvent.setup();
await user.type(await screen.findByLabelText('Name'), USER.name);
await user.type(screen.getByLabelText('Email'), USER.email);
await user.type(screen.getByLabelText('Password'), 'hunter2hunter2');
await user.type(screen.getByLabelText('Confirm Password'), 'hunter2hunter2');
await user.click(screen.getByRole('button', { name: 'Create Account' }));
}

/** Where a full-page navigation lands, per the browser's own resolution. */
const lands = (target: string) => new URL(target, document.baseURI).pathname;

describe('console /register — a sign-up from an invitation link joins it (#30125)', () => {
it('accepts the invitation the link names, switches to its organization, and enters the root once', async () => {
const client = createMockClient();
renderRegister(client);
await signUpOnTheForm();

await waitFor(() => expect(assign).toHaveBeenCalled());
expect(client.getInvitation).toHaveBeenCalledWith(INVITATION_ID);
expect(client.acceptInvitation).toHaveBeenCalledTimes(1);
expect(client.acceptInvitation).toHaveBeenCalledWith(INVITATION_ID);
expect(client.setActiveOrganization).toHaveBeenCalledWith(ORG.id);
expect(assign).toHaveBeenCalledTimes(1);
// The root, never the accept page and its "Invitation accepted" step.
expect(lands(assign.mock.calls[0][0] as string)).toBe('/_console/');
});

it('the server refuses this account: accepts nothing and opens the accept page, as before', async () => {
const client = createMockClient({ refuseRecipient: true });
renderRegister(client);
await signUpOnTheForm();

await waitFor(() => expect(assign).toHaveBeenCalled());
expect(client.acceptInvitation).not.toHaveBeenCalled();
expect(assign).toHaveBeenCalledTimes(1);
expect(lands(assign.mock.calls[0][0] as string)).toBe(`/_console${ACCEPT_PATH}`);
});

it('CONTROL: already signed in when the page opens — nothing is accepted, the accept page decides', async () => {
const client = createMockClient({ signedInOnArrival: true });
renderRegister(client);

await waitFor(() => expect(assign).toHaveBeenCalled());
expect(client.getInvitation).not.toHaveBeenCalled();
expect(client.acceptInvitation).not.toHaveBeenCalled();
expect(lands(assign.mock.calls[0][0] as string)).toBe(`/_console${ACCEPT_PATH}`);
});
});
28 changes: 27 additions & 1 deletion ui/packages/app-shell/src/console/auth/RegisterPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,13 @@
* with `SELF_REGISTRATION_CLOSED` re-reads the preview, so an invitation that
* went away meanwhile ends the same way, and a live one names the address it
* was sent to (#27509, `./invitationArrival`).
*
* Registered from an invitation link, the new account accepts THAT invitation
* and enters its organization at the console root, instead of going on to the
* accept page and its "Invitation accepted" step (#30125,
* `./invitationSignUpJoin`); an address the server refuses goes on to the
* accept page, which shows the refusal. A visitor already signed in when the
* page opened still goes to `/` and accepts nothing here.
*/

import { useEffect, useState } from 'react';
Expand All @@ -49,6 +56,8 @@ import { decideSignUpOffer, isInvitationRedirect, needsBootstrapProbe } from './
import { useBootstrapStatus } from './bootstrapStatus.js';
import { ServerUnreachable } from './LoginPage.js';
import { InvitationGoneNotice, invitationArrivalCopy, useInvitationArrival } from './invitationArrival.js';
import { useInvitationSignUpJoin } from './invitationSignUpJoin.js';
import { resolveRootUrl } from '../organizations/resolveHomeUrl.js';

const RouterLink = ({ href, className, children }: AuthLinkComponentProps) => (
<Link to={href} className={className}>{children}</Link>
Expand Down Expand Up @@ -115,6 +124,13 @@ export function RegisterPage() {
// #26473 — who invited this visitor, and to what; `null` keeps the generic
// copy. #27509 — `gone` when the server no longer knows the invitation.
const invitationArrival = useInvitationArrival(redirect);
// #30125 — the sign-up made on this page from an invitation link accepts it.
const invitationJoin = useInvitationSignUpJoin(redirect);
// Entered by a full-page navigation to the root, as the accept page's
// "Continue" does: every data scope re-seats on the joined organization.
useEffect(() => {
if (invitationJoin === 'joined') window.location.assign(resolveRootUrl());
}, [invitationJoin]);

// Sign-up switched off — bounce a signed-out visitor to /login, keeping
// `?redirect=`. A signed-in one is moved on below instead, never to /login.
Expand All @@ -124,6 +140,13 @@ export function RegisterPage() {
navigate(`/login${search}`, { replace: true });
}, [signedOut, signUpOffer, navigate, redirect]);

// #30125 — the invitation sign-up holds while it is accepted and while the
// page leaves for the root; refused, it opens the accept page as before.
if (user && (invitationJoin === 'joining' || invitationJoin === 'joined')) {
return <AuthPageLayout>{null}</AuthPageLayout>;
}
if (user && invitationJoin === 'refused' && redirect) return <Navigate to={redirect} replace />;

// objectui#11714 — signed in: go where a successful sign-up goes, without
// waiting for the config or the probe. `<Navigate>` renders nothing.
if (user) return <Navigate to="/" replace />;
Expand Down Expand Up @@ -243,7 +266,10 @@ export function RegisterPage() {
return (
<AuthPageLayout>
<RegisterForm
onSuccess={() => navigate('/')}
// An invitation sign-up moves on from the join above (#30125).
onSuccess={() => {
if (!invitationRedirect) navigate('/');
}}
onVerificationRequired={(email) => setPendingEmail(email)}
loginUrl={loginUrl}
// #25886 — an invitee is told to register the invited address: the
Expand Down
Loading
Loading