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
new file mode 100644
index 00000000000..8afddab1f61
--- /dev/null
+++ b/.changeset/invitation-acceptance-verified-address.md
@@ -0,0 +1,28 @@
+---
+'@objectstack/plugin-auth': patch
+'@objectstack/verify': patch
+'@object-ui/app-shell': 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
+
+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.
+
+- 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 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 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.
+
+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/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/self-hosting.mdx b/content/docs/deployment/self-hosting.mdx
index c2078f5f997..563c557f024 100644
--- a/content/docs/deployment/self-hosting.mdx
+++ b/content/docs/deployment/self-hosting.mdx
@@ -755,26 +755,41 @@ 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 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
+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 +846,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/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/docs/qa/platform-checklist/RUNNER.md b/docs/qa/platform-checklist/RUNNER.md
index 54cbecf8d2d..dec92df6305 100644
--- a/docs/qa/platform-checklist/RUNNER.md
+++ b/docs/qa/platform-checklist/RUNNER.md
@@ -586,21 +586,22 @@ 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 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
+ ⚠️ **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
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/plugins/plugin-auth/src/accept-invitation-adopt-membership.test.ts b/packages/plugins/plugin-auth/src/accept-invitation-adopt-membership.test.ts
index ee25ee1f7b8..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();
@@ -198,6 +202,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 +274,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 +316,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 +353,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 +394,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/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/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-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 97171743e03..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,19 +85,99 @@ export interface MembershipAdmissionHost {
getMembershipPolicy: AuthManager['getMembershipPolicy'];
hasPendingInvitationFor: AuthManager['hasPendingInvitationFor'];
hasPresentedPendingInvitation: AuthManager['hasPresentedPendingInvitation'];
+ hasInvitationAdmissionInRequest: AuthManager['hasInvitationAdmissionInRequest'];
isBootstrapCreation: AuthManager['isBootstrapCreation'];
isOperatorProvisioning: AuthManager['isOperatorProvisioning'];
+ isInvitationAdmissionInRequest: AuthManager['isInvitationAdmissionInRequest'];
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, 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,
+ userId: string,
+ ctx: unknown,
+): Promise {
+ if (!this.hasInvitationAdmissionInRequest(ctx)) 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.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, userId: unknown): Promise {
+export async function settleMembership(
+ 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, 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 },
+ );
+ 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 +200,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 +248,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 +264,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 +313,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(ctx, 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..8c145edf8af 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(); },
@@ -2717,14 +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),
+ hasInvitationAdmissionInRequest: (...a) => this.hasInvitationAdmissionInRequest(...a),
+ isInvitationAdmissionInRequest: (...a) => this.isInvitationAdmissionInRequest(...a),
};
- return settleMembership.call(host, userId);
+ return settleMembership.call(host, userId, ctx);
}
/**
@@ -2833,6 +2834,7 @@ export class AuthManager {
private static readonly OWNER_STAMP_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 +2990,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 +3000,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 +3414,45 @@ export class AuthManager {
}
}
+ /**
+ * 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
} />
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';
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/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;