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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions MIGRATIONS.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,18 @@ Breaking changes and upgrade notes for downstream projects.

---

## billing: only organization owners and admins can pay — checkout, extras checkout, Stripe portal (2026-11-16)

#4290: `billingAbilities` now grants `create` on `BillingCheckout`, `BillingPortal` and `BillingExtrasCheckout` only to a membership whose `role` is `owner` or `admin`. A plain `member` gets **403** on `POST /api/billing/checkout`, `POST /api/billing/portal` and `POST /api/billing/extras/checkout`, and those three rules disappear from the abilities sent to the client (signin, signup, token refresh, organization switch). Members keep `read` on `BillingSubscription`, `BillingUsage`, `BillingExtrasBalance` and `BillingExtrasLedger`. Platform admins are unchanged.

### Action for downstream

- **Nothing to do if your billing policy is the stack's.** A solo user is the owner of their own organization and keeps every right.
- **Your own code or tests that start a checkout or open the portal as a `member`**: run them as an owner or admin instead.
- **Vue**: ship the matching Vue stack update in the same batch — the organization billing tab now needs `create BillingPortal` and the pricing page hides checkout from members.

---

## Node 26 required: `.nvmrc` 26, `FROM node:26-slim`, `engines.node` `>=26.0.0` (2026-11-09)

