From 76b6d9c6b7e443bf38ebe23dced8bc4bda646e8e Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 10:00:24 +0000 Subject: [PATCH 01/13] wip(plugin-auth): accepting an organization invitation requires a verified email address Claude-Session: https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj Co-authored-by: Claude --- content/docs/deployment/self-hosting.mdx | 17 +++++- docs/qa/platform-checklist/RUNNER.md | 16 ++++-- .../plugin-auth/src/audience-posture.ts | 4 +- .../src/auth-manager-organization-plugin.ts | 52 +++++++++++-------- .../src/list-user-invitations-verification.ts | 18 +++---- 5 files changed, 66 insertions(+), 41 deletions(-) diff --git a/content/docs/deployment/self-hosting.mdx b/content/docs/deployment/self-hosting.mdx index 305af41567a..83914c8f38b 100644 --- a/content/docs/deployment/self-hosting.mdx +++ b/content/docs/deployment/self-hosting.mdx @@ -760,6 +760,21 @@ 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. +**Accepting an invitation needs a verified email address.** The invitation's +`id`, which the link carries, proves nothing about the mailbox, so +`POST /api/v1/auth/organization/accept-invitation` refuses a session whose +address is not verified with `403 +EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION`, and +declining, reading (`get-invitation`) and listing (`list-user-invitations`) an +invitation are refused alike (`EMAIL_VERIFICATION_REQUIRED_FOR_INVITATION` for +the two reads). A password account verifies through the verification mail; an +account made by a social or SSO sign-in counts only when its provider verified +the address. The invitation mail's own link carries a proof of the mailbox and +accepts in one step; a copied link carries none. No setting relaxes this. On a +deployment with no mail transport, a platform administrator adds the person to +the organization directly with the member list's **Add Member** action +instead of an invitation. + **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: @@ -815,7 +830,7 @@ has a cost: `/api/v1/auth/config` reports `requireEmailVerification: false` — the value actually wired. - Anyone can register an address they do not control. An organization - invitation sent to that address can then be accepted by that account. + invitation sent to that address still waits for the address to be verified. - It is the deployment's to declare. A `false` stored only through the settings console is refused under `open`, and verification stays on. diff --git a/docs/qa/platform-checklist/RUNNER.md b/docs/qa/platform-checklist/RUNNER.md index 54cbecf8d2d..20e6a4ea969 100644 --- a/docs/qa/platform-checklist/RUNNER.md +++ b/docs/qa/platform-checklist/RUNNER.md @@ -597,11 +597,17 @@ contradicts it, and correct it here when it does. invitation's role onto that membership and the invitation reads `accepted` (`adoptExistingMembership` in `packages/plugins/plugin-auth/src/adopt-membership.ts`, which never lowers a grade; pinned by `accept-invitation-adopt-membership.test.ts` - beside it, 6 passed at `bfc1539fe0`). The invitee's email need not be verified: the - deployment declares `requireEmailVerificationOnInvitation: false`. QA run #24616 met it: - an `admin` invitation signed up as `member`, and the persona held `org_admin` only after - the accept. **Check:** read the persona's `sys_member` row (`role`) before scoring a - role-gated clause, never the invitation you sent. + beside it, 6 passed at `bfc1539fe0`). The invitee's email must be verified before the + accept: the deployment declares `requireEmailVerificationOnInvitation: true` + (`auth-manager-organization-plugin.ts`), so an unverified persona's accept, decline, + `get-invitation` and listing answer `403` + (`EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION`, + `EMAIL_VERIFICATION_REQUIRED_FOR_INVITATION`). Verify the persona first through the + verification mail (`POST /api/v1/auth/send-verification-email`, then open its link). + QA run #24616 met the role half: an `admin` invitation signed up as `member`, and the + persona held `org_admin` only after the accept. **Check:** read the persona's + `sys_member` row (`role`) before scoring a role-gated clause, never the invitation you + sent. 2. **Admin create.** `POST /api/v1/auth/admin/create-user`, which answers `mustChangePassword: true` by default (`packages/plugins/plugin-auth/src/admin-user-endpoints.ts`, `runAdminCreateUser`); diff --git a/packages/plugins/plugin-auth/src/audience-posture.ts b/packages/plugins/plugin-auth/src/audience-posture.ts index 2ca4f85bf9a..adc5b61f2f8 100644 --- a/packages/plugins/plugin-auth/src/audience-posture.ts +++ b/packages/plugins/plugin-auth/src/audience-posture.ts @@ -222,8 +222,8 @@ export function resolveEmailVerificationRequirement( export const OPEN_POSTURE_VERIFICATION_OFF_WARNING = "[auth] audience posture 'open' is running with email verification explicitly OFF " + '(emailAndPassword.requireEmailVerification: false, or OS_AUTH_REQUIRE_EMAIL_VERIFICATION=false). ' + - 'Anyone can register an address they do not control and is signed in at once, and an organization ' + - 'invitation sent to that address can then be accepted by that account. Keep this to a deployment ' + + 'Anyone can register an address they do not control and is signed in at once; an organization ' + + 'invitation sent to that address still waits for the address to be verified. Keep this to a deployment ' + 'with no mail transport that trusts its sign-ups, such as a pre-production environment; remove the ' + 'explicit false to force verification back on.'; 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..66e9e3b7b3d 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-organization-plugin.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-organization-plugin.ts @@ -192,12 +192,22 @@ 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. - requireEmailVerificationOnInvitation: false, + // Accepting an invitation needs the session's email address verified. + // The invitation's id is no proof of the mailbox: the accept link carries + // it, `copy_invitation_link` answers it and the invitation row holds it. + // So the vendor's id-addressed invitation routes (accept, reject, + // get-invitation) and the listing below refuse a session whose address is + // not verified, `403` with the vendor's code + // (`EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION`, + // `EMAIL_VERIFICATION_REQUIRED_FOR_INVITATION`). A password account + // verifies by the mail round trip; a social or SSO account counts only + // when its provider verified the address, which is what the vendor stores + // on the account it creates. The one-step door + // (`invitation-mailbox-proof.ts`) verifies the address with the mail's own + // proof before it accepts through this route, and its session mode asks + // for a verified address first. A constant, not an option: no deployment + // setting relaxes it. + requireEmailVerificationOnInvitation: true, // 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 — // so a generous cap stops scripted org/free-env spam (each new org can @@ -697,14 +707,13 @@ export async function buildOrganizationPlugin(this: OrganizationPluginHost) { } satisfies OrganizationOptions; const organizationPlugin: any = organization(organizationOptions); - // [#16569] `GET /organization/list-user-invitations` — make the vendor's - // listing honour the `requireEmailVerificationOnInvitation: false` - // declared above, the way `accept-invitation`, `reject-invitation` and - // `get-invitation` already do. better-auth 1.7.2's `listUserInvitations` - // refuses every unverified session UNCONDITIONALLY (it never reads the - // option), so on exactly the no-mailer deployment the declaration exists - // for, an invitee could accept an invitation but never list it and the - // SDK's `organizations.invitations.listMine()` inbox was empty-by-403. + // [#16569] `GET /organization/list-user-invitations` — the vendor's + // listing honours the `requireEmailVerificationOnInvitation` declared + // above, the way `accept-invitation`, `reject-invitation` and + // `get-invitation` do: with the declaration `true`, a session whose + // address is not verified lists nothing and is refused, so the listing + // never hands such a session an invitation's id. better-auth's own + // `listUserInvitations` never reads the option. // Rebuilt IN PLACE on this plugin's own endpoints record — the same // shape as `applyPlatformAdminImpersonation` above, for the same reasons // (one owner for the path; every hook keyed on it still fires; the @@ -718,19 +727,16 @@ export async function buildOrganizationPlugin(this: OrganizationPluginHost) { organizationOptions, ); if (!listingRewired) { - // The vendor renamed or dropped the endpoint. Say so loudly: the - // route then falls back to the vendor's own handler, which refuses - // every unverified session — an empty inbox, not an open door. - // `warn`, not `error` (AGENTS.md → Degradation log levels): the - // system is VISIBLY smaller — the inbox answers a 403 the caller sees - // — and nothing claims a persistence it did not perform. + // The vendor renamed or dropped the endpoint. Say so loudly: whatever + // the vendor now serves for the inbox is not this module's rebuild. + // `warn`, not `error` (AGENTS.md → Degradation log levels): nothing + // claims a persistence it did not perform. console.warn( '[AuthManager] better-auth\'s organization plugin no longer exposes a ' + '`listUserInvitations` endpoint at /organization/list-user-invitations, ' + 'so the declared `requireEmailVerificationOnInvitation` could NOT be ' + - 'applied to the invitation inbox. Unverified users will be refused ' + - '(403 EMAIL_VERIFICATION_REQUIRED_FOR_INVITATION) until ' + - 'list-user-invitations-verification.ts is updated for the new vendor shape.', + 'applied to the invitation inbox by list-user-invitations-verification.ts; ' + + 'update it for the new vendor shape.', ); } return organizationPlugin; diff --git a/packages/plugins/plugin-auth/src/list-user-invitations-verification.ts b/packages/plugins/plugin-auth/src/list-user-invitations-verification.ts index a8d7c389296..584fb78f79b 100644 --- a/packages/plugins/plugin-auth/src/list-user-invitations-verification.ts +++ b/packages/plugins/plugin-auth/src/list-user-invitations-verification.ts @@ -26,16 +26,14 @@ * throw APIError.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.EMAIL_VERIFICATION_REQUIRED_FOR_INVITATION); * ``` * - * unconditionally. `auth-manager.ts` declares the option `false` on purpose - * (no mailer wired ⇒ nothing can ever verify an invitee ⇒ requiring - * verification dead-ends every invite flow), so on exactly the deployment - * shape the option exists for an invitee can ACCEPT an invitation and can - * never LIST it, and the SDK's `organizations.invitations.listMine()` inbox - * is empty-by-403 for every user. `list-user-invitations-verification.test.ts` - * measures both halves on the real pipeline — the 403, and the 200s from the - * three siblings for the same unverified session — and pins that the vendor - * still has the defect, so an upstream fix turns that pin red and this module - * is what gets deleted. + * unconditionally. The platform declares the option `true` + * (`auth-manager-organization-plugin.ts`): accepting an invitation needs a + * verified address, so a session whose address is not verified can neither + * accept, reject, read nor list one, and the listing answers it exactly as + * its three siblings do. `list-user-invitations-verification.test.ts` + * measures the four routes on the real pipeline for the same session, and + * pins that the vendor's listing still never reads the option, so an + * upstream change turns that pin red and this module is what gets deleted. * * ## Why this shape: the endpoint is rebuilt IN PLACE, from the vendor's own options * From 776d9a10ca0cd7f6facb52f8eda2854bec27535a Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 10:05:58 +0000 Subject: [PATCH 02/13] test(plugin-auth): accepting an organization invitation requires a verified email address at every door Claude-Session: https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj Co-authored-by: Claude --- ...tation-acceptance-verified-address.test.ts | 331 ++++++++++++++++++ 1 file changed, 331 insertions(+) create mode 100644 packages/plugins/plugin-auth/src/invitation-acceptance-verified-address.test.ts diff --git a/packages/plugins/plugin-auth/src/invitation-acceptance-verified-address.test.ts b/packages/plugins/plugin-auth/src/invitation-acceptance-verified-address.test.ts new file mode 100644 index 00000000000..455ce3610cd --- /dev/null +++ b/packages/plugins/plugin-auth/src/invitation-acceptance-verified-address.test.ts @@ -0,0 +1,331 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Accepting an organization invitation requires a verified email address. + * + * A password account verifies by the mail round trip; an account a social + * provider made counts only when the provider verified the address. Holding + * the invitation's id, which its accept link and its copied link carry, + * proves nothing about the mailbox. + * + * The real `AuthManager` over a real driver (`@objectstack/driver-sql` on + * better-sqlite3 `:memory:`, plugin-auth's own identity objects), driven + * through `AuthManager.handleRequest` at every acceptance door: the vendor's + * `POST /organization/accept-invitation`, its decline, read and listing + * siblings, and the one-step door (`invitation-mailbox-proof.ts`). The + * invitation is into an organization that is not the deployment's default + * one, so a membership in it can only come from an acceptance. + */ + +import { describe, it, expect, afterAll, afterEach, beforeEach, vi } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { AuthManager } from './auth-manager.js'; +import { authIdentityObjects } from './manifest.js'; +import { SIGN_UP_INVITATION_ID_FIELD } from './presented-invitation.js'; +import { ACCEPT_INVITATION_ONE_STEP_PATH } from './invitation-mailbox-proof.js'; +import { memoizeScrypt } from './__tests__/scrypt-memo.testkit'; + +const BASE = 'http://localhost:3000'; +const AUTH = `${BASE}/api/v1/auth`; +const SECRET = 'test-secret-at-least-32-chars-long-verified-accept'; +const PASSWORD = 'S3cure!Passw0rd-verified-accept'; +const SYSTEM = { context: { isSystem: true } } as never; +const DEFAULT_ORG = 'org_default'; +const PARTNER_ORG = 'org_partner'; +const OWNER = 'owner@acme.example'; +const INVITEE = 'invitee@acme.example'; + +/** The vendor's refusal codes for a session whose address is not verified. */ +const ACCEPT_OR_DECLINE_REFUSED = 'EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION'; +const READ_OR_LIST_REFUSED = 'EMAIL_VERIFICATION_REQUIRED_FOR_INVITATION'; + +const scrypt = memoizeScrypt(); +afterAll(scrypt.restore); + +const engines: ObjectQL[] = []; +afterEach(async () => { + vi.restoreAllMocks(); + while (engines.length) { + try { + await (engines.pop() as unknown as { destroy?(): Promise })?.destroy?.(); + } catch { + /* noop */ + } + } +}); +beforeEach(() => { + vi.spyOn(console, 'info').mockImplementation(() => {}); + vi.spyOn(console, 'warn').mockImplementation(() => {}); +}); + +interface SentMail { + template: string; + to: string | { address: string }; + data: Record; + deliverOnlyData?: Record; +} + +/** What the social provider asserts about the person signing in. */ +let providerProfile: { sub: string; email: string; email_verified: boolean } | null = null; + +async function bootEngine(): Promise { + const engine = new ObjectQL(); + engines.push(engine); + engine.registerDriver( + new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }), + true, + ); + await engine.init(); + for (const object of authIdentityObjects) { + engine.registry.registerObject(object as never, '@objectstack/plugin-auth'); + } + await engine.syncSchemas(); + await engine.insert('sys_organization', { id: DEFAULT_ORG, name: 'Default', slug: 'default' }, SYSTEM); + await engine.insert('sys_organization', { id: PARTNER_ORG, name: 'Partner', slug: 'partner' }, SYSTEM); + return engine; +} + +const singleTenancy = () => + ({ + posture: 'single', + requestedPosture: 'single', + isolationActive: false, + requested: false, + degraded: false, + defaultOrgId: async () => DEFAULT_ORG, + }) as never; + +function makeManager(engine: ObjectQL, sent: SentMail[], config: Record = {}): AuthManager { + const manager = new AuthManager({ + secret: SECRET, + baseUrl: BASE, + dataEngine: engine as never, + membershipPolicy: 'auto', + getTenancy: singleTenancy, + socialProviders: { + google: { + clientId: 'google-client', + clientSecret: 'google-secret', + // The id token is synthetic: the profile is the one the test sets. + verifyIdToken: async () => true, + getUserInfo: async () => + providerProfile + ? { + user: { + id: providerProfile.sub, + email: providerProfile.email, + emailVerified: providerProfile.email_verified, + name: 'Social Person', + }, + data: { ...providerProfile }, + } + : null, + }, + }, + ...config, + } as never); + manager.setEmailService({ + isConfigured: () => true, + sendTemplate: async (input: SentMail) => { + sent.push(input); + return { id: `mail_${sent.length}`, status: 'sent' }; + }, + } as never); + return manager; +} + +const cookieFrom = (res: Response): string => + (res.headers.getSetCookie?.() ?? [res.headers.get('set-cookie') ?? '']) + .map((c) => c.split(';')[0]) + .filter(Boolean) + .join('; '); + +function send(manager: AuthManager, method: 'GET' | 'POST', path: string, body?: unknown, cookie?: string) { + return manager.handleRequest( + new Request(path.startsWith('http') ? path : `${AUTH}${path}`, { + method, + headers: { 'content-type': 'application/json', origin: BASE, ...(cookie ? { cookie } : {}) }, + ...(body !== undefined ? { body: JSON.stringify(body) } : {}), + }), + ); +} + +async function rows(engine: ObjectQL, object: string, where: Record = {}) { + const found = await engine.find(object, { where, limit: 100 }, SYSTEM); + return (Array.isArray(found) ? found : []) as Array>; +} + +/** Status and code of a refusal, in either envelope. */ +async function verdict(res: Response): Promise<{ status: number; code?: unknown }> { + const body = (await res.clone().json().catch(() => ({}))) as { code?: unknown; error?: { code?: unknown } }; + return { status: res.status, code: body?.error?.code ?? body?.code }; +} + +/** + * A deployment whose first account owns the partner organization and has + * invited {@link INVITEE} into it as `admin`. `config` reaches the manager + * that serves every request. + */ +async function deployment(config: Record = {}) { + const engine = await bootEngine(); + const sent: SentMail[] = []; + const manager = makeManager(engine, sent, config); + const first = await send(manager, 'POST', '/sign-up/email', { email: OWNER, password: PASSWORD, name: 'Owner' }); + expect(first.status, `the first account enters without an invitation: ${await first.clone().text()}`).toBe(200); + const [owner] = await rows(engine, 'sys_user', { email: OWNER }); + await engine.update('sys_user', { id: owner.id, email_verified: true } as never, SYSTEM); + const signIn = await send(manager, 'POST', '/sign-in/email', { email: OWNER, password: PASSWORD }); + expect(signIn.status, await signIn.clone().text()).toBe(200); + const ownerCookie = cookieFrom(signIn); + await engine.insert( + 'sys_member', + { id: 'mem_owner_partner', organization_id: PARTNER_ORG, user_id: owner.id, role: 'owner', created_at: new Date() }, + SYSTEM, + ); + const invited = await send( + manager, + 'POST', + '/organization/invite-member', + { email: INVITEE, role: 'admin', organizationId: PARTNER_ORG }, + ownerCookie, + ); + expect(invited.status, await invited.clone().text()).toBe(200); + const invitationId = String(((await invited.json()) as { id: unknown }).id); + const invitation = async () => (await rows(engine, 'sys_invitation', { id: invitationId }))[0]; + const partnerMembership = async () => { + const [user] = await rows(engine, 'sys_user', { email: INVITEE }); + return user ? rows(engine, 'sys_member', { user_id: user.id, organization_id: PARTNER_ORG }) : []; + }; + const inviteeRow = async () => (await rows(engine, 'sys_user', { email: INVITEE }))[0]; + return { engine, manager, sent, invitationId, invitation, partnerMembership, inviteeRow }; +} + +type Deployment = Awaited>; + +/** The invitee signs up presenting the invitation's id, and never verifies. */ +async function unverifiedPasswordSession(d: Deployment): Promise { + const res = await send(d.manager, 'POST', '/sign-up/email', { + email: INVITEE, + password: PASSWORD, + name: 'Invitee', + [SIGN_UP_INVITATION_ID_FIELD]: d.invitationId, + }); + expect(res.status, await res.clone().text()).toBe(200); + expect(Boolean((await d.inviteeRow())?.email_verified)).toBe(false); + const cookie = cookieFrom(res); + expect(cookie, 'the unverified sign-up is signed in').not.toBe(''); + return cookie; +} + +/** The invitee signs in through the social provider, which asserts the address. */ +async function socialSession(d: Deployment, verified: boolean): Promise { + providerProfile = { sub: `google-${verified ? 'v' : 'u'}`, email: INVITEE, email_verified: verified }; + const res = await send(d.manager, 'POST', '/sign-in/social', { provider: 'google', idToken: { token: 'synthetic' } }); + expect(res.status, await res.clone().text()).toBe(200); + expect(Boolean((await d.inviteeRow())?.email_verified)).toBe(verified); + const cookie = cookieFrom(res); + expect(cookie, 'the social sign-in is signed in').not.toBe(''); + return cookie; +} + +/** Every door refuses the session, and the invitation stays pending with no membership written. */ +async function expectEveryDoorRefuses(d: Deployment, cookie: string) { + const accept = await send(d.manager, 'POST', '/organization/accept-invitation', { invitationId: d.invitationId }, cookie); + expect(await verdict(accept), await accept.clone().text()).toEqual({ status: 403, code: ACCEPT_OR_DECLINE_REFUSED }); + + const oneStep = await send(d.manager, 'POST', ACCEPT_INVITATION_ONE_STEP_PATH, { invitationId: d.invitationId }, cookie); + expect(oneStep.status, await oneStep.clone().text()).toBe(200); + expect(((await oneStep.json()) as { data: unknown }).data).toEqual({ outcome: 'verify_email' }); + + const decline = await send(d.manager, 'POST', '/organization/reject-invitation', { invitationId: d.invitationId }, cookie); + expect(await verdict(decline), await decline.clone().text()).toEqual({ status: 403, code: ACCEPT_OR_DECLINE_REFUSED }); + + const read = await send(d.manager, 'GET', `/organization/get-invitation?id=${d.invitationId}`, undefined, cookie); + expect(await verdict(read), await read.clone().text()).toEqual({ status: 403, code: READ_OR_LIST_REFUSED }); + + const list = await send(d.manager, 'GET', '/organization/list-user-invitations', undefined, cookie); + const listed = await list.clone().text(); + expect(await verdict(list), listed).toEqual({ status: 403, code: READ_OR_LIST_REFUSED }); + expect(listed).not.toContain(d.invitationId); + + expect((await d.invitation())?.status).toBe('pending'); + expect(await d.partnerMembership()).toEqual([]); +} + +/** The vendor route accepts for the session, with the invited role. */ +async function expectAccepted(d: Deployment, cookie: string) { + const accept = await send(d.manager, 'POST', '/organization/accept-invitation', { invitationId: d.invitationId }, cookie); + expect(accept.status, await accept.clone().text()).toBe(200); + expect((await d.invitation())?.status).toBe('accepted'); + expect((await d.partnerMembership()).map((m) => m.role)).toEqual(['admin']); +} + +describe('accepting an organization invitation requires a verified email address', () => { + it('a password account that never verified its address cannot accept, decline, read or list the invitation at any door', async () => { + const d = await deployment(); + await expectEveryDoorRefuses(d, await unverifiedPasswordSession(d)); + }); + + it('a password account accepts once it completes the verification mail round trip', async () => { + const d = await deployment(); + const cookie = await unverifiedPasswordSession(d); + await expectEveryDoorRefuses(d, cookie); + + const asked = await send(d.manager, 'POST', '/send-verification-email', { email: INVITEE }, cookie); + expect(asked.status, await asked.clone().text()).toBe(200); + const mail = [...d.sent].reverse().find((m) => m.template === 'auth.verify_email'); + expect(mail, 'the verification mail was sent').toBeDefined(); + const verified = await send(d.manager, 'GET', String(mail!.data.verificationUrl)); + expect(verified.status, await verified.clone().text()).toBeLessThan(400); + expect(Boolean((await d.inviteeRow())?.email_verified)).toBe(true); + + await expectAccepted(d, cookie); + }); + + it('an account whose social provider asserted the address unverified cannot accept at any door', async () => { + const d = await deployment({ audience: { posture: 'open', selfRegistrationPermissionSet: 'member_default' } }); + await expectEveryDoorRefuses(d, await socialSession(d, false)); + }); + + it('an account whose social provider verified the address accepts', async () => { + const d = await deployment({ audience: { posture: 'open', selfRegistrationPermissionSet: 'member_default' } }); + await expectAccepted(d, await socialSession(d, true)); + }); + + it('the one-step door accepts for a signed-in account only once its address is verified', async () => { + const d = await deployment({ audience: { posture: 'open', selfRegistrationPermissionSet: 'member_default' } }); + const cookie = await socialSession(d, false); + await expectEveryDoorRefuses(d, cookie); + + // The provider now asserts the address verified; the next sign-in records it. + providerProfile = { sub: 'google-u', email: INVITEE, email_verified: true }; + const again = await send(d.manager, 'POST', '/sign-in/social', { provider: 'google', idToken: { token: 'synthetic' } }); + expect(again.status, await again.clone().text()).toBe(200); + expect(Boolean((await d.inviteeRow())?.email_verified)).toBe(true); + + const oneStep = await send(d.manager, 'POST', ACCEPT_INVITATION_ONE_STEP_PATH, { invitationId: d.invitationId }, cookieFrom(again)); + expect(oneStep.status, await oneStep.clone().text()).toBe(200); + expect(((await oneStep.json()) as { data: unknown }).data).toEqual({ outcome: 'accepted', organizationId: PARTNER_ORG }); + expect((await d.partnerMembership()).map((m) => m.role)).toEqual(['admin']); + }); + + it('the one-step door accepts with the proof the invitation mail carries, which verifies the address', async () => { + const d = await deployment(); + const mail = [...d.sent].reverse().find((m) => m.template === 'auth.invitation'); + const link = String(mail?.deliverOnlyData?.acceptUrl ?? ''); + const match = /#proof=([^&]+)$/.exec(link); + expect(match, `the invitation mail's link carries the proof: ${link}`).not.toBeNull(); + + const res = await send(d.manager, 'POST', ACCEPT_INVITATION_ONE_STEP_PATH, { + invitationId: d.invitationId, + proof: decodeURIComponent(match![1]!), + name: 'Invitee', + password: PASSWORD, + }); + expect(res.status, await res.clone().text()).toBe(200); + expect(((await res.json()) as { data: unknown }).data).toEqual({ outcome: 'accepted', organizationId: PARTNER_ORG }); + expect(Boolean((await d.inviteeRow())?.email_verified)).toBe(true); + expect((await d.partnerMembership()).map((m) => m.role)).toEqual(['admin']); + }); +}); From cf95aa5c0d3aa3bd480570e4d1279e7e36467d23 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 10:28:38 +0000 Subject: [PATCH 03/13] fix(plugin-auth)!: an invitation's acceptance, decline, read and listing need a verified address; the Console answers the refusal with its verify-email state Claude-Session: https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj Co-authored-by: Claude --- .../invitation-acceptance-verified-address.md | 17 +++ ...accept-invitation-adopt-membership.test.ts | 15 ++ .../plugin-auth/src/cloud-managed.test.ts | 4 + .../src/invitation-delivery-outcome.test.ts | 4 +- .../src/invitation-preview.test.ts | 8 +- ...list-user-invitations-verification.test.ts | 131 ++++++++---------- .../src/presented-invitation.test.ts | 21 ++- .../src/remove-user-atomicity.test.ts | 2 + .../invitationVendorRefusals-33650.test.tsx | 51 +++++++ .../manage/AcceptInvitationPage.tsx | 40 +++++- 10 files changed, 210 insertions(+), 83 deletions(-) create mode 100644 .changeset/invitation-acceptance-verified-address.md diff --git a/.changeset/invitation-acceptance-verified-address.md b/.changeset/invitation-acceptance-verified-address.md new file mode 100644 index 00000000000..5503db4f6ce --- /dev/null +++ b/.changeset/invitation-acceptance-verified-address.md @@ -0,0 +1,17 @@ +--- +'@objectstack/plugin-auth': patch +--- + +fix(plugin-auth)!: accepting an organization invitation requires a verified email address + +Clause-②: yes (narrowing) — narrowed: `POST /api/v1/auth/organization/accept-invitation` and `POST /api/v1/auth/organization/reject-invitation` answer `403 EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION` to a session whose email address is not verified, and `GET /api/v1/auth/organization/get-invitation` and `GET /api/v1/auth/organization/list-user-invitations` answer it `403 EMAIL_VERIFICATION_REQUIRED_FOR_INVITATION`; nothing is accepted or declined and no membership is written. The codes are better-auth's own. The `sys_invitation` actions **Accept Invitation** and **Decline Invitation** post to those routes and answer the same. The boot warning for the `open` posture with verification declared off says that an invitation to an unverified address waits for the address to be verified. +Metadata-protocol: none +Skills-docs: none — no skill under `skills/**` teaches accepting an organization invitation; `content/docs/deployment/self-hosting.mdx` gains the rule in this change. + + + +**BREAKING** for a deployment whose invitees sign in with an address that is not verified: email verification off (the default under the `invite_only` posture, or declared off under `open`), or a social or SSO provider that does not verify the address. Accepting an organization invitation requires a verified email address. A password account verifies by the verification mail; an account a social or SSO provider made counts only when the provider verified the address. The invitation's id, which its accept link and a copied link carry, is no proof of the mailbox. No setting relaxes the rule. + +Unchanged: the invitation mail's own link, which carries a proof of the mailbox and accepts in one step (`POST /api/v1/auth/organization/accept-invitation-one-step`), and that door's signed-in mode, which already asks for a verified address; a verified account, which accepts, declines, reads and lists its invitations as before; sending, resending and cancelling invitations. + +What to do: an invitee completes the verification mail (`POST /api/v1/auth/send-verification-email`, then the link it carries) before accepting, or opens the invitation mail's own link. On a deployment with no mail transport, a platform administrator adds the person to the organization with the member list's **Add Member** action instead of an invitation. diff --git a/packages/plugins/plugin-auth/src/accept-invitation-adopt-membership.test.ts b/packages/plugins/plugin-auth/src/accept-invitation-adopt-membership.test.ts index ee25ee1f7b8..80563b8cd10 100644 --- a/packages/plugins/plugin-auth/src/accept-invitation-adopt-membership.test.ts +++ b/packages/plugins/plugin-auth/src/accept-invitation-adopt-membership.test.ts @@ -198,6 +198,17 @@ const membersOf = (engine: MemoryEngine, organizationId: string, userId: string) const invitationsFor = (engine: MemoryEngine, email: string) => (engine.tables.get('sys_invitation') ?? []).filter((i) => i.email === email); +/** + * Mark a fixture user's address verified, as completing the verification mail + * does: accepting an invitation needs a verified address + * (`invitation-acceptance-verified-address.test.ts`). + */ +const verify = (engine: MemoryEngine, userId: string) => { + const user = (engine.tables.get('sys_user') ?? []).find((u) => u.id === userId); + expect(user, `no user ${userId}`).toBeDefined(); + user!.email_verified = true; +}; + /** Force a membership role directly, the way an operator's data would look. */ const setRole = (engine: MemoryEngine, organizationId: string, userId: string, role: string) => { const [row] = membersOf(engine, organizationId, userId); @@ -259,6 +270,7 @@ describe('#7725 — accepting an invitation when the invitee is already auto-bou const invitee = await signUp(manager, engine, 'invitee@example.com'); expect(membersOf(engine, DEFAULT_ORG, invitee.userId)).toHaveLength(1); + verify(engine, invitee.userId); const accept = await post( manager, '/organization/accept-invitation', @@ -300,6 +312,7 @@ describe('#7725 — accepting an invitation when the invitee is already auto-bou // The reconciler's default, which adoption must not silently keep. expect(membersOf(engine, DEFAULT_ORG, invitee.userId)[0]!.role).toBe('member'); + verify(engine, invitee.userId); const accept = await post( manager, '/organization/accept-invitation', @@ -336,6 +349,7 @@ describe('#7725 — accepting an invitation when the invitee is already auto-bou expires_at: new Date(Date.now() + 86_400_000), }); + verify(engine, owner.userId); const accept = await post( manager, '/organization/accept-invitation', @@ -376,6 +390,7 @@ describe('#7725 — accepting an invitation when the invitee is already auto-bou expect(membersOf(engine, DEFAULT_ORG, invitee.userId)).toHaveLength(1); expect(membersOf(engine, PARTNER_ORG, invitee.userId)).toHaveLength(0); + verify(engine, invitee.userId); const accept = await post( manager, '/organization/accept-invitation', diff --git a/packages/plugins/plugin-auth/src/cloud-managed.test.ts b/packages/plugins/plugin-auth/src/cloud-managed.test.ts index 88621b4d096..492155250da 100644 --- a/packages/plugins/plugin-auth/src/cloud-managed.test.ts +++ b/packages/plugins/plugin-auth/src/cloud-managed.test.ts @@ -966,6 +966,10 @@ describe('on a cloud-managed environment, membership and its tiers are managed b expect(issued.status, `fixture: the invitation is issued while unmanaged — ${issued.text}`).toBe(200); const [invitation] = s.invitationsOf(email); expect(invitation?.status, 'fixture: the invitation is pending').toBe('pending'); + // The invitee's address is verified, so only the posture decides: accepting + // or declining an invitation needs a verified address + // (`invitation-acceptance-verified-address.test.ts`). + s.users().find((u) => String(u.id) === s.ids.member)!.email_verified = true; return String(invitation.id); }; diff --git a/packages/plugins/plugin-auth/src/invitation-delivery-outcome.test.ts b/packages/plugins/plugin-auth/src/invitation-delivery-outcome.test.ts index 7fce91d9791..d343d2efd3e 100644 --- a/packages/plugins/plugin-auth/src/invitation-delivery-outcome.test.ts +++ b/packages/plugins/plugin-auth/src/invitation-delivery-outcome.test.ts @@ -326,7 +326,7 @@ describe('#27843 (c) — copy_invitation_link is answered only inside the invite }); it('a canceled invitation is refused 409, and so is an accepted one', async () => { - const { direct, invite, owner, signUp, copyLink, invitationRow } = await stage(); + const { engine, direct, invite, owner, signUp, copyLink, invitationRow } = await stage(); const canceled = (await invite('carl.canceled@acme.test')).body.id as string; const cancelRes = await direct('POST', '/organization/cancel-invitation', { invitationId: canceled }, owner.cookie); expect(cancelRes.status, await cancelRes.clone().text()).toBe(200); @@ -334,6 +334,8 @@ describe('#27843 (c) — copy_invitation_link is answered only inside the invite const accepted = (await invite('ada.accepted@acme.test')).body.id as string; const acceptor = await signUp('ada.accepted@acme.test', 'Ada Accepted'); + // Accepting needs a verified address (`invitation-acceptance-verified-address.test.ts`). + (engine.tables.get('sys_user') ?? []).find((u: any) => u.id === acceptor.userId)!.email_verified = true; const acceptRes = await direct('POST', '/organization/accept-invitation', { invitationId: accepted }, acceptor.cookie); expect(acceptRes.status, await acceptRes.clone().text()).toBe(200); expect(invitationRow(accepted).status).toBe('accepted'); diff --git a/packages/plugins/plugin-auth/src/invitation-preview.test.ts b/packages/plugins/plugin-auth/src/invitation-preview.test.ts index c892b97275f..423fc69420d 100644 --- a/packages/plugins/plugin-auth/src/invitation-preview.test.ts +++ b/packages/plugins/plugin-auth/src/invitation-preview.test.ts @@ -206,7 +206,11 @@ describe('#26020 — the signed-out invitation preview', () => { }); it('unknown, expired, accepted, rejected and cancelled ids all answer the identical not-found', async () => { - const { direct, invite, preview, owner, signUp, invitationRow } = await stage(); + const { engine, direct, invite, preview, owner, signUp, invitationRow } = await stage(); + // Accepting or declining needs a verified address (`invitation-acceptance-verified-address.test.ts`). + const verified = (userId: string) => { + (engine.tables.get('sys_user') ?? []).find((u: any) => u.id === userId)!.email_verified = true; + }; const expired = await invite('expired@acme.test'); invitationRow(expired).expires_at = new Date(Date.now() - 60_000); @@ -216,12 +220,14 @@ describe('#26020 — the signed-out invitation preview', () => { const accepted = await invite('accepted@acme.test'); const acceptor = await signUp('accepted@acme.test', 'Acceptor'); + verified(acceptor.userId); const acceptRes = await direct('POST', '/organization/accept-invitation', { invitationId: accepted }, acceptor.cookie); expect(acceptRes.status, await acceptRes.clone().text()).toBe(200); expect(invitationRow(accepted).status).toBe('accepted'); const rejected = await invite('rejected@acme.test'); const rejector = await signUp('rejected@acme.test', 'Rejector'); + verified(rejector.userId); const rejectRes = await direct('POST', '/organization/reject-invitation', { invitationId: rejected }, rejector.cookie); expect(rejectRes.status, await rejectRes.clone().text()).toBe(200); expect(invitationRow(rejected).status).toBe('rejected'); diff --git a/packages/plugins/plugin-auth/src/list-user-invitations-verification.test.ts b/packages/plugins/plugin-auth/src/list-user-invitations-verification.test.ts index 9c897b27a14..3223f9277bf 100644 --- a/packages/plugins/plugin-auth/src/list-user-invitations-verification.test.ts +++ b/packages/plugins/plugin-auth/src/list-user-invitations-verification.test.ts @@ -1,8 +1,10 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // -// [#16569] `GET /organization/list-user-invitations` must honour the declared -// `requireEmailVerificationOnInvitation: false`, exactly as `accept-invitation`, -// `reject-invitation` and `get-invitation` already do. +// [#16569] `GET /organization/list-user-invitations` honours the declared +// `requireEmailVerificationOnInvitation`, exactly as `accept-invitation`, +// `reject-invitation` and `get-invitation` do. The platform declares it +// `true`: a session whose address is not verified can neither list, read, +// accept nor decline an invitation, so the listing never hands it an id. // // These run the REAL better-auth pipeline through a REAL `AuthManager` — the // organization plugin, the audience-gate invitation carve-out, the membership @@ -13,11 +15,6 @@ // invitations may this session see" — this suite pins that the rebuilt route // never widens it (own email only, no client-side `?email=`). // -// The premise the fix rests on is MEASURED here, not quoted: the same -// unverified invitee already gets 200 from accept / reject / get-invitation on -// this deployment shape, so a listing scoped to the session's own email grants -// nothing the deployment has not already granted. -// // ## One fixture fact every inbox assertion has to know // // Fixture users beyond the first enter through the audience gate's invitation @@ -172,9 +169,9 @@ const get = (manager: AuthManager, path: string, cookie?: string) => ); /** - * Sign a user up and return their session cookie + user id. No mailer is wired - * (the deployment shape the declared option exists for), so the account stays - * UNVERIFIED — asserted, because that is the whole population of this suite. + * Sign a user up and return their session cookie + user id. No mailer is wired, + * so the account starts UNVERIFIED — asserted; a case that needs a verified + * session marks it with {@link verify}. */ const signUp = async (manager: AuthManager, engine: MemoryEngine, email: string) => { const invitationId = await inviteForAudienceGate(engine, email); @@ -182,7 +179,7 @@ const signUp = async (manager: AuthManager, engine: MemoryEngine, email: string) expect(res.status, await res.clone().text()).toBe(200); const user = (engine.tables.get('sys_user') ?? []).find((u) => u.email === email); expect(user, `sign-up did not create ${email}`).toBeDefined(); - expect(Boolean(user!.email_verified), `${email} should be unverified (no mailer)`).toBe(false); + expect(Boolean(user!.email_verified), `${email} should start unverified (no mailer)`).toBe(false); return { cookie: cookieFrom(res), userId: String(user!.id) }; }; @@ -228,10 +225,7 @@ const issuedRows = (body: any[]) => body.filter((i) => i.organizationId !== AUDI /** * Bring up a deployment with an owner of BOTH organizations who can issue - * invitations into either. The owner is unverified too (no mailer), which is - * what makes the owner's own `/invite-member` 200s a second reading of the - * premise: invitation-family routes are already open to unverified sessions - * on this shape. + * invitations into either. */ const bootWithOwner = async () => { const engine = createMemoryEngine(); @@ -265,7 +259,14 @@ const bootInbox = async () => { return { engine, manager, owner, b, bDefault, bPartner, cPartner }; }; -describe('#16569 — list-user-invitations honours the declared requireEmailVerificationOnInvitation', () => { +/** Mark a fixture user's address verified, as completing the verification mail does. */ +const verify = (engine: MemoryEngine, userId: string) => { + const user = (engine.tables.get('sys_user') ?? []).find((u) => u.id === userId); + expect(user, `no user ${userId}`).toBeDefined(); + user!.email_verified = true; +}; + +describe('the invitation inbox and its three siblings require a verified address, as the platform declares', () => { beforeEach(() => { vi.spyOn(console, 'info').mockImplementation(() => {}); vi.spyOn(console, 'warn').mockImplementation(() => {}); @@ -275,44 +276,43 @@ describe('#16569 — list-user-invitations honours the declared requireEmailVeri vi.restoreAllMocks(); }); - it('PREMISE (measured, not quoted): the same unverified invitee already gets 200 from accept, reject and get-invitation', async () => { + it('a session whose address is not verified is refused by the listing, accept, reject and get-invitation alike', async () => { const { engine, manager, b, bDefault, bPartner } = await bootInbox(); - - // get-invitation — the vendor reads the option here. - const got = await get(manager, `/organization/get-invitation?id=${bPartner.id}`, b.cookie); - expect(got.status, await got.clone().text()).toBe(200); - - // reject — reads the option. - const rejected = await post( - manager, - '/organization/reject-invitation', - { invitationId: bPartner.id }, - b.cookie, + const refused = async (res: Response, code: string) => { + const text = await res.clone().text(); + expect(res.status, text).toBe(403); + expect((JSON.parse(text) as { code?: unknown }).code).toBe(code); + return text; + }; + + const listed = await refused(await get(manager, LIST_USER_INVITATIONS_PATH, b.cookie), EMAIL_VERIFICATION_REQUIRED_FOR_INVITATION.code); + expect(listed).not.toContain(bDefault.id); + expect(listed).not.toContain(bPartner.id); + await refused( + await get(manager, `/organization/get-invitation?id=${bPartner.id}`, b.cookie), + EMAIL_VERIFICATION_REQUIRED_FOR_INVITATION.code, ); - expect(rejected.status, await rejected.clone().text()).toBe(200); - - // accept — reads the option. Accepting is strictly stronger than listing: - // it writes a membership. - const accepted = await post( - manager, - '/organization/accept-invitation', - { invitationId: bDefault.id }, - b.cookie, + await refused( + await post(manager, '/organization/reject-invitation', { invitationId: bPartner.id }, b.cookie), + 'EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION', + ); + await refused( + await post(manager, '/organization/accept-invitation', { invitationId: bPartner.id }, b.cookie), + 'EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION', ); - expect(accepted.status, await accepted.clone().text()).toBe(200); - expect(membersOf(engine, DEFAULT_ORG, b.userId)).toHaveLength(1); - // Still unverified after all three — the option, not a verification, let - // them through. - const user = (engine.tables.get('sys_user') ?? []).find((u) => u.id === b.userId); - expect(Boolean(user?.email_verified)).toBe(false); + expect(membersOf(engine, PARTNER_ORG, b.userId)).toHaveLength(0); + const statuses = (engine.tables.get('sys_invitation') ?? []) + .filter((i) => i.id === bDefault.id || i.id === bPartner.id) + .map((i) => i.status); + expect(statuses).toEqual(['pending', 'pending']); }); - it('the reported bug: the unverified invitee can LIST the invitations they can already accept', async () => { - const { manager, b, bDefault, bPartner } = await bootInbox(); + it('a verified session lists the invitations addressed to it, and accepts one', async () => { + const { engine, manager, b, bDefault, bPartner } = await bootInbox(); + verify(engine, b.userId); const res = await get(manager, LIST_USER_INVITATIONS_PATH, b.cookie); - // Before the fix: 403 EMAIL_VERIFICATION_REQUIRED_FOR_INVITATION. expect(res.status, await res.clone().text()).toBe(200); const body: any = await res.json(); expect(Array.isArray(body), 'the vendor route answers a bare array').toBe(true); @@ -321,10 +321,15 @@ describe('#16569 — list-user-invitations honours the declared requireEmailVeri expect(inv.email).toBe('b@example.com'); expect(inv.status).toBe('pending'); } + + const accepted = await post(manager, '/organization/accept-invitation', { invitationId: bPartner.id }, b.cookie); + expect(accepted.status, await accepted.clone().text()).toBe(200); + expect(membersOf(engine, PARTNER_ORG, b.userId)).toHaveLength(1); }); it('SCOPE PIN: the listing is the session email\'s own — another user\'s invitation is never visible', async () => { - const { manager, b, cPartner } = await bootInbox(); + const { engine, manager, b, cPartner } = await bootInbox(); + verify(engine, b.userId); const res = await get(manager, LIST_USER_INVITATIONS_PATH, b.cookie); expect(res.status, await res.clone().text()).toBe(200); @@ -337,7 +342,8 @@ describe('#16569 — list-user-invitations honours the declared requireEmailVeri }); it('SCOPE PIN: a client-side `?email=` is still refused with the vendor\'s 400 — no listing by arbitrary address', async () => { - const { manager, b } = await bootInbox(); + const { engine, manager, b } = await bootInbox(); + verify(engine, b.userId); const res = await get( manager, @@ -355,8 +361,9 @@ describe('#16569 — list-user-invitations honours the declared requireEmailVeri expect(res.status, await res.clone().text()).toBe(400); }); - it('only PENDING rows are listed — a rejected invitation drops out, as it does for a verified user', async () => { - const { manager, b, bDefault, bPartner } = await bootInbox(); + it('only PENDING rows are listed — a rejected invitation drops out', async () => { + const { engine, manager, b, bDefault, bPartner } = await bootInbox(); + verify(engine, b.userId); const rejected = await post( manager, @@ -371,32 +378,14 @@ describe('#16569 — list-user-invitations honours the declared requireEmailVeri const body: any[] = await res.json(); expect(issuedRows(body).map((i) => i.id)).toEqual([bDefault.id]); }); - - it('PARITY: the unverified answer is byte-for-byte the VERIFIED answer — the option grants exactly the verified listing, nothing more', async () => { - const { engine, manager, b, bDefault, bPartner } = await bootInbox(); - - const unverified = await get(manager, LIST_USER_INVITATIONS_PATH, b.cookie); - expect(unverified.status, await unverified.clone().text()).toBe(200); - const unverifiedBody: any[] = await unverified.json(); - - const user = (engine.tables.get('sys_user') ?? []).find((u) => u.id === b.userId); - user!.email_verified = true; - - const verified = await get(manager, LIST_USER_INVITATIONS_PATH, b.cookie); - expect(verified.status, await verified.clone().text()).toBe(200); - const verifiedBody: any[] = await verified.json(); - - expect(unverifiedBody).toEqual(verifiedBody); - expect(issuedRows(verifiedBody).map((i) => i.id).sort()).toEqual([bDefault.id, bPartner.id].sort()); - }); }); describe('#16569 — listingRequiresVerifiedEmail honours ONLY the declared option', () => { - it('declared false → not required (the deployment shape the option exists for)', () => { + it('declared false → not required', () => { expect(listingRequiresVerifiedEmail({ requireEmailVerificationOnInvitation: false })).toBe(false); }); - it('declared true → required, exactly as the vendor answers today', () => { + it('declared true → required, as the platform declares it and as the vendor answers', () => { expect(listingRequiresVerifiedEmail({ requireEmailVerificationOnInvitation: true })).toBe(true); }); diff --git a/packages/plugins/plugin-auth/src/presented-invitation.test.ts b/packages/plugins/plugin-auth/src/presented-invitation.test.ts index c26df260b7b..84f607abdfa 100644 --- a/packages/plugins/plugin-auth/src/presented-invitation.test.ts +++ b/packages/plugins/plugin-auth/src/presented-invitation.test.ts @@ -119,6 +119,18 @@ async function rows(engine: ObjectQL, object: string, where: Record>; } +/** + * Mark an address verified, as completing the verification mail does. + * Accepting, reading or listing an invitation needs a verified address + * (`invitation-acceptance-verified-address.test.ts` holds that rule at every + * door); the presented id admits the sign-up only. + */ +async function verifyAddress(engine: ObjectQL, email: string) { + const [user] = await rows(engine, 'sys_user', { email }); + expect(user, `no account for ${email}`).toBeDefined(); + await engine.update('sys_user', { id: user.id, email_verified: true } as never, SYSTEM); +} + /** Status, code and message of a refusal, in either envelope. */ async function verdict(res: Response): Promise<{ status: number; code?: unknown; message?: unknown }> { const body = (await res.clone().json().catch(() => ({}))) as { @@ -152,7 +164,7 @@ async function deployment(config: Record = {}) { } describe('under invite_only, a self-serve sign-up is admitted only by the invitation it presents', () => { - it('admits the sign-up that presents its invitation, and the invitee accepts it with the invited role', async () => { + it('admits the sign-up that presents its invitation, and the invitee, once verified, accepts it with the invited role', async () => { const d = await deployment(); const invitationId = await d.invite(INVITEE, 'admin'); @@ -163,6 +175,7 @@ describe('under invite_only, a self-serve sign-up is admitted only by the invita // The presented id never becomes a column of the account. expect(Object.keys(invitee)).not.toContain(SIGN_UP_INVITATION_ID_FIELD); + await verifyAddress(d.engine, INVITEE); const accept = await send(d.manager, 'POST', '/organization/accept-invitation', { invitationId }, cookieFrom(res)); expect(accept.status, await accept.clone().text()).toBe(200); const members = await rows(d.engine, 'sys_member', { user_id: invitee.id, organization_id: ORG }); @@ -233,7 +246,7 @@ describe('under invite_only, a self-serve sign-up is admitted only by the invita expect(res.status, await res.clone().text()).toBe(200); }); - it('an address-only attempt does not spend the invitation: the invitee still signs up with the link, and accepts', async () => { + it('an address-only attempt does not spend the invitation: the invitee still signs up with the link, and, once verified, accepts', async () => { const d = await deployment(); const invitationId = await d.invite(INVITEE); @@ -243,6 +256,7 @@ describe('under invite_only, a self-serve sign-up is admitted only by the invita const invitee = await signUp(d.manager, INVITEE, { invitationId }); expect(invitee.status, await invitee.clone().text()).toBe(200); + await verifyAddress(d.engine, INVITEE); const accept = await send(d.manager, 'POST', '/organization/accept-invitation', { invitationId }, cookieFrom(invitee)); expect(accept.status, await accept.clone().text()).toBe(200); expect((await rows(d.engine, 'sys_invitation', { id: invitationId }))[0]?.status).toBe('accepted'); @@ -264,7 +278,7 @@ describe('under invite_only, a self-serve sign-up is admitted only by the invita expect(res.status, await res.clone().text()).toBe(200); }); - it('a pending invitation lists in the session it admitted, its own and another organization\'s alike', async () => { + it('a pending invitation lists in the session it admitted once its address is verified, its own and another organization\'s alike', async () => { const d = await deployment(); const invitationId = await d.invite(INVITEE); await d.engine.insert('sys_organization', { id: 'org_partner', name: 'Partner', slug: 'partner' }, SYSTEM); @@ -283,6 +297,7 @@ describe('under invite_only, a self-serve sign-up is admitted only by the invita ); const invitee = await signUp(d.manager, INVITEE, { invitationId }); expect(invitee.status, await invitee.clone().text()).toBe(200); + await verifyAddress(d.engine, INVITEE); const listed = await send(d.manager, 'GET', '/organization/list-user-invitations', undefined, cookieFrom(invitee)); expect(listed.status, await listed.clone().text()).toBe(200); diff --git a/packages/plugins/plugin-auth/src/remove-user-atomicity.test.ts b/packages/plugins/plugin-auth/src/remove-user-atomicity.test.ts index b1c837818ba..b477802de7b 100644 --- a/packages/plugins/plugin-auth/src/remove-user-atomicity.test.ts +++ b/packages/plugins/plugin-auth/src/remove-user-atomicity.test.ts @@ -364,6 +364,8 @@ describe('#7724 — removing a user is one unit of work that can actually comple expect(invitation).toBeDefined(); const invitee = await signUp(manager, engine, 'invitee@example.com'); + // Accepting needs a verified address (`invitation-acceptance-verified-address.test.ts`). + userRow(engine, invitee.userId)!.email_verified = true; const accept = await post( manager, '/organization/accept-invitation', diff --git a/ui/packages/app-shell/src/console/organizations/__tests__/invitationVendorRefusals-33650.test.tsx b/ui/packages/app-shell/src/console/organizations/__tests__/invitationVendorRefusals-33650.test.tsx index d63a037c127..204d4b33492 100644 --- a/ui/packages/app-shell/src/console/organizations/__tests__/invitationVendorRefusals-33650.test.tsx +++ b/ui/packages/app-shell/src/console/organizations/__tests__/invitationVendorRefusals-33650.test.tsx @@ -278,6 +278,57 @@ describe('#33650 face 2 — inviting someone who is already a member', () => { }); }); +describe('an invitation needs a verified email address: the refusal draws the verify-email state', () => { + // better-auth 1.7.12 (`crud-invites.mjs`), verbatim: the two refusals the + // server answers a session whose address is not verified. + const READ_REFUSED_MESSAGE = 'Email verification required to view or list invitations for the session email'; + const READ_REFUSED: Answer = { + status: 403, + body: { code: 'EMAIL_VERIFICATION_REQUIRED_FOR_INVITATION', message: READ_REFUSED_MESSAGE }, + }; + const ACCEPT_OR_DECLINE_REFUSED: Answer = { + status: 403, + body: { + code: 'EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION', + message: 'Email verification required before accepting or rejecting invitation', + }, + }; + + it('a refused invitation read draws the verify-email state, not the vendor\'s English', async () => { + answers.set('/organization/get-invitation', READ_REFUSED); + renderIn('zh', ); + + const state = await screen.findByTestId('accept-invitation-verify-email'); + expect(state).toHaveTextContent(zh.organization.accept.verifyEmailTitle); + expect(state).toHaveTextContent(zh.organization.accept.verifyEmailDescription); + expect(screen.getByTestId('accept-invitation-page')).not.toHaveTextContent(READ_REFUSED_MESSAGE); + }); + + it('a refused accept draws the verify-email state, not a toast', async () => { + answers.set('/organization/get-invitation', { status: 200, body: PENDING }); + answers.set('/organization/accept-invitation', ACCEPT_OR_DECLINE_REFUSED); + renderIn('en', ); + + await screen.findByTestId('accept-invitation-role'); + fireEvent.click(screen.getByText(en.organization.accept.accept)); + const state = await screen.findByTestId('accept-invitation-verify-email'); + expect(state).toHaveTextContent(en.organization.accept.verifyEmailTitle); + expect(toastError).not.toHaveBeenCalled(); + }); + + it('a refused decline draws the verify-email state, not a toast', async () => { + answers.set('/organization/get-invitation', { status: 200, body: PENDING }); + answers.set('/organization/reject-invitation', ACCEPT_OR_DECLINE_REFUSED); + renderIn('en', ); + + await screen.findByTestId('accept-invitation-role'); + fireEvent.click(screen.getByText(en.organization.accept.decline)); + const state = await screen.findByTestId('accept-invitation-verify-email'); + expect(state).toHaveTextContent(en.organization.accept.verifyEmailTitle); + expect(toastError).not.toHaveBeenCalled(); + }); +}); + describe('#33650 — every shipped pack carries the new sentence', () => { it('organization.errors.alreadyMember is a translated string in each pack', () => { const packs = Object.keys(builtInLocales) as Array; 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..12419d55af8 100644 --- a/ui/packages/app-shell/src/console/organizations/manage/AcceptInvitationPage.tsx +++ b/ui/packages/app-shell/src/console/organizations/manage/AcceptInvitationPage.tsx @@ -81,6 +81,19 @@ const readCode = (err: unknown): string | undefined => { return typeof code === 'string' ? code : undefined; }; +/** + * The server's refusals for a session whose email address is not verified: + * accepting, declining, reading or listing an invitation needs a verified + * address (better-auth's own codes). The page answers them with its + * verify-email state. + */ +const UNVERIFIED_ADDRESS_CODES: ReadonlySet = new Set([ + 'EMAIL_VERIFICATION_REQUIRED_FOR_INVITATION', + 'EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION', +]); + +const isUnverifiedAddressRefusal = (err: unknown): boolean => UNVERIFIED_ADDRESS_CODES.has(readCode(err) ?? ''); + export function AcceptInvitationPage() { const { t } = useObjectTranslation(); // Dates and numbers on this surface read the display locale; a bare @@ -125,7 +138,8 @@ export function AcceptInvitationPage() { // Joined through the one-step door: the organization's name to welcome the // visitor to (the door answers no role). const [oneStepJoined, setOneStepJoined] = useState<{ orgName: string } | null>(null); - // The provider session's address is not the invited one, or not verified. + // The session's address is not the invited one, or not verified: the + // one-step door's `verify_email`, or a refusal in UNVERIFIED_ADDRESS_CODES. const [needsVerifiedEmail, setNeedsVerifiedEmail] = useState(false); // The proof leaves the address bar as soon as it has been read. @@ -199,10 +213,14 @@ export function AcceptInvitationPage() { if (!cancelled) setInvitation(inv); }) .catch((err) => { - if (!cancelled) - // objectstack#33650 — the lookup's own not-found answer carries no - // code; read by route, status and the missing code, never the text. - setError(resolveInvitationLookupMessage(err, t)); + if (cancelled) return; + if (isUnverifiedAddressRefusal(err)) { + setNeedsVerifiedEmail(true); + return; + } + // objectstack#33650 — the lookup's own not-found answer carries no + // code; read by route, status and the missing code, never the text. + setError(resolveInvitationLookupMessage(err, t)); }) .finally(() => { if (!cancelled) setIsLoading(false); @@ -220,6 +238,11 @@ export function AcceptInvitationPage() { await switchOrganization(invitation.organizationId).catch(() => null); setJoined(true); } catch (err) { + setIsAccepting(false); + if (isUnverifiedAddressRefusal(err)) { + setNeedsVerifiedEmail(true); + 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( @@ -228,7 +251,6 @@ export function AcceptInvitationPage() { defaultValue: 'Failed to accept invitation', }), ); - setIsAccepting(false); } }; @@ -277,13 +299,17 @@ export function AcceptInvitationPage() { toast.success(t('organization.accept.declined', { defaultValue: 'Invitation declined' })); navigate('/organizations'); } catch (err) { + setIsDeclining(false); + if (isUnverifiedAddressRefusal(err)) { + setNeedsVerifiedEmail(true); + return; + } toast.error( resolveOrgErrorMessage(err, t, { key: 'organization.accept.declineFailed', defaultValue: 'Failed to decline invitation', }), ); - setIsDeclining(false); } }; From 65652db1422b78b4087252a3c067213c6e992af5 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 10:29:07 +0000 Subject: [PATCH 04/13] chore(changeset): name the Console packages the accept page change ships in Claude-Session: https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj Co-authored-by: Claude --- .changeset/invitation-acceptance-verified-address.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.changeset/invitation-acceptance-verified-address.md b/.changeset/invitation-acceptance-verified-address.md index 5503db4f6ce..c79822c8924 100644 --- a/.changeset/invitation-acceptance-verified-address.md +++ b/.changeset/invitation-acceptance-verified-address.md @@ -1,5 +1,7 @@ --- '@objectstack/plugin-auth': patch +'@object-ui/app-shell': patch +'@object-ui/console': patch --- fix(plugin-auth)!: accepting an organization invitation requires a verified email address @@ -14,4 +16,6 @@ Skills-docs: none — no skill under `skills/**` teaches accepting an organizati Unchanged: the invitation mail's own link, which carries a proof of the mailbox and accepts in one step (`POST /api/v1/auth/organization/accept-invitation-one-step`), and that door's signed-in mode, which already asks for a verified address; a verified account, which accepts, declines, reads and lists its invitations as before; sending, resending and cancelling invitations. +The Console's accept-invitation page answers either refusal with its verify-email state, which asks the invitee to verify the address and open the invitation link from the mailbox again. + What to do: an invitee completes the verification mail (`POST /api/v1/auth/send-verification-email`, then the link it carries) before accepting, or opens the invitation mail's own link. On a deployment with no mail transport, a platform administrator adds the person to the organization with the member list's **Add Member** action instead of an invitation. From 9736d090742a87f18c71d96059dff967af10d00b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 10:39:10 +0000 Subject: [PATCH 05/13] test: invitees verify their address before they accept an invitation Claude-Session: https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj Co-authored-by: Claude --- .../src/object-extension-managed-target.wall.test.ts | 5 +++++ .../src/storage-upload-door-ownership.wall.test.ts | 4 ++++ .../test/membership-actor-attribution.dogfood.test.ts | 3 +++ 3 files changed, 12 insertions(+) diff --git a/packages/plugins/organizations/src/object-extension-managed-target.wall.test.ts b/packages/plugins/organizations/src/object-extension-managed-target.wall.test.ts index be66248e82f..e9f91d370c5 100644 --- a/packages/plugins/organizations/src/object-extension-managed-target.wall.test.ts +++ b/packages/plugins/organizations/src/object-extension-managed-target.wall.test.ts @@ -114,6 +114,11 @@ describe('an objectExtensions entry on sys_organization and sys_user, on a boote }), ); expect(invited.status).toBe(200); + // Accepting an invitation needs a verified address; marked in place, as + // completing the verification mail does. + const system = { context: { isSystem: true } }; + const [memberRow] = await ql.find('sys_user', { where: { email: MEMBER_EMAIL }, limit: 1 }, system); + await ql.update('sys_user', { id: memberRow.id, email_verified: true }, system); expect( (await stack.apiAs(member, 'POST', '/auth/organization/accept-invitation', { invitationId: invited.body.id })).status, ).toBe(200); diff --git a/packages/plugins/organizations/src/storage-upload-door-ownership.wall.test.ts b/packages/plugins/organizations/src/storage-upload-door-ownership.wall.test.ts index 5b761594cd4..bbb388a750c 100644 --- a/packages/plugins/organizations/src/storage-upload-door-ownership.wall.test.ts +++ b/packages/plugins/organizations/src/storage-upload-door-ownership.wall.test.ts @@ -197,6 +197,10 @@ describe('the upload doors on a booted organization wall (#22046)', () => { }), ); expect(invited.status).toBe(200); + // Accepting an invitation needs a verified address; marked in place, as + // completing the verification mail does. + const [colleagueRow] = await ql.find('sys_user', { where: { email: COLLEAGUE_EMAIL }, limit: 1 }, SYS); + await ql.update('sys_user', { id: colleagueRow.id, email_verified: true }, SYS); const accepted = await stack.apiAs(colleague, 'POST', '/auth/organization/accept-invitation', { invitationId: invited.body.id, }); diff --git a/packages/qa/dogfood/test/membership-actor-attribution.dogfood.test.ts b/packages/qa/dogfood/test/membership-actor-attribution.dogfood.test.ts index ba00e6ed68a..d3ca9c23409 100644 --- a/packages/qa/dogfood/test/membership-actor-attribution.dogfood.test.ts +++ b/packages/qa/dogfood/test/membership-actor-attribution.dogfood.test.ts @@ -238,6 +238,9 @@ describe('#4586: the better-auth actor reaches sys_member history and the grant' ); expect(invitation).toBeDefined(); + // Accepting an invitation needs a verified address; marked in place, as + // completing the verification mail does. + await ql.update('sys_user', { id: memberUserId, email_verified: true }, { context: SYSTEM_CTX }); const accept = await stack.apiAs(memberToken, 'POST', '/auth/organization/accept-invitation', { invitationId: String(invitation.id), }); From 5c6c591b3578400d57ff99f3ec7998c046b802c6 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 12:24:32 +0000 Subject: [PATCH 06/13] fix(plugin-auth)!: accepting, declining and listing an invitation need a verified address on every deployment; an invitation sign-up joins by accepting once verified Claude-Session: https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj Co-authored-by: Claude --- .../src/auth-manager-membership-admission.ts | 76 ++++- .../src/auth-manager-organization-plugin.ts | 75 +++-- .../src/auth-manager-plugin-list.ts | 2 - .../plugins/plugin-auth/src/auth-manager.ts | 46 ++- .../invitation-accept-verified-email.test.ts | 194 +++++------- .../src/invitation-accept-verified-email.ts | 84 +++--- ...tation-acceptance-verified-address.test.ts | 277 +++++++++++++----- ...list-user-invitations-verification.test.ts | 56 +--- .../src/list-user-invitations-verification.ts | 108 +++---- scripts/check-route-envelope.mjs | 2 +- ...ceptInvitationVerifiedEmail-34272.test.tsx | 31 +- .../invitationVendorRefusals-33650.test.tsx | 51 ---- .../manage/AcceptInvitationPage.tsx | 25 +- .../console/organizations/orgErrorMessage.ts | 13 +- 14 files changed, 580 insertions(+), 460 deletions(-) diff --git a/packages/plugins/plugin-auth/src/auth-manager-membership-admission.ts b/packages/plugins/plugin-auth/src/auth-manager-membership-admission.ts index 97171743e03..bb3442a2011 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-membership-admission.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-membership-admission.ts @@ -85,19 +85,82 @@ export interface MembershipAdmissionHost { getMembershipPolicy: AuthManager['getMembershipPolicy']; hasPendingInvitationFor: AuthManager['hasPendingInvitationFor']; hasPresentedPendingInvitation: AuthManager['hasPresentedPendingInvitation']; + hasStagedInvitationAdmissions: AuthManager['hasStagedInvitationAdmissions']; isBootstrapCreation: AuthManager['isBootstrapCreation']; isOperatorProvisioning: AuthManager['isOperatorProvisioning']; + isStagedInvitationAdmission: AuthManager['isStagedInvitationAdmission']; selfRegistrationSetResolvable: AuthManager['selfRegistrationSetResolvable']; + stageInvitationAdmission: AuthManager['stageInvitationAdmission']; stageOwnerVerifiedStamp: AuthManager['stageOwnerVerifiedStamp']; stageSelfRegistrationGrant: AuthManager['stageSelfRegistrationGrant']; } +/** + * Under `invite_only`, a sign-up admitted by the invitation it PRESENTS is not + * bound into the deployment's organization while its address is unverified. + * + * The presented id is the admission ticket, and nothing more: the accept link + * and a copied link both carry it, so it proves nothing about the invited + * mailbox. Membership comes from accepting the invitation, which needs a + * verified address (`invitation-accept-verified-email.ts`) and writes the role + * the issuer chose, or from a platform administrator's Add Member. + * + * A policy-skip, not a bind deferred to the moment the address is verified: + * - the invitation is the instrument of admission under this posture, and its + * acceptance already writes the membership once the address is verified; a + * second, role-less bind at verification would let a verified person who + * never accepted (or who declined) join the organization by a route no + * issuer chose; + * - ADR-0093 D7 decides membership at creation and nowhere later; a bind + * triggered by an identity update would be a new decision point on every + * path that can write `email_verified` (the verification link, an + * administrator's edit, a provider sign-in, a directory sync). + * + * Answers whether the user `userId` is such a sign-up. Asked only while an + * admission is staged (`stageInvitationAdmission`), so every other creation + * pays one in-memory lookup. A user row that cannot be read while one is + * staged answers yes: the settle then binds nothing, the direction that keeps + * the rule. + */ +async function invitationSignUpAwaitsVerification( + this: Pick, + userId: string, +): Promise { + if (!this.hasStagedInvitationAdmissions()) return false; + const engine = this.config.dataEngine; + if (!engine) return true; + try { + const reader = withSystemReadContext(engine) as unknown as { + find(object: string, query: Record): Promise; + }; + const rows = await reader.find('sys_user', { where: { id: userId }, fields: ['id', 'email', 'email_verified'], limit: 1 }); + const row = (Array.isArray(rows) ? rows[0] : undefined) as { email?: unknown; email_verified?: unknown } | undefined; + if (!row || typeof row.email !== 'string') return true; + return this.isStagedInvitationAdmission(row.email) && !row.email_verified; + } catch { + return true; + } +} + /** The body of `AuthManager#settleMembership`; the method's docblock there is its contract. */ -export async function settleMembership(this: Pick, userId: unknown): Promise { +export async function settleMembership( + this: Pick, + userId: unknown, +): Promise { try { + const id = typeof userId === 'string' && userId ? userId : undefined; + // A sign-up admitted by a presented invitation is not bound while its + // address is unverified ({@link invitationSignUpAwaitsVerification}). + if (id && (await invitationSignUpAwaitsVerification.call(this, id))) { + this.config.logger?.info?.( + '[membership] not bound: a sign-up admitted by the invitation it presents joins by accepting the invitation once its address is verified', + { userId: id }, + ); + return 'policy-skip'; + } const result = await reconcileMembership( this.config.dataEngine, - typeof userId === 'string' && userId ? userId : undefined, + id, { // #5152 — read through the accessor, not `this.config` directly: it is // the single source the backfill path reads too. @@ -120,7 +183,7 @@ export async function settleMembership(this: Pick, + this: Pick, data: { user?: Record; source?: { action?: string; method?: string; oauth?: { providerId?: string }; sso?: { providerId?: string } }; @@ -168,6 +231,7 @@ export async function validateAudienceAdmission( : undefined; let isBootstrap = false; let hasPendingInvitation = false; + let admittedByPresentedInvitation = false; if (creationClass === 'self-serve' || (ssoProvider !== undefined && !ssoProvider.allowJit)) { // Only the gated creations pay for the probes. isBootstrap = await this.isBootstrapCreation(); @@ -183,6 +247,7 @@ export async function validateAudienceAdmission( }); if (proof === 'presented') { hasPendingInvitation = await this.hasPresentedPendingInvitation(presentedInvitationId(ctx), email); + admittedByPresentedInvitation = hasPendingInvitation; } else if (proof === 'address') { hasPendingInvitation = await this.hasPendingInvitationFor(email); } @@ -231,6 +296,11 @@ export async function validateAudienceAdmission( ) { this.stageOwnerVerifiedStamp(email); } + // Admitted by the invitation it presents: the membership settle does not + // bind this sign-up while its address is unverified (`settleMembership`). + if (email && admittedByPresentedInvitation) { + this.stageInvitationAdmission(email); + } if (verdict.grantPermissionSet) { const setName = audience.selfRegistrationPermissionSet; if (!setName) { 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 33b3e7d025f..abdbd7ca3e1 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-organization-plugin.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-organization-plugin.ts @@ -81,12 +81,12 @@ 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 { refuseUnverifiedInvitationAnswer } 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'; import { invitationRoleLabel } from './invitation-role-label.js'; -import { applyDeclaredInvitationVerificationToListing } from './list-user-invitations-verification.js'; +import { requireVerifiedAddressOnListing } from './list-user-invitations-verification.js'; import { resolveMembershipLimitOption } from './membership-limit.js'; import { withSystemContext, withSystemReadContext } from './objectql-adapter.js'; import { isDefaultOrganizationTarget, removeOrganizationAuthStructure } from './organization-delete.js'; @@ -109,7 +109,6 @@ export interface OrganizationPluginHost { getConsolePageUrl: AuthManager['getConsolePageUrl']; getDataEngine: AuthManager['getDataEngine']; getEmailService: AuthManager['getEmailService']; - isEmailDeliveryLive: AuthManager['isEmailDeliveryLive']; multiOrgPostureEffective: AuthManager['multiOrgPostureEffective']; orgRolesMap: AuthManager['orgRolesMap']; resolveMembershipRole: AuthManager['resolveMembershipRole']; @@ -195,14 +194,13 @@ export async function buildOrganizationPlugin(this: OrganizationPluginHost) { // 404 and the section silently breaks. teams: { enabled: true }, // 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. + // together, and is read once, at boot. Declared off here so that + // get-invitation stays open: the accept page names the invitation before + // the person verifies. Accepting and declining still need a verified + // address, on every deployment: `beforeAcceptInvitation` and + // `beforeRejectInvitation` below refuse an unverified session + // (`invitation-accept-verified-email.ts`), and the listing refuses it + // too (`list-user-invitations-verification.ts`). 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 — @@ -431,15 +429,22 @@ 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. + // An unverified session may neither accept nor decline: the address it + // holds was never proven to be the invitee's mailbox. Fired by the + // vendor inside each endpoint, after its recipient and expiry checks + // and before anything is written, with the `session.user` its own + // verification check reads. Asked on every deployment, whatever the + // state of its mail transport. `invitation-accept-verified-email.ts` + // states the rule. beforeAcceptInvitation: async ({ user }: any) => { - await refuseUnverifiedAcceptWhileMailIsLive(user, { - isEmailDeliveryLive: () => this.isEmailDeliveryLive(), + await refuseUnverifiedInvitationAnswer(user, { + verificationRequired: + organizationPlugin?.$ERROR_CODES + ?.EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION, + }); + }, + beforeRejectInvitation: async ({ user }: any) => { + await refuseUnverifiedInvitationAnswer(user, { verificationRequired: organizationPlugin?.$ERROR_CODES ?.EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION, @@ -717,14 +722,12 @@ export async function buildOrganizationPlugin(this: OrganizationPluginHost) { } satisfies OrganizationOptions; const organizationPlugin: any = organization(organizationOptions); - // [#16569] `GET /organization/list-user-invitations` — make the vendor's - // listing honour the `requireEmailVerificationOnInvitation: false` - // declared above, the way `accept-invitation`, `reject-invitation` and - // `get-invitation` already do. better-auth 1.7.2's `listUserInvitations` - // refuses every unverified session UNCONDITIONALLY (it never reads the - // option), so on exactly the no-mailer deployment the declaration exists - // for, an invitee could accept an invitation but never list it and the - // SDK's `organizations.invitations.listMine()` inbox was empty-by-403. + // [#16569] `GET /organization/list-user-invitations` — the listing needs a + // verified address, on every deployment, whatever the option above says: + // a session whose address is not verified is refused, so the listing never + // hands it an invitation's id. better-auth's own `listUserInvitations` + // refuses that session today without reading the option; the rebuild makes + // the rule this plugin's, so no vendor change to that handler can open it. // Rebuilt IN PLACE on this plugin's own endpoints record — the same // shape as `applyPlatformAdminImpersonation` above, for the same reasons // (one owner for the path; every hook keyed on it still fires; the @@ -733,24 +736,20 @@ export async function buildOrganizationPlugin(this: OrganizationPluginHost) { // .listUserInvitations(sessionEmail)`: no second definition of which // rows a session may see. `list-user-invitations-verification.ts` // carries the full reading. - const listingRewired = await applyDeclaredInvitationVerificationToListing( + const listingRewired = await requireVerifiedAddressOnListing( organizationPlugin, organizationOptions, ); if (!listingRewired) { - // The vendor renamed or dropped the endpoint. Say so loudly: the - // route then falls back to the vendor's own handler, which refuses - // every unverified session — an empty inbox, not an open door. - // `warn`, not `error` (AGENTS.md → Degradation log levels): the - // system is VISIBLY smaller — the inbox answers a 403 the caller sees - // — and nothing claims a persistence it did not perform. + // The vendor renamed or dropped the endpoint. Say so loudly: whatever + // the vendor now serves for the inbox does not carry this plugin's rule. + // `warn`, not `error` (AGENTS.md → Degradation log levels): nothing + // claims a persistence it did not perform. console.warn( '[AuthManager] better-auth\'s organization plugin no longer exposes a ' + '`listUserInvitations` endpoint at /organization/list-user-invitations, ' + - 'so the declared `requireEmailVerificationOnInvitation` could NOT be ' + - 'applied to the invitation inbox. Unverified users will be refused ' + - '(403 EMAIL_VERIFICATION_REQUIRED_FOR_INVITATION) until ' + - 'list-user-invitations-verification.ts is updated for the new vendor shape.', + 'so the invitation inbox could NOT be held to a verified address by ' + + 'list-user-invitations-verification.ts; update it for the new vendor shape.', ); } return organizationPlugin; 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 8988d6c2c1e..d85256f8bb9 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-plugin-list.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-plugin-list.ts @@ -123,7 +123,6 @@ export interface PluginListHost { getEmailService: AuthManager['getEmailService']; getMcpResourceUrl: AuthManager['getMcpResourceUrl']; getApi: AuthManager['getApi']; - isEmailDeliveryLive: AuthManager['isEmailDeliveryLive']; isPlatformAdminUserId: AuthManager['isPlatformAdminUserId']; isSsoOnlyMode: AuthManager['isSsoOnlyMode']; jwtSigningFailureReported: AuthManager['jwtSigningFailureReported']; @@ -294,7 +293,6 @@ 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 aed38c019a4..5b769c8095d 100644 --- a/packages/plugins/plugin-auth/src/auth-manager.ts +++ b/packages/plugins/plugin-auth/src/auth-manager.ts @@ -2444,7 +2444,6 @@ 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(); }, @@ -2720,9 +2719,11 @@ export class AuthManager { private settleMembership(userId: unknown): Promise { // [#25224 cut 8] The body moved to `auth-manager-membership-admission.ts` (see `MembershipAdmissionHost`). const readConfig = () => this.config; - const host: Pick = { + const host: Pick = { get config() { return readConfig(); }, getMembershipPolicy: (...a) => this.getMembershipPolicy(...a), + hasStagedInvitationAdmissions: (...a) => this.hasStagedInvitationAdmissions(...a), + isStagedInvitationAdmission: (...a) => this.isStagedInvitationAdmission(...a), }; return settleMembership.call(host, userId); } @@ -2833,6 +2834,19 @@ export class AuthManager { private static readonly OWNER_STAMP_STAGE_TTL_MS = 10 * 60 * 1000; + /** + * Sign-ups the admission gate admitted by the invitation they PRESENT (under + * `invite_only`), staged for the membership settle — same shape and lifetime + * discipline as {@link pendingSelfRegistrationGrants} (keyed by lowercased + * email, pruned by age). Read, never consumed: both settle seams (the first + * session and `user.create.after`) ask it about the same creation and must + * answer alike. `settleMembership` (`auth-manager-membership-admission.ts`) + * states the rule it serves. + */ + private pendingInvitationAdmissions = new Map(); + + private static readonly INVITATION_ADMISSION_STAGE_TTL_MS = 10 * 60 * 1000; + /** * [#14157] Addresses the deployment's OWN boot command is provisioning right * now — see {@link stageOperatorProvisioning} for why this exists and why it @@ -2988,7 +3002,7 @@ export class AuthManager { ): Promise<{ error: string; errorDescription?: string } | undefined> { // [#25224 cut 8] The body moved to `auth-manager-membership-admission.ts` (see `MembershipAdmissionHost`). const readConfig = () => this.config; - const host: Pick = { + const host: Pick = { audienceLogError: (...a) => this.audienceLogError(...a), get config() { return readConfig(); }, enterpriseOAuthProviderIds: (...a) => this.enterpriseOAuthProviderIds(...a), @@ -2998,6 +3012,7 @@ export class AuthManager { isBootstrapCreation: (...a) => this.isBootstrapCreation(...a), isOperatorProvisioning: (...a) => this.isOperatorProvisioning(...a), selfRegistrationSetResolvable: (...a) => this.selfRegistrationSetResolvable(...a), + stageInvitationAdmission: (...a) => this.stageInvitationAdmission(...a), stageOwnerVerifiedStamp: (...a) => this.stageOwnerVerifiedStamp(...a), stageSelfRegistrationGrant: (...a) => this.stageSelfRegistrationGrant(...a), }; @@ -3411,6 +3426,31 @@ export class AuthManager { } } + /** Stage a sign-up the admission gate admitted by the invitation it presents. */ + private stageInvitationAdmission(email: string): void { + this.prunePendingInvitationAdmissions(); + this.pendingInvitationAdmissions.set(email.trim().toLowerCase(), { stagedAtMs: Date.now() }); + } + + /** Is any sign-up admitted by a presented invitation staged now? */ + private hasStagedInvitationAdmissions(): boolean { + this.prunePendingInvitationAdmissions(); + return this.pendingInvitationAdmissions.size > 0; + } + + /** Was the sign-up of this address admitted by the invitation it presented? Not consumed. */ + private isStagedInvitationAdmission(email: string): boolean { + this.prunePendingInvitationAdmissions(); + return this.pendingInvitationAdmissions.has(email.trim().toLowerCase()); + } + + private prunePendingInvitationAdmissions(): void { + const cutoff = Date.now() - AuthManager.INVITATION_ADMISSION_STAGE_TTL_MS; + for (const [key, value] of this.pendingInvitationAdmissions) { + if (value.stagedAtMs < cutoff) this.pendingInvitationAdmissions.delete(key); + } + } + /** * [#14157] Declare that the deployment's own boot command is provisioning * this address right now, so its creation is judged as the **operator** 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 index a87792a38ce..56f065aa36a 100644 --- a/packages/plugins/plugin-auth/src/invitation-accept-verified-email.test.ts +++ b/packages/plugins/plugin-auth/src/invitation-accept-verified-email.test.ts @@ -1,15 +1,16 @@ // 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. +// `POST /organization/accept-invitation` and `POST /organization/reject-invitation` +// refuse a session whose address is not verified, on every deployment; +// `GET /organization/get-invitation` stays open. // // 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. +// `list-user-invitations-verification.test.ts`. Every fixture account starts +// UNVERIFIED (asserted). The door-level matrix over account kinds and mail +// transport states lives in `invitation-acceptance-verified-address.test.ts`; +// this file pins the hooks' order, the bearer path and the function. import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { AuthManager } from './auth-manager'; @@ -18,16 +19,16 @@ import { createMemoryEngine } from './impersonation-bearer-rotation.test'; import { ACCEPT_INVITATION_PATH, EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_INVITATION, - refuseUnverifiedAcceptWhileMailIsLive, + REJECT_INVITATION_PATH, + refuseUnverifiedInvitationAnswer, } 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 PASSWORD = 'S3cure!Passw0rd-verified-answer'; const REFUSAL_CODE = 'EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION'; type MemoryEngine = ReturnType; @@ -98,7 +99,9 @@ const invitationRow = (engine: MemoryEngine, id: string) => /** * 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. + * member). Every account is created unverified. Each invitee's address is + * marked verified where a case says so, as completing the verification mail + * does. */ const boot = async () => { const engine = createMemoryEngine(); @@ -154,8 +157,13 @@ const boot = async () => { const accept = (invitationId: string, as: { cookie?: string; bearer?: string }) => request(manager, 'POST', ACCEPT_INVITATION_PATH, { body: { invitationId }, ...as }); + const decline = (invitationId: string, as: { cookie?: string; bearer?: string }) => + request(manager, 'POST', REJECT_INVITATION_PATH, { body: { invitationId }, ...as }); + const verify = (email: string) => { + userRow(engine, email)!.email_verified = true; + }; - return { engine, manager, mail, owner, b, c, bInvitation, cInvitation, invite, accept }; + return { engine, manager, mail, owner, b, c, bInvitation, cInvitation, invite, accept, decline, verify }; }; /** The refusal's status and body, read once. */ @@ -176,31 +184,18 @@ afterEach(() => { vi.restoreAllMocks(); }); -describe('#34272 — the refusal is the vendor’s own', () => { +describe('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'; - +describe('an unverified session may neither accept nor decline an invitation, and may read it', () => { + it('accept: refused 403 with the vendor’s code, and nothing is written', 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(403); expect(res.body).toMatchObject(EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_INVITATION); @@ -208,64 +203,58 @@ describe('#34272 — while mail is live, an unverified session may not accept', 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 })); + it('decline: refused 403 with the vendor’s code, and the invitation stays pending', async () => { + const { engine, b, bInvitation, decline } = await boot(); + const res = await answerOf(await decline(bInvitation.id, { cookie: b.cookie })); expect(res.status, res.text).toBe(403); - expect(res.body?.code).toBe(REFUSAL_CODE); + expect(res.body).toMatchObject(EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_INVITATION); + expect(invitationRow(engine, bInvitation.id)?.status).toBe('pending'); + }); + + it('a bearer-token session is refused alike at accept and decline', async () => { + const { engine, b, bInvitation, accept, decline } = await boot(); + expect(b.bearer, 'sign-up handed out no bearer token').toBeTruthy(); + for (const answer of [accept, decline]) { + const res = await answerOf(await answer(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); + expect(invitationRow(engine, bInvitation.id)?.status).toBe('pending'); }); - 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); + it('get-invitation stays open to the unverified recipient', async () => { + const { manager, b, bInvitation } = await boot(); + const got = await request(manager, 'GET', `/organization/get-invitation?id=${bInvitation.id}`, { cookie: b.cookie }); + expect(got.status, await got.clone().text()).toBe(200); + expect(((await got.json()) as { id?: unknown }).id).toBe(bInvitation.id); + }); - 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); + it('ORDER PIN: a session that is not the recipient still gets the vendor’s recipient refusal at accept and decline, not this one', async () => { + const { c, bInvitation, accept, decline } = await boot(); + for (const answer of [accept, decline]) { + const res = await answerOf(await answer(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'); + } + }); - const res = await answerOf(await accept(bInvitation.id, { cookie: cookieFrom(signIn) })); + it('CONTROL: once the address is verified, the same session accepts', async () => { + const { engine, b, bInvitation, accept, verify } = await boot(); + expect((await accept(bInvitation.id, { cookie: b.cookie })).status).toBe(403); + verify('b@example.com'); + 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); 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); + it('CONTROL: once the address is verified, the same session declines', async () => { + const { engine, b, bInvitation, decline, verify } = await boot(); + expect((await decline(bInvitation.id, { cookie: b.cookie })).status).toBe(403); + verify('b@example.com'); + const res = await answerOf(await decline(bInvitation.id, { cookie: b.cookie })); + expect(res.status, res.text).toBe(200); expect(invitationRow(engine, bInvitation.id)?.status).toBe('rejected'); }); @@ -295,61 +284,18 @@ describe('#34272 — while mail is live, an unverified session may not accept', }); }); -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(); +describe('refuseUnverifiedInvitationAnswer', () => { + it('a verified user passes', async () => { + await expect(refuseUnverifiedInvitationAnswer({ emailVerified: true })).resolves.toBeUndefined(); }); - it('an unverified (or unknown) user is refused while mail is live, with the entry the caller hands in', async () => { + it('an unverified (or unknown) user is refused, 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 } }); + await expect(refuseUnverifiedInvitationAnswer(user)).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 }, - ), + refuseUnverifiedInvitationAnswer({ emailVerified: false }, { 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 index 9e7b502e790..91438c8c4a1 100644 --- a/packages/plugins/plugin-auth/src/invitation-accept-verified-email.ts +++ b/packages/plugins/plugin-auth/src/invitation-accept-verified-email.ts @@ -1,41 +1,43 @@ // 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. + * Accepting or declining an organization invitation needs a verified email + * address — on every deployment, whether or not it delivers mail. * * ## The rule * - * While mail is live, accepting an invitation needs a verified address, - * because an unverified address is not proof of the invited mailbox. + * The invitation's id is no proof of the invited mailbox: its accept link + * carries it, `copy_invitation_link` answers it and the invitation row holds + * it. What proves the mailbox is a verified address: a password account + * verifies it by the mail round trip, and an account a social or SSO provider + * made counts only when the provider verified it (that is what the vendor + * stores on the account it creates). So: * - * - **While email delivery is live** (`AuthManager.isEmailDeliveryLive`, the - * one reader of `IEmailService.isConfigured()`, read at call time): an - * unverified session is refused, `403 + * - `POST /organization/accept-invitation` and + * `POST /organization/reject-invitation` refuse a session whose address is + * not verified, `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. + * Nothing is written: no membership, and the invitation stays pending. + * - `GET /organization/list-user-invitations` refuses it too + * (`list-user-invitations-verification.ts`), so the listing never hands an + * invitation's id to such a session. + * - `GET /organization/get-invitation` stays open to the recipient, so the + * accept page can name the invitation before the person verifies. + * - The one-step door (`invitation-mailbox-proof.ts`) verifies the address + * with the proof only the invitation mail carries before it accepts, and + * its signed-in mode answers `verify_email` for an unverified session. * - * 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. + * Nothing here reads whether mail is live, so no state of the mail transport + * (live, absent, or one whose liveness cannot be read) relaxes the rule. A + * deployment that cannot deliver the verification mail cannot onboard anyone + * by invitation link; the self-hosting docs name the operator's alternatives. * - * ## Why this seam: the vendor's own `beforeAcceptInvitation` + * ## Why these seams: the vendor's own `beforeAcceptInvitation` and `beforeRejectInvitation` * - * The rule is asked from `organizationHooks.beforeAcceptInvitation`, which - * better-auth 1.7.12 calls inside the accept endpoint + * better-auth 1.7.12 calls both hooks inside its endpoints * (`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. + * not-found / expiry / status and recipient checks and before the invitation + * row or a 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 @@ -48,15 +50,16 @@ * `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. + * - **Not the vendor's option.** `requireEmailVerificationOnInvitation` + * governs accept, reject and get-invitation together, so turning it on + * would close the read the accept page needs. It stays declared `false` + * (`auth-manager-organization-plugin.ts`) and the two hooks carry the rule. * * ## 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 + * its accept and reject routes throw 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 @@ -66,6 +69,9 @@ /** The vendor's path for accepting an invitation by id. */ export const ACCEPT_INVITATION_PATH = '/organization/accept-invitation'; +/** The vendor's path for declining an invitation by id. */ +export const REJECT_INVITATION_PATH = '/organization/reject-invitation'; + /** * better-auth's * `ORGANIZATION_ERROR_CODES.EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION`, @@ -78,23 +84,19 @@ export const EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_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. + * The accept and decline doors' half of the rule: refuse a `user` whose + * address is not verified. The verified test is the vendor's own + * (`!user.emailVerified`), on the user the vendor's endpoint resolved; an + * absent user is refused. * * `verificationRequired` is the plugin's own `$ERROR_CODES` entry when the * caller has it. */ -export async function refuseUnverifiedAcceptWhileMailIsLive( +export async function refuseUnverifiedInvitationAnswer( user: { emailVerified?: unknown } | null | undefined, - deps: { - isEmailDeliveryLive: () => boolean; - verificationRequired?: { code: string; message: string }; - }, + deps: { 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', diff --git a/packages/plugins/plugin-auth/src/invitation-acceptance-verified-address.test.ts b/packages/plugins/plugin-auth/src/invitation-acceptance-verified-address.test.ts index 455ce3610cd..e8dd41df8c0 100644 --- a/packages/plugins/plugin-auth/src/invitation-acceptance-verified-address.test.ts +++ b/packages/plugins/plugin-auth/src/invitation-acceptance-verified-address.test.ts @@ -1,20 +1,23 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * Accepting an organization invitation requires a verified email address. + * Accepting, declining and listing an organization invitation require a + * verified email address, on every deployment; reading one stays open. * * A password account verifies by the mail round trip; an account a social * provider made counts only when the provider verified the address. Holding * the invitation's id, which its accept link and its copied link carry, - * proves nothing about the mailbox. + * proves nothing about the mailbox — and, under `invite_only`, a sign-up + * admitted by the id it presents is not bound into the deployment's + * organization while its address is unverified. * * The real `AuthManager` over a real driver (`@objectstack/driver-sql` on * better-sqlite3 `:memory:`, plugin-auth's own identity objects), driven - * through `AuthManager.handleRequest` at every acceptance door: the vendor's - * `POST /organization/accept-invitation`, its decline, read and listing - * siblings, and the one-step door (`invitation-mailbox-proof.ts`). The - * invitation is into an organization that is not the deployment's default - * one, so a membership in it can only come from an acceptance. + * through `AuthManager.handleRequest` at every door: the vendor's accept, + * decline, read and listing routes, and the one-step door + * (`invitation-mailbox-proof.ts`). Unless a case says otherwise the invitation + * is into an organization that is not the deployment's default one, so a + * membership in it can only come from an acceptance. */ import { describe, it, expect, afterAll, afterEach, beforeEach, vi } from 'vitest'; @@ -38,7 +41,7 @@ const INVITEE = 'invitee@acme.example'; /** The vendor's refusal codes for a session whose address is not verified. */ const ACCEPT_OR_DECLINE_REFUSED = 'EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION'; -const READ_OR_LIST_REFUSED = 'EMAIL_VERIFICATION_REQUIRED_FOR_INVITATION'; +const LIST_REFUSED = 'EMAIL_VERIFICATION_REQUIRED_FOR_INVITATION'; const scrypt = memoizeScrypt(); afterAll(scrypt.restore); @@ -96,7 +99,14 @@ const singleTenancy = () => defaultOrgId: async () => DEFAULT_ORG, }) as never; -function makeManager(engine: ObjectQL, sent: SentMail[], config: Record = {}): AuthManager { +/** + * The deployment's mail transport: `live` (`isConfigured()` true), `log` + * (false), `none` (no email service), `unknown` (a service with no + * `isConfigured`) and `throws` (one whose `isConfigured` throws). + */ +type MailState = 'live' | 'log' | 'none' | 'unknown' | 'throws'; + +function makeManager(engine: ObjectQL, sent: SentMail[], config: Record = {}, mail: MailState = 'live'): AuthManager { const manager = new AuthManager({ secret: SECRET, baseUrl: BASE, @@ -125,13 +135,17 @@ function makeManager(engine: ObjectQL, sent: SentMail[], config: Record true, - sendTemplate: async (input: SentMail) => { - sent.push(input); - return { id: `mail_${sent.length}`, status: 'sent' }; - }, - } as never); + if (mail === 'none') return manager; + const sendTemplate = async (input: SentMail) => { + sent.push(input); + return { id: `mail_${sent.length}`, status: 'sent' }; + }; + const isConfigured = + mail === 'live' ? () => true + : mail === 'log' ? () => false + : mail === 'throws' ? () => { throw new Error('transport state unreadable'); } + : undefined; + manager.setEmailService({ sendTemplate, ...(isConfigured ? { isConfigured } : {}) } as never); return manager; } @@ -163,14 +177,18 @@ async function verdict(res: Response): Promise<{ status: number; code?: unknown } /** - * A deployment whose first account owns the partner organization and has - * invited {@link INVITEE} into it as `admin`. `config` reaches the manager - * that serves every request. + * A deployment whose first account owns the partner organization (and the + * default one) and has invited {@link INVITEE} as `admin` into `into`. + * `config` reaches the manager that serves every request; `mail` is its mail + * transport. */ -async function deployment(config: Record = {}) { +async function deployment( + config: Record = {}, + { mail = 'live', into = PARTNER_ORG }: { mail?: MailState; into?: string } = {}, +) { const engine = await bootEngine(); const sent: SentMail[] = []; - const manager = makeManager(engine, sent, config); + const manager = makeManager(engine, sent, config, mail); const first = await send(manager, 'POST', '/sign-up/email', { email: OWNER, password: PASSWORD, name: 'Owner' }); expect(first.status, `the first account enters without an invitation: ${await first.clone().text()}`).toBe(200); const [owner] = await rows(engine, 'sys_user', { email: OWNER }); @@ -178,6 +196,9 @@ async function deployment(config: Record = {}) { const signIn = await send(manager, 'POST', '/sign-in/email', { email: OWNER, password: PASSWORD }); expect(signIn.status, await signIn.clone().text()).toBe(200); const ownerCookie = cookieFrom(signIn); + const [ownerDefault] = await rows(engine, 'sys_member', { user_id: owner.id, organization_id: DEFAULT_ORG }); + expect(ownerDefault, 'the first account is bound to the default organization').toBeDefined(); + await engine.update('sys_member', { id: ownerDefault.id, role: 'owner' } as never, SYSTEM); await engine.insert( 'sys_member', { id: 'mem_owner_partner', organization_id: PARTNER_ORG, user_id: owner.id, role: 'owner', created_at: new Date() }, @@ -187,18 +208,22 @@ async function deployment(config: Record = {}) { manager, 'POST', '/organization/invite-member', - { email: INVITEE, role: 'admin', organizationId: PARTNER_ORG }, + { email: INVITEE, role: 'admin', organizationId: into }, ownerCookie, ); expect(invited.status, await invited.clone().text()).toBe(200); const invitationId = String(((await invited.json()) as { id: unknown }).id); const invitation = async () => (await rows(engine, 'sys_invitation', { id: invitationId }))[0]; - const partnerMembership = async () => { + const membershipsIn = async (organizationId: string) => { + const [user] = await rows(engine, 'sys_user', { email: INVITEE }); + return user ? rows(engine, 'sys_member', { user_id: user.id, organization_id: organizationId }) : []; + }; + const allMemberships = async () => { const [user] = await rows(engine, 'sys_user', { email: INVITEE }); - return user ? rows(engine, 'sys_member', { user_id: user.id, organization_id: PARTNER_ORG }) : []; + return user ? rows(engine, 'sys_member', { user_id: user.id }) : []; }; const inviteeRow = async () => (await rows(engine, 'sys_user', { email: INVITEE }))[0]; - return { engine, manager, sent, invitationId, invitation, partnerMembership, inviteeRow }; + return { engine, manager, sent, into, invitationId, invitation, membershipsIn, allMemberships, inviteeRow }; } type Deployment = Awaited>; @@ -229,74 +254,114 @@ async function socialSession(d: Deployment, verified: boolean): Promise return cookie; } -/** Every door refuses the session, and the invitation stays pending with no membership written. */ -async function expectEveryDoorRefuses(d: Deployment, cookie: string) { + +/** The answer the one-step door gives a signed-in session (no proof). */ +async function oneStepAnswer(d: Deployment, cookie: string): Promise { + const res = await send(d.manager, 'POST', ACCEPT_INVITATION_ONE_STEP_PATH, { invitationId: d.invitationId }, cookie); + expect(res.status, await res.clone().text()).toBe(200); + return ((await res.json()) as { data: unknown }).data; +} + +/** + * The session is refused at accept, decline and the listing, and the one-step + * door asks it to verify; reading the invitation still answers. The invitation + * stays pending and no membership is written in the invited organization. + */ +async function expectAnswerRefusedReadOpen(d: Deployment, cookie: string) { const accept = await send(d.manager, 'POST', '/organization/accept-invitation', { invitationId: d.invitationId }, cookie); expect(await verdict(accept), await accept.clone().text()).toEqual({ status: 403, code: ACCEPT_OR_DECLINE_REFUSED }); - const oneStep = await send(d.manager, 'POST', ACCEPT_INVITATION_ONE_STEP_PATH, { invitationId: d.invitationId }, cookie); - expect(oneStep.status, await oneStep.clone().text()).toBe(200); - expect(((await oneStep.json()) as { data: unknown }).data).toEqual({ outcome: 'verify_email' }); + expect(await oneStepAnswer(d, cookie)).toEqual({ outcome: 'verify_email' }); const decline = await send(d.manager, 'POST', '/organization/reject-invitation', { invitationId: d.invitationId }, cookie); expect(await verdict(decline), await decline.clone().text()).toEqual({ status: 403, code: ACCEPT_OR_DECLINE_REFUSED }); - const read = await send(d.manager, 'GET', `/organization/get-invitation?id=${d.invitationId}`, undefined, cookie); - expect(await verdict(read), await read.clone().text()).toEqual({ status: 403, code: READ_OR_LIST_REFUSED }); - const list = await send(d.manager, 'GET', '/organization/list-user-invitations', undefined, cookie); const listed = await list.clone().text(); - expect(await verdict(list), listed).toEqual({ status: 403, code: READ_OR_LIST_REFUSED }); + expect(await verdict(list), listed).toEqual({ status: 403, code: LIST_REFUSED }); expect(listed).not.toContain(d.invitationId); + const read = await send(d.manager, 'GET', `/organization/get-invitation?id=${d.invitationId}`, undefined, cookie); + expect(read.status, await read.clone().text()).toBe(200); + expect(((await read.json()) as { id?: unknown }).id).toBe(d.invitationId); + expect((await d.invitation())?.status).toBe('pending'); - expect(await d.partnerMembership()).toEqual([]); + expect(await d.membershipsIn(d.into)).toEqual([]); } -/** The vendor route accepts for the session, with the invited role. */ +/** The listing names the invitation, and the vendor route accepts it with the invited role. */ async function expectAccepted(d: Deployment, cookie: string) { + const list = await send(d.manager, 'GET', '/organization/list-user-invitations', undefined, cookie); + expect(list.status, await list.clone().text()).toBe(200); + expect(((await list.json()) as Array<{ id: unknown }>).map((i) => i.id)).toContain(d.invitationId); + const accept = await send(d.manager, 'POST', '/organization/accept-invitation', { invitationId: d.invitationId }, cookie); expect(accept.status, await accept.clone().text()).toBe(200); expect((await d.invitation())?.status).toBe('accepted'); - expect((await d.partnerMembership()).map((m) => m.role)).toEqual(['admin']); + expect((await d.membershipsIn(d.into)).map((m) => m.role)).toEqual(['admin']); } -describe('accepting an organization invitation requires a verified email address', () => { - it('a password account that never verified its address cannot accept, decline, read or list the invitation at any door', async () => { +/** The vendor route declines it. */ +async function expectDeclined(d: Deployment, cookie: string) { + const decline = await send(d.manager, 'POST', '/organization/reject-invitation', { invitationId: d.invitationId }, cookie); + expect(decline.status, await decline.clone().text()).toBe(200); + expect((await d.invitation())?.status).toBe('rejected'); + expect(await d.membershipsIn(d.into)).toEqual([]); +} + +/** Complete the verification mail round trip for the signed-in invitee. */ +async function verifyByMail(d: Deployment, cookie: string) { + const asked = await send(d.manager, 'POST', '/send-verification-email', { email: INVITEE }, cookie); + expect(asked.status, await asked.clone().text()).toBe(200); + const mail = [...d.sent].reverse().find((m) => m.template === 'auth.verify_email'); + expect(mail, 'the verification mail was sent').toBeDefined(); + const verified = await send(d.manager, 'GET', String(mail!.data.verificationUrl)); + expect(verified.status, await verified.clone().text()).toBeLessThan(400); + expect(Boolean((await d.inviteeRow())?.email_verified)).toBe(true); +} + +const OPEN = { audience: { posture: 'open', selfRegistrationPermissionSet: 'member_default' } }; + +describe('accepting, declining and listing an invitation require a verified email address; reading it does not', () => { + it('a password account that never verified its address is refused at accept, decline and the listing, and can read the invitation', async () => { const d = await deployment(); - await expectEveryDoorRefuses(d, await unverifiedPasswordSession(d)); + await expectAnswerRefusedReadOpen(d, await unverifiedPasswordSession(d)); }); it('a password account accepts once it completes the verification mail round trip', async () => { const d = await deployment(); const cookie = await unverifiedPasswordSession(d); - await expectEveryDoorRefuses(d, cookie); - - const asked = await send(d.manager, 'POST', '/send-verification-email', { email: INVITEE }, cookie); - expect(asked.status, await asked.clone().text()).toBe(200); - const mail = [...d.sent].reverse().find((m) => m.template === 'auth.verify_email'); - expect(mail, 'the verification mail was sent').toBeDefined(); - const verified = await send(d.manager, 'GET', String(mail!.data.verificationUrl)); - expect(verified.status, await verified.clone().text()).toBeLessThan(400); - expect(Boolean((await d.inviteeRow())?.email_verified)).toBe(true); - + await expectAnswerRefusedReadOpen(d, cookie); + await verifyByMail(d, cookie); await expectAccepted(d, cookie); }); - it('an account whose social provider asserted the address unverified cannot accept at any door', async () => { - const d = await deployment({ audience: { posture: 'open', selfRegistrationPermissionSet: 'member_default' } }); - await expectEveryDoorRefuses(d, await socialSession(d, false)); + it('a password account declines once its address is verified', async () => { + const d = await deployment(); + const cookie = await unverifiedPasswordSession(d); + await verifyByMail(d, cookie); + await expectDeclined(d, cookie); + }); + + it('an account whose social provider asserted the address unverified is refused at accept, decline and the listing', async () => { + const d = await deployment(OPEN); + await expectAnswerRefusedReadOpen(d, await socialSession(d, false)); }); it('an account whose social provider verified the address accepts', async () => { - const d = await deployment({ audience: { posture: 'open', selfRegistrationPermissionSet: 'member_default' } }); + const d = await deployment(OPEN); await expectAccepted(d, await socialSession(d, true)); }); + it('an account whose social provider verified the address declines', async () => { + const d = await deployment(OPEN); + await expectDeclined(d, await socialSession(d, true)); + }); + it('the one-step door accepts for a signed-in account only once its address is verified', async () => { - const d = await deployment({ audience: { posture: 'open', selfRegistrationPermissionSet: 'member_default' } }); + const d = await deployment(OPEN); const cookie = await socialSession(d, false); - await expectEveryDoorRefuses(d, cookie); + await expectAnswerRefusedReadOpen(d, cookie); // The provider now asserts the address verified; the next sign-in records it. providerProfile = { sub: 'google-u', email: INVITEE, email_verified: true }; @@ -304,28 +369,106 @@ describe('accepting an organization invitation requires a verified email address expect(again.status, await again.clone().text()).toBe(200); expect(Boolean((await d.inviteeRow())?.email_verified)).toBe(true); - const oneStep = await send(d.manager, 'POST', ACCEPT_INVITATION_ONE_STEP_PATH, { invitationId: d.invitationId }, cookieFrom(again)); - expect(oneStep.status, await oneStep.clone().text()).toBe(200); - expect(((await oneStep.json()) as { data: unknown }).data).toEqual({ outcome: 'accepted', organizationId: PARTNER_ORG }); - expect((await d.partnerMembership()).map((m) => m.role)).toEqual(['admin']); + expect(await oneStepAnswer(d, cookieFrom(again))).toEqual({ outcome: 'accepted', organizationId: PARTNER_ORG }); + expect((await d.membershipsIn(PARTNER_ORG)).map((m) => m.role)).toEqual(['admin']); }); it('the one-step door accepts with the proof the invitation mail carries, which verifies the address', async () => { const d = await deployment(); - const mail = [...d.sent].reverse().find((m) => m.template === 'auth.invitation'); - const link = String(mail?.deliverOnlyData?.acceptUrl ?? ''); - const match = /#proof=([^&]+)$/.exec(link); - expect(match, `the invitation mail's link carries the proof: ${link}`).not.toBeNull(); - const res = await send(d.manager, 'POST', ACCEPT_INVITATION_ONE_STEP_PATH, { invitationId: d.invitationId, - proof: decodeURIComponent(match![1]!), + proof: proofFromMail(d), name: 'Invitee', password: PASSWORD, }); expect(res.status, await res.clone().text()).toBe(200); expect(((await res.json()) as { data: unknown }).data).toEqual({ outcome: 'accepted', organizationId: PARTNER_ORG }); expect(Boolean((await d.inviteeRow())?.email_verified)).toBe(true); - expect((await d.partnerMembership()).map((m) => m.role)).toEqual(['admin']); + expect((await d.membershipsIn(PARTNER_ORG)).map((m) => m.role)).toEqual(['admin']); }); }); + +describe('the rule holds whatever the state of the mail transport', () => { + const states: Array<[MailState, string]> = [ + ['live', 'mail is live'], + ['log', 'the transport only logs'], + ['none', 'no email service is wired'], + ['unknown', 'the email service cannot say whether it delivers'], + ['throws', 'the email service throws when asked whether it delivers'], + ]; + for (const [mail, label] of states) { + it(`${label}: an unverified password account is refused at accept, decline and the listing, and can read the invitation`, async () => { + const d = await deployment({}, { mail }); + await expectAnswerRefusedReadOpen(d, await unverifiedPasswordSession(d)); + }); + + it(`${label}: an unverified social account is refused at accept, decline and the listing`, async () => { + const d = await deployment(OPEN, { mail }); + await expectAnswerRefusedReadOpen(d, await socialSession(d, false)); + }); + + it(`${label}: a verified account accepts`, async () => { + const d = await deployment(OPEN, { mail }); + await expectAccepted(d, await socialSession(d, true)); + }); + } +}); + +describe('under invite_only, a sign-up admitted by the invitation it presents joins only by accepting it once verified', () => { + const sessionOrganization = async (d: Deployment, cookie: string) => { + const res = await d.manager.handleRequest(new Request(`${AUTH}/get-session`, { headers: { cookie } })); + const body = (await res.json().catch(() => null)) as { session?: { activeOrganizationId?: unknown } } | null; + return body?.session?.activeOrganizationId ?? null; + }; + + it('the unverified sign-up holds no membership, not even in the default organization, and its session has no active organization', async () => { + const d = await deployment({}, { into: DEFAULT_ORG }); + const cookie = await unverifiedPasswordSession(d); + expect(await d.allMemberships()).toEqual([]); + expect(await sessionOrganization(d, cookie)).toBeNull(); + await expectAnswerRefusedReadOpen(d, cookie); + expect(await d.allMemberships()).toEqual([]); + }); + + it('verifying the address binds nothing by itself; accepting the invitation then writes its membership with the invited role', async () => { + const d = await deployment({}, { into: DEFAULT_ORG }); + const cookie = await unverifiedPasswordSession(d); + await verifyByMail(d, cookie); + expect(await d.allMemberships()).toEqual([]); + await expectAccepted(d, cookie); + expect((await d.allMemberships()).map((m) => [m.organization_id, m.role])).toEqual([[DEFAULT_ORG, 'admin']]); + }); + + it('the same sign-up with no mail transport holds no membership', async () => { + const d = await deployment({}, { mail: 'none', into: DEFAULT_ORG }); + await unverifiedPasswordSession(d); + expect(await d.allMemberships()).toEqual([]); + }); + + it('CONTROL: a sign-up the invitation mail proof verifies is bound and accepted with the invited role', async () => { + const d = await deployment({}, { into: DEFAULT_ORG }); + const res = await send(d.manager, 'POST', ACCEPT_INVITATION_ONE_STEP_PATH, { + invitationId: d.invitationId, + proof: proofFromMail(d), + name: 'Invitee', + password: PASSWORD, + }); + expect(res.status, await res.clone().text()).toBe(200); + expect((await d.allMemberships()).map((m) => [m.organization_id, m.role])).toEqual([[DEFAULT_ORG, 'admin']]); + }); + + it('CONTROL: the first account of the deployment is still bound to the default organization', async () => { + const d = await deployment({}, { into: DEFAULT_ORG }); + const [owner] = await rows(d.engine, 'sys_user', { email: OWNER }); + expect((await rows(d.engine, 'sys_member', { user_id: owner.id, organization_id: DEFAULT_ORG })).length).toBe(1); + }); +}); + +/** The proof the invitation mail's own link carries. */ +function proofFromMail(d: Deployment): string { + const mail = [...d.sent].reverse().find((m) => m.template === 'auth.invitation'); + const link = String(mail?.deliverOnlyData?.acceptUrl ?? ''); + const match = /#proof=([^&]+)$/.exec(link); + expect(match, `the invitation mail's link carries the proof: ${link}`).not.toBeNull(); + return decodeURIComponent(match![1]!); +} diff --git a/packages/plugins/plugin-auth/src/list-user-invitations-verification.test.ts b/packages/plugins/plugin-auth/src/list-user-invitations-verification.test.ts index 3223f9277bf..16df1777b0b 100644 --- a/packages/plugins/plugin-auth/src/list-user-invitations-verification.test.ts +++ b/packages/plugins/plugin-auth/src/list-user-invitations-verification.test.ts @@ -1,10 +1,9 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // -// [#16569] `GET /organization/list-user-invitations` honours the declared -// `requireEmailVerificationOnInvitation`, exactly as `accept-invitation`, -// `reject-invitation` and `get-invitation` do. The platform declares it -// `true`: a session whose address is not verified can neither list, read, -// accept nor decline an invitation, so the listing never hands it an id. +// [#16569] `GET /organization/list-user-invitations` needs a verified email +// address, on every deployment: a session whose address is not verified is +// refused, as it is at accept and decline, so the listing never hands it an +// invitation's id. `get-invitation` alone stays open to the recipient. // // These run the REAL better-auth pipeline through a REAL `AuthManager` — the // organization plugin, the audience-gate invitation carve-out, the membership @@ -35,8 +34,7 @@ import { inviteForAudienceGate } from './audience-gate-test-support'; import { EMAIL_VERIFICATION_REQUIRED_FOR_INVITATION, LIST_USER_INVITATIONS_PATH, - applyDeclaredInvitationVerificationToListing, - listingRequiresVerifiedEmail, + requireVerifiedAddressOnListing, } from './list-user-invitations-verification'; const SECRET = 'test-secret-at-least-32-chars-long!!'; @@ -266,7 +264,7 @@ const verify = (engine: MemoryEngine, userId: string) => { user!.email_verified = true; }; -describe('the invitation inbox and its three siblings require a verified address, as the platform declares', () => { +describe('the invitation inbox requires a verified address, as accept and decline do; reading an invitation does not', () => { beforeEach(() => { vi.spyOn(console, 'info').mockImplementation(() => {}); vi.spyOn(console, 'warn').mockImplementation(() => {}); @@ -276,7 +274,7 @@ describe('the invitation inbox and its three siblings require a verified address vi.restoreAllMocks(); }); - it('a session whose address is not verified is refused by the listing, accept, reject and get-invitation alike', async () => { + it('a session whose address is not verified is refused by the listing, accept and reject alike, and can read the invitation', async () => { const { engine, manager, b, bDefault, bPartner } = await bootInbox(); const refused = async (res: Response, code: string) => { const text = await res.clone().text(); @@ -288,10 +286,8 @@ describe('the invitation inbox and its three siblings require a verified address const listed = await refused(await get(manager, LIST_USER_INVITATIONS_PATH, b.cookie), EMAIL_VERIFICATION_REQUIRED_FOR_INVITATION.code); expect(listed).not.toContain(bDefault.id); expect(listed).not.toContain(bPartner.id); - await refused( - await get(manager, `/organization/get-invitation?id=${bPartner.id}`, b.cookie), - EMAIL_VERIFICATION_REQUIRED_FOR_INVITATION.code, - ); + const read = await get(manager, `/organization/get-invitation?id=${bPartner.id}`, b.cookie); + expect(read.status, await read.clone().text()).toBe(200); await refused( await post(manager, '/organization/reject-invitation', { invitationId: bPartner.id }, b.cookie), 'EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION', @@ -380,27 +376,7 @@ describe('the invitation inbox and its three siblings require a verified address }); }); -describe('#16569 — listingRequiresVerifiedEmail honours ONLY the declared option', () => { - it('declared false → not required', () => { - expect(listingRequiresVerifiedEmail({ requireEmailVerificationOnInvitation: false })).toBe(false); - }); - - it('declared true → required, as the platform declares it and as the vendor answers', () => { - expect(listingRequiresVerifiedEmail({ requireEmailVerificationOnInvitation: true })).toBe(true); - }); - - it('undeclared → required: the vendor\'s own list-route posture, never a re-derivation of its id-generation heuristic', () => { - expect(listingRequiresVerifiedEmail({})).toBe(true); - expect(listingRequiresVerifiedEmail({ requireEmailVerificationOnInvitation: undefined })).toBe(true); - }); - - it('a non-boolean is not a declaration → required (fail closed)', () => { - expect(listingRequiresVerifiedEmail({ requireEmailVerificationOnInvitation: 'false' as any })).toBe(true); - expect(listingRequiresVerifiedEmail({ requireEmailVerificationOnInvitation: 0 as any })).toBe(true); - }); -}); - -describe('#16569 — the rebuilt endpoint is the vendor\'s contract with one predicate changed', () => { +describe('#16569 — the rebuilt endpoint is the vendor\'s contract, carrying the verified-address rule itself', () => { it('replaces the endpoint IN PLACE, under the vendor\'s key, from the vendor\'s own options object', async () => { const { organization } = await import('better-auth/plugins/organization'); const options = { requireEmailVerificationOnInvitation: false as const }; @@ -409,7 +385,7 @@ describe('#16569 — the rebuilt endpoint is the vendor\'s contract with one pre expect(vendor?.path).toBe(LIST_USER_INVITATIONS_PATH); const keysBefore = Object.keys(plugin.endpoints).sort(); - await expect(applyDeclaredInvitationVerificationToListing(plugin, options)).resolves.toBe(true); + await expect(requireVerifiedAddressOnListing(plugin, options)).resolves.toBe(true); const rebuilt = plugin.endpoints.listUserInvitations; expect(rebuilt).not.toBe(vendor); @@ -431,7 +407,7 @@ describe('#16569 — the rebuilt endpoint is the vendor\'s contract with one pre it('a plugin without the endpoint is left untouched and reported (the vendor-drift door)', async () => { const plugin = { id: 'organization', endpoints: { listInvitations: { path: '/organization/list-invitations', options: {} } } }; - await expect(applyDeclaredInvitationVerificationToListing(plugin, {})).resolves.toBe(false); + await expect(requireVerifiedAddressOnListing(plugin, {})).resolves.toBe(false); expect(Object.keys(plugin.endpoints)).toEqual(['listInvitations']); }); @@ -447,7 +423,7 @@ describe('#16569 — the rebuilt endpoint is the vendor\'s contract with one pre }); // --------------------------------------------------------------------------- -// The vendor still has the defect — the pin that retires this module +// The vendor handler as it stands — the pin that sees an upstream change // --------------------------------------------------------------------------- /** @@ -479,7 +455,7 @@ const require_ = createRequire(join(PKG, 'probe.js')); const VENDOR_DIST = dirname(require_.resolve('better-auth')); const CRUD_INVITES = join(VENDOR_DIST, 'plugins', 'organization', 'routes', 'crud-invites.mjs'); -describe('#16569 — vendor pin: better-auth\'s listUserInvitations still refuses unconditionally', () => { +describe('#16569 — vendor pin: better-auth\'s listUserInvitations refuses unconditionally, and its siblings read the option', () => { const source = readFileSync(CRUD_INVITES, 'utf8'); const start = source.indexOf('const listUserInvitations = '); const listing = start >= 0 ? source.slice(start) : ''; @@ -494,8 +470,8 @@ describe('#16569 — vendor pin: better-auth\'s listUserInvitations still refuse const siblingCalls = source.slice(0, start).match(/shouldRequireVerifiedEmailForInvitationIdAction\(\{/g) ?? []; expect(siblingCalls).toHaveLength(3); // The listing: the unconditional refusal, verbatim. When upstream makes - // this line read the option, this pin goes red and - // `list-user-invitations-verification.ts` is what should be deleted. + // this line read the option, this pin goes red: the rebuild then is what + // keeps the inbox closed under the platform's `false` declaration. expect(listing).toMatch( /if \(session && !session\.user\.emailVerified\) throw APIError\.from\("FORBIDDEN", ORGANIZATION_ERROR_CODES\.EMAIL_VERIFICATION_REQUIRED_FOR_INVITATION\);/, ); diff --git a/packages/plugins/plugin-auth/src/list-user-invitations-verification.ts b/packages/plugins/plugin-auth/src/list-user-invitations-verification.ts index 584fb78f79b..51d3515d056 100644 --- a/packages/plugins/plugin-auth/src/list-user-invitations-verification.ts +++ b/packages/plugins/plugin-auth/src/list-user-invitations-verification.ts @@ -1,39 +1,31 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * [#16569] `GET /organization/list-user-invitations` — honour the DECLARED - * `requireEmailVerificationOnInvitation`, exactly as `accept-invitation`, - * `reject-invitation` and `get-invitation` already do. - * - * ## The defect, and where it is minted - * - * Not here: it comes out of the pinned vendor. Re-measured 2026-10-21 for - * #25096 against better-auth `1.7.12` (unchanged since the `1.7.2` reading), - * `dist/plugins/organization/routes/crud-invites.mjs`: - * the three id-addressed routes ask - * `shouldRequireVerifiedEmailForInvitationIdAction({ organizationOptions, … })`, - * whose first line is - * - * ```js - * if (organizationOptions.requireEmailVerificationOnInvitation !== void 0) - * return organizationOptions.requireEmailVerificationOnInvitation; - * ``` - * - * while `listUserInvitations` never asks — its handler reads - * - * ```js - * if (session && !session.user.emailVerified) - * throw APIError.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.EMAIL_VERIFICATION_REQUIRED_FOR_INVITATION); - * ``` - * - * unconditionally. The platform declares the option `true` - * (`auth-manager-organization-plugin.ts`): accepting an invitation needs a - * verified address, so a session whose address is not verified can neither - * accept, reject, read nor list one, and the listing answers it exactly as - * its three siblings do. `list-user-invitations-verification.test.ts` - * measures the four routes on the real pipeline for the same session, and - * pins that the vendor's listing still never reads the option, so an - * upstream change turns that pin red and this module is what gets deleted. + * [#16569] `GET /organization/list-user-invitations` — the invitation inbox + * needs a verified email address, on every deployment. + * + * ## The rule + * + * A session whose address is not verified is refused, `403 + * EMAIL_VERIFICATION_REQUIRED_FOR_INVITATION`, so the listing never hands an + * invitation's id to an identity that has not proven the invited mailbox. It + * is the listing's half of the rule `invitation-accept-verified-email.ts` + * states for accepting and declining; `get-invitation` alone stays open to the + * recipient, so the accept page can name the invitation. + * + * ## Why the host owns it + * + * The platform declares `requireEmailVerificationOnInvitation: false` + * (`auth-manager-organization-plugin.ts`) so that `get-invitation` stays open: + * better-auth's option governs accept, reject and get-invitation together. + * better-auth 1.7.12's own `listUserInvitations` + * (`dist/plugins/organization/routes/crud-invites.mjs`) never reads that + * option and refuses an unverified session unconditionally — the rule this + * module wants. Rebuilding the endpoint with the refusal written here makes + * the rule this plugin's: no vendor release that teaches its listing to read + * the option can open the inbox under the declaration above. + * `list-user-invitations-verification.test.ts` pins the vendor's handler as + * it stands, so a change upstream is seen. * * ## Why this shape: the endpoint is rebuilt IN PLACE, from the vendor's own options * @@ -68,26 +60,12 @@ * consulted, and a request with neither session nor email is refused with the * vendor's 400 AFTER it. * - * ## What actually changed vs. the vendor handler — ONE predicate + * ## What differs from the vendor handler — nothing a caller can see * - * The verification refusal is asked through {@link listingRequiresVerifiedEmail} - * instead of unconditionally. That predicate honours the DECLARED option only: - * - * - `false` → the listing is open to an unverified session — the declared - * posture, and the one `accept` / `reject` / `get-invitation` already apply - * to the same session on this deployment; - * - `true` → refused, byte-identical to the vendor's answer today; - * - undeclared (or any non-boolean) → refused, the vendor's own list-route - * posture. The siblings derive an undeclared option from - * `hasBuiltInOpaqueInvitationIdGeneration(...)`, a vendor internal this - * module deliberately refuses to re-implement: honouring what is DECLARED - * restores `declared = enforced`; re-deriving an undeclared default would - * be a second definition of a security posture. - * - * Direction, stated: the accept set of this route GROWS only for a session the - * deployment has explicitly declared exempt from verification, and only by the - * rows the same session can already accept one by one. Nothing the vendor - * refuses for any other reason is admitted. + * Today the rebuilt handler answers exactly as the vendor's does: the same + * refusal for an unverified session, at the same point (after the client-side + * `?email=` refusal, before the listing is read). What differs is who owns + * the refusal. * * ## Refusal envelope — the vendor's, on purpose * @@ -123,24 +101,12 @@ export const EMAIL_VERIFICATION_REQUIRED_FOR_INVITATION = { } as const; /** - * Does the listing refuse an UNVERIFIED session? Honours the DECLARED option - * only — see the module header for why an undeclared option is read as the - * vendor's own list-route posture rather than re-derived. - */ -export function listingRequiresVerifiedEmail( - options: Pick, -): boolean { - return options.requireEmailVerificationOnInvitation !== false; -} - -/** - * Replace `organization`'s `/organization/list-user-invitations` with the - * declared-option-honouring endpoint, in place, on the plugin's own - * `endpoints` record. + * Replace `organization`'s `/organization/list-user-invitations` with an + * endpoint that refuses a session whose address is not verified, in place, on + * the plugin's own `endpoints` record. * * `options` MUST be the very object handed to `organization(options)`: it is - * what the vendor's own `getOrgAdapter(ctx.context, options)` reads, and the - * declaration this module honours lives on it. + * what the vendor's own `getOrgAdapter(ctx.context, options)` reads. * * Returns the SAME plugin object (mutated), so the plugin's id, schema, hooks, * `$ERROR_CODES` and every other endpoint stay exactly as the vendor built @@ -150,7 +116,7 @@ export function listingRequiresVerifiedEmail( * and reports `false` — loudly handled by the caller — rather than silently * adding a second endpoint nobody routes to. */ -export async function applyDeclaredInvitationVerificationToListing( +export async function requireVerifiedAddressOnListing( plugin: OrganizationPluginLike, options: OrganizationOptions, ): Promise { @@ -182,8 +148,8 @@ export async function applyDeclaredInvitationVerificationToListing( }); } - // ── THE changed predicate: asked, not assumed ──────────────────────── - if (session && !session.user.emailVerified && listingRequiresVerifiedEmail(options)) { + // ── the rule: an unverified session lists nothing ──────────────────── + if (session && !session.user.emailVerified) { throw APIError.from('FORBIDDEN', verificationRequired); } diff --git a/scripts/check-route-envelope.mjs b/scripts/check-route-envelope.mjs index 5d589c98966..e90677fd739 100644 --- a/scripts/check-route-envelope.mjs +++ b/scripts/check-route-envelope.mjs @@ -1449,7 +1449,7 @@ const PLUGIN_ROUTE_MODULES = { // [#16569] FIRST AUDIT — swept in by the walk, verdict conformant. The module // rebuilds better-auth's `/organization/list-user-invitations` endpoint in place - // so the DECLARED `requireEmailVerificationOnInvitation` is honoured, and it + // so the listing's verified-address rule is plugin-auth's own, and it // BUILDS exactly ONE body: `return ctx.json(pendingInvitations)`. The argument // is an IDENTIFIER, so the counters read it as relayed — the same deliberate // blindness `inbound-rate-limit.ts` sits behind on surface 4 — and what it names 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 index 503021e5a12..f74e4ae90f5 100644 --- 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 @@ -1,11 +1,13 @@ // 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 + * Accepting or declining an invitation needs a verified email address: the + * server refuses either 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. + * account's address, whose link returns here, instead of a toast. Reading the + * invitation stays open, so the page still names it. * * The auth client is the REAL `createAuthClient` over a stubbed `fetch` that * answers with the server's body, as `invitationVendorRefusals-33650.test.tsx` @@ -115,7 +117,7 @@ beforeEach(() => { afterEach(() => cleanup()); -describe('#34272 — an accept refused for an unverified address goes to the verification mail', () => { +describe('an accept or a decline 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); @@ -139,6 +141,27 @@ describe('#34272 — an accept refused for an unverified address goes to the ver ).toBe(true); }); + it('a refused decline hands over to /verify-email-prompt alike, with no toast', async () => { + answers.set('/organization/get-invitation', { status: 200, body: PENDING }); + answers.set('/organization/reject-invitation', NEEDS_VERIFIED_EMAIL); + renderPage(); + + await screen.findByTestId('accept-invitation-role'); + fireEvent.click(screen.getByText(en.organization.accept.decline)); + + 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( + fetchFn.mock.calls.some(([u]) => String(u instanceof Request ? u.url : u).includes('/organization/reject-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', { diff --git a/ui/packages/app-shell/src/console/organizations/__tests__/invitationVendorRefusals-33650.test.tsx b/ui/packages/app-shell/src/console/organizations/__tests__/invitationVendorRefusals-33650.test.tsx index 204d4b33492..d63a037c127 100644 --- a/ui/packages/app-shell/src/console/organizations/__tests__/invitationVendorRefusals-33650.test.tsx +++ b/ui/packages/app-shell/src/console/organizations/__tests__/invitationVendorRefusals-33650.test.tsx @@ -278,57 +278,6 @@ describe('#33650 face 2 — inviting someone who is already a member', () => { }); }); -describe('an invitation needs a verified email address: the refusal draws the verify-email state', () => { - // better-auth 1.7.12 (`crud-invites.mjs`), verbatim: the two refusals the - // server answers a session whose address is not verified. - const READ_REFUSED_MESSAGE = 'Email verification required to view or list invitations for the session email'; - const READ_REFUSED: Answer = { - status: 403, - body: { code: 'EMAIL_VERIFICATION_REQUIRED_FOR_INVITATION', message: READ_REFUSED_MESSAGE }, - }; - const ACCEPT_OR_DECLINE_REFUSED: Answer = { - status: 403, - body: { - code: 'EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION', - message: 'Email verification required before accepting or rejecting invitation', - }, - }; - - it('a refused invitation read draws the verify-email state, not the vendor\'s English', async () => { - answers.set('/organization/get-invitation', READ_REFUSED); - renderIn('zh', ); - - const state = await screen.findByTestId('accept-invitation-verify-email'); - expect(state).toHaveTextContent(zh.organization.accept.verifyEmailTitle); - expect(state).toHaveTextContent(zh.organization.accept.verifyEmailDescription); - expect(screen.getByTestId('accept-invitation-page')).not.toHaveTextContent(READ_REFUSED_MESSAGE); - }); - - it('a refused accept draws the verify-email state, not a toast', async () => { - answers.set('/organization/get-invitation', { status: 200, body: PENDING }); - answers.set('/organization/accept-invitation', ACCEPT_OR_DECLINE_REFUSED); - renderIn('en', ); - - await screen.findByTestId('accept-invitation-role'); - fireEvent.click(screen.getByText(en.organization.accept.accept)); - const state = await screen.findByTestId('accept-invitation-verify-email'); - expect(state).toHaveTextContent(en.organization.accept.verifyEmailTitle); - expect(toastError).not.toHaveBeenCalled(); - }); - - it('a refused decline draws the verify-email state, not a toast', async () => { - answers.set('/organization/get-invitation', { status: 200, body: PENDING }); - answers.set('/organization/reject-invitation', ACCEPT_OR_DECLINE_REFUSED); - renderIn('en', ); - - await screen.findByTestId('accept-invitation-role'); - fireEvent.click(screen.getByText(en.organization.accept.decline)); - const state = await screen.findByTestId('accept-invitation-verify-email'); - expect(state).toHaveTextContent(en.organization.accept.verifyEmailTitle); - expect(toastError).not.toHaveBeenCalled(); - }); -}); - describe('#33650 — every shipped pack carries the new sentence', () => { it('organization.errors.alreadyMember is a translated string in each pack', () => { const packs = Object.keys(builtInLocales) as Array; 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 a1d0ae319d0..97e500e39c1 100644 --- a/ui/packages/app-shell/src/console/organizations/manage/AcceptInvitationPage.tsx +++ b/ui/packages/app-shell/src/console/organizations/manage/AcceptInvitationPage.tsx @@ -217,6 +217,15 @@ export function AcceptInvitationPage() { }; }, [invitationId, isAuthenticated, getInvitation, t]); + // The verification-mail screen for this account's address, whose link + // brings the person back to this page to answer the invitation. + const toVerifyEmailPrompt = () => { + 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()}`); + }; + const handleAccept = async () => { if (!invitation || !invitationId) return; setIsAccepting(true); @@ -225,15 +234,10 @@ 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. + // 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. 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()}`); + toVerifyEmailPrompt(); return; } // objectui#4474 — the card's site 5: a wrong recipient produced better-auth's @@ -293,6 +297,11 @@ export function AcceptInvitationPage() { toast.success(t('organization.accept.declined', { defaultValue: 'Invitation declined' })); navigate('/organizations'); } catch (err) { + // Declining needs a verified address too: the same hand-over as accept. + if (isAcceptNeedsVerifiedEmail(err)) { + toVerifyEmailPrompt(); + return; + } toast.error( resolveOrgErrorMessage(err, t, { key: 'organization.accept.declineFailed', diff --git a/ui/packages/app-shell/src/console/organizations/orgErrorMessage.ts b/ui/packages/app-shell/src/console/organizations/orgErrorMessage.ts index cc660f4cd65..6c4aa76d827 100644 --- a/ui/packages/app-shell/src/console/organizations/orgErrorMessage.ts +++ b/ui/packages/app-shell/src/console/organizations/orgErrorMessage.ts @@ -178,18 +178,17 @@ function errorCode(err: unknown): string | 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. + * better-auth's code for an accept or a decline refused because the session's + * address is not verified. objectstack answers it on every deployment + * (plugin-auth `invitation-accept-verified-email.ts`). */ 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. + * Was this rejection an accept or a decline 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; From 42edc8b5d4c2312172cf4260119fa3860b7757c0 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 12:43:55 +0000 Subject: [PATCH 07/13] fix(plugin-auth)!: fixtures mint members through the operator door; docs and changeset state the verified-address rule Claude-Session: https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj Co-authored-by: Claude --- .../invitation-acceptance-verified-address.md | 21 +++++--- content/docs/deployment/self-hosting.mdx | 54 +++++++++++-------- docs/qa/platform-checklist/RUNNER.md | 39 ++++++-------- ...accept-invitation-adopt-membership.test.ts | 14 +++-- .../src/audience-gate-test-support.ts | 25 +++++++++ .../plugin-auth/src/cloud-managed.test.ts | 10 ++-- .../plugin-auth/src/presented-invitation.ts | 9 ++++ .../src/remove-user-atomicity.test.ts | 12 +++-- packages/verify/src/harness.ts | 44 ++++++++++++--- 9 files changed, 156 insertions(+), 72 deletions(-) diff --git a/.changeset/invitation-acceptance-verified-address.md b/.changeset/invitation-acceptance-verified-address.md index c79822c8924..69ccdbf1844 100644 --- a/.changeset/invitation-acceptance-verified-address.md +++ b/.changeset/invitation-acceptance-verified-address.md @@ -4,18 +4,23 @@ '@object-ui/console': patch --- -fix(plugin-auth)!: accepting an organization invitation requires a verified email address +fix(plugin-auth)!: accepting, declining and listing an organization invitation need a verified email address on every deployment, and an invitation sign-up joins by accepting once verified -Clause-②: yes (narrowing) — narrowed: `POST /api/v1/auth/organization/accept-invitation` and `POST /api/v1/auth/organization/reject-invitation` answer `403 EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION` to a session whose email address is not verified, and `GET /api/v1/auth/organization/get-invitation` and `GET /api/v1/auth/organization/list-user-invitations` answer it `403 EMAIL_VERIFICATION_REQUIRED_FOR_INVITATION`; nothing is accepted or declined and no membership is written. The codes are better-auth's own. The `sys_invitation` actions **Accept Invitation** and **Decline Invitation** post to those routes and answer the same. The boot warning for the `open` posture with verification declared off says that an invitation to an unverified address waits for the address to be verified. +Clause-②: no (narrowing) — narrowed: from a session whose email address is not verified, `POST /api/v1/auth/organization/accept-invitation` and `POST /api/v1/auth/organization/reject-invitation` answer `403 EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION` and `GET /api/v1/auth/organization/list-user-invitations` answers `403 EMAIL_VERIFICATION_REQUIRED_FOR_INVITATION`, on every deployment, whatever the state of its mail transport; nothing is accepted or declined and no membership is written. Under the `invite_only` posture with `membershipPolicy: 'auto'`, a sign-up admitted by the invitation it presents is no longer bound to the Default Organization while its address is unverified; it joins by accepting the invitation. The codes are better-auth's own. The `sys_invitation` actions **Accept Invitation** and **Decline Invitation** post to those routes and answer the same. Metadata-protocol: none -Skills-docs: none — no skill under `skills/**` teaches accepting an organization invitation; `content/docs/deployment/self-hosting.mdx` gains the rule in this change. +Skills-docs: none — no skill under `skills/**` teaches accepting an organization invitation or invitation sign-up; `content/docs/deployment/self-hosting.mdx` gains the rules in this change. - + -**BREAKING** for a deployment whose invitees sign in with an address that is not verified: email verification off (the default under the `invite_only` posture, or declared off under `open`), or a social or SSO provider that does not verify the address. Accepting an organization invitation requires a verified email address. A password account verifies by the verification mail; an account a social or SSO provider made counts only when the provider verified the address. The invitation's id, which its accept link and a copied link carry, is no proof of the mailbox. No setting relaxes the rule. +**BREAKING** for a deployment whose people answer invitations with an address that is not verified: email verification off (the default under `invite_only`, or declared off under `open`), no live mail transport, or a social or SSO provider that does not verify the address. -Unchanged: the invitation mail's own link, which carries a proof of the mailbox and accepts in one step (`POST /api/v1/auth/organization/accept-invitation-one-step`), and that door's signed-in mode, which already asks for a verified address; a verified account, which accepts, declines, reads and lists its invitations as before; sending, resending and cancelling invitations. +- Accepting, declining and listing an organization invitation require a verified email address, on every deployment. A password account verifies by the verification mail; an account a social or SSO provider made counts only when the provider verified the address. The invitation's id, which its accept link and a copied link carry, is no proof of the mailbox, and no setting relaxes the rule. +- Reading one invitation by its id (`GET /api/v1/auth/organization/get-invitation`) stays open, so the accept page can show it. +- Under `invite_only` with `membershipPolicy: 'auto'`, an account a sign-up admitted by the invitation it presents is not bound to the Default Organization while its address is unverified. Its membership comes from accepting the invitation once the address is verified, with the role the invitation carries, or from a platform administrator. +- A deployment without a live mail transport cannot onboard anyone by invitation link. -The Console's accept-invitation page answers either refusal with its verify-email state, which asks the invitee to verify the address and open the invitation link from the mailbox again. +Unchanged: the invitation mail's own link, which carries a proof of the mailbox and accepts in one step (`POST /api/v1/auth/organization/accept-invitation-one-step`); a verified account, which accepts, declines and lists its invitations as before; the first account of a deployment, accounts an administrator creates and accounts a boot command provisions, which are bound as before; sending, resending and cancelling invitations. -What to do: an invitee completes the verification mail (`POST /api/v1/auth/send-verification-email`, then the link it carries) before accepting, or opens the invitation mail's own link. On a deployment with no mail transport, a platform administrator adds the person to the organization with the member list's **Add Member** action instead of an invitation. +The Console's accept-invitation page answers a refused accept or decline with the verification-mail screen for the account's address, whose link brings the person back to answer the invitation. + +What to do: an invitee completes the verification mail (`POST /api/v1/auth/send-verification-email`, then the link it carries) before answering, or opens the invitation mail's own link. On a deployment with no live mail transport, a platform administrator creates the account (`POST /api/v1/auth/admin/create-user`) or attaches an account that already exists with the member list's **Add Member** action, which is open to platform administrators only and attaches existing accounts only. diff --git a/content/docs/deployment/self-hosting.mdx b/content/docs/deployment/self-hosting.mdx index c2078f5f997..fd6b7cd6c25 100644 --- a/content/docs/deployment/self-hosting.mdx +++ b/content/docs/deployment/self-hosting.mdx @@ -755,26 +755,38 @@ presents.** The sign-up sends the invitation's `id`, the last segment of its `/accept-invitation/` link, as `invitationId` beside the email: the Console's register page does this for an invitee who arrived from the link, and `os register --invitation` does it from a terminal. An address alone gets the -same `403 SELF_REGISTRATION_CLOSED` as an address nobody invited. The link -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. 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. +same `403 SELF_REGISTRATION_CLOSED` as an address nobody invited. The first +account of a new deployment needs no invitation. Admission is all the +invitation's `id` grants: the account it admits joins no organization until it +accepts the invitation, and accepting needs a verified address. + +**Accepting, declining and listing an invitation need a verified email +address, on every deployment.** The invitation's `id`, which its link carries, +proves nothing about the mailbox. From a session whose address is not +verified, `POST /api/v1/auth/organization/accept-invitation` and +`POST /api/v1/auth/organization/reject-invitation` answer `403 +EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION` and write +nothing, and `GET /api/v1/auth/organization/list-user-invitations` answers `403 +EMAIL_VERIFICATION_REQUIRED_FOR_INVITATION`. Reading one invitation by its id +(`get-invitation`) stays open, so the accept page can show it. A password +account verifies through the verification mail; an account a social or SSO +sign-in made counts only when its provider verified the address. The Console's +accept page sends an unverified person to the verification-mail screen, and +the link in that mail brings them back to accept. A visitor who is not signed +in and opens the 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. No setting relaxes this rule. + +**A deployment without a live mail transport cannot onboard anyone by +invitation link.** With no transport configured, or the log transport, no +verification mail and no invitation mail reaches anyone, so no invitee can +verify an address or accept; a link handed over with the invitation's **Copy +Invite Link** action admits the sign-up and nothing more. To bring a person in +there, a platform administrator creates the account +(`POST /api/v1/auth/admin/create-user`), or attaches an account that already +exists with the member list's **Add Member** action. Add Member is open to +platform administrators only, and it attaches existing accounts only: it +creates no account and sends no invitation. **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 @@ -831,7 +843,7 @@ has a cost: `/api/v1/auth/config` reports `requireEmailVerification: false` — the value actually wired. - Anyone can register an address they do not control. An organization - invitation sent to that address can then be accepted by that account. + invitation sent to that address still waits for the address to be verified. - It is the deployment's to declare. A `false` stored only through the settings console is refused under `open`, and verification stays on. diff --git a/docs/qa/platform-checklist/RUNNER.md b/docs/qa/platform-checklist/RUNNER.md index 20e6a4ea969..dec92df6305 100644 --- a/docs/qa/platform-checklist/RUNNER.md +++ b/docs/qa/platform-checklist/RUNNER.md @@ -586,28 +586,23 @@ contradicts it, and correct it here when it does. unexpired and addressed to that email (`packages/plugins/plugin-auth/src/presented-invitation.ts`); the address alone answers the same 403. - ⚠️ **The sign-up does not apply the invitation's role.** It binds the new user to the - Default Organization as `member` whatever role was invited, and leaves the invitation - `pending` (`reconcileMembership` in - `packages/plugins/plugin-auth/src/reconcile-membership.ts` writes `role: 'member'`). For - any other role (`admin`, `owner`), the persona — signed in as itself — then sends - `POST /api/v1/auth/organization/accept-invitation` with `{"invitationId": "ID"}` (the - `id` the invite-member call answered, or the row its own - `GET /api/v1/auth/organization/list-user-invitations` lists). Acceptance writes the - invitation's role onto that membership and the invitation reads `accepted` - (`adoptExistingMembership` in `packages/plugins/plugin-auth/src/adopt-membership.ts`, - which never lowers a grade; pinned by `accept-invitation-adopt-membership.test.ts` - beside it, 6 passed at `bfc1539fe0`). The invitee's email must be verified before the - accept: the deployment declares `requireEmailVerificationOnInvitation: true` - (`auth-manager-organization-plugin.ts`), so an unverified persona's accept, decline, - `get-invitation` and listing answer `403` - (`EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION`, - `EMAIL_VERIFICATION_REQUIRED_FOR_INVITATION`). Verify the persona first through the - verification mail (`POST /api/v1/auth/send-verification-email`, then open its link). - QA run #24616 met the role half: an `admin` invitation signed up as `member`, and the - persona held `org_admin` only after the accept. **Check:** read the persona's - `sys_member` row (`role`) before scoring a role-gated clause, never the invitation you - sent. + ⚠️ **The sign-up joins no organization.** A sign-up admitted by the invitation it + presents is not bound to the Default Organization while its address is unverified + (`settleMembership` in `packages/plugins/plugin-auth/src/auth-manager-membership-admission.ts`), + and the invitation stays `pending`. The persona joins by accepting it, and accepting, + declining and listing need a verified address on every deployment + (`packages/plugins/plugin-auth/src/invitation-accept-verified-email.ts`): an unverified + persona's accept and decline answer `403 + EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION`, its + `list-user-invitations` answers `403 EMAIL_VERIFICATION_REQUIRED_FOR_INVITATION`, and + `get-invitation` answers. So verify the persona first through the verification mail + (`POST /api/v1/auth/send-verification-email`, then open its link; the mail transport has to + be live), then, signed in as itself, send + `POST /api/v1/auth/organization/accept-invitation` with `{"invitationId": "ID"}` (the `id` + the invite-member call answered). Acceptance writes the membership with the invitation's + role and the invitation reads `accepted`. Without a live mail transport this door mints no + member: use door 2. **Check:** read the persona's `sys_member` row (`role`) before scoring a + role-gated clause, never the invitation you sent. 2. **Admin create.** `POST /api/v1/auth/admin/create-user`, which answers `mustChangePassword: true` by default (`packages/plugins/plugin-auth/src/admin-user-endpoints.ts`, `runAdminCreateUser`); diff --git a/packages/plugins/plugin-auth/src/accept-invitation-adopt-membership.test.ts b/packages/plugins/plugin-auth/src/accept-invitation-adopt-membership.test.ts index 80563b8cd10..ac09fd78494 100644 --- a/packages/plugins/plugin-auth/src/accept-invitation-adopt-membership.test.ts +++ b/packages/plugins/plugin-auth/src/accept-invitation-adopt-membership.test.ts @@ -23,7 +23,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate } from '@objectstack/objectql'; import { AuthManager } from './auth-manager'; -import { inviteForAudienceGate } from './audience-gate-test-support'; +import { operatorProvisioningField } from './audience-gate-test-support'; const SECRET = 'test-secret-at-least-32-chars-long!!'; const BASE = 'http://localhost:3000'; @@ -180,10 +180,14 @@ const post = (manager: AuthManager, path: string, body: unknown, cookie?: string /** Sign a user up and return their session cookie + user id. */ const signUp = async (manager: AuthManager, engine: MemoryEngine, email: string) => { - // [#11739] default posture invite_only: fixture users beyond the first - // enter through the invitation carve-out (see audience-gate-test-support). - const invitationId = await inviteForAudienceGate(engine, email); - const res = await post(manager, '/sign-up/email', { email, password: PASSWORD, name: email, invitationId }); + // [#11739] default posture invite_only: fixture users beyond the first are + // members bound at creation — the auto-bound invitee this suite is about — + // so they enter through the operator door (`operatorProvisioningField`, + // audience-gate-test-support). A sign-up admitted by the invitation it + // presents joins no organization until it accepts. + const res = await post(manager, '/sign-up/email', { + email, password: PASSWORD, name: email, ...operatorProvisioningField(manager, email), + }); expect(res.status, await res.clone().text()).toBe(200); const user = (engine.tables.get('sys_user') ?? []).find((u) => u.email === email); expect(user, `sign-up did not create ${email}`).toBeDefined(); diff --git a/packages/plugins/plugin-auth/src/audience-gate-test-support.ts b/packages/plugins/plugin-auth/src/audience-gate-test-support.ts index d915679e04e..a2538d8a5ce 100644 --- a/packages/plugins/plugin-auth/src/audience-gate-test-support.ts +++ b/packages/plugins/plugin-auth/src/audience-gate-test-support.ts @@ -94,3 +94,28 @@ function resolveInsertEngine( if (typeof viaManager?.insert === 'function') return viaManager; return null; } + +/** + * The sign-up body field that admits a fixture account as one the + * deployment's own boot command provisions (the operator class), for a suite + * whose fixture needs a MEMBER rather than an invitee. + * + * A sign-up admitted by the invitation it presents is not bound into the + * deployment's organization while its address is unverified: it joins by + * accepting the invitation once verified (`settleMembership`, + * `auth-manager-membership-admission.ts`). A suite whose subject is not that + * path, and whose fixture user must already hold the Default Organization + * membership the reconciler writes at creation, enters through the operator + * door instead, which binds at creation like an account an administrator + * creates. `manager` is the `AuthManager` that will serve the sign-up; the + * ticket is staged on it for exactly this address. + */ +export function operatorProvisioningField( + manager: { stageOperatorProvisioning(email: string): string }, + email: string, +): Record { + return { [OPERATOR_PROVISIONING_TICKET_FIELD]: manager.stageOperatorProvisioning(email) }; +} + +/** `AuthManager.OPERATOR_PROVISIONING_TICKET_FIELD`, restated so this module imports nothing from the manager. */ +const OPERATOR_PROVISIONING_TICKET_FIELD = '__osOperatorProvisioningTicket'; diff --git a/packages/plugins/plugin-auth/src/cloud-managed.test.ts b/packages/plugins/plugin-auth/src/cloud-managed.test.ts index 492155250da..f41e1c9cf4f 100644 --- a/packages/plugins/plugin-auth/src/cloud-managed.test.ts +++ b/packages/plugins/plugin-auth/src/cloud-managed.test.ts @@ -31,7 +31,7 @@ import { assertAudienceConfig, decideAudienceAdmission, resolveAudience } from ' import { CLOUD_MANAGED_REFUSAL_MESSAGES } from './cloud-managed'; import { SSO_ONLY_REFUSAL_MESSAGES } from './sso-only-local-password'; import { createMemoryEngine } from './impersonation-bearer-rotation.test'; -import { inviteForAudienceGate } from './audience-gate-test-support'; +import { inviteForAudienceGate, operatorProvisioningField } from './audience-gate-test-support'; const SECRET = 'test-secret-at-least-32-chars-long!!'; const PASSWORD = 'S3cure!Passw0rd-25083'; @@ -154,9 +154,13 @@ async function produceStagedRows() { member: 'member.25083@example.com', idp: 'idp.25083@example.com', } as const; + // Members bound at creation: the operator door (`operatorProvisioningField`), + // since a sign-up admitted by the invitation it presents joins no + // organization until it accepts. for (const email of Object.values(emails)) { - const invitationId = await inviteForAudienceGate(manager, email); - const res = await direct('/sign-up/email', { email, password: PASSWORD, name: email, invitationId }); + const res = await direct('/sign-up/email', { + email, password: PASSWORD, name: email, ...operatorProvisioningField(manager, email), + }); expect(res.status, `sign-up ${email}: ${await res.clone().text()}`).toBe(200); } diff --git a/packages/plugins/plugin-auth/src/presented-invitation.ts b/packages/plugins/plugin-auth/src/presented-invitation.ts index a49f9a8f98d..e93ca2043d8 100644 --- a/packages/plugins/plugin-auth/src/presented-invitation.ts +++ b/packages/plugins/plugin-auth/src/presented-invitation.ts @@ -41,6 +41,15 @@ * An invitation id is the vendor's `generateId()` (plugin-auth configures no * id generator of its own): 32 characters of `[a-zA-Z0-9]` from a * cryptographic generator, pinned by this module's test. + * + * ## What admission by the presented id grants + * + * The account, and nothing more. The id is no proof of the invited mailbox + * (the accept link and a copied link both carry it), so a sign-up it admits is + * not bound into the deployment's organization while its address is + * unverified (`settleMembership`, `auth-manager-membership-admission.ts`), and + * it joins by accepting the invitation, which needs a verified address + * (`invitation-accept-verified-email.ts`). */ import { InvitationStatus } from '@objectstack/spec/identity'; diff --git a/packages/plugins/plugin-auth/src/remove-user-atomicity.test.ts b/packages/plugins/plugin-auth/src/remove-user-atomicity.test.ts index b477802de7b..2e408a3664d 100644 --- a/packages/plugins/plugin-auth/src/remove-user-atomicity.test.ts +++ b/packages/plugins/plugin-auth/src/remove-user-atomicity.test.ts @@ -36,7 +36,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate } from '@objectstack/objectql'; import { SysMember } from '@objectstack/platform-objects'; import { AuthManager } from './auth-manager'; -import { inviteForAudienceGate } from './audience-gate-test-support'; +import { operatorProvisioningField } from './audience-gate-test-support'; const SECRET = 'test-secret-at-least-32-chars-long!!'; const BASE = 'http://localhost:3000'; @@ -266,10 +266,12 @@ const post = (manager: AuthManager, path: string, body: unknown, cookie?: string ); const signUp = async (manager: AuthManager, engine: MemoryEngine, email: string) => { - // [#11739] default posture invite_only: fixture users beyond the first - // enter through the invitation carve-out (see audience-gate-test-support). - const invitationId = await inviteForAudienceGate(engine, email); - const res = await post(manager, '/sign-up/email', { email, password: PASSWORD, name: email, invitationId }); + // [#11739] default posture invite_only: fixture users beyond the first are + // members, so they enter through the operator door, which binds at creation + // (`operatorProvisioningField`, audience-gate-test-support). + const res = await post(manager, '/sign-up/email', { + email, password: PASSWORD, name: email, ...operatorProvisioningField(manager, email), + }); expect(res.status, await res.clone().text()).toBe(200); const user = (engine.tables.get('sys_user') ?? []).find((u: any) => u.email === email); expect(user, `sign-up did not create ${email}`).toBeDefined(); diff --git a/packages/verify/src/harness.ts b/packages/verify/src/harness.ts index 7072d5ddc13..6c05d5eb2cc 100644 --- a/packages/verify/src/harness.ts +++ b/packages/verify/src/harness.ts @@ -35,7 +35,7 @@ import { import { ObjectQLPlugin } from '@objectstack/objectql'; import { HonoServerPlugin } from '@objectstack/plugin-hono-server'; import { createRestApiPlugin } from '@objectstack/rest'; -import { AuthPlugin } from '@objectstack/plugin-auth'; +import { AuthManager, AuthPlugin } from '@objectstack/plugin-auth'; import { SecurityPlugin, appSecurityPluginOptions } from '@objectstack/plugin-security'; import { SharingServicePlugin } from '@objectstack/plugin-sharing'; import { SettingsServicePlugin, LocalCryptoProvider } from '@objectstack/service-settings'; @@ -1482,7 +1482,10 @@ async function bootClaimed( * * Under `invite_only` a sign-up is admitted only by the invitation it * presents, so the helper answers the row's id and `signUp` sends it as - * `invitationId`, the way a real invitee's accept link carries it. + * `invitationId`, the way a real invitee's accept link carries it. That is + * now `signUp`'s fallback lane only, for a stack whose auth service offers no + * operator door: an account it admits joins no organization until it + * verifies its address and accepts (see `signUp`). * * Best-effort: a stack whose engine or `sys_invitation` object is not * reachable simply signs up without the row and lets the gate answer. @@ -1566,17 +1569,42 @@ async function bootClaimed( return id; }; + /** + * Mint a fixture MEMBER: a signed-in account bound to the deployment's + * organization at creation, as the membership reconciler binds every + * account it may bind. + * + * It enters through the operator door — the ticket the stack's own + * `AuthManager` stages for exactly this address + * (`stageOperatorProvisioning`, the door the deployment's boot command and + * the demo staff use), cleared whatever the sign-up answers. Not the + * invitation lane: a sign-up admitted by the invitation it presents joins no + * organization while its address is unverified, and joins by accepting the + * invitation once verified, so it would mint an invitee, not a member. A + * stack whose auth service offers no operator door falls back to that lane + * ({@link inviteForAudienceGate}). + */ const signUp = async ( email: string, password = 'Member-Pass-123', name?: string, ): Promise => { - const invitationId = await inviteForAudienceGate(email); - const res = await api('/auth/sign-up/email', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ email, password, name: name ?? email.split('@')[0], invitationId }), - }); + const auth = await kernel.getServiceAsync('auth').catch(() => undefined); + const canProvision = + typeof auth?.stageOperatorProvisioning === 'function' && typeof auth?.clearOperatorProvisioning === 'function'; + const admission: Record = canProvision + ? { [AuthManager.OPERATOR_PROVISIONING_TICKET_FIELD]: auth.stageOperatorProvisioning(email) } + : { invitationId: await inviteForAudienceGate(email) }; + let res: Response; + try { + res = await api('/auth/sign-up/email', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ email, password, name: name ?? email.split('@')[0], ...admission }), + }); + } finally { + if (canProvision) auth.clearOperatorProvisioning(email); + } if (!res.ok) { throw new Error(`verify signUp failed: ${res.status} ${await res.text()}`); } From 809bd3f2bb06cf71f6ecdef7d1e105661ba9f853 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 12:44:16 +0000 Subject: [PATCH 08/13] chore(changeset): name the verify package the fixture door ships in Claude-Session: https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj Co-authored-by: Claude --- .changeset/invitation-acceptance-verified-address.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.changeset/invitation-acceptance-verified-address.md b/.changeset/invitation-acceptance-verified-address.md index 69ccdbf1844..0db1f4f10cd 100644 --- a/.changeset/invitation-acceptance-verified-address.md +++ b/.changeset/invitation-acceptance-verified-address.md @@ -1,5 +1,6 @@ --- '@objectstack/plugin-auth': patch +'@objectstack/verify': patch '@object-ui/app-shell': patch '@object-ui/console': patch --- @@ -23,4 +24,6 @@ Unchanged: the invitation mail's own link, which carries a proof of the mailbox The Console's accept-invitation page answers a refused accept or decline with the verification-mail screen for the account's address, whose link brings the person back to answer the invitation. +`@objectstack/verify`: a booted stack's `signUp` mints its fixture member through the operator door (the ticket the stack's own auth manager stages for that address), so the account is bound at creation as before; a stack whose auth service offers no such door falls back to the invitation lane. + What to do: an invitee completes the verification mail (`POST /api/v1/auth/send-verification-email`, then the link it carries) before answering, or opens the invitation mail's own link. On a deployment with no live mail transport, a platform administrator creates the account (`POST /api/v1/auth/admin/create-user`) or attaches an account that already exists with the member list's **Add Member** action, which is open to platform administrators only and attaches existing accounts only. From 48e427708a5c276946073104bbc6b568463ff3e8 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 13:06:21 +0000 Subject: [PATCH 09/13] chore(changeset): state the sign-up binding rule as a rule Claude-Session: https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj Co-authored-by: Claude --- .changeset/invitation-acceptance-verified-address.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.changeset/invitation-acceptance-verified-address.md b/.changeset/invitation-acceptance-verified-address.md index 0db1f4f10cd..b6e5aa56f4e 100644 --- a/.changeset/invitation-acceptance-verified-address.md +++ b/.changeset/invitation-acceptance-verified-address.md @@ -7,11 +7,11 @@ fix(plugin-auth)!: accepting, declining and listing an organization invitation need a verified email address on every deployment, and an invitation sign-up joins by accepting once verified -Clause-②: no (narrowing) — narrowed: from a session whose email address is not verified, `POST /api/v1/auth/organization/accept-invitation` and `POST /api/v1/auth/organization/reject-invitation` answer `403 EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION` and `GET /api/v1/auth/organization/list-user-invitations` answers `403 EMAIL_VERIFICATION_REQUIRED_FOR_INVITATION`, on every deployment, whatever the state of its mail transport; nothing is accepted or declined and no membership is written. Under the `invite_only` posture with `membershipPolicy: 'auto'`, a sign-up admitted by the invitation it presents is no longer bound to the Default Organization while its address is unverified; it joins by accepting the invitation. The codes are better-auth's own. The `sys_invitation` actions **Accept Invitation** and **Decline Invitation** post to those routes and answer the same. +Clause-②: no (narrowing) — narrowed: from a session whose email address is not verified, `POST /api/v1/auth/organization/accept-invitation` and `POST /api/v1/auth/organization/reject-invitation` answer `403 EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION` and `GET /api/v1/auth/organization/list-user-invitations` answers `403 EMAIL_VERIFICATION_REQUIRED_FOR_INVITATION`, on every deployment, whatever the state of its mail transport; nothing is accepted or declined and no membership is written. Under the `invite_only` posture with `membershipPolicy: 'auto'`, a sign-up admitted by the invitation it presents is not bound to the Default Organization while its address is unverified; it joins by accepting the invitation. The codes are better-auth's own. The `sys_invitation` actions **Accept Invitation** and **Decline Invitation** post to those routes and answer the same. Metadata-protocol: none Skills-docs: none — no skill under `skills/**` teaches accepting an organization invitation or invitation sign-up; `content/docs/deployment/self-hosting.mdx` gains the rules in this change. - + **BREAKING** for a deployment whose people answer invitations with an address that is not verified: email verification off (the default under `invite_only`, or declared off under `open`), no live mail transport, or a social or SSO provider that does not verify the address. From 3536fcff63ba0b68da663c58cd2863d868e4da9c Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 15:15:13 +0000 Subject: [PATCH 10/13] fix(plugin-auth): an invitation sign-up's admission is held on the request that creates it, so no other creation of the address reads it Claude-Session: https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj Co-authored-by: Claude --- .../src/auth-manager-database-hooks.ts | 12 ++-- .../src/auth-manager-membership-admission.ts | 43 +++++++---- .../plugins/plugin-auth/src/auth-manager.ts | 72 ++++++++++--------- ...tation-acceptance-verified-address.test.ts | 49 ++++++++++++- 4 files changed, 119 insertions(+), 57 deletions(-) diff --git a/packages/plugins/plugin-auth/src/auth-manager-database-hooks.ts b/packages/plugins/plugin-auth/src/auth-manager-database-hooks.ts index 3dc563d6cf0..cd100636566 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-database-hooks.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-database-hooks.ts @@ -278,7 +278,7 @@ export function composeDatabaseHooks( // means a membership now EXISTS, so the common no-bind login costs no // extra query at all. if (!orgId && this.isCreatedInThisRequest(ctx, userId)) { - const outcome = await this.settleMembership(userId); + const outcome = await this.settleMembership(userId, ctx); if (outcome === 'bound' || outcome === 'yielded') { orgId = await selectActiveOrg(reader, userId); } @@ -492,8 +492,8 @@ export function composeDatabaseHooks( // reconciler then yields to whatever membership exists, so there is never a // double bind. Best-effort — never fails user creation. const hostUserAfter = (host as any)?.user?.create?.after; - const membershipReconciler = async (user: any) => { - await this.settleMembership(user?.id); + const membershipReconciler = async (user: any, ctx?: unknown) => { + await this.settleMembership(user?.id, ctx); // [#11739] The second half of an admitted SELF-registration: settle the // DECLARED permission-set grant staged by the validateUserInfo gate — // landed now, owned by the membership the line above bound, or held as @@ -507,11 +507,11 @@ export function composeDatabaseHooks( const userAfter = hostUserAfter ? async (user: any, ctx: any) => { const hostResult = await hostUserAfter(user, ctx); - await membershipReconciler(user); + await membershipReconciler(user, ctx); return hostResult; } - : async (user: any) => { - await membershipReconciler(user); + : async (user: any, ctx?: unknown) => { + await membershipReconciler(user, ctx); }; // [#12751] Walled owner-verified stamp, the CONSUMING half: the admission diff --git a/packages/plugins/plugin-auth/src/auth-manager-membership-admission.ts b/packages/plugins/plugin-auth/src/auth-manager-membership-admission.ts index bb3442a2011..382e50d959c 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-membership-admission.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-membership-admission.ts @@ -85,10 +85,10 @@ export interface MembershipAdmissionHost { getMembershipPolicy: AuthManager['getMembershipPolicy']; hasPendingInvitationFor: AuthManager['hasPendingInvitationFor']; hasPresentedPendingInvitation: AuthManager['hasPresentedPendingInvitation']; - hasStagedInvitationAdmissions: AuthManager['hasStagedInvitationAdmissions']; + hasInvitationAdmissionInRequest: AuthManager['hasInvitationAdmissionInRequest']; isBootstrapCreation: AuthManager['isBootstrapCreation']; isOperatorProvisioning: AuthManager['isOperatorProvisioning']; - isStagedInvitationAdmission: AuthManager['isStagedInvitationAdmission']; + isInvitationAdmissionInRequest: AuthManager['isInvitationAdmissionInRequest']; selfRegistrationSetResolvable: AuthManager['selfRegistrationSetResolvable']; stageInvitationAdmission: AuthManager['stageInvitationAdmission']; stageOwnerVerifiedStamp: AuthManager['stageOwnerVerifiedStamp']; @@ -116,17 +116,22 @@ export interface MembershipAdmissionHost { * path that can write `email_verified` (the verification link, an * administrator's edit, a provider sign-in, a directory sync). * - * Answers whether the user `userId` is such a sign-up. Asked only while an - * admission is staged (`stageInvitationAdmission`), so every other creation - * pays one in-memory lookup. A user row that cannot be read while one is - * staged answers yes: the settle then binds nothing, the direction that keeps - * the rule. + * Answers whether the user `userId` is such a sign-up, for the creation in the + * request `ctx` (the endpoint context better-auth hands the admission gate + * and both settle seams of one creation; `tryGetCurrentAuthEndpointContext()` + * when a seam hands none). The admission is staged on that request + * (`stageInvitationAdmission`), so it never reaches another creation of the + * same address in another request, and every creation this request did not + * admit by a presented invitation pays one in-memory lookup. A user row that + * cannot be read while this request staged an admission answers yes: the + * settle then binds nothing, the direction that keeps the rule. */ async function invitationSignUpAwaitsVerification( - this: Pick, + this: Pick, userId: string, + ctx: unknown, ): Promise { - if (!this.hasStagedInvitationAdmissions()) return false; + if (!this.hasInvitationAdmissionInRequest(ctx)) return false; const engine = this.config.dataEngine; if (!engine) return true; try { @@ -136,22 +141,34 @@ async function invitationSignUpAwaitsVerification( const rows = await reader.find('sys_user', { where: { id: userId }, fields: ['id', 'email', 'email_verified'], limit: 1 }); const row = (Array.isArray(rows) ? rows[0] : undefined) as { email?: unknown; email_verified?: unknown } | undefined; if (!row || typeof row.email !== 'string') return true; - return this.isStagedInvitationAdmission(row.email) && !row.email_verified; + return this.isInvitationAdmissionInRequest(ctx, row.email) && !row.email_verified; } catch { return true; } } +/** The request a settle seam runs in: the context it was handed, else better-auth's current one. */ +async function settleRequestContext(ctx: unknown): Promise { + if (ctx && typeof ctx === 'object') return ctx; + try { + const { tryGetCurrentAuthEndpointContext } = await import('@better-auth/core/context'); + return tryGetCurrentAuthEndpointContext(); + } catch { + return undefined; + } +} + /** The body of `AuthManager#settleMembership`; the method's docblock there is its contract. */ export async function settleMembership( - this: Pick, + this: Pick, userId: unknown, + ctx?: unknown, ): Promise { try { const id = typeof userId === 'string' && userId ? userId : undefined; // A sign-up admitted by a presented invitation is not bound while its // address is unverified ({@link invitationSignUpAwaitsVerification}). - if (id && (await invitationSignUpAwaitsVerification.call(this, id))) { + if (id && (await invitationSignUpAwaitsVerification.call(this, id, await settleRequestContext(ctx)))) { this.config.logger?.info?.( '[membership] not bound: a sign-up admitted by the invitation it presents joins by accepting the invitation once its address is verified', { userId: id }, @@ -299,7 +316,7 @@ export async function validateAudienceAdmission( // Admitted by the invitation it presents: the membership settle does not // bind this sign-up while its address is unverified (`settleMembership`). if (email && admittedByPresentedInvitation) { - this.stageInvitationAdmission(email); + this.stageInvitationAdmission(ctx, email); } if (verdict.grantPermissionSet) { const setName = audience.selfRegistrationPermissionSet; diff --git a/packages/plugins/plugin-auth/src/auth-manager.ts b/packages/plugins/plugin-auth/src/auth-manager.ts index 5b769c8095d..8c145edf8af 100644 --- a/packages/plugins/plugin-auth/src/auth-manager.ts +++ b/packages/plugins/plugin-auth/src/auth-manager.ts @@ -2716,16 +2716,16 @@ export class AuthManager { * "policy says there will never be one" and skip a pointless re-read; * `undefined` means the reconciler could not be consulted at all. */ - private settleMembership(userId: unknown): Promise { + private settleMembership(userId: unknown, ctx?: unknown): Promise { // [#25224 cut 8] The body moved to `auth-manager-membership-admission.ts` (see `MembershipAdmissionHost`). const readConfig = () => this.config; - const host: Pick = { + const host: Pick = { get config() { return readConfig(); }, getMembershipPolicy: (...a) => this.getMembershipPolicy(...a), - hasStagedInvitationAdmissions: (...a) => this.hasStagedInvitationAdmissions(...a), - isStagedInvitationAdmission: (...a) => this.isStagedInvitationAdmission(...a), + hasInvitationAdmissionInRequest: (...a) => this.hasInvitationAdmissionInRequest(...a), + isInvitationAdmissionInRequest: (...a) => this.isInvitationAdmissionInRequest(...a), }; - return settleMembership.call(host, userId); + return settleMembership.call(host, userId, ctx); } /** @@ -2834,18 +2834,6 @@ export class AuthManager { private static readonly OWNER_STAMP_STAGE_TTL_MS = 10 * 60 * 1000; - /** - * Sign-ups the admission gate admitted by the invitation they PRESENT (under - * `invite_only`), staged for the membership settle — same shape and lifetime - * discipline as {@link pendingSelfRegistrationGrants} (keyed by lowercased - * email, pruned by age). Read, never consumed: both settle seams (the first - * session and `user.create.after`) ask it about the same creation and must - * answer alike. `settleMembership` (`auth-manager-membership-admission.ts`) - * states the rule it serves. - */ - private pendingInvitationAdmissions = new Map(); - - private static readonly INVITATION_ADMISSION_STAGE_TTL_MS = 10 * 60 * 1000; /** * [#14157] Addresses the deployment's OWN boot command is provisioning right @@ -3426,29 +3414,43 @@ export class AuthManager { } } - /** Stage a sign-up the admission gate admitted by the invitation it presents. */ - private stageInvitationAdmission(email: string): void { - this.prunePendingInvitationAdmissions(); - this.pendingInvitationAdmissions.set(email.trim().toLowerCase(), { stagedAtMs: Date.now() }); - } + /** + * The addresses the admission gate admitted in each in-flight better-auth + * request by the invitation they PRESENT (under `invite_only`), keyed by + * that request's endpoint context — the object better-auth hands the + * admission gate and every database hook of the same endpoint call, as + * {@link usersCreatedInRequest} is. `settleMembership` + * (`auth-manager-membership-admission.ts`) states the rule it serves. + * + * Request-scoped on purpose: the admission belongs to the creation it + * admitted, so nothing staged here can be read by another creation of the + * same address (an administrator's, a boot command's) in a later request, + * and both settle seams of THIS creation read the same entry. A `WeakMap`, + * so the entry dies with the endpoint context. + */ + private invitationAdmissionsInRequest = new WeakMap>(); - /** Is any sign-up admitted by a presented invitation staged now? */ - private hasStagedInvitationAdmissions(): boolean { - this.prunePendingInvitationAdmissions(); - return this.pendingInvitationAdmissions.size > 0; + /** Record that the current request's admission gate admitted `email` by the invitation it presents. */ + private stageInvitationAdmission(ctx: unknown, email: string): void { + if (!ctx || typeof ctx !== 'object') return; + let staged = this.invitationAdmissionsInRequest.get(ctx); + if (!staged) { + staged = new Set(); + this.invitationAdmissionsInRequest.set(ctx, staged); + } + staged.add(email.trim().toLowerCase()); } - /** Was the sign-up of this address admitted by the invitation it presented? Not consumed. */ - private isStagedInvitationAdmission(email: string): boolean { - this.prunePendingInvitationAdmissions(); - return this.pendingInvitationAdmissions.has(email.trim().toLowerCase()); + /** Did this request admit any address by the invitation it presents? In-memory only. */ + private hasInvitationAdmissionInRequest(ctx: unknown): boolean { + if (!ctx || typeof ctx !== 'object') return false; + return (this.invitationAdmissionsInRequest.get(ctx)?.size ?? 0) > 0; } - private prunePendingInvitationAdmissions(): void { - const cutoff = Date.now() - AuthManager.INVITATION_ADMISSION_STAGE_TTL_MS; - for (const [key, value] of this.pendingInvitationAdmissions) { - if (value.stagedAtMs < cutoff) this.pendingInvitationAdmissions.delete(key); - } + /** Did this request admit `email` by the invitation it presents? In-memory only. */ + private isInvitationAdmissionInRequest(ctx: unknown, email: string): boolean { + if (!ctx || typeof ctx !== 'object') return false; + return this.invitationAdmissionsInRequest.get(ctx)?.has(email.trim().toLowerCase()) === true; } /** diff --git a/packages/plugins/plugin-auth/src/invitation-acceptance-verified-address.test.ts b/packages/plugins/plugin-auth/src/invitation-acceptance-verified-address.test.ts index e8dd41df8c0..d2c0483aeb1 100644 --- a/packages/plugins/plugin-auth/src/invitation-acceptance-verified-address.test.ts +++ b/packages/plugins/plugin-auth/src/invitation-acceptance-verified-address.test.ts @@ -26,6 +26,7 @@ import { SqlDriver } from '@objectstack/driver-sql'; import { AuthManager } from './auth-manager.js'; import { authIdentityObjects } from './manifest.js'; import { SIGN_UP_INVITATION_ID_FIELD } from './presented-invitation.js'; +import { operatorProvisioningField } from './audience-gate-test-support'; import { ACCEPT_INVITATION_ONE_STEP_PATH } from './invitation-mailbox-proof.js'; import { memoizeScrypt } from './__tests__/scrypt-memo.testkit'; @@ -445,8 +446,11 @@ describe('under invite_only, a sign-up admitted by the invitation it presents jo expect(await d.allMemberships()).toEqual([]); }); - it('CONTROL: a sign-up the invitation mail proof verifies is bound and accepted with the invited role', async () => { - const d = await deployment({}, { into: DEFAULT_ORG }); + it('CONTROL: a sign-up the invitation mail proof verifies is bound to the default organization at creation, and accepts the invited role', async () => { + // Invited into the partner organization: a default-organization row can + // only come from the bind at creation, and the partner row only from the + // acceptance. + const d = await deployment(); const res = await send(d.manager, 'POST', ACCEPT_INVITATION_ONE_STEP_PATH, { invitationId: d.invitationId, proof: proofFromMail(d), @@ -454,7 +458,46 @@ describe('under invite_only, a sign-up admitted by the invitation it presents jo password: PASSWORD, }); expect(res.status, await res.clone().text()).toBe(200); - expect((await d.allMemberships()).map((m) => [m.organization_id, m.role])).toEqual([[DEFAULT_ORG, 'admin']]); + const held = (await d.allMemberships()).map((m) => [m.organization_id, m.role]).sort(); + expect(held).toEqual([[DEFAULT_ORG, 'member'], [PARTNER_ORG, 'admin']].sort()); + }); + + it('CONTROL: an unrelated address an operator provisions while an invitation sign-up is in flight is bound to the default organization', async () => { + const d = await deployment({}, { into: DEFAULT_ORG }); + const other = 'provisioned@acme.example'; + const [invitee, provisioned] = await Promise.all([ + send(d.manager, 'POST', '/sign-up/email', { + email: INVITEE, password: PASSWORD, name: 'Invitee', [SIGN_UP_INVITATION_ID_FIELD]: d.invitationId, + }), + send(d.manager, 'POST', '/sign-up/email', { + email: other, password: PASSWORD, name: 'Provisioned', ...operatorProvisioningField(d.manager, other), + }), + ]); + expect(invitee.status, await invitee.clone().text()).toBe(200); + expect(provisioned.status, await provisioned.clone().text()).toBe(200); + const [user] = await rows(d.engine, 'sys_user', { email: other }); + expect((await rows(d.engine, 'sys_member', { user_id: user.id })).map((m) => [m.organization_id, m.role])).toEqual([[DEFAULT_ORG, 'member']]); + expect(await d.allMemberships()).toEqual([]); + }); + + it('CONTROL: the same address, created again through the operator door after an invitation sign-up of it, is bound to the default organization', async () => { + const d = await deployment({}, { into: DEFAULT_ORG }); + await unverifiedPasswordSession(d); + expect(await d.allMemberships()).toEqual([]); + // The invitation sign-up's account is removed, and an operator provisions + // the address afresh, moments later. + const first = await d.inviteeRow(); + for (const object of ['sys_session', 'sys_account']) { + await d.engine.delete(object, { where: { user_id: first.id }, multi: true, context: { isSystem: true } } as never); + } + await d.engine.delete('sys_user', { where: { id: first.id }, context: { isSystem: true } } as never); + expect(await d.inviteeRow()).toBeUndefined(); + + const res = await send(d.manager, 'POST', '/sign-up/email', { + email: INVITEE, password: PASSWORD, name: 'Invitee', ...operatorProvisioningField(d.manager, INVITEE), + }); + expect(res.status, await res.clone().text()).toBe(200); + expect((await d.allMemberships()).map((m) => [m.organization_id, m.role])).toEqual([[DEFAULT_ORG, 'member']]); }); it('CONTROL: the first account of the deployment is still bound to the default organization', async () => { From 79a6877ea1640be7c710974b4348c90887ee5631 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 15:16:34 +0000 Subject: [PATCH 11/13] test(runtime): fixture members enter through the operator door Claude-Session: https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj Co-authored-by: Claude --- ...clarative-update-refusal-order.pin.test.ts | 38 +++++++++--------- .../mcp-list-objects-statements.pin.test.ts | 28 ++++++++----- ...lugin-driver-external-object.spike.test.ts | 39 +++++++++--------- ...tored-metadata-reader-contexts.pin.test.ts | 40 +++++++++---------- 4 files changed, 71 insertions(+), 74 deletions(-) diff --git a/packages/runtime/src/declarative-update-refusal-order.pin.test.ts b/packages/runtime/src/declarative-update-refusal-order.pin.test.ts index 2ce9e249ff8..02fbc27ecaf 100644 --- a/packages/runtime/src/declarative-update-refusal-order.pin.test.ts +++ b/packages/runtime/src/declarative-update-refusal-order.pin.test.ts @@ -48,7 +48,7 @@ import type { Plugin, PluginContext } from '@objectstack/core'; import { ObjectQLPlugin } from '@objectstack/objectql'; import { HonoServerPlugin } from '@objectstack/plugin-hono-server'; import { createRestApiPlugin } from '@objectstack/rest'; -import { AuthPlugin } from '@objectstack/plugin-auth'; +import { AuthManager, AuthPlugin } from '@objectstack/plugin-auth'; import { SecurityPlugin, appSecurityPluginOptions } from '@objectstack/plugin-security'; import { SharingServicePlugin } from '@objectstack/plugin-sharing'; import { PlatformObjectsPlugin } from '@objectstack/platform-objects/plugin'; @@ -215,25 +215,23 @@ async function signIn(who: { email: string; password: string }): Promise } async function signUpMember(who: { email: string; password: string }, n: number): Promise { - // Default audience posture is invite_only: enter through a pending invitation. - await engine.insert( - 'sys_invitation', - { - id: `inv_pin_30848_${n}`, - email: who.email, - status: 'pending', - organization_id: ORG, - role: 'member', - inviter_id: 'usr_pin_30848', - expires_at: new Date(Date.now() + 3_600_000), - }, - { context: { isSystem: true } }, - ); - const res = await req('/auth/sign-up/email', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ email: who.email, password: who.password, name: `pin member ${n}`, invitationId: `inv_pin_30848_${n}` }), - }); + // Default audience posture is invite_only. A member bound at creation enters + // through the operator door — the ticket the stack's own auth manager stages + // for exactly this address, as `@objectstack/verify`'s signUp mints its + // member. A sign-up admitted by the invitation it presents joins no + // organization until it verifies its address and accepts. + const auth: any = await kernel.getServiceAsync('auth'); + const ticket = auth.stageOperatorProvisioning(who.email); + let res: Response; + try { + res = await req('/auth/sign-up/email', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ email: who.email, password: who.password, name: `pin member ${n}`, [AuthManager.OPERATOR_PROVISIONING_TICKET_FIELD]: ticket }), + }); + } finally { + auth.clearOperatorProvisioning(who.email); + } if (!res.ok) throw new Error(`pin signUp failed: ${res.status} ${await res.text()}`); return (await res.json() as any).token; } diff --git a/packages/runtime/src/mcp-list-objects-statements.pin.test.ts b/packages/runtime/src/mcp-list-objects-statements.pin.test.ts index 9bee500acd3..18e6cb27a93 100644 --- a/packages/runtime/src/mcp-list-objects-statements.pin.test.ts +++ b/packages/runtime/src/mcp-list-objects-statements.pin.test.ts @@ -49,7 +49,7 @@ import { ObjectKernel, assembleExecutionContext, type Plugin, type PluginContext import { ObjectQLPlugin } from '@objectstack/objectql'; import { HonoServerPlugin } from '@objectstack/plugin-hono-server'; import { createRestApiPlugin } from '@objectstack/rest'; -import { AuthPlugin } from '@objectstack/plugin-auth'; +import { AuthManager, AuthPlugin } from '@objectstack/plugin-auth'; import { SecurityPlugin, appSecurityPluginOptions } from '@objectstack/plugin-security'; import { SharingServicePlugin } from '@objectstack/plugin-sharing'; import { PlatformObjectsPlugin } from '@objectstack/platform-objects/plugin'; @@ -269,16 +269,22 @@ beforeAll(async () => { statements.getStore()?.push(String(q?.sql ?? '')); }); const owner = await personContext(await signIn(OWNER)); - // The default audience posture is invite_only: the member enters the - // owner's organization through a pending invitation. - await engine.insert('sys_invitation', { - id: 'inv_pin_33179', email: MEMBER.email, status: 'pending', organization_id: owner.tenantId, - role: 'member', inviter_id: owner.userId, expires_at: new Date(Date.now() + 3_600_000), - }, { context: { isSystem: true } }); - const signUp = await app.request(`${ORIGIN}${API}/auth/sign-up/email`, { - method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ ...MEMBER, invitationId: 'inv_pin_33179' }), - }); + // The default audience posture is invite_only. The member is bound to the + // owner's organization at creation through the operator door — the ticket + // the stack's own auth manager stages for exactly this address. A sign-up + // admitted by the invitation it presents joins no organization until it + // verifies its address and accepts. + const auth: any = await kernel.getServiceAsync('auth'); + const ticket = auth.stageOperatorProvisioning(MEMBER.email); + let signUp: Response; + try { + signUp = await app.request(`${ORIGIN}${API}/auth/sign-up/email`, { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ ...MEMBER, [AuthManager.OPERATOR_PROVISIONING_TICKET_FIELD]: ticket }), + }); + } finally { + auth.clearOperatorProvisioning(MEMBER.email); + } expect(signUp.status, await signUp.clone().text()).toBe(200); const member = await personContext(await signIn(MEMBER)); callers = { owner, member, ownerAgent: agentFor(owner), memberAgent: agentFor(member) }; diff --git a/packages/runtime/src/plugin-driver-external-object.spike.test.ts b/packages/runtime/src/plugin-driver-external-object.spike.test.ts index 982fbfdf4bf..c31b30ac169 100644 --- a/packages/runtime/src/plugin-driver-external-object.spike.test.ts +++ b/packages/runtime/src/plugin-driver-external-object.spike.test.ts @@ -42,7 +42,7 @@ import type { DriverQuery, IDataDriver, IExternalDatasourceService } from '@obje import { ObjectQLPlugin, EXTERNAL_ROW_CAP, unwrapExternalDriverFloor } from '@objectstack/objectql'; import { HonoServerPlugin } from '@objectstack/plugin-hono-server'; import { createRestApiPlugin } from '@objectstack/rest'; -import { AuthPlugin } from '@objectstack/plugin-auth'; +import { AuthManager, AuthPlugin } from '@objectstack/plugin-auth'; import { SecurityPlugin, appSecurityPluginOptions, RLS_DENY_FILTER } from '@objectstack/plugin-security'; import { SharingServicePlugin } from '@objectstack/plugin-sharing'; import { PlatformObjectsPlugin } from '@objectstack/platform-objects/plugin'; @@ -369,28 +369,25 @@ async function signIn(email: string, password: string): Promise { } /** - * A second human under the default `invite_only` audience posture enters - * through a pending invitation, as `@objectstack/verify`'s `signUp` does. + * A second human under the default `invite_only` audience posture, bound to + * the organization at creation: the operator door — the ticket the stack's + * own auth manager stages for exactly this address — as `@objectstack/verify`'s + * `signUp` mints its member. A sign-up admitted by the invitation it presents + * joins no organization until it verifies its address and accepts. */ async function signUp(email: string): Promise { - await engine.insert( - 'sys_invitation', - { - id: `inv_spike_${email.split('@')[0]}`, - email, - status: 'pending', - organization_id: 'org_spike_audience_gate', - role: 'member', - inviter_id: 'usr_spike_audience_gate', - expires_at: new Date(Date.now() + 3_600_000), - }, - { context: { isSystem: true } }, - ); - const res = await req('/auth/sign-up/email', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ email, password: MEMBER_PASSWORD, name: email.split('@')[0], invitationId: `inv_spike_${email.split('@')[0]}` }), - }); + const auth: any = await kernel.getServiceAsync('auth'); + const ticket = auth.stageOperatorProvisioning(email); + let res: Response; + try { + res = await req('/auth/sign-up/email', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ email, password: MEMBER_PASSWORD, name: email.split('@')[0], [AuthManager.OPERATOR_PROVISIONING_TICKET_FIELD]: ticket }), + }); + } finally { + auth.clearOperatorProvisioning(email); + } if (!res.ok) throw new Error(`spike signUp failed: ${res.status} ${await res.text()}`); return ((await res.json()) as any).token; } diff --git a/packages/runtime/src/stored-metadata-reader-contexts.pin.test.ts b/packages/runtime/src/stored-metadata-reader-contexts.pin.test.ts index 404570f9389..0011a43ed0e 100644 --- a/packages/runtime/src/stored-metadata-reader-contexts.pin.test.ts +++ b/packages/runtime/src/stored-metadata-reader-contexts.pin.test.ts @@ -63,7 +63,7 @@ import { ObjectQLPlugin } from '@objectstack/objectql'; import type { ObjectQL } from '@objectstack/objectql'; import { HonoServerPlugin } from '@objectstack/plugin-hono-server'; import { createRestApiPlugin } from '@objectstack/rest'; -import { AuthPlugin } from '@objectstack/plugin-auth'; +import { AuthManager, AuthPlugin } from '@objectstack/plugin-auth'; import { SecurityPlugin, appSecurityPluginOptions } from '@objectstack/plugin-security'; import { SharingServicePlugin } from '@objectstack/plugin-sharing'; import { PlatformObjectsPlugin } from '@objectstack/platform-objects/plugin'; @@ -384,27 +384,23 @@ async function signIn(who: { email: string; password: string }): Promise } async function signUpMember(): Promise { - // Default audience posture is invite_only: enter through a pending invitation, - // the same lane `@objectstack/verify`'s signUp takes. - const engine: any = await kernel.getServiceAsync('objectql'); - await engine.insert( - 'sys_invitation', - { - id: 'inv_pin_21454', - email: MEMBER.email, - status: 'pending', - organization_id: 'org_pin_audience_gate', - role: 'member', - inviter_id: 'usr_pin_audience_gate', - expires_at: new Date(Date.now() + 3_600_000), - }, - { context: { isSystem: true } }, - ); - const res = await req('/auth/sign-up/email', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ email: MEMBER.email, password: MEMBER.password, name: 'pin member', invitationId: 'inv_pin_21454' }), - }); + // Default audience posture is invite_only. A member bound at creation enters + // through the operator door — the ticket the stack's own auth manager stages + // for exactly this address, the lane `@objectstack/verify`'s signUp takes. A + // sign-up admitted by the invitation it presents joins no organization until + // it verifies its address and accepts. + const auth: any = await kernel.getServiceAsync('auth'); + const ticket = auth.stageOperatorProvisioning(MEMBER.email); + let res: Response; + try { + res = await req('/auth/sign-up/email', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ email: MEMBER.email, password: MEMBER.password, name: 'pin member', [AuthManager.OPERATOR_PROVISIONING_TICKET_FIELD]: ticket }), + }); + } finally { + auth.clearOperatorProvisioning(MEMBER.email); + } if (!res.ok) throw new Error(`pin signUp failed: ${res.status} ${await res.text()}`); const data: any = await res.json(); return data.token; From 7da458bbce673ced98df7d96b9020359ee6af239 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 15:18:12 +0000 Subject: [PATCH 12/13] fix(app-shell)!: an invitation sign-up whose address is not verified goes straight to the verification mail; release notes state one rule Claude-Session: https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj Co-authored-by: Claude --- .../34272-accept-invitation-verified-email.md | 16 +++------ .../invitation-acceptance-verified-address.md | 5 ++- content/docs/deployment/self-hosting.mdx | 15 ++++---- .../invitationSignUpJoin-30125.test.tsx | 32 +++++++++++++++-- .../src/console/auth/invitationSignUpJoin.ts | 34 +++++++++++++++---- 5 files changed, 74 insertions(+), 28 deletions(-) diff --git a/.changeset/34272-accept-invitation-verified-email.md b/.changeset/34272-accept-invitation-verified-email.md index 1a16c2edbd1..ec3dd59293b 100644 --- a/.changeset/34272-accept-invitation-verified-email.md +++ b/.changeset/34272-accept-invitation-verified-email.md @@ -4,23 +4,17 @@ '@objectstack/runtime': patch --- -fix(plugin-auth,app-shell)!: while mail is live, accepting an invitation needs a verified address +fix(plugin-auth,app-shell): an accept refused for an unverified address answers the vendor's own code, and the Console's accept page takes the person to verify -Clause-②: no (narrowing) +Clause-②: no 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. +Skills-docs: none — `git grep` of `skills/` finds no page that teaches accepting an invitation or `/organization/accept-invitation`; the rule is stated 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. The rule: while mail is live, accepting an invitation needs a verified address, because an unverified address is not proof of the invited mailbox. +The rule that refuses the accept is stated, with its BREAKING notice and its migration, in this release's entry "accepting, declining and listing an organization invitation need a verified email address on every deployment, and an invitation sign-up joins by accepting once verified". This entry carries only the parts of that change that ship beside it. **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. +- `POST /api/v1/auth/organization/accept-invitation` (`@objectstack/plugin-auth`) answers a session whose address is unverified with better-auth's own `403 EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION` and its sentence, the answer its accept route gives when its option is on, and writes nothing. 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). - 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`. 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. - `@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/.changeset/invitation-acceptance-verified-address.md b/.changeset/invitation-acceptance-verified-address.md index b6e5aa56f4e..8afddab1f61 100644 --- a/.changeset/invitation-acceptance-verified-address.md +++ b/.changeset/invitation-acceptance-verified-address.md @@ -2,7 +2,6 @@ '@objectstack/plugin-auth': patch '@objectstack/verify': patch '@object-ui/app-shell': patch -'@object-ui/console': patch --- fix(plugin-auth)!: accepting, declining and listing an organization invitation need a verified email address on every deployment, and an invitation sign-up joins by accepting once verified @@ -18,11 +17,11 @@ Skills-docs: none — no skill under `skills/**` teaches accepting an organizati - Accepting, declining and listing an organization invitation require a verified email address, on every deployment. A password account verifies by the verification mail; an account a social or SSO provider made counts only when the provider verified the address. The invitation's id, which its accept link and a copied link carry, is no proof of the mailbox, and no setting relaxes the rule. - Reading one invitation by its id (`GET /api/v1/auth/organization/get-invitation`) stays open, so the accept page can show it. - Under `invite_only` with `membershipPolicy: 'auto'`, an account a sign-up admitted by the invitation it presents is not bound to the Default Organization while its address is unverified. Its membership comes from accepting the invitation once the address is verified, with the role the invitation carries, or from a platform administrator. -- A deployment without a live mail transport cannot onboard anyone by invitation link. +- A deployment without a live mail transport cannot onboard a password account by invitation link; an invitee whose social or SSO provider verifies the address can still accept a copied link there. Unchanged: the invitation mail's own link, which carries a proof of the mailbox and accepts in one step (`POST /api/v1/auth/organization/accept-invitation-one-step`); a verified account, which accepts, declines and lists its invitations as before; the first account of a deployment, accounts an administrator creates and accounts a boot command provisions, which are bound as before; sending, resending and cancelling invitations. -The Console's accept-invitation page answers a refused accept or decline with the verification-mail screen for the account's address, whose link brings the person back to answer the invitation. +The Console's accept-invitation page answers a refused decline with the verification-mail screen for the account's address, as it answers a refused accept, and that screen's link brings the person back to answer the invitation. `@objectstack/verify`: a booted stack's `signUp` mints its fixture member through the operator door (the ticket the stack's own auth manager stages for that address), so the account is bound at creation as before; a stack whose auth service offers no such door falls back to the invitation lane. diff --git a/content/docs/deployment/self-hosting.mdx b/content/docs/deployment/self-hosting.mdx index fd6b7cd6c25..563c557f024 100644 --- a/content/docs/deployment/self-hosting.mdx +++ b/content/docs/deployment/self-hosting.mdx @@ -777,12 +777,15 @@ in and opens the 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. No setting relaxes this rule. -**A deployment without a live mail transport cannot onboard anyone by -invitation link.** With no transport configured, or the log transport, no -verification mail and no invitation mail reaches anyone, so no invitee can -verify an address or accept; a link handed over with the invitation's **Copy -Invite Link** action admits the sign-up and nothing more. To bring a person in -there, a platform administrator creates the account +**A deployment without a live mail transport cannot onboard a password +account by invitation link.** With no transport configured, or the log +transport, no verification mail and no invitation mail reaches anyone, so an +invitee who signs up with a password cannot verify the address or accept; a +link handed over with the invitation's **Copy Invite Link** action admits the +sign-up and nothing more. The one exception is an invitee who signs in through +a social or SSO provider that verifies the address: that account counts as +verified, so it can accept a copied link without any mail. To bring anyone +else in there, a platform administrator creates the account (`POST /api/v1/auth/admin/create-user`), or attaches an account that already exists with the member list's **Add Member** action. Add Member is open to platform administrators only, and it attaches existing accounts only: it diff --git a/ui/packages/app-shell/src/console/auth/__tests__/invitationSignUpJoin-30125.test.tsx b/ui/packages/app-shell/src/console/auth/__tests__/invitationSignUpJoin-30125.test.tsx index 8fa0957ca8c..e1930d1fc11 100644 --- a/ui/packages/app-shell/src/console/auth/__tests__/invitationSignUpJoin-30125.test.tsx +++ b/ui/packages/app-shell/src/console/auth/__tests__/invitationSignUpJoin-30125.test.tsx @@ -29,7 +29,7 @@ import '@testing-library/jest-dom/vitest'; 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, Routes, Route } from 'react-router-dom'; +import { MemoryRouter, Routes, Route, useLocation } from 'react-router-dom'; import { I18nProvider } from '@object-ui/i18n'; import { builtInLocales } from '@object-ui/i18n/locales'; import { AuthProvider } from '@object-ui/auth'; @@ -56,7 +56,7 @@ afterEach(() => { vi.restoreAllMocks(); }); -function createMockClient({ signedInOnArrival = false, refuseRecipient = false } = {}) { +function createMockClient({ signedInOnArrival = false, refuseRecipient = false, refuseUnverified = false } = {}) { let signedIn = signedInOnArrival; let member = false; let active: typeof ORG | null = null; @@ -84,6 +84,13 @@ function createMockClient({ signedInOnArrival = false, refuseRecipient = false } return { id, organizationId: ORG.id, email: USER.email, role: 'member', status: 'pending' }; }), acceptInvitation: vi.fn(async () => { + if (refuseUnverified) { + // The server's answer to an account whose address is not verified. + throw Object.assign(new Error('Email verification required before accepting or rejecting invitation'), { + status: 403, + code: 'EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION', + }); + } member = true; }), listOrganizations: vi.fn(async () => (member ? [ORG] : [])), @@ -107,6 +114,7 @@ function renderRegister(client: AuthClient) { } /> accept page

} /> home

} /> + } /> @@ -114,6 +122,12 @@ function renderRegister(client: AuthClient) { ); } +/** The verification-mail screen's stand-in: shows the query it was opened with. */ +function VerifyPromptProbe() { + const location = useLocation(); + return

{location.search}

; +} + async function signUpOnTheForm() { const user = userEvent.setup(); await user.type(await screen.findByLabelText(en.nameLabel), USER.name); @@ -148,6 +162,20 @@ describe('DefaultRegisterPage — a sign-up from an invitation link joins it (#3 expect(assign).not.toHaveBeenCalled(); }); + it('accepting needs a verified address: an unverified account goes straight to the verification mail, which returns to the accept page', async () => { + const client = createMockClient({ refuseUnverified: true }); + renderRegister(client); + await signUpOnTheForm(); + + const prompt = await screen.findByTestId('verify-prompt'); + const sp = new URLSearchParams(prompt.textContent ?? ''); + expect(sp.get('email')).toBe(USER.email); + expect(sp.get('redirect')).toBe(ACCEPT_PATH); + expect(client.acceptInvitation).toHaveBeenCalledTimes(1); + expect(screen.queryByText('accept page')).toBeNull(); + expect(assign).not.toHaveBeenCalled(); + }); + it('CONTROL: already signed in when the page opens — accepts nothing and goes to /', async () => { const client = createMockClient({ signedInOnArrival: true }); renderRegister(client); diff --git a/ui/packages/app-shell/src/console/auth/invitationSignUpJoin.ts b/ui/packages/app-shell/src/console/auth/invitationSignUpJoin.ts index 01993e085d7..3fc29468e39 100644 --- a/ui/packages/app-shell/src/console/auth/invitationSignUpJoin.ts +++ b/ui/packages/app-shell/src/console/auth/invitationSignUpJoin.ts @@ -26,12 +26,20 @@ * A person who opens the page already signed in accepts nothing here. * - The server decides as it always does. The page reads the invitation * (`get-invitation`) and accepts it (`accept-invitation`) as the new - * account; an address that is not the invited one is refused by the server, - * the hook answers `refused`, and the page goes on to the accept page as - * before, which shows that refusal. + * account. An address that is not the invited one is refused by the + * server, the hook answers `refused`, and the page goes on to the accept + * page as before, which shows that refusal. + * - Accepting needs a verified address. An account whose address is not + * verified is refused for that, and the hook hands over straight to the + * verification-mail screen (`/verify-email-prompt`) for the account's + * address, whose link returns to the accept page; it answers `joining` + * meanwhile, so the page holds instead of moving on. * - A sign-up that waits for email verification creates no session here, so * nothing is accepted on this page; the verification mail returns to the * accept page. + * - An account a sign-up admitted by the invitation it presents is not a + * member of any organization until it accepts, so a sign-up whose address + * is not verified lands on the accept page with no organization. * * After the acceptance the session is switched to the organization, and the * page then enters it by a full-page navigation to the console root, the way @@ -40,8 +48,10 @@ */ import { useEffect, useRef, useState } from 'react'; +import { useNavigate } from 'react-router-dom'; import { useAuth } from '@object-ui/auth'; import { invitationIdOf } from './invitationArrival.js'; +import { isAcceptNeedsVerifiedEmail } from '../organizations/orgErrorMessage.js'; /** * Where a register page's invitation join stands: @@ -53,7 +63,9 @@ import { invitationIdOf } from './invitationArrival.js'; * - `joined`: the server accepted the invitation and the session is on its * organization — the page enters the console root; * - `refused`: the server refused the read or the acceptance — the page goes - * on to the accept page, as it did before. + * on to the accept page, as it did before. A refusal for an unverified + * address is not this outcome: the hook hands over to the verification-mail + * screen and stays `joining`. */ export type InvitationSignUpJoin = 'none' | 'joining' | 'joined' | 'refused'; @@ -63,6 +75,7 @@ export type InvitationSignUpJoin = 'none' | 'joining' | 'joined' | 'refused'; */ export function useInvitationSignUpJoin(redirect: string | null | undefined): InvitationSignUpJoin { const { user, isLoading, getInvitation, acceptInvitation, switchOrganization } = useAuth(); + const navigate = useNavigate(); const invitationId = invitationIdOf(redirect); // Latched the first time the session check answers with nobody signed in. @@ -88,7 +101,16 @@ export function useInvitationSignUpJoin(redirect: string | null | undefined): In const invitation = await getInvitation(id); await acceptInvitation(id); organizationId = invitation.organizationId; - } catch { + } catch (err) { + // Accepting needs a verified address: hand over to the verification + // mail, whose link returns to the accept page, and hold meanwhile. + if (isAcceptNeedsVerifiedEmail(err) && redirect) { + const sp = new URLSearchParams(); + if (user?.email) sp.set('email', user.email); + sp.set('redirect', redirect); + navigate(`/verify-email-prompt?${sp.toString()}`, { replace: true }); + return; + } setOutcome({ id, result: 'refused' }); return; } @@ -97,7 +119,7 @@ export function useInvitationSignUpJoin(redirect: string | null | undefined): In await switchOrganization(organizationId).catch(() => undefined); setOutcome({ id, result: 'joined' }); })(); - }, [applies, invitationId, getInvitation, acceptInvitation, switchOrganization]); + }, [applies, invitationId, getInvitation, acceptInvitation, switchOrganization, navigate, redirect, user]); if (!applies) return 'none'; return outcome && outcome.id === invitationId ? outcome.result : 'joining'; From 7a9d7e5068c48c21929908712b8bc2e0278dfeaf Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 15:37:57 +0000 Subject: [PATCH 13/13] test(runtime): drop the fixture's unused organization id; docs state the sign-up binding rule Claude-Session: https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj Co-authored-by: Claude --- content/docs/deployment/environment-variables.mdx | 2 +- content/docs/deployment/tenancy-modes.mdx | 4 ++++ content/docs/permissions/authentication.mdx | 8 +++++--- content/docs/permissions/sso.mdx | 5 +++++ .../src/declarative-update-refusal-order.pin.test.ts | 1 - 5 files changed, 15 insertions(+), 5 deletions(-) diff --git a/content/docs/deployment/environment-variables.mdx b/content/docs/deployment/environment-variables.mdx index 2ec8ac1d094..0d2bd0d37d2 100644 --- a/content/docs/deployment/environment-variables.mdx +++ b/content/docs/deployment/environment-variables.mdx @@ -97,7 +97,7 @@ Read by `@objectstack/service-print` when `PrintServicePlugin` is composed; see | `OS_AUTH_EMAIL_PASSWORD_ENABLED` | boolean | settings default | Settings env override for `auth.email_password_enabled`. Controls local email/password login. | | `OS_AUTH_SIGNUP_ENABLED` | boolean | settings default | Settings env override for `auth.signup_enabled`. Takes precedence over UI settings and is preferred over `OS_DISABLE_SIGNUP`. | | `OS_AUTH_REQUIRE_EMAIL_VERIFICATION` | boolean | settings default | Settings env override for `auth.require_email_verification`. Under the `open` audience posture, `false` is the deployment's opt-out from the forced verification (one boot warning; see [Email verification under each posture](/docs/deployment/self-hosting#email-verification-under-each-posture)); under `email_domain` it is refused, since verification is forced there. | -| `OS_AUTH_MEMBERSHIP_POLICY` | `auto` \| `invite-only` | `auto` | Settings env override for `auth.membership_policy` — what a newly created user joins (ADR-0093 D1). `auto` binds every new user to the deployment's default organization. `invite-only` grants membership solely through an explicit act: creating a workspace, accepting an invitation, an admin adding them, or SSO just-in-time provisioning. Applies to sign-up **and** to the backfill of pre-existing member-less users. An unrecognized value is rejected with an `error` log and **ignored** — the deployment keeps its current policy rather than silently reverting to `auto`. | +| `OS_AUTH_MEMBERSHIP_POLICY` | `auto` \| `invite-only` | `auto` | Settings env override for `auth.membership_policy` — what a newly created user joins (ADR-0093 D1). `auto` binds every new user to the deployment's default organization, except, under the `invite_only` audience posture, a sign-up admitted by the invitation it presents whose address is unverified, which joins by accepting. `invite-only` grants membership solely through an explicit act: creating a workspace, accepting an invitation, an admin adding them, or SSO just-in-time provisioning. Applies to sign-up **and** to the backfill of pre-existing member-less users. An unrecognized value is rejected with an `error` log and **ignored** — the deployment keeps its current policy rather than silently reverting to `auto`. | | `OS_ORG_INVITATION_LIMIT` | integer \| `off` | unset (100) | How many **pending** invitations one organization may hold at once. When the organization already holds that many, `POST /api/v1/auth/organization/invite-member` answers `403 INVITATION_LIMIT_REACHED` (`Invitation limit reached`) until an invitation is accepted, rejected, cancelled or expires. Unset keeps the auth library's own limit of 100, so a deployment that sets nothing behaves as before. A positive integer `N` allows `N`. `off`, `unlimited` or `none` (any case) removes the limit, for a host that invites people in bulk. `0`, or any value that is not plain digits (`-5`, `2.5`, `1e3`, `1_000`), reads as unset (100), so a typo never refuses every invitation. The count is per organization, not per inviter. Read when the auth plugin builds its organization plugin, so a change needs a process reload. | | `OS_AUTH_GOOGLE_ENABLED` | boolean | settings default | Settings env override for `auth.google_enabled`. Requires Google OAuth credentials from Settings or env. | | `GOOGLE_CLIENT_ID` | string | — | Deployment-level Google OAuth client id for the open-source Google login implementation. | diff --git a/content/docs/deployment/tenancy-modes.mdx b/content/docs/deployment/tenancy-modes.mdx index 04b2e75bc06..c63215515e6 100644 --- a/content/docs/deployment/tenancy-modes.mdx +++ b/content/docs/deployment/tenancy-modes.mdx @@ -243,6 +243,10 @@ The reconciler: - **yields** to any membership that already exists (e.g. one created by an invitation, `add-member`, SSO provisioning, or a host hook) — it never creates a second membership; +- does **not** bind, under the `invite_only` audience posture, a sign-up + admitted by the invitation it presents while the account's email address is + unverified: that account joins by accepting the invitation, which needs a + verified address ([Self-hosting](/docs/deployment/self-hosting)); - binds only to an **unambiguous** target org — that is `tenancy.defaultOrgId()`, which returns the single-org default organization under `single` and `null` under any walled **request** (invitations, `add-member` and SSO provisioning diff --git a/content/docs/permissions/authentication.mdx b/content/docs/permissions/authentication.mdx index 40e5b0bf763..103710f043e 100644 --- a/content/docs/permissions/authentication.mdx +++ b/content/docs/permissions/authentication.mdx @@ -123,7 +123,9 @@ OS_AUTH_SIGNUP_ENABLED=false OS_AUTH_GOOGLE_ENABLED=true # Optional: what a new user joins (ADR-0093 D1). `auto` (default) binds every -# new user to the default organization; `invite-only` grants membership only +# new user to the default organization (except, under the `invite_only` +# audience posture, a sign-up admitted by the invitation it presents whose +# address is unverified: it joins by accepting); `invite-only` grants membership only # through an explicit act — creating a workspace, accepting an invitation, an # admin adding them, or SSO just-in-time provisioning. # Also configurable in Setup → Authentication → Membership. @@ -1208,8 +1210,8 @@ organization the administrator has switched to in the console. There is no organization choice: to add someone to another organization, switch to it first. An administrator with no current organization is refused with `400 NO_ACTIVE_ORGANIZATION` and no user is created. Under the `single` posture -(a degraded wall included) the user joins the default organization, as every new -user does ([Membership](/docs/deployment/tenancy-modes#membership-how-new-users-join-an-organization)). +(a degraded wall included) the user joins the default organization, as every +user an administrator creates does ([Membership](/docs/deployment/tenancy-modes#membership-how-new-users-join-an-organization)). The join is better-auth's `addMember`, the same act as **Add Member**, inside the account's transaction: an organization at its membership limit refuses the diff --git a/content/docs/permissions/sso.mdx b/content/docs/permissions/sso.mdx index a445578273a..2e6cda877c4 100644 --- a/content/docs/permissions/sso.mdx +++ b/content/docs/permissions/sso.mdx @@ -748,6 +748,11 @@ and no user is created. These sign-ins are unchanged: - the first human of a deployment that has none yet; - every sign-in under the `email_domain` or `open` posture. +Admission is not acceptance: accepting an organization invitation needs a +verified email address, and an account an SSO sign-in creates counts as +verified only when the provider verified the address +([Self-hosting](/docs/deployment/self-hosting)). + To let a provider create accounts for everyone its IdP authenticates, as it did before this rule, turn on `allowJit` for that provider. With [domain verification](#domain-verification-opt-in) on, a provider still creates diff --git a/packages/runtime/src/declarative-update-refusal-order.pin.test.ts b/packages/runtime/src/declarative-update-refusal-order.pin.test.ts index 02fbc27ecaf..0bae166fe27 100644 --- a/packages/runtime/src/declarative-update-refusal-order.pin.test.ts +++ b/packages/runtime/src/declarative-update-refusal-order.pin.test.ts @@ -62,7 +62,6 @@ const BOOT_TIMEOUT = 180_000; const ORIGIN = 'http://localhost:3000'; const API = '/api/v1'; const ADMIN = { email: 'admin@objectos.ai', password: 'admin123' }; -const ORG = 'org_pin_30848'; const READER = { email: 'pin-30848-reader@example.invalid', password: 'Reader-Pass-123' }; const EDITOR = { email: 'pin-30848-editor@example.invalid', password: 'Editor-Pass-123' }; const OBJECT = 'pin_step';