Skip to content
Open
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
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [20, 22, 24]
node-version: [22, 24, 26]

steps:
- name: Checkout repo
Expand Down
41 changes: 41 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Important information for agents

- When writing something intended for human consumption, (comment, commit message, reply to prompt) use as few words as possible. Pick every word meticulously to reduce the volume to a strict minimum. Be down to the point. Less is more.

- Avoid superlatives and praise. Stop telling me I am absolutely right. Give me the cold hard truth.

- Avoid magic numbers and strings by extracting recurring or meaningful values into descriptive constants (const) or enums. Keep self-explanatory, one-off values inline to avoid clutter. If a value comes from a spec (e.g. HTTP 200 OK), use a constant regardless.

- Reduce code indentation. Avoid Arrow Anti-Pattern. Leverage early return and continue.

- Keep function names short. Less than 30 characters.

- Use enums instead of booleans for function parameters.

- Let the reader of the code breathe. Add empty lines between logical blocks of code.

- Add a small, to the point, comment to explain *what* the block does and *why*. Use examples when possible. Propose ASCII drawings to explain complete systems.

- Treat member visibility changes as a breaking design shift. Keep all fields and functions private unless external access is strictly required by the design. Prompt the user for explicit approval before changing any access modifier from private to internal or public.

- Program to levels of abstraction. Lower-level mechanics (e.g., raw hardware I/O, sector parsing, direct socket streams) must be encapsulated in a dedicated driver/abstraction layer. Expose clean, high-level APIs to the rest of the application so calling code works with domain concepts, not raw implementation details.

- Don't touch blocks of code unrelated to the feature you implement. e.g. Don't add comments to a block of code if you did not create it or modify it. As much as possible try to minimize the number of changed lines when implementing a feature.

- Strictly adhere to the layered boundary hierarchy: each layer may only communicate with its immediate neighbor directly below it. Never "punch holes" through layers (e.g., controllers or UI components must never directly call database queries, raw hardware drivers, or low-level network clients; always route through the intermediate service/abstraction layer).

- Always use {}, even on a one-line "if" statement.

When you write a commit message, follow these 7 rules:
Rule 1: Separate the subject line from the body with a single blank line.
Rule 2: Limit the subject line to 50 characters (72 is the absolute hard limit).
Rule 3: Capitalize the first letter of the subject line.
Rule 4: Do not end the subject line with a period.
Rule 5: Use the imperative mood in the subject line (e.g., "Fix bug," "Add feature,"
not "Fixed" or "Adds"). Test formula: It must complete the sentence: "If applied,
this commit will [your subject line here]".
Rule 6: Wrap the body text manually at 72 characters to prevent Git formatting issues.
Rule 7: Use the body to explain what and why vs. how. Assume the code explains the how;
the message must explain the context and reasoning.