#4263: the stack now declares and builds on Node 26. `.npmrc` carries `engine-strict=true`, so **`npm ci` fails with `EBADENGINE` on Node 24** (or any Node below 26) as soon as this change is merged. `engines.npm` stays `>=11.0.0`. CI needs no change of its own: `actions/setup-node` reads `.nvmrc` via `node-version-file`.
Expand Down
2 changes: 1 addition & 1 deletion lib/middlewares/policy.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ const registerAbilities = (entry) => {
* Build a CASL ability instance for a given user and optional membership.
* Iterates over all registered ability builder functions from module policy files.
* @param {Object|null} user - The authenticated user, or null/undefined for guests
* @param {Object|null} [membership] - Optional organization membership (reserved for future use)
* @param {Object|null} [membership] - Optional organization membership; policies read its `role` (e.g. billing pay rights)
* @returns {Promise<import('@casl/ability').MongoAbility>} CASL ability instance
*/
const defineAbilityFor = async (user, membership) => {
Expand Down
20 changes: 14 additions & 6 deletions modules/billing/policies/billing.policy.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
/**
* Billing ability definitions for CASL document-level authorization.
*/
import { MEMBERSHIP_ROLES } from '../../organizations/lib/constants.js';

/** Membership roles allowed to pay for the organization (checkout, extras, Stripe portal). */
const BILLING_MANAGER_ROLES = [MEMBERSHIP_ROLES.OWNER, MEMBERSHIP_ROLES.ADMIN];

/**
* Register billing-related subjects for path-level resolution.
Expand Down Expand Up @@ -39,9 +43,11 @@ export function billingSubjectRegistration({ registerPathSubject }) {

/**
* Define billing-related abilities for an authenticated user.
* Any authenticated user with an organization membership can manage billing.
* Every organization member can read the subscription, usage and extras balance/ledger.
* Only owners and admins can pay for the organization: start a plan checkout,
* buy extras, or open the Stripe billing portal.
* @param {Object} user - The authenticated user
* @param {Object|null} membership - Optional organization membership
* @param {Object|null} membership - Organization membership; its `role` decides the pay rights
* @param {Object} builder - CASL AbilityBuilder helpers
* @param {Function} builder.can - Grant an ability
* @returns {void}
Expand All @@ -54,14 +60,16 @@ export function billingAbilities(user, membership, { can }) {

if (!membership) return;

can('create', 'BillingCheckout');
can('create', 'BillingPortal');
can('read', 'BillingSubscription');
can('read', 'BillingUsage');
// Extras: members can purchase packs and read their own balance/ledger
can('create', 'BillingExtrasCheckout');
can('read', 'BillingExtrasBalance');
can('read', 'BillingExtrasLedger');

if (BILLING_MANAGER_ROLES.includes(membership.role)) {
can('create', 'BillingCheckout');
can('create', 'BillingPortal');
can('create', 'BillingExtrasCheckout');
}
}

/**
Expand Down
77 changes: 77 additions & 0 deletions modules/billing/tests/billing.abilities.unit.tests.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/**
* Module dependencies.
*/
import { describe, test, expect } from '@jest/globals';
import { AbilityBuilder, createMongoAbility } from '@casl/ability';

import { billingAbilities } from '../policies/billing.policy.js';
import { MEMBERSHIP_ROLES } from '../../organizations/lib/constants.js';

/**
* Unit tests for billingAbilities with a real CASL AbilityBuilder: only organization
* owners and admins can pay for the organization (checkout, extras checkout, Stripe
* portal); every member keeps the billing read rights.
*/

const PAY_SUBJECTS = ['BillingCheckout', 'BillingPortal', 'BillingExtrasCheckout'];
const READ_SUBJECTS = ['BillingSubscription', 'BillingUsage', 'BillingExtrasBalance', 'BillingExtrasLedger'];

/**
* Build a real CASL ability from billingAbilities.
* @param {Object} user - user fixture
* @param {Object|null} membership - membership fixture (plain object, as defineAbilityFor passes it)
* @returns {import('@casl/ability').MongoAbility} built ability
*/
function buildAbility(user, membership) {
const { can, cannot, build } = new AbilityBuilder(createMongoAbility);
billingAbilities(user, membership, { can, cannot });
return build();
}

/**
* @param {string} role - membership role
* @returns {Object} membership fixture
*/
const membership = (role) => ({ role, organizationId: '507f1f77bcf86cd799439011' });

const user = { _id: 'u1', roles: ['user'] };

describe('billingAbilities (real CASL):', () => {
describe.each([MEMBERSHIP_ROLES.OWNER, MEMBERSHIP_ROLES.ADMIN])('%s', (role) => {
test.each(PAY_SUBJECTS)('can create %s', (subject) => {
expect(buildAbility(user, membership(role)).can('create', subject)).toBe(true);
});

test.each(READ_SUBJECTS)('can read %s', (subject) => {
expect(buildAbility(user, membership(role)).can('read', subject)).toBe(true);
});
});

describe('member', () => {
test.each(PAY_SUBJECTS)('cannot create %s', (subject) => {
expect(buildAbility(user, membership(MEMBERSHIP_ROLES.MEMBER)).can('create', subject)).toBe(false);
});

test.each(READ_SUBJECTS)('can still read %s', (subject) => {
expect(buildAbility(user, membership(MEMBERSHIP_ROLES.MEMBER)).can('read', subject)).toBe(true);
});
});

test('membership without a role gets no pay rights', () => {
const ability = buildAbility(user, { organizationId: 'x' });
for (const subject of PAY_SUBJECTS) expect(ability.can('create', subject)).toBe(false);
});

test('no membership gets no billing rights', () => {
const ability = buildAbility(user, null);
for (const subject of [...PAY_SUBJECTS, ...READ_SUBJECTS]) {
expect(ability.can('create', subject)).toBe(false);
expect(ability.can('read', subject)).toBe(false);
}
});

test('platform admin manages everything, whatever the membership', () => {
const ability = buildAbility({ roles: ['user', 'admin'] }, membership(MEMBERSHIP_ROLES.MEMBER));
for (const subject of PAY_SUBJECTS) expect(ability.can('create', subject)).toBe(true);
});
});
164 changes: 164 additions & 0 deletions modules/billing/tests/billing.policy.integration.tests.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
/**
* Module dependencies.
*/
import request from 'supertest';
import path from 'path';

import { beforeAll, afterAll, describe, test, expect } from '@jest/globals';
import { bootstrap } from '../../../lib/app.js';
import config from '../../../config/index.js';

/**
* Billing policy integration tests — through the real auth, organization and policy
* middlewares. Only organization owners and admins can start a plan checkout, an
* extras checkout or open the Stripe portal; a plain member gets 403 on all three
* and keeps read access. The abilities sent to the client say the same thing.
*
* Owner/admin requests send a body the route validator rejects (unknown key): a 422
* proves the policy let the request through without reaching Stripe.
*/
describe('Billing policy — owner/admin only pay routes:', () => {
let app;
let UserService;
let MembershipService;
let MembershipRepository;
let OrganizationsRepository;

const PASSWORD = 'W@os.jsI$Aw3$0m3';
const EMAILS = {
owner: 'billing-policy-owner@test.com',
admin: 'billing-policy-admin@test.com',
member: 'billing-policy-member@test.com',
};
const PAY_ROUTES = ['/api/billing/checkout', '/api/billing/portal', '/api/billing/extras/checkout'];
const PAY_SUBJECTS = ['BillingCheckout', 'BillingPortal', 'BillingExtrasCheckout'];
const originalOrganizations = { ...config.organizations };

const agents = {};
const users = {};
const signupAbilities = {};
const switchAbilities = {};
let orgId;

/**
* @param {Array<Object>} abilities - serialized CASL rules
* @param {string} subject - CASL subject
* @returns {boolean} true when a `create` rule exists for the subject
*/
const hasCreate = (abilities, subject) => abilities.some((r) => r.action === 'create' && r.subject === subject && !r.inverted);

/**
* Remove a user, their memberships and the organizations they own.
* @param {string} email - user email
* @returns {Promise<void>}
*/
const cleanup = async (email) => {
try {
const existing = await UserService.getBrut({ email });
if (!existing) return;
const memberships = await MembershipRepository.list({ userId: existing._id });
for (const m of memberships) {
if (m.role !== 'owner') continue;
const id = m.organizationId._id || m.organizationId;
await MembershipRepository.deleteMany({ organizationId: id });
await OrganizationsRepository.deleteMany({ _id: id });
}
await MembershipRepository.deleteMany({ userId: existing._id });
await UserService.remove(existing);
} catch (_) { /* cleanup — ignore */ }
};

beforeAll(async () => {
config.organizations = { ...config.organizations, enabled: true, autoCreate: true, domainMatching: false };
app = (await bootstrap()).app;
UserService = (await import(path.resolve('./modules/users/services/users.service.js'))).default;
MembershipService = (await import(path.resolve('./modules/organizations/services/organizations.membership.service.js'))).default;
MembershipRepository = (await import(path.resolve('./modules/organizations/repositories/organizations.membership.repository.js'))).default;
OrganizationsRepository = (await import(path.resolve('./modules/organizations/repositories/organizations.repository.js'))).default;

for (const email of Object.values(EMAILS)) await cleanup(email);

for (const [key, email] of Object.entries(EMAILS)) {
agents[key] = request.agent(app);
const res = await agents[key]
.post('/api/auth/signup')
.send({ firstName: 'Billing', lastName: key, email, password: PASSWORD, provider: 'local' })
.expect(200);
users[key] = res.body.user;
signupAbilities[key] = res.body.abilities;
}

orgId = String(users.owner.currentOrganization);
await MembershipService.create({ userId: users.admin.id || users.admin._id, organizationId: orgId, role: 'admin' });
await MembershipService.create({ userId: users.member.id || users.member._id, organizationId: orgId, role: 'member' });

// Billing routes act on the caller's current organization: move admin and member into the owner's.
for (const key of ['admin', 'member']) {
const res = await agents[key].post(`/api/organizations/${orgId}/switch`).expect(200);
switchAbilities[key] = res.body.data.abilities;
}
});

afterAll(async () => {
for (const email of Object.values(EMAILS)) await cleanup(email);
config.organizations = originalOrganizations;
});

describe('pay routes', () => {
test.each(PAY_ROUTES)('member gets 403 from the policy on POST %s', async (route) => {
const res = await agents.member.post(route).send({ bogus: true });
expect(res.status).toBe(403);
expect(res.body.description).toBe('User is not authorized');
});

test.each(PAY_ROUTES)('owner passes the policy on POST %s', async (route) => {
const res = await agents.owner.post(route).send({ bogus: true });
expect(res.status).toBe(422);
});

test.each(PAY_ROUTES)('admin passes the policy on POST %s', async (route) => {
const res = await agents.admin.post(route).send({ bogus: true });
expect(res.status).toBe(422);
});
});

describe('member read routes stay open', () => {
test.each(['/api/billing/subscription', '/api/billing/usage', '/api/billing/extras/balance', '/api/billing/extras/ledger'])(
'member is not refused by the policy on GET %s',
async (route) => {
const res = await agents.member.get(route);
expect(res.status).toBe(200);
expect(res.body.type).toBe('success');
},
);
});

describe('abilities sent to the client', () => {
test.each(PAY_SUBJECTS)('owner signup response grants create %s', (subject) => {
expect(hasCreate(signupAbilities.owner, subject)).toBe(true);
});

test.each(PAY_SUBJECTS)('admin switch response grants create %s', (subject) => {
expect(hasCreate(switchAbilities.admin, subject)).toBe(true);
});

test.each(PAY_SUBJECTS)('member switch response does not grant create %s', (subject) => {
expect(hasCreate(switchAbilities.member, subject)).toBe(false);
});

test('token refresh: owner has the pay rights, member has none', async () => {
const owner = (await agents.owner.get('/api/auth/token').expect(200)).body.abilities;
const member = (await agents.member.get('/api/auth/token').expect(200)).body.abilities;
for (const subject of PAY_SUBJECTS) {
expect(hasCreate(owner, subject)).toBe(true);
expect(hasCreate(member, subject)).toBe(false);
}
expect(member.some((r) => r.action === 'read' && r.subject === 'BillingSubscription')).toBe(true);
});

test('signin: member signed back in keeps no pay rights', async () => {
const res = await agents.member.post('/api/auth/signin').send({ email: EMAILS.member, password: PASSWORD }).expect(200);
for (const subject of PAY_SUBJECTS) expect(hasCreate(res.body.abilities, subject)).toBe(false);
});
});
});
Loading