Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions .changeset/29158-invite-blank-role-refused.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
---
'@objectstack/plugin-auth': patch
---

fix(plugin-auth)!: `invite-member` refuses a blank role 400 `ROLE_NOT_FOUND`, the way it refuses an unknown one, and writes no invitation (#29158)

Clause-②: no (narrowing) — `POST /api/v1/auth/organization/invite-member` with a blank role (`""`, whitespace only, or an empty role array) answered 200 and stored the invitation; it is now refused 400 `ROLE_NOT_FOUND`. A role list with an empty entry (`"member,"`) was already refused 400 `VALIDATION_FAILED` by the `sys_invitation.role` select validator, and now answers 400 `ROLE_NOT_FOUND`. Nothing is widened.
Metadata-protocol: none

<!-- adr-0087: not-required (no-migration-prescription) No key of any schema is added, removed, renamed or re-shaped, and no export or type of the spec changes: the invite door now refuses a role value that names no role, with the code it already answers for an unknown role, so there is nothing for a migration to rewrite and no tombstone. -->

**BREAKING** accept-set narrowing at the invite door (`@objectstack/plugin-auth`).

- **Before.** better-auth's role check splits the role list and drops empty entries before it looks for unknown names, so a blank role named no unknown role and passed. A blank value (`""`, whitespace only, an empty role array) was then stored as the invitation's role (`role: ''`). A role list with an empty entry (`"member,"`) was refused 400 `VALIDATION_FAILED` (`invalid_option`) by the `sys_invitation.role` select validator, and was stored only on a composition without the ObjectQL validator. Under a walled `group` posture, accepting it wrote a membership with no organization role, whose holder read less than a member and gave the administrator no reason why. An unknown role such as `superuser` was already refused 400 `ROLE_NOT_FOUND`.
- **Now.** The framework's `beforeCreateInvitation` refuses a blank role first, before the invitation role cap and before any row is written: 400, `code: 'ROLE_NOT_FOUND'`, and a message that says the invitation role is empty. A blank role is refused, never defaulted to `member`.
- **Unchanged.** Every named role is judged as before: the vocabulary, the role cap's three refusals and the placement gate. A resend of an invitation that is already pending keeps the stored role, as before.
- **Who sees it.** A script or form that invites with an empty role: it now gets the refusal instead of an invitation outside the role vocabulary. Invitations already stored with a blank role are not rewritten.
- **Who sees it, by code.** A client branching on `error.code` sees `VALIDATION_FAILED` become `ROLE_NOT_FOUND` for a role list with a blank entry; the status (400) and the absence of a row are unchanged.

**The remedy.** Send the organization role the invitee joins with, for example `member`.
Original file line number Diff line number Diff line change
Expand Up @@ -515,3 +515,81 @@ describe('#24750 — invite-member refuses an unknown role with the ADR-0112 cod
expect(membersOf(engine, DEFAULT_ORG, colleague.userId)[0]!.role).toBe('member');
});
});

