From 094b5e45ca9fa1c5431083847e0cf0b5cb7ddbd4 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 04:09:45 +0000 Subject: [PATCH 1/5] fix(plugin-auth,app-shell)!: while mail is live, accepting an invitation needs a verified address MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit While the email service is live, POST /organization/accept-invitation refuses a session whose address is unverified with better-auth's own 403 EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION and writes nothing. The check runs on the vendor's beforeAcceptInvitation hook, after its recipient and expiry checks, on the session user the vendor resolved; it asks isEmailDeliveryLive per request. Without live mail nothing changes. get, list and reject are unchanged; the one-step door verifies before it accepts. The Console's accept page sends that refusal to /verify-email-prompt for the account's address. Clause-②: no (narrowing) Metadata-protocol: none Skills-docs: none — no page under skills/ teaches accepting an invitation; the rule is stated in the changeset and the self-hosting docs. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01ADHkmSYe73LCZ6WxGFvcko --- .../34272-accept-invitation-verified-email.md | 23 ++ content/docs/deployment/self-hosting.mdx | 14 + .../src/auth-manager-organization-plugin.ts | 30 +- .../src/auth-manager-plugin-list.ts | 2 + .../plugins/plugin-auth/src/auth-manager.ts | 1 + .../invitation-accept-verified-email.test.ts | 355 ++++++++++++++++++ .../src/invitation-accept-verified-email.ts | 106 ++++++ ...ceptInvitationVerifiedEmail-34272.test.tsx | 160 ++++++++ .../manage/AcceptInvitationPage.tsx | 18 +- .../console/organizations/orgErrorMessage.ts | 18 + 10 files changed, 721 insertions(+), 6 deletions(-) create mode 100644 .changeset/34272-accept-invitation-verified-email.md create mode 100644 packages/plugins/plugin-auth/src/invitation-accept-verified-email.test.ts create mode 100644 packages/plugins/plugin-auth/src/invitation-accept-verified-email.ts create mode 100644 ui/packages/app-shell/src/console/organizations/__tests__/acceptInvitationVerifiedEmail-34272.test.tsx diff --git a/.changeset/34272-accept-invitation-verified-email.md b/.changeset/34272-accept-invitation-verified-email.md new file mode 100644 index 00000000000..022221ae6fd --- /dev/null +++ b/.changeset/34272-accept-invitation-verified-email.md @@ -0,0 +1,23 @@ +--- +'@objectstack/plugin-auth': minor +'@object-ui/app-shell': patch +--- + +fix(plugin-auth,app-shell)!: while mail is live, accepting an invitation needs a verified address + +Clause-②: no (narrowing) +Metadata-protocol: none +Skills-docs: none — `git grep` of `skills/` finds no page that teaches accepting an invitation or `/organization/accept-invitation`; the rule is stated here and in the self-hosting docs. + + + +**BREAKING** for a person who accepts an invitation from an account whose address was never verified, on a deployment whose mail transport is live. An unverified address does not prove the person holds the invited mailbox, so on a deployment that can mail, anyone who registered the invited address first could take the invitation's membership. + +**What changes.** + +- `POST /api/v1/auth/organization/accept-invitation` (`@objectstack/plugin-auth`), from a session whose address is unverified, while the email service answers `isConfigured() === true`, now answers `403 EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION` (better-auth's own code and sentence, the ones its accept route answers when its option is on) and writes nothing; the invitation stays pending. It used to answer `200` and write the membership. The vendor's not-found, expiry and recipient refusals still come first, so a session that is not the invitee learns nothing new. The check runs on the vendor's `beforeAcceptInvitation` hook, on the session user the vendor itself resolved (cookie or bearer token alike), and asks whether mail is live on every request. +- The Console's accept page (`@object-ui/app-shell`) answers that refusal with the verification-mail screen (`/verify-email-prompt`) for the account's address, whose link returns to the accept page, instead of a toast. + +**Who moves.** A person in that state verifies their address (the Console's accept page takes them to the screen that sends the mail), then accepts; an API client that accepts for its user does the same, through `POST /api/v1/auth/send-verification-email`. An invitee who opens the invitation mail's own link is not affected: that link verifies the address as it accepts. + +**Unchanged.** Every deployment without a live mail transport (no email service, or the log transport), where nothing could verify an address, so acceptance stays open to an unverified address; `get-invitation`, `list-user-invitations` and `reject-invitation`, which write no membership; the one-step door `POST /api/v1/auth/organization/accept-invitation-one-step`; and a verified session everywhere. better-auth's `requireEmailVerificationOnInvitation` stays declared `false`: it governs reading and declining too, and is read once at boot. diff --git a/content/docs/deployment/self-hosting.mdx b/content/docs/deployment/self-hosting.mdx index 305af41567a..4e57a1f59a3 100644 --- a/content/docs/deployment/self-hosting.mdx +++ b/content/docs/deployment/self-hosting.mdx @@ -760,6 +760,20 @@ reaches the invitee in the invitation mail; on a deployment with no mail transport, an administrator hands it over with the invitation's **Copy Invite Link** action. The first account of a new deployment needs no invitation. +**While the mail transport is live, accepting an invitation needs a verified +address.** `POST /api/v1/auth/organization/accept-invitation` from a session +whose address was never verified answers `403 +EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION` and +writes nothing: an unverified address does not prove the person holds the +invited mailbox. The Console's accept page sends the person to the +verification-mail screen for their address, and the link in that mail brings +them back to accept. Opening the invitation's link from the invitation mail +itself needs no separate step, because that link verifies the address as it +accepts. Reading, listing and declining an invitation are not affected. On a +deployment with no live transport (none configured, or the log transport) +nothing can verify an address, so acceptance stays open to an unverified +address, as before. + **What decides it on `open` and `email_domain`.** A sign-up for an address that already has an account gets the same answer as a successful new sign-up, and writes nothing, when all three of these hold: diff --git a/packages/plugins/plugin-auth/src/auth-manager-organization-plugin.ts b/packages/plugins/plugin-auth/src/auth-manager-organization-plugin.ts index 9a51cffffee..33b3e7d025f 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-organization-plugin.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-organization-plugin.ts @@ -81,6 +81,7 @@ import { import { buildOrganizationPluginSchema } from './auth-schema-config.js'; import { CLOUD_MANAGED_REFUSAL_CODE, CLOUD_MANAGED_REFUSAL_MESSAGES } from './cloud-managed.js'; import { resolveInvitationLimitOption } from './invitation-limit.js'; +import { refuseUnverifiedAcceptWhileMailIsLive } from './invitation-accept-verified-email.js'; import { invitationAcceptPath } from './invitation-link-action.js'; import { invitationRoleCapFailure, isPlainMemberInvitation } from './invitation-role-cap.js'; import { blankInvitationRoleRefusal } from './invite-role-not-found-code.js'; @@ -108,6 +109,7 @@ export interface OrganizationPluginHost { getConsolePageUrl: AuthManager['getConsolePageUrl']; getDataEngine: AuthManager['getDataEngine']; getEmailService: AuthManager['getEmailService']; + isEmailDeliveryLive: AuthManager['isEmailDeliveryLive']; multiOrgPostureEffective: AuthManager['multiOrgPostureEffective']; orgRolesMap: AuthManager['orgRolesMap']; resolveMembershipRole: AuthManager['resolveMembershipRole']; @@ -192,11 +194,15 @@ export async function buildOrganizationPlugin(this: OrganizationPluginHost) { // portal exposes a Teams page; without this flag those endpoints // 404 and the section silently breaks. teams: { enabled: true }, - // Without a mailer wired in framework, requiring email verification - // before accepting invitations dead-ends every invite flow with - // FORBIDDEN EMAIL_VERIFICATION_REQUIRED…. Default-off here keeps - // the built-in /accept-invitation route usable for pilots; operators - // who wire a real mailer can re-enable downstream. + // The vendor's switch governs accept, reject and get-invitation + // together, and is read once, at boot. Declared off here: on a + // deployment with no live mail nothing can ever verify an address, so + // turning it on would dead-end every invite flow with FORBIDDEN + // EMAIL_VERIFICATION_REQUIRED…. [#34272] Where mail IS live, the + // accept door alone still refuses an unverified session, asked per + // request by `beforeAcceptInvitation` below + // (`invitation-accept-verified-email.ts`); reading and declining an + // invitation stay open, as does every door while mail is not live. requireEmailVerificationOnInvitation: false, // Cap how many orgs a user can CREATE (OS_ORG_LIMIT). Counts only orgs // the user OWNS (role=owner) — never orgs they were merely invited into — @@ -425,6 +431,20 @@ export async function buildOrganizationPlugin(this: OrganizationPluginHost) { }); } }, + // [#34272] While mail is live, an unverified session may not accept: + // the address it holds was never proven to be the invitee's mailbox. + // Fired by the vendor inside the accept endpoint, after its recipient + // and expiry checks and before anything is written, with the + // `session.user` its own verification check reads. A no-op while mail + // is not live. `invitation-accept-verified-email.ts` states the rule. + beforeAcceptInvitation: async ({ user }: any) => { + await refuseUnverifiedAcceptWhileMailIsLive(user, { + isEmailDeliveryLive: () => this.isEmailDeliveryLive(), + verificationRequired: + organizationPlugin?.$ERROR_CODES + ?.EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION, + }); + }, // [ADR-0105 D8] Accept-time application + host seam. The placement // the issuance gate approved lands WITH the better-auth membership, // so the invitee arrives already in the right unit and role. The diff --git a/packages/plugins/plugin-auth/src/auth-manager-plugin-list.ts b/packages/plugins/plugin-auth/src/auth-manager-plugin-list.ts index d85256f8bb9..8988d6c2c1e 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-plugin-list.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-plugin-list.ts @@ -123,6 +123,7 @@ export interface PluginListHost { getEmailService: AuthManager['getEmailService']; getMcpResourceUrl: AuthManager['getMcpResourceUrl']; getApi: AuthManager['getApi']; + isEmailDeliveryLive: AuthManager['isEmailDeliveryLive']; isPlatformAdminUserId: AuthManager['isPlatformAdminUserId']; isSsoOnlyMode: AuthManager['isSsoOnlyMode']; jwtSigningFailureReported: AuthManager['jwtSigningFailureReported']; @@ -293,6 +294,7 @@ export async function buildPluginList(this: PluginListHost): Promise { getConsolePageUrl: (...a) => this.getConsolePageUrl(...a), getDataEngine: (...a) => this.getDataEngine(...a), getEmailService: (...a) => this.getEmailService(...a), + isEmailDeliveryLive: (...a) => this.isEmailDeliveryLive(...a), multiOrgPostureEffective: (...a) => this.multiOrgPostureEffective(...a), get orgRolesMap() { return readOrgRolesMap(); }, set orgRolesMap(v) { writeOrgRolesMap(v); }, diff --git a/packages/plugins/plugin-auth/src/auth-manager.ts b/packages/plugins/plugin-auth/src/auth-manager.ts index bfe06d9c1f6..aed38c019a4 100644 --- a/packages/plugins/plugin-auth/src/auth-manager.ts +++ b/packages/plugins/plugin-auth/src/auth-manager.ts @@ -2444,6 +2444,7 @@ export class AuthManager { getEmailService: (...a) => this.getEmailService(...a), getMcpResourceUrl: (...a) => this.getMcpResourceUrl(...a), getApi: (...a) => this.getApi(...a), + isEmailDeliveryLive: (...a) => this.isEmailDeliveryLive(...a), isPlatformAdminUserId: (...a) => this.isPlatformAdminUserId(...a), isSsoOnlyMode: (...a) => this.isSsoOnlyMode(...a), get jwtSigningFailureReported() { return readJwtSigningFailureReported(); }, diff --git a/packages/plugins/plugin-auth/src/invitation-accept-verified-email.test.ts b/packages/plugins/plugin-auth/src/invitation-accept-verified-email.test.ts new file mode 100644 index 00000000000..a87792a38ce --- /dev/null +++ b/packages/plugins/plugin-auth/src/invitation-accept-verified-email.test.ts @@ -0,0 +1,355 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// [#34272] `POST /organization/accept-invitation` refuses an UNVERIFIED +// session while this deployment delivers mail, and only then. +// +// These run the REAL better-auth pipeline through a REAL `AuthManager` (the +// organization plugin, the audience-gate invitation carve-out, the membership +// reconciler, the ObjectQL adapter), the same shape as +// `list-user-invitations-verification.test.ts`. "Mail is live" is the one +// reader the rule asks, `IEmailService.isConfigured()`, swapped between +// requests: sign-ups run with mail off so every fixture account starts +// UNVERIFIED (asserted), then each leg sets the deployment it measures. + +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { AuthManager } from './auth-manager'; +import { inviteForAudienceGate } from './audience-gate-test-support'; +import { createMemoryEngine } from './impersonation-bearer-rotation.test'; +import { + ACCEPT_INVITATION_PATH, + EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_INVITATION, + refuseUnverifiedAcceptWhileMailIsLive, +} from './invitation-accept-verified-email'; +import { ACCEPT_INVITATION_ONE_STEP_PATH } from './invitation-mailbox-proof'; +import { LIST_USER_INVITATIONS_PATH } from './list-user-invitations-verification'; + +const SECRET = 'test-secret-at-least-32-chars-long!!'; +const BASE = 'http://localhost:3000'; +const DEFAULT_ORG = 'org_default'; +const PARTNER_ORG = 'org_partner'; +const PASSWORD = 'S3cure!Passw0rd-34272'; +const REFUSAL_CODE = 'EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION'; + +type MemoryEngine = ReturnType; + +const singleOrgTenancy = () => + ({ + posture: 'single', + requestedPosture: 'single', + isolationActive: false, + requested: false, + degraded: false, + defaultOrgId: async () => DEFAULT_ORG, + }) as any; + +const cookieFrom = (response: Response): string => + (response.headers.getSetCookie?.() ?? [response.headers.get('set-cookie') ?? '']) + .map((c) => c.split(';')[0]) + .filter(Boolean) + .join('; '); + +const request = ( + manager: AuthManager, + method: 'GET' | 'POST', + path: string, + { body, cookie, bearer }: { body?: unknown; cookie?: string; bearer?: string } = {}, +) => + manager.handleRequest( + new Request(`${BASE}/api/v1/auth${path}`, { + method, + headers: { + ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}), + ...(cookie ? { cookie } : {}), + ...(bearer ? { authorization: `Bearer ${bearer}` } : {}), + }, + ...(body !== undefined ? { body: JSON.stringify(body) } : {}), + }), + ); + +/** + * The email service: `mode` is what `isConfigured()` answers, read on every + * call; `'absent'` means no service at all. Every send is recorded. + */ +const mailer = () => { + const sent: any[] = []; + const state: { mode: 'live' | 'log' } = { mode: 'log' }; + const service = { + async send() { return { id: 'e', status: 'sent' }; }, + async sendTemplate(input: any) { + sent.push(input); + return { id: `e${sent.length}`, status: 'sent' }; + }, + isConfigured: () => state.mode === 'live', + }; + return { sent, state, service }; +}; + +const userRow = (engine: MemoryEngine, email: string) => + (engine.tables.get('sys_user') ?? []).find((u: any) => u.email === email); + +const membersOf = (engine: MemoryEngine, organizationId: string, userId: string) => + (engine.tables.get('sys_member') ?? []).filter( + (m: any) => m.organization_id === organizationId && m.user_id === userId, + ); + +const invitationRow = (engine: MemoryEngine, id: string) => + (engine.tables.get('sys_invitation') ?? []).find((r: any) => r.id === id); + +/** + * An owner of the partner organization, and invitations to b@ and c@ issued + * BEFORE they sign up (`invite-member` refuses an address that is already a + * member). Every account is created with mail NOT live, so unverified. + */ +const boot = async () => { + const engine = createMemoryEngine(); + engine.tables.set('sys_organization', [ + { id: DEFAULT_ORG, name: 'Default', slug: 'default' }, + { id: PARTNER_ORG, name: 'Partner', slug: 'partner' }, + ]); + const manager = new AuthManager({ + secret: SECRET, + baseUrl: BASE, + dataEngine: engine as any, + membershipPolicy: 'auto', + getTenancy: () => singleOrgTenancy(), + }); + const mail = mailer(); + + const signUp = async (email: string) => { + const invitationId = await inviteForAudienceGate(engine, email); + const res = await request(manager, 'POST', '/sign-up/email', { + body: { email, password: PASSWORD, name: email, invitationId }, + }); + expect(res.status, await res.clone().text()).toBe(200); + const user = userRow(engine, email); + expect(user, `sign-up did not create ${email}`).toBeDefined(); + expect(Boolean(user!.email_verified), `${email} should start unverified`).toBe(false); + return { + cookie: cookieFrom(res), + bearer: res.headers.get('set-auth-token') ?? undefined, + userId: String(user!.id), + }; + }; + + const owner = await signUp('owner@example.com'); + await engine.insert('sys_member', { + id: 'mem_owner_partner', + organization_id: PARTNER_ORG, + user_id: owner.userId, + role: 'owner', + created_at: new Date(), + }); + const invite = async (email: string) => { + const res = await request(manager, 'POST', '/organization/invite-member', { + body: { email, role: 'member', organizationId: PARTNER_ORG }, + cookie: owner.cookie, + }); + expect(res.status, await res.clone().text()).toBe(200); + return (await res.json()) as { id: string }; + }; + const bInvitation = await invite('b@example.com'); + const cInvitation = await invite('c@example.com'); + const b = await signUp('b@example.com'); + const c = await signUp('c@example.com'); + + const accept = (invitationId: string, as: { cookie?: string; bearer?: string }) => + request(manager, 'POST', ACCEPT_INVITATION_PATH, { body: { invitationId }, ...as }); + + return { engine, manager, mail, owner, b, c, bInvitation, cInvitation, invite, accept }; +}; + +/** The refusal's status and body, read once. */ +const answerOf = async (res: Response) => { + const text = await res.text(); + let body: any; + try { body = JSON.parse(text); } catch { body = text; } + return { status: res.status, body, text }; +}; + +beforeEach(() => { + vi.spyOn(console, 'info').mockImplementation(() => {}); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + vi.spyOn(console, 'log').mockImplementation(() => {}); + vi.spyOn(console, 'error').mockImplementation(() => {}); +}); +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe('#34272 — the refusal is the vendor’s own', () => { + it('the local fallback equals better-auth’s own $ERROR_CODES entry (a vendor rename turns this red)', async () => { + const { organization } = await import('better-auth/plugins/organization'); + const plugin: any = organization({}); + const vendor = plugin.$ERROR_CODES?.[REFUSAL_CODE]; + expect({ code: vendor?.code, message: vendor?.message }).toEqual(EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_INVITATION); + }); + + it('PREMISE (measured): the vendor’s own accept route still lets an unverified session through with the option declared false', async () => { + // The vendor gate this module stands beside is the declared option; with + // it `false` the vendor never asks. If an upstream release starts asking + // on its own, this leg and the no-mail legs below disagree and say so. + const { b, bInvitation, accept, engine } = await boot(); + const res = await answerOf(await accept(bInvitation.id, { cookie: b.cookie })); + expect(res.status, res.text).toBe(200); + expect(membersOf(engine, PARTNER_ORG, b.userId)).toHaveLength(1); + }); +}); + +describe('#34272 — while mail is live, an unverified session may not accept', () => { + it('the reported hole: an unverified invitee is refused 403 with the vendor’s code, and nothing is written', async () => { + const { engine, manager, mail, b, bInvitation, accept } = await boot(); + manager.setEmailService(mail.service as never); + mail.state.mode = 'live'; + + const res = await answerOf(await accept(bInvitation.id, { cookie: b.cookie })); + expect(res.status, res.text).toBe(403); + expect(res.body).toMatchObject(EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_INVITATION); + expect(membersOf(engine, PARTNER_ORG, b.userId)).toHaveLength(0); + expect(invitationRow(engine, bInvitation.id)?.status).toBe('pending'); + }); + + it('a bearer-token session is refused alike', async () => { + const { engine, manager, mail, b, bInvitation, accept } = await boot(); + expect(b.bearer, 'sign-up handed out no bearer token').toBeTruthy(); + manager.setEmailService(mail.service as never); + mail.state.mode = 'live'; + + const res = await answerOf(await accept(bInvitation.id, { bearer: b.bearer })); + expect(res.status, res.text).toBe(403); + expect(res.body?.code).toBe(REFUSAL_CODE); + expect(membersOf(engine, PARTNER_ORG, b.userId)).toHaveLength(0); + }); + + it('once the address is verified, the same invitation is accepted', async () => { + const { engine, manager, mail, b, bInvitation, accept } = await boot(); + manager.setEmailService(mail.service as never); + mail.state.mode = 'live'; + expect((await accept(bInvitation.id, { cookie: b.cookie })).status).toBe(403); + + userRow(engine, 'b@example.com')!.email_verified = true; + // A fresh sign-in, as after following the verification link. + const signIn = await request(manager, 'POST', '/sign-in/email', { + body: { email: 'b@example.com', password: PASSWORD }, + }); + expect(signIn.status, await signIn.clone().text()).toBe(200); + + const res = await answerOf(await accept(bInvitation.id, { cookie: cookieFrom(signIn) })); + expect(res.status, res.text).toBe(200); + expect(membersOf(engine, PARTNER_ORG, b.userId)).toHaveLength(1); + expect(invitationRow(engine, bInvitation.id)?.status).toBe('accepted'); + }); + + it('ORDER PIN: a session that is not the recipient still gets the vendor’s recipient refusal, not this one', async () => { + const { manager, mail, c, bInvitation, accept } = await boot(); + manager.setEmailService(mail.service as never); + mail.state.mode = 'live'; + + const res = await answerOf(await accept(bInvitation.id, { cookie: c.cookie })); + expect(res.status, res.text).toBe(403); + expect(res.body?.code).toBe('YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION'); + }); + + it('ONLY ACCEPT: the same unverified invitee still reads, lists and declines', async () => { + const { engine, manager, mail, b, bInvitation } = await boot(); + manager.setEmailService(mail.service as never); + mail.state.mode = 'live'; + + const got = await request(manager, 'GET', `/organization/get-invitation?id=${bInvitation.id}`, { cookie: b.cookie }); + expect(got.status, await got.clone().text()).toBe(200); + + const listed = await request(manager, 'GET', LIST_USER_INVITATIONS_PATH, { cookie: b.cookie }); + expect(listed.status, await listed.clone().text()).toBe(200); + expect(((await listed.json()) as any[]).map((i) => i.id)).toContain(bInvitation.id); + + const rejected = await request(manager, 'POST', '/organization/reject-invitation', { + body: { invitationId: bInvitation.id }, + cookie: b.cookie, + }); + expect(rejected.status, await rejected.clone().text()).toBe(200); + expect(invitationRow(engine, bInvitation.id)?.status).toBe('rejected'); + }); + + it('the one-step door still accepts with the mail’s proof: it verifies the address before it accepts', async () => { + const { engine, manager, mail, invite } = await boot(); + manager.setEmailService(mail.service as never); + mail.state.mode = 'live'; + + const invitation = await invite('newcomer@example.com'); + const sentMail = [...mail.sent].reverse().find( + (m) => m.template === 'auth.invitation' && m.to === 'newcomer@example.com', + ); + expect(sentMail, 'no invitation mail').toBeDefined(); + const match = /#proof=([^&]+)$/.exec(String(sentMail.deliverOnlyData?.acceptUrl ?? '')); + expect(match, 'the mail carries no proof').not.toBeNull(); + + const res = await answerOf( + await request(manager, 'POST', ACCEPT_INVITATION_ONE_STEP_PATH, { + body: { invitationId: invitation.id, proof: decodeURIComponent(match![1]!), name: 'Newcomer', password: PASSWORD }, + }), + ); + expect(res.status, res.text).toBe(200); + expect(res.body).toEqual({ success: true, data: { outcome: 'accepted', organizationId: PARTNER_ORG } }); + const user = userRow(engine, 'newcomer@example.com'); + expect(user?.email_verified).toBeTruthy(); + expect(membersOf(engine, PARTNER_ORG, String(user!.id))).toHaveLength(1); + }); +}); + +describe('#34272 — while mail is not live, accept is unchanged', () => { + it('no email service at all: the unverified invitee accepts', async () => { + const { engine, b, bInvitation, accept } = await boot(); + const res = await answerOf(await accept(bInvitation.id, { cookie: b.cookie })); + expect(res.status, res.text).toBe(200); + expect(membersOf(engine, PARTNER_ORG, b.userId)).toHaveLength(1); + }); + + it('a log transport (isConfigured() false): the unverified invitee accepts', async () => { + const { engine, manager, mail, b, bInvitation, accept } = await boot(); + manager.setEmailService(mail.service as never); + mail.state.mode = 'log'; + const res = await answerOf(await accept(bInvitation.id, { cookie: b.cookie })); + expect(res.status, res.text).toBe(200); + expect(membersOf(engine, PARTNER_ORG, b.userId)).toHaveLength(1); + }); + + it('read per request: mail going live between two requests closes the door for the next one', async () => { + const { engine, manager, mail, b, c, bInvitation, cInvitation, accept } = await boot(); + manager.setEmailService(mail.service as never); + mail.state.mode = 'live'; + expect((await accept(bInvitation.id, { cookie: b.cookie })).status).toBe(403); + mail.state.mode = 'log'; + expect((await accept(bInvitation.id, { cookie: b.cookie })).status).toBe(200); + mail.state.mode = 'live'; + expect((await accept(cInvitation.id, { cookie: c.cookie })).status).toBe(403); + expect(membersOf(engine, PARTNER_ORG, c.userId)).toHaveLength(0); + }); +}); + +describe('#34272 — refuseUnverifiedAcceptWhileMailIsLive', () => { + it('a verified user passes without asking whether mail is live', async () => { + const isEmailDeliveryLive = vi.fn(() => true); + await expect(refuseUnverifiedAcceptWhileMailIsLive({ emailVerified: true }, { isEmailDeliveryLive })).resolves.toBeUndefined(); + expect(isEmailDeliveryLive).not.toHaveBeenCalled(); + }); + + it('an unverified user passes while mail is not live', async () => { + await expect( + refuseUnverifiedAcceptWhileMailIsLive({ emailVerified: false }, { isEmailDeliveryLive: () => false }), + ).resolves.toBeUndefined(); + }); + + it('an unverified (or unknown) user is refused while mail is live, with the entry the caller hands in', async () => { + for (const user of [{ emailVerified: false }, {}, null, undefined]) { + await expect( + refuseUnverifiedAcceptWhileMailIsLive(user, { isEmailDeliveryLive: () => true }), + ).rejects.toMatchObject({ statusCode: 403, body: { code: REFUSAL_CODE } }); + } + const vendorEntry = { code: REFUSAL_CODE, message: 'vendor sentence' }; + await expect( + refuseUnverifiedAcceptWhileMailIsLive( + { emailVerified: false }, + { isEmailDeliveryLive: () => true, verificationRequired: vendorEntry }, + ), + ).rejects.toMatchObject({ body: { message: 'vendor sentence' } }); + }); +}); diff --git a/packages/plugins/plugin-auth/src/invitation-accept-verified-email.ts b/packages/plugins/plugin-auth/src/invitation-accept-verified-email.ts new file mode 100644 index 00000000000..56eb3a1bbe2 --- /dev/null +++ b/packages/plugins/plugin-auth/src/invitation-accept-verified-email.ts @@ -0,0 +1,106 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#34272] `POST /organization/accept-invitation` — while this deployment + * delivers mail, a session whose address is NOT verified may not accept an + * invitation. + * + * ## The rule + * + * The accept door writes a membership for the session's user on the strength + * of one fact: the session's address equals the invited one. An address that + * was never verified proves nothing about the mailbox, so on a deployment that + * can mail, anyone who registered the invited address first (an account the + * real owner never confirmed) could take the seat. + * + * - **While email delivery is live** (`AuthManager.isEmailDeliveryLive`, the + * one reader of `IEmailService.isConfigured()`, read at call time): an + * unverified session is refused, `403 + * EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION`. + * Nothing is written. The person verifies the address (the mail can reach + * them) and accepts again. + * - **While it is not live** the door is unchanged: an unverified session + * accepts, as before. Nothing on such a deployment can ever verify an + * address, so refusing there would dead-end every invitation — the reason + * `requireEmailVerificationOnInvitation` is declared `false` in + * `auth-manager-organization-plugin.ts`, which still holds there. + * + * Unchanged: `get-invitation`, `reject-invitation` and + * `list-user-invitations` (they write no membership: reading or declining an + * invitation addressed to you takes nothing), the one-step door + * (`invitation-mailbox-proof.ts`, whose proof mode verifies the address + * before it accepts and whose session mode already answers `verify_email` for + * an unverified session), and a verified session everywhere. + * + * ## Why this seam: the vendor's own `beforeAcceptInvitation` + * + * The rule is asked from `organizationHooks.beforeAcceptInvitation`, which + * better-auth 1.7.12 calls inside the accept endpoint + * (`dist/plugins/organization/routes/crud-invites.mjs`), after its own + * not-found / expiry / status, recipient and membership-limit checks and + * before the invitation row or the membership is written. + * + * - **The user is the vendor's.** The hook receives `session.user` as the + * endpoint's session middleware resolved it, cookie and bearer token alike + * — the very object the vendor's own verification check reads + * (`!session.user.emailVerified`). No second session read, no user read. + * A global before-hook could not say the same: it runs before `bearer()` + * turns a bearer credential into a session. + * - **Nothing is retyped.** The vendor's recipient and expiry checks run + * first, so a session that is not the invitee still gets the vendor's + * `YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION`, and an unknown id its + * `INVITATION_NOT_FOUND`; this refusal tells only the invitee, about their + * own address. + * - **Only accept.** The vendor's option governs accept, reject and + * get-invitation together; turning it on would refuse reading and + * declining too. This hook fires on accept alone. + * + * ## Refusal envelope — the vendor's, on purpose + * + * better-auth's flat `{ message, code }` with the vendor's OWN code, the one + * its accept route throws when the option is on, so a client that already + * handles the vendor's refusal handles this one. Read off the plugin's + * `$ERROR_CODES` where the caller has it; the local restatement below is the + * fallback, and `invitation-accept-verified-email.test.ts` pins it equal to + * the vendor's. No new public error code is minted, so nothing here reaches + * the spec error-code ledger. + */ + +/** The vendor's path for accepting an invitation by id. */ +export const ACCEPT_INVITATION_PATH = '/organization/accept-invitation'; + +/** + * better-auth's + * `ORGANIZATION_ERROR_CODES.EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION`, + * restated locally as the fallback for a plugin object carrying no + * `$ERROR_CODES` (the vendor does not export the constant from a public entry). + */ +export const EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_INVITATION = { + code: 'EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION', + message: 'Email verification required before accepting or rejecting invitation', +} as const; + +/** + * The accept door's half of the rule: refuse an unverified `user` while email + * delivery is live. A no-op for a verified user and while delivery is not + * live. The verified test is the vendor's own (`!user.emailVerified`), on the + * user the vendor's endpoint resolved. + * + * `verificationRequired` is the plugin's own `$ERROR_CODES` entry when the + * caller has it. + */ +export async function refuseUnverifiedAcceptWhileMailIsLive( + user: { emailVerified?: unknown } | null | undefined, + deps: { + isEmailDeliveryLive: () => boolean; + verificationRequired?: { code: string; message: string }; + }, +): Promise { + if (user?.emailVerified) return; + if (!deps.isEmailDeliveryLive()) return; + const { APIError } = await import('better-auth/api'); + throw APIError.from( + 'FORBIDDEN', + deps.verificationRequired ?? EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_INVITATION, + ); +} diff --git a/ui/packages/app-shell/src/console/organizations/__tests__/acceptInvitationVerifiedEmail-34272.test.tsx b/ui/packages/app-shell/src/console/organizations/__tests__/acceptInvitationVerifiedEmail-34272.test.tsx new file mode 100644 index 00000000000..503021e5a12 --- /dev/null +++ b/ui/packages/app-shell/src/console/organizations/__tests__/acceptInvitationVerifiedEmail-34272.test.tsx @@ -0,0 +1,160 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#34272 — while the deployment delivers mail, the server refuses an + * accept from a session whose address is not verified, with better-auth's own + * `403 EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION`. + * The page answers that refusal with the verification-mail screen for this + * account's address, whose link returns here, instead of a toast. + * + * The auth client is the REAL `createAuthClient` over a stubbed `fetch` that + * answers with the server's body, as `invitationVendorRefusals-33650.test.tsx` + * does: the code must survive the client's own error mapping to be routed. + */ + +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'; + +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', +}; + +/** The server's refusal, verbatim (better-auth `ORGANIZATION_ERROR_CODES`). */ +const NEEDS_VERIFIED_EMAIL: Answer = { + status: 403, + body: { + code: 'EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION', + message: 'Email verification required before accepting or rejecting invitation', + }, +}; + +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 = { + user: { id: 'u-1', email: 'zhang.wei@example.com', name: 'Zhang Wei' }, + isAuthenticated: true, + isLoading: false, + getInvitation: (id: string) => client.getInvitation(id), + acceptInvitation: (id: string) => client.acceptInvitation(id), + rejectInvitation: (id: string) => client.rejectInvitation(id), + switchOrganization: vi.fn(async () => undefined), +}; + +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) } })); + +const navigate = vi.fn(); +vi.mock('react-router-dom', async (importActual) => { + const location = { pathname: '/accept-invitation/inv-1', search: '' }; + const params = { invitationId: 'inv-1' }; + return { + ...(await importActual()), + useNavigate: () => navigate, + useLocation: () => location, + useParams: () => params, + }; +}); + +import { AcceptInvitationPage } from '../manage/AcceptInvitationPage'; + +const en = builtInLocales.en as any; + +const renderPage = () => + render( + + + , + ); + +beforeEach(() => { + answers.clear(); + fetchFn.mockClear(); + toastError.mockClear(); + navigate.mockClear(); + auth.switchOrganization.mockClear(); +}); + +afterEach(() => cleanup()); + +describe('#34272 — an accept refused for an unverified address goes to the verification mail', () => { + it('hands over to /verify-email-prompt for this account’s address, returning here, with no toast', async () => { + answers.set('/organization/get-invitation', { status: 200, body: PENDING }); + answers.set('/organization/accept-invitation', NEEDS_VERIFIED_EMAIL); + renderPage(); + + await screen.findByTestId('accept-invitation-role'); + fireEvent.click(screen.getByText(en.organization.accept.accept)); + + await waitFor(() => expect(navigate).toHaveBeenCalled()); + const target = String(navigate.mock.calls.at(-1)?.[0]); + const [path, query] = target.split('?'); + expect(path).toBe('/verify-email-prompt'); + const sp = new URLSearchParams(query); + expect(sp.get('email')).toBe('zhang.wei@example.com'); + expect(sp.get('redirect')).toBe('/accept-invitation/inv-1'); + expect(toastError).not.toHaveBeenCalled(); + expect(auth.switchOrganization).not.toHaveBeenCalled(); + // The refusal really came over the wire from the accept route. + expect( + fetchFn.mock.calls.some(([u]) => String(u instanceof Request ? u.url : u).includes('/organization/accept-invitation')), + ).toBe(true); + }); + + it('CONTROL: another refusal of the same route still toasts and stays on the page', async () => { + answers.set('/organization/get-invitation', { status: 200, body: PENDING }); + answers.set('/organization/accept-invitation', { + status: 403, + body: { + code: 'YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION', + message: 'You are not the recipient of the invitation', + }, + }); + renderPage(); + + await screen.findByTestId('accept-invitation-role'); + fireEvent.click(screen.getByText(en.organization.accept.accept)); + + await waitFor(() => expect(toastError).toHaveBeenCalled()); + expect(toastError).toHaveBeenLastCalledWith(en.organization.errors.notTheRecipient); + expect(navigate.mock.calls.some(([to]) => String(to).startsWith('/verify-email-prompt'))).toBe(false); + }); +}); 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 29a467ab98c..a1d0ae319d0 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,11 @@ 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 { resolveInvitationLookupMessage, resolveOrgErrorMessage } from '../orgErrorMessage.js'; +import { + isAcceptNeedsVerifiedEmail, + resolveInvitationLookupMessage, + resolveOrgErrorMessage, +} from '../orgErrorMessage.js'; import { resolveRootUrl } from '../resolveHomeUrl.js'; type InvitationWithOrg = AuthInvitation & { @@ -90,6 +94,7 @@ export function AcceptInvitationPage() { const location = useLocation(); const { invitationId } = useParams<{ invitationId: string }>(); const { + user, isAuthenticated, isLoading: isAuthLoading, getInvitation, @@ -220,6 +225,17 @@ export function AcceptInvitationPage() { await switchOrganization(invitation.organizationId).catch(() => null); setJoined(true); } catch (err) { + // objectstack#34272 — while the deployment delivers mail, an address that + // was never verified may not accept. The next step is to verify it, so + // the page hands over to the verification-mail screen for this account's + // address, whose link brings the person back here to accept. + if (isAcceptNeedsVerifiedEmail(err)) { + const sp = new URLSearchParams(); + if (user?.email) sp.set('email', user.email); + sp.set('redirect', location.pathname + location.search); + navigate(`/verify-email-prompt?${sp.toString()}`); + return; + } // objectui#4474 — the card's site 5: a wrong recipient produced better-auth's // English sentence under the translated title. Mapped by `code` now. toast.error( diff --git a/ui/packages/app-shell/src/console/organizations/orgErrorMessage.ts b/ui/packages/app-shell/src/console/organizations/orgErrorMessage.ts index ec5a7e26a09..cc660f4cd65 100644 --- a/ui/packages/app-shell/src/console/organizations/orgErrorMessage.ts +++ b/ui/packages/app-shell/src/console/organizations/orgErrorMessage.ts @@ -177,6 +177,24 @@ function errorCode(err: unknown): string | undefined { return typeof code === 'string' && code ? code : undefined; } +/** + * better-auth's code for an accept refused because the session's address is + * not verified. objectstack answers it while the deployment delivers mail + * (objectstack#34272, plugin-auth `invitation-accept-verified-email.ts`), and + * the vendor's own accept route answers it when its option is on. + */ +export const ACCEPT_NEEDS_VERIFIED_EMAIL_CODE = + 'EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION'; + +/** + * Was this rejection the accept refused for an unverified address? Read by + * code only. The accept page answers it with the verification screen rather + * than a toast: the person's next step is to verify, not to retry. + */ +export function isAcceptNeedsVerifiedEmail(err: unknown): boolean { + return errorCode(err) === ACCEPT_NEEDS_VERIFIED_EMAIL_CODE; +} + /** * Resolve a rejected organization call into the message to show the user. * From 3bf177b87f36fae2fbb68570f149bdea8c2e7872 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 04:26:39 +0000 Subject: [PATCH 2/5] chore(runtime): classify the vendor accept-verification code in the dispatcher vocabulary Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01ADHkmSYe73LCZ6WxGFvcko --- .../34272-accept-invitation-verified-email.md | 3 +++ .../runtime/src/dispatcher-error-vocabulary.ts | 18 ++++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/.changeset/34272-accept-invitation-verified-email.md b/.changeset/34272-accept-invitation-verified-email.md index 022221ae6fd..084038789e3 100644 --- a/.changeset/34272-accept-invitation-verified-email.md +++ b/.changeset/34272-accept-invitation-verified-email.md @@ -1,6 +1,7 @@ --- '@objectstack/plugin-auth': minor '@object-ui/app-shell': patch +'@objectstack/runtime': patch --- fix(plugin-auth,app-shell)!: while mail is live, accepting an invitation needs a verified address @@ -21,3 +22,5 @@ Skills-docs: none — `git grep` of `skills/` finds no page that teaches accepti **Who moves.** A person in that state verifies their address (the Console's accept page takes them to the screen that sends the mail), then accepts; an API client that accepts for its user does the same, through `POST /api/v1/auth/send-verification-email`. An invitee who opens the invitation mail's own link is not affected: that link verifies the address as it accepts. **Unchanged.** Every deployment without a live mail transport (no email service, or the log transport), where nothing could verify an address, so acceptance stays open to an unverified address; `get-invitation`, `list-user-invitations` and `reject-invitation`, which write no membership; the one-step door `POST /api/v1/auth/organization/accept-invitation-one-step`; and a verified session everywhere. better-auth's `requireEmailVerificationOnInvitation` stays declared `false`: it governs reading and declining too, and is read once at boot. + +`@objectstack/runtime` carries only the dispatcher error-vocabulary row that classifies the vendor code above as foreign vocabulary; nothing it runs changes. diff --git a/packages/runtime/src/dispatcher-error-vocabulary.ts b/packages/runtime/src/dispatcher-error-vocabulary.ts index af90a87ddb0..e991a6d42b0 100644 --- a/packages/runtime/src/dispatcher-error-vocabulary.ts +++ b/packages/runtime/src/dispatcher-error-vocabulary.ts @@ -582,6 +582,24 @@ export const UNREGISTERED_CODE_SITES: readonly UnregisteredCodeSite[] = [ "vendor's own `Response` on the vendor's wire — the identical refusal the vendor handler " + 'raised unconditionally before the rebuild — and never as a throw this repo classifies.', }, + { + code: 'EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION', + file: 'packages/plugins/plugin-auth/src/invitation-accept-verified-email.ts', + shape: 'objlit', + door: 'none', + verdict: 'foreign-vocabulary', + why: + "better-auth 1.7.12's own organization-plugin vocabulary — spelled exactly so in the " + + 'installed vendor at `dist/plugins/organization/error-codes.mjs`, the code its own ' + + '`/organization/accept-invitation` answers when `requireEmailVerificationOnInvitation` is on ' + + "(`crud-invites.mjs`) — and read at runtime off `plugin.$ERROR_CODES`; the local " + + 'restatement is only the fallback for a plugin object carrying no `$ERROR_CODES`, and ' + + "`invitation-accept-verified-email.test.ts` pins it equal to the vendor's own entry so a " + + "vendor rename turns the pin red rather than minting a local code. Raised " + + "`APIError.from('FORBIDDEN', …)` from the vendor's `beforeAcceptInvitation` hook inside the " + + "accept endpoint (#34272), so it leaves as the vendor's own `Response` on the vendor's wire " + + 'and never as a throw this repo classifies.', + }, { code: 'OS_METADATA_CONVERTED', From 7fabd3a9ca62993bc9474c0a296b48bf85e4c93a Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 05:13:43 +0000 Subject: [PATCH 3/5] chore(changeset): grade the plugin-auth entry patch (Metadata-protocol: none) Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01ADHkmSYe73LCZ6WxGFvcko --- .changeset/34272-accept-invitation-verified-email.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/34272-accept-invitation-verified-email.md b/.changeset/34272-accept-invitation-verified-email.md index 084038789e3..6838aca4a71 100644 --- a/.changeset/34272-accept-invitation-verified-email.md +++ b/.changeset/34272-accept-invitation-verified-email.md @@ -1,5 +1,5 @@ --- -'@objectstack/plugin-auth': minor +'@objectstack/plugin-auth': patch '@object-ui/app-shell': patch '@objectstack/runtime': patch --- From b2d54a28284f43bba26f0c77f6f9fc72ea6ef2ba Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 05:22:07 +0000 Subject: [PATCH 4/5] chore(runtime): keep the tracker id out of the vocabulary row's prose Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01ADHkmSYe73LCZ6WxGFvcko --- packages/runtime/src/dispatcher-error-vocabulary.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/runtime/src/dispatcher-error-vocabulary.ts b/packages/runtime/src/dispatcher-error-vocabulary.ts index e991a6d42b0..7778536052c 100644 --- a/packages/runtime/src/dispatcher-error-vocabulary.ts +++ b/packages/runtime/src/dispatcher-error-vocabulary.ts @@ -597,7 +597,7 @@ export const UNREGISTERED_CODE_SITES: readonly UnregisteredCodeSite[] = [ "`invitation-accept-verified-email.test.ts` pins it equal to the vendor's own entry so a " + "vendor rename turns the pin red rather than minting a local code. Raised " + "`APIError.from('FORBIDDEN', …)` from the vendor's `beforeAcceptInvitation` hook inside the " + - "accept endpoint (#34272), so it leaves as the vendor's own `Response` on the vendor's wire " + + "accept endpoint, so it leaves as the vendor's own `Response` on the vendor's wire " + 'and never as a throw this repo classifies.', }, From 8e828209b5ce1d69a9c3513e319dce15eaa58101 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 06:29:55 +0000 Subject: [PATCH 5/5] docs(plugin-auth): state the rule only, and narrow the mail-link sentence to a signed-out visitor Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01ADHkmSYe73LCZ6WxGFvcko --- .changeset/34272-accept-invitation-verified-email.md | 4 ++-- content/docs/deployment/self-hosting.mdx | 8 +++++--- .../plugin-auth/src/invitation-accept-verified-email.ts | 7 ++----- 3 files changed, 9 insertions(+), 10 deletions(-) diff --git a/.changeset/34272-accept-invitation-verified-email.md b/.changeset/34272-accept-invitation-verified-email.md index 6838aca4a71..1a16c2edbd1 100644 --- a/.changeset/34272-accept-invitation-verified-email.md +++ b/.changeset/34272-accept-invitation-verified-email.md @@ -12,14 +12,14 @@ Skills-docs: none — `git grep` of `skills/` finds no page that teaches accepti -**BREAKING** for a person who accepts an invitation from an account whose address was never verified, on a deployment whose mail transport is live. An unverified address does not prove the person holds the invited mailbox, so on a deployment that can mail, anyone who registered the invited address first could take the invitation's membership. +**BREAKING** for a person who accepts an invitation from an account whose address was never verified, on a deployment whose mail transport is live. The rule: while mail is live, accepting an invitation needs a verified address, because an unverified address is not proof of the invited mailbox. **What changes.** - `POST /api/v1/auth/organization/accept-invitation` (`@objectstack/plugin-auth`), from a session whose address is unverified, while the email service answers `isConfigured() === true`, now answers `403 EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION` (better-auth's own code and sentence, the ones its accept route answers when its option is on) and writes nothing; the invitation stays pending. It used to answer `200` and write the membership. The vendor's not-found, expiry and recipient refusals still come first, so a session that is not the invitee learns nothing new. The check runs on the vendor's `beforeAcceptInvitation` hook, on the session user the vendor itself resolved (cookie or bearer token alike), and asks whether mail is live on every request. - The Console's accept page (`@object-ui/app-shell`) answers that refusal with the verification-mail screen (`/verify-email-prompt`) for the account's address, whose link returns to the accept page, instead of a toast. -**Who moves.** A person in that state verifies their address (the Console's accept page takes them to the screen that sends the mail), then accepts; an API client that accepts for its user does the same, through `POST /api/v1/auth/send-verification-email`. An invitee who opens the invitation mail's own link is not affected: that link verifies the address as it accepts. +**Who moves.** A person in that state verifies their address (the Console's accept page takes them to the screen that sends the mail), then accepts; an API client that accepts for its user does the same, through `POST /api/v1/auth/send-verification-email`. A visitor who is not signed in and opens the invitation mail's own link is not affected: the accept page offers the one-step form, which verifies the address as it accepts. A visitor already signed in to an account whose address is unverified who opens the same link accepts through `/organization/accept-invitation`, so is refused as above and sent to verify. **Unchanged.** Every deployment without a live mail transport (no email service, or the log transport), where nothing could verify an address, so acceptance stays open to an unverified address; `get-invitation`, `list-user-invitations` and `reject-invitation`, which write no membership; the one-step door `POST /api/v1/auth/organization/accept-invitation-one-step`; and a verified session everywhere. better-auth's `requireEmailVerificationOnInvitation` stays declared `false`: it governs reading and declining too, and is read once at boot. diff --git a/content/docs/deployment/self-hosting.mdx b/content/docs/deployment/self-hosting.mdx index 4e57a1f59a3..c2078f5f997 100644 --- a/content/docs/deployment/self-hosting.mdx +++ b/content/docs/deployment/self-hosting.mdx @@ -767,9 +767,11 @@ EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION` and writes nothing: an unverified address does not prove the person holds the invited mailbox. The Console's accept page sends the person to the verification-mail screen for their address, and the link in that mail brings -them back to accept. Opening the invitation's link from the invitation mail -itself needs no separate step, because that link verifies the address as it -accepts. Reading, listing and declining an invitation are not affected. On a +them back to accept. A visitor who is not signed in and opens the invitation's +link from the invitation mail itself needs no separate step: the accept page +offers the one-step form, which verifies the address as it accepts. A visitor +already signed in to an unverified account who opens that link is sent to +verify first, like any other unverified session. Reading, listing and declining an invitation are not affected. On a deployment with no live transport (none configured, or the log transport) nothing can verify an address, so acceptance stays open to an unverified address, as before. diff --git a/packages/plugins/plugin-auth/src/invitation-accept-verified-email.ts b/packages/plugins/plugin-auth/src/invitation-accept-verified-email.ts index 56eb3a1bbe2..9e7b502e790 100644 --- a/packages/plugins/plugin-auth/src/invitation-accept-verified-email.ts +++ b/packages/plugins/plugin-auth/src/invitation-accept-verified-email.ts @@ -7,11 +7,8 @@ * * ## The rule * - * The accept door writes a membership for the session's user on the strength - * of one fact: the session's address equals the invited one. An address that - * was never verified proves nothing about the mailbox, so on a deployment that - * can mail, anyone who registered the invited address first (an account the - * real owner never confirmed) could take the seat. + * While mail is live, accepting an invitation needs a verified address, + * because an unverified address is not proof of the invited mailbox. * * - **While email delivery is live** (`AuthManager.isEmailDeliveryLive`, the * one reader of `IEmailService.isConfigured()`, read at call time): an