- If the prompt indicates that a bug is being fixed, don't write the fix right away. First write the test. Observe it failing. Then write the fix. And observe the test passing.
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@
"private": true,
"license": "MIT",
"engines": {
"node": ">=20",
"pnpm": ">=10"
"node": ">=22",
"pnpm": ">=11"
},
"packageManager": "pnpm@10.18.1",
"packageManager": "pnpm@11.21.0",
Comment thread
coderabbitai[bot] marked this conversation as resolved.
"devDependencies": {
"@biomejs/biome": "^2.2.2",
"@sindresorhus/tsconfig": "^7.0.0",
Expand Down
12 changes: 12 additions & 0 deletions packages/better-auth/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,15 @@
### Unreleased
* * *

### Feature:
- Added entitlements, backed by `@chargebee/entitlements` (optional peer dependency). Pass a `ChargebeeEntitlements` client as the new `entitlements` option.
- Added `auth.api.hasAccess` (`POST /entitlements/has-access`) for switch features and `auth.api.getEntitlements` (`GET /entitlements/list`), also on the client plugin.
- Added `entitlementsMiddleware(options)`, which puts `hasAccess` and `getEntitlements` on `ctx.context.entitlements` in Better Auth endpoints.
- Targets default to the user's or active organization's Chargebee customer. `subscriptionId` targets one subscription owned by the reference.
- Added the `read-entitlements` `authorizeReference` action, the `ENTITLEMENTS_NOT_CONFIGURED` error code, and the `EntitlementsAccess` and `BooleanFeature` types.

---

### v1.2.0 (2026-07-10)
* * *

Expand Down
67 changes: 67 additions & 0 deletions packages/better-auth/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ The Chargebee plugin integrates [Chargebee's](https://www.chargebee.com) subscri
- Team subscription support with seats management
- Hosted checkout and portal via Chargebee Hosted Pages
- Self-service billing portal for managing payment methods, invoices, and subscriptions
- Feature gating with Chargebee entitlements (`hasAccess`, `getEntitlements`)

## Requirements

Expand Down Expand Up @@ -568,6 +569,71 @@ await authClient.subscription.cancel({
});
```

### Entitlements

Gate features on the signed-in user's or organization's [Chargebee entitlements](https://www.chargebee.com/docs/billing/2.0/entitlements/entitlements), backed by [`@chargebee/entitlements`](https://github.com/chargebee/js-framework-adapters/blob/main/packages/entitlements/README.md) and its caching:

```bash
pnpm add @chargebee/entitlements
```

```ts
import { ChargebeeEntitlements } from "@chargebee/entitlements/server"

chargebee({
chargebeeClient,
entitlements: new ChargebeeEntitlements({ chargebeeClient }),
})
```

`hasAccess` takes switch features only, because other feature types need usage tracking to decide access. It returns `true` only when Chargebee grants the feature. Missing, disabled, and unavailable entitlements return the feature's default, which is `false` for a plain feature ID. `getEntitlements` returns every entitlement of the reference.

**Server:**

```ts
const { hasAccess } = await auth.api.hasAccess({
headers,
body: { featureId: "advanced-reports" },
})
const entitlements = await auth.api.getEntitlements({ headers })
```

**Client:**

```ts
const { data } = await authClient.entitlements.hasAccess({ featureId: "advanced-reports" })
const { data: entitlements } = await authClient.entitlements.list()
```

**Better Auth endpoints and plugins:** `entitlementsMiddleware` adds `ctx.context.entitlements` for the request:

```ts
import { Feature } from "@chargebee/entitlements"
import { entitlementsMiddleware } from "@chargebee/better-auth"

const reports = new Feature("advanced-reports", false)

createAuthEndpoint("/reports", { method: "GET", use: [entitlementsMiddleware(chargebeeOptions)] }, async (ctx) => {
if (!(await ctx.context.entitlements.hasAccess(reports))) {
throw new APIError("FORBIDDEN")
}
return ctx.json(await ctx.context.entitlements.getEntitlements())
})
```

All three accept the same optional fields as the subscription routes:

| Field | Target |
| ---------------- | ------------------------------------------------------------------------------------------------------------ |
| none | The user's Chargebee customer, consolidated across their subscriptions. |
| `customerType` | `"organization"` targets the active organization's customer. Requires `authorizeReference`. |
| `referenceId` | Another user or organization, authorized with `authorizeReference` and the `read-entitlements` action. |
| `subscriptionId` | That Chargebee subscription. Rejected with `403` unless it belongs to the reference. |

A reference without a Chargebee customer has no entitlements.

> **Note:** Subscription webhooks don't refresh entitlement snapshots yet, so plan changes take effect after `snapshotTtlMs` (5 minutes by default). To apply them sooner, call `entitlements.refreshSnapshot({ customerId })` from your own `webhookHandler`.

### Webhook Handling

The plugin automatically processes common webhook events from Chargebee:
Expand Down Expand Up @@ -776,6 +842,7 @@ chargebee({
| `getCustomerCreateParams`| `function` | Return additional params for `cb.customer.create` (e.g. `first_name`, `last_name`). Receives `user` and optional `ctx`. |
| `onCustomerCreate` | `function` | Callback called after a customer is created. Receives `{ chargebeeCustomer, user }`. |
| `webhookHandler` | `function` | Callback receiving the webhook handler instance. Call `handler.on(EventType, fn)` to register typed event listeners. |
| `entitlements` | `ChargebeeEntitlements` | Entitlements client from `@chargebee/entitlements/server`. See [Entitlements](#entitlements). |
| `subscription` | `object` | Subscription configuration. See [Subscription options](#subscription-options). |
| `organization` | `object` | Enable Organization Customer support. See [Organization options](#organization-options). |

Expand Down
9 changes: 8 additions & 1 deletion packages/better-auth/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@chargebee/better-auth",
"author": "DX Chargebee",
"version": "1.2.0",
"version": "1.3.0",
Comment thread
cb-srinaths marked this conversation as resolved.
"type": "module",
"main": "dist/index.mjs",
"types": "dist/index.d.mts",
Expand Down Expand Up @@ -64,12 +64,19 @@
},
"peerDependencies": {
"@better-auth/core": "^1.4.18",
"@chargebee/entitlements": "^0.1.0-alpha.2",
"better-auth": "^1.4.0",
"better-call": "^1.1.7",
"chargebee": "^3.23.1"
},
"peerDependenciesMeta": {
"@chargebee/entitlements": {
"optional": true
}
},
"devDependencies": {
"@better-auth/core": "^1.5.3",
"@chargebee/entitlements": "workspace:*",
"@vitest/coverage-v8": "^4.0.18",
"better-auth": "^1.5.3",
"better-call": "^1.1.8",
Expand Down
2 changes: 2 additions & 0 deletions packages/better-auth/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ export const chargebeeClient = <
"/subscription/cancel": "POST",
"/subscription/portal": "POST",
"/subscription/list": "GET",
"/entitlements/has-access": "POST",
"/entitlements/list": "GET",
},
} satisfies BetterAuthClientPlugin;

Expand Down
Loading
Loading