describe('#29158 — invite-member refuses a blank role 400 ROLE_NOT_FOUND, like an unknown one', () => {
// better-auth's role check splits the role list and drops empty entries, so a
// blank role yields no unknown role and the vendor would store it verbatim
// (`sys_invitation.role = ''`); under a wall, accepting that invitation writes
// a membership with no organization role. The framework's
// `beforeCreateInvitation` refuses it before any row exists — and never
// defaults it to `member`.
beforeEach(() => {
vi.spyOn(console, 'info').mockImplementation(() => {});
vi.spyOn(console, 'warn').mockImplementation(() => {});
});

afterEach(() => {
vi.restoreAllMocks();
});

const BLANK_ROLES: ReadonlyArray<[string, unknown]> = [
['an empty string', ''],
['a whitespace-only string', ' '],
['an empty entry at the end of a role list', 'member,'],
['an empty entry at the start of a role list', ',admin'],
['an empty entry in a role array', ['member', '']],
['an empty role array', []],
];

for (const [label, role] of BLANK_ROLES) {
it(`${label} is refused 400 ROLE_NOT_FOUND, the message says the role is empty, and no invitation row exists`, async () => {
const { engine, manager, owner } = await bootWithOwner();
const email = 'qa-blank-role@example.com';

const res = await post(
manager,
'/organization/invite-member',
{ email, role, organizationId: DEFAULT_ORG },
owner.cookie,
);
const text = await res.clone().text();
expect(res.status, text).toBe(400);
const body: any = await res.json();
expect(body.code).toBe('ROLE_NOT_FOUND');
expect(body.message).toMatch(/^ROLE_NOT_FOUND: the invitation role is empty/);
expect(invitationsFor(engine, email)).toHaveLength(0);
});
}

it('a delegated admin\'s blank role answers ROLE_NOT_FOUND too — the blank refusal runs before the role cap', async () => {
const { engine, manager } = await bootWithOwner();
const delegate = await signUp(manager, engine, 'delegate.blank@example.com');
setRole(engine, DEFAULT_ORG, delegate.userId, 'delegated_admin');

const res = await post(
manager,
'/organization/invite-member',
{ email: 'qa-delegate-blank@example.com', role: '', organizationId: DEFAULT_ORG },
delegate.cookie,
);
const text = await res.clone().text();
expect(res.status, text).toBe(400);
expect(((await res.json()) as any).code).toBe('ROLE_NOT_FOUND');
expect(invitationsFor(engine, 'qa-delegate-blank@example.com')).toHaveLength(0);
});

it('CONTROL: a named role is unchanged — the owner invites an admin, 200 and the role stored as sent', async () => {
const { engine, manager, owner } = await bootWithOwner();

const ok = await post(
manager,
'/organization/invite-member',
{ email: 'qa-list@example.com', role: 'admin', organizationId: DEFAULT_ORG },
owner.cookie,
);
expect(ok.status, await ok.clone().text()).toBe(200);
const rows = invitationsFor(engine, 'qa-list@example.com');
expect(rows).toHaveLength(1);
expect(rows[0]!.role).toBe('admin');
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ import { buildOrganizationPluginSchema } from './auth-schema-config.js';
import { CLOUD_MANAGED_REFUSAL_CODE, CLOUD_MANAGED_REFUSAL_MESSAGES } from './cloud-managed.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 { resolveMembershipLimitOption } from './membership-limit.js';
Expand Down Expand Up @@ -339,6 +340,19 @@ export async function buildOrganizationPlugin(this: OrganizationPluginHost) {
code: CLOUD_MANAGED_REFUSAL_CODE,
});
}
// [#29158] A blank role — `""`, whitespace, or an empty entry in a
// role list — names no role, so it is refused like an unknown one:
// 400 `ROLE_NOT_FOUND`, before the role cap and before any row is
// written. better-auth's own check drops empty entries, so without
// this the invitation is stored with `role: ''` and, under a wall, its
// acceptance writes a membership with no organization role. Refused,
// never defaulted to `member`.
const blankRole = blankInvitationRoleRefusal(invitation?.role);
if (blankRole) {
const { APIError } = await import('better-auth/api');
throw new APIError('BAD_REQUEST', { message: blankRole.message, code: blankRole.code });
}

const inviterUserId = inviter?.id ?? inviter?.userId ?? null;
const organizationId = organization?.id ?? invitation?.organizationId;

Expand Down
6 changes: 4 additions & 2 deletions packages/plugins/plugin-auth/src/invitation-role-cap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -184,8 +184,10 @@ export function invitationRoleCapFailure(
issuerRole: unknown,
): InvitationRoleCapRefusal | null {
const requested = parseOrgRoles(requestedRole);
// No role at all: better-auth's body schema requires one, so this is not a
// reachable invitation shape. Nothing to cap — the route rejects it upstream.
// No role at all: nothing to cap. A blank role IS reachable — better-auth's
// body schema accepts `""` and its role check drops empty entries — and it is
// refused before this cap is asked (`blankInvitationRoleRefusal`,
// `invite-role-not-found-code.ts`), so a blank entry never reaches a verdict here.
if (requested.length === 0) return null;
if (isPlainMemberInvitation(requestedRole)) return null;

Expand Down
41 changes: 41 additions & 0 deletions packages/plugins/plugin-auth/src/invite-role-not-found-code.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,3 +66,44 @@ export async function codeInviteRoleNotFound(ctx: any): Promise<void> {
if (typeof message !== 'string' || !message.startsWith(VENDOR_MESSAGE_PREFIX)) return;
throw new APIError('BAD_REQUEST', { code: ROLE_NOT_FOUND_CODE, message });
}

/** A refusal this module answers on the invite door: the ADR-0112 code and the sentence. */
export interface InviteRoleRefusal {
readonly code: typeof ROLE_NOT_FOUND_CODE;
readonly message: string;
}

/**
* Does the requested role value carry a BLANK entry — the whole value empty or
* whitespace-only (`""`, `" "`, `[]`), or one empty entry in a role list
* (`"member,"`, `["member", ""]`)?
*
* better-auth's role check splits the list and drops empty entries before it
* looks for unknown names, so a blank entry yields no unknown role and the
* vendor writes the raw value: `sys_invitation.role = ''` (or `'member,'`).
* Under a walled group, accepting such an invitation writes a membership with
* no organization role. A blank entry names no role in the ADR-0108
* vocabulary, so it is refused exactly like an unknown one — never defaulted
* to `member`, which would be a product choice and not a refusal.
*/
export function hasBlankInvitationRoleEntry(requestedRole: unknown): boolean {
const flat = Array.isArray(requestedRole) ? requestedRole.join(',') : requestedRole;
if (typeof flat !== 'string') return false;
return flat.split(',').some((entry) => entry.trim().length === 0);
}

/**
* The refusal for a blank invitation role, or `null` when every entry names a
* role. Same code and status family as the vendor's unknown-role refusal
* (`400 ROLE_NOT_FOUND`), with a sentence that says the role is empty. Asked
* in `beforeCreateInvitation`, so no invitation row is written.
*/
export function blankInvitationRoleRefusal(requestedRole: unknown): InviteRoleRefusal | null {
if (!hasBlankInvitationRoleEntry(requestedRole)) return null;
return {
code: ROLE_NOT_FOUND_CODE,
message:
`${VENDOR_MESSAGE_PREFIX}the invitation role is empty — name the organization role ` +
`the invitee joins with; a blank role, or an empty entry in a role list, names no role.`,
};
}
107 changes: 107 additions & 0 deletions packages/qa/dogfood/test/invitation-blank-role-refusal.dogfood.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
//
// [#29158] `POST /auth/organization/invite-member` refuses a BLANK role the way
// it refuses an unknown one — 400 `ROLE_NOT_FOUND`, and no `sys_invitation`
// row — in both postures the defect was measured in.
//
// better-auth's own role check splits the role list and drops empty entries, so
// a blank role yields no unknown role: on `main` before this the door answered
// 200 and stored `role: ''`, and on a walled `group` boot the invitee's
// acceptance wrote a `sys_member` row with no organization role. The
// framework's `beforeCreateInvitation` now refuses it before any row exists;
// it never defaults the role to `member`.
//
// Why a dogfood beside the unit pins: only the composed stack runs the vendor
// route, the framework hook and the ObjectQL write together, on both postures.

import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import crmStack from '@objectstack/example-crm';
import { bootStack, type VerifyStack } from '@objectstack/verify';

const SYS = { context: { isSystem: true } };

for (const posture of ['single', 'group'] as const) {
describe(`[#29158] ${posture}: invite-member refuses a blank role 400 ROLE_NOT_FOUND`, () => {
let stack: VerifyStack;
let ql: any;
let token: string;
let orgId: string;
const previous = process.env.OS_TENANCY_POSTURE;

const invitationsFor = async (email: string): Promise<Record<string, unknown>[]> =>
ql.find('sys_invitation', { where: { email }, ...SYS });

beforeAll(async () => {
process.env.OS_TENANCY_POSTURE = posture;
stack = await bootStack(crmStack as never, posture === 'single' ? {} : { multiTenant: 'posture-only' });
const adminToken = await stack.signIn();
ql = await stack.kernel.getServiceAsync<any>('objectql');

if (posture === 'single') {
// The seeded admin owns the Default Organization the boot created.
token = adminToken;
const [org] = await ql.find('sys_organization', { where: { slug: 'default' }, limit: 1, ...SYS });
expect(org?.id, 'the boot created the Default Organization').toBeTruthy();
orgId = String(org.id);
return;
}

// Walled: the admin creates a second organization and owns it — the
// issuer the card measured is the owner of an organization other than
// the Default one.
token = adminToken;
const created = await stack.apiAs(token, 'POST', '/auth/organization/create', {
name: 'Blank Role Org',
slug: 'blank-role-org',
});
expect(created.status, `organization/create: ${await created.clone().text()}`).toBe(200);
orgId = String(((await created.json()) as { id?: string }).id ?? '');
expect(orgId).not.toBe('');
}, 180_000);

afterAll(async () => {
await stack?.stop?.();
if (previous === undefined) delete process.env.OS_TENANCY_POSTURE;
else process.env.OS_TENANCY_POSTURE = previous;
});

it('guard: the boot runs the posture under test', async () => {
const tenancy = await stack.kernel.getServiceAsync<{ posture: string; degraded: boolean }>('tenancy');
expect(tenancy.posture).toBe(posture);
expect(tenancy.degraded).toBe(false);
});

const BLANK_ROLES = [
['an empty role', ''],
['a whitespace-only role', ' '],
['an empty entry in a role list', 'member,'],
] as const;
for (const [label, role] of BLANK_ROLES) {
it(`${label} is refused 400 ROLE_NOT_FOUND and leaves no invitation row`, async () => {
const email = `blank-${posture}-${BLANK_ROLES.findIndex(([, r]) => r === role)}@dogfood.test`;
const res = await stack.apiAs(token, 'POST', '/auth/organization/invite-member', {
email,
role,
organizationId: orgId,
});
const text = await res.clone().text();
expect(res.status, text).toBe(400);
const body = JSON.parse(text) as { code?: string; error?: { code?: string } };
expect(body.code ?? body.error?.code, text).toBe('ROLE_NOT_FOUND');
expect(await invitationsFor(email)).toEqual([]);
}, 60_000);
}

it('CONTROL: a named role is unchanged — 200 and one pending row carrying it', async () => {
const email = `named-${posture}@dogfood.test`;
const res = await stack.apiAs(token, 'POST', '/auth/organization/invite-member', {
email,
role: 'member',
organizationId: orgId,
});
expect(res.status, await res.clone().text()).toBe(200);
const rows = await invitationsFor(email);
expect(rows.map((r) => [r.role, r.status])).toEqual([['member', 'pending']]);
}, 60_000);
});
}
Loading