Authorization Policies

Write business rules as policies with @kit/policies: define, register and run them, with stages, ALL/ANY operators and fail-closed errors.

Permissions answer "may this role do this action?". Policies answer the business questions on top: "may this user delete their account while they still have an active subscription?", "has this organization hit its seat limit?". @kit/policies gives you five functions for that: definePolicy, allow and deny to write a rule, createPolicyRegistry to collect rules, and createPolicyRuntime to run them against a context.

End-to-End Example

Block account deletion while the user has an active subscription or still owns an organization:

import {
allow,
createPolicyRegistry,
createPolicyRuntime,
definePolicy,
deny,
} from '@kit/policies';
interface DeleteAccountContext {
userId: string;
hasActiveSubscription: boolean;
ownedOrganizationCount: number;
}
const noActiveSubscription = definePolicy<DeleteAccountContext>({
id: 'delete-account.no-active-subscription',
evaluate: async (ctx) =>
ctx.hasActiveSubscription
? deny({
code: 'ACTIVE_SUBSCRIPTION',
message: 'Cancel your subscription before deleting your account',
})
: allow(),
});
const ownsNoOrganization = definePolicy<DeleteAccountContext>({
id: 'delete-account.owns-no-organization',
evaluate: async (ctx) =>
ctx.ownedOrganizationCount > 0
? deny({
code: 'OWNS_ORGANIZATION',
message: 'Transfer or delete your organizations first',
remediation: 'Open Settings > Organizations',
})
: allow(),
});
export const deleteAccountPolicies = createPolicyRuntime(
createPolicyRegistry<DeleteAccountContext>()
.registerPolicy(noActiveSubscription)
.registerPolicy(ownsNoOrganization),
);

Then, inside the action that deletes the account, after you've loaded the facts:

const { allowed, reasons } = await deleteAccountPolicies.run({
userId: user.id,
hasActiveSubscription,
ownedOrganizationCount,
});
if (!allowed) {
return { error: reasons[0] };
}

Load data before run and pass it in the context, so policies stay pure, fast and easy to test.

Writing a Policy

definePolicy({ id, stages?, evaluate }) takes:

  • id: unique and stable, e.g. 'delete-account.no-active-subscription'. Every result records it as metadata.policyId, so it's what you'll see when you log results.
  • evaluate(ctx, stage): returns allow(metadata?) or deny({ code, message, remediation?, metadata? }).
  • stages (optional): see Stages.

deny's message becomes the result's reason, which callers show to users: keep it short and free of internals. code, remediation and your metadata go into metadata for the UI and logs. allow and deny results also get policyId and stage in their metadata.

The context arrives frozen (a shallow copy), so a policy can't reassign a field the next one reads. Pass a plain object: class instances lose their prototype methods in the copy.

Policies Fail Closed

A policy that throws, rejects, or returns anything other than { allowed: boolean } is denied, never skipped:

{
allowed: false,
reason: 'Policy evaluation failed',
metadata: {
code: 'POLICY_EVALUATION_ERROR',
policyId: 'delete-account.no-active-subscription',
stage: undefined,
error: 'connection terminated unexpectedly',
},
}

A deny that has no reason still adds 'Policy denied' to reasons, so reasons[0] is never undefined on a deny.

Running Policies

createPolicyRuntime(registry).run(ctx, { operator, stage }) runs the registry's policies one at a time, in registration order, and returns { allowed, reasons, results }.

operatorAllows whenStops atEmpty registry
'ALL' (default)every policy allowsthe first deny, with its reasonallows
'ANY'at least one policy allowsthe first allowdenies ('No policies matched the criteria')

run(ctx) with no options means ALL across every policy, whatever its stages. An unknown operator throws.

The runtime is typed by the registry: create the registry with your context type (createPolicyRegistry<DeleteAccountContext>()) and run only accepts that context. Registering a policy written for another context type fails type-checking, and registering anything not created by definePolicy throws at runtime.

Stages

Stages let one registry run different rules at different points of a flow. They're plain strings you choose:

const emailDomainAllowed = definePolicy<InviteContext>({
id: 'invite.email-domain',
stages: ['submission'],
evaluate: async (ctx) =>
ctx.email.endsWith('@acme.com')
? allow()
: deny({ code: 'EMAIL_DOMAIN', message: 'Invite people from acme.com' }),
});
await invitePolicies.run(ctx, { stage: 'preliminary' }); // skips it
await invitePolicies.run(ctx, { stage: 'submission' }); // runs it

With stage set, only policies that list it, plus policies with no stages, run. stages: [] throws: omit stages to run in every stage.

Spell stages exactly. A typo filters out every policy that lists stages, and with ALL an empty run allows. To catch typos, give the registry its stages, as a type and a list:

const INVITE_STAGES = ['preliminary', 'submission'] as const;
type InviteStage = (typeof INVITE_STAGES)[number];
const inviteRegistry = createPolicyRegistry<InviteContext, InviteStage>({
stages: INVITE_STAGES,
});
definePolicy<InviteContext, InviteStage>({
id: 'invite.typo',
stages: ['submision'], // type error
evaluate: async () => allow(),
});

Registering a policy that lists any other stage (a cast, plain JS) throws Policy "<id>" lists the stage "<stage>"; use preliminary, submission, and run only takes those stages.

The Registry

const registry = createPolicyRegistry<DeleteAccountContext>()
.registerPolicy(noActiveSubscription);
registry.hasPolicy('delete-account.no-active-subscription'); // true
registry.listPolicies(); // ids, in registration order
registry.getPolicy('missing'); // throws: Policy "missing" is not registered

Registering an id twice throws Policy "<id>" is already registered. Policy definitions are frozen, so they can't be patched after registration. A registry at module scope lives for the whole Worker isolate and is shared by every request, so keep policies free of per-request state.

Invitation Policies

The kit runs your rules before an organization invitation is created, resent or accepted. Register them in apps/web/config/invitation-policies.config.server.ts (yours to edit, empty by default), with defineInvitationPolicy from @kit/organizations/server:

import { allow, deny } from '@kit/policies';
import {
createInvitationPolicies,
defineInvitationPolicy,
} from '@kit/organizations/server';
export const invitationPolicies = createInvitationPolicies()
.registerPolicy(
defineInvitationPolicy({
id: 'invitations.seat-limit',
stages: ['invite', 'accept'],
evaluate: async ({ memberCount, pendingCount }) =>
memberCount + pendingCount >= 10
? deny({
code: 'SEAT_LIMIT',
message: 'app.invitations.seatLimit',
remediation: 'app.invitations.upgrade',
})
: allow(),
}),
);

with its copy in apps/web/messages/en/app.json:

{
"invitations": {
"seatLimit": "Your plan has no seats left.",
"upgrade": "Upgrade to add members."
}
}

createInvitationPolicies() is a registry with the invitation context and stages, and defineInvitationPolicy is definePolicy with both typed: a misspelled stage is a type error, and a policy that still lists one (a cast, plain JS) throws when it's registered, naming the policy and the stage, instead of a rule that silently never runs.

  • Stages: invite, resend and accept. Declining and canceling always go through. One policy can serve several stages and branch on ctx.stage: at accept the reader is the invitee, so give them their own copy (message: ctx.stage === 'accept' ? 'app.invitations.orgFull' : 'app.invitations.seatLimit').

  • Context: stage, organizationId, actorUserId (who invites or resends; the invitee when accepting), email, role, memberCount and pendingCount: the organization's members and live (pending, unexpired) invitations, not counting the one being resent or accepted, so the example's last seat still fits. The counts are loaded once, before your policies run, and only when at least one is registered.

  • Your own data: the context has what the kit knows. For anything else (the plan's seats, an allow-list), read it inside evaluate by organizationId: an invitation policy runs once per action, so this is the place, unlike the "load before run" rule for policies you run yourself:

    defineInvitationPolicy({
    id: 'invitations.plan-seats',
    stages: ['invite', 'accept'],
    evaluate: async ({ organizationId, memberCount, pendingCount }) => {
    const seats = await getPlanSeats(organizationId); // your billing lookup
    return memberCount + pendingCount >= seats
    ? deny({ code: 'SEAT_LIMIT', message: 'app.invitations.seatLimit' })
    : allow();
    },
    });
  • Order: after the kit's permission, role-cap and send-limit checks, never instead of them; Better Auth's own refusals (already a member, already invited, the pending cap) come after your policies. A denial creates, claims, queues and joins nothing.

  • Limits are checked, not locked: two invites or accepts at the same moment can both pass a count-based policy. For a limit that must never be exceeded, also enforce it where the write happens (a database constraint, or a check in your own code that holds a lock).

  • Message: message and remediation are translation keys in your messages; the invite dialog, the resend toast and the invitation page show the message, then the remediation. An unknown key, or a policy that threw, shows the kit's generic "This can't be done right now", and in development the browser console names the key it couldn't find.

  • Logs: a denial logs invitation.refused (warn) with code: 'POLICY_DENIED', the policy's id and its policyCode. A policy that threw is logged at error with policyCode: 'POLICY_EVALUATION_ERROR', so a bug that blocks every invite stands out; its error text (metadata.error) is not logged, since it could contain the invited address. Log what you need inside your policy, without personal data.

  • Testing: a policy is a plain function of its context: call evaluate with the case you care about.

    const context = {
    stage: 'invite',
    organizationId: 'org-1',
    actorUserId: 'user-1',
    email: 'new@acme.dev',
    role: 'member',
    memberCount: 9,
    pendingCount: 1,
    } as const;
    expect(await seatLimit.evaluate(context)).toMatchObject({ allowed: false });
    expect(
    await seatLimit.evaluate({ ...context, stage: 'accept', pendingCount: 0 }),
    ).toMatchObject({ allowed: true });

Member Policies

The kit runs your rules before a member's role changes or a member is removed, from the members page. Register them in apps/web/config/member-policies.config.server.ts (yours to edit, empty by default), with defineMemberPolicy from @kit/organizations/server:

import { allow, deny } from '@kit/policies';
import {
createMemberPolicies,
defineMemberPolicy,
} from '@kit/organizations/server';
export const memberPolicies = createMemberPolicies()
.registerPolicy(
defineMemberPolicy({
id: 'members.keep-billing-contact',
stages: ['remove', 'changeRole'],
evaluate: async ({ organizationId, targetUserId }) =>
(await getBillingContact(organizationId)) === targetUserId // yours
? deny({
code: 'BILLING_CONTACT',
message: 'app.members.billingContact',
remediation: 'app.members.changeBillingContact',
})
: allow(),
}),
);
  • Stages: changeRole and remove. Leaving the organization always goes through, and no policy runs on it: a rule such as "keep the billing contact" stops a manager from removing them, not the member from leaving. Like invitations, a misspelled stage is a type error, and a policy that still lists one throws when it's registered (createMemberPolicies()).
  • Context: stage, organizationId, actorUserId, memberId, targetUserId, currentRoles (the member's roles; several only for a legacy comma-joined row, so test with currentRoles.includes('admin')), newRole (changeRole only), and memberCount and ownerCount before the change. Everything comes from the database after the kit's checks, never from the request beyond the ids; the counts are loaded only when a policy runs at that stage.
  • Order: after the kit's checks (the organization, the permission, the member being in it, who may act on whom, a valid role), never instead of them. Picking a member's current role is a no-op and runs no policy. The database's at-least-one-owner guard still applies after your policies allow.
  • Checked, not locked: two managers acting at the same moment can both pass a count-based policy ("at most 3 admins"). For a limit that must never be exceeded, also enforce it where the write happens.
  • Message: a denial answers 409 with your message and remediation (translation keys), shown in the toast; nothing changes. An unknown key, or a policy that threw, shows the kit's generic message.
  • Logs: a denial logs member.refused (warn) with code: 'POLICY_DENIED', the policy's id and its policyCode, the member id and its role (and the new role, for a role change); a policy that threw is logged at error with policyCode: 'POLICY_EVALUATION_ERROR'. Its error text is not logged.
  • Testing: call evaluate with a context, as for invitation policies.

Organization Policies

The kit runs these before an organization is deleted: when the owner asks for the deletion code, and again when they confirm. Register yours in apps/web/config/organization-policies.config.server.ts (yours to edit, empty by default), with defineOrganizationPolicy from @kit/organizations/server:

import { allow, deny } from '@kit/policies';
import {
createOrganizationPolicies,
defineOrganizationPolicy,
} from '@kit/organizations/server';
export const organizationPolicies = createOrganizationPolicies()
.registerPolicy(
defineOrganizationPolicy({
id: 'organizations.legal-hold',
stages: ['delete'],
evaluate: async ({ organizationId }) =>
(await isOnLegalHold(organizationId)) // yours
? deny({
code: 'LEGAL_HOLD',
message: 'app.organizations.legalHold',
remediation: 'app.organizations.contactLegal',
// a path in your app: the remediation becomes a link to it
remediationHref: '/settings/organization',
})
: allow(),
}),
);
  • Stages: delete only.
  • Context: stage, organizationId, actorUserId.
  • The kit's own: billing.live-subscription (apps/web/config/kit-organization-policies.server.ts, kit-owned) matters only with billing off: then nothing can cancel a subscription, so it refuses while the organization has one Stripe could still bill (not canceled or incomplete_expired, not already set to cancel) and says to contact support. It reads the app's rows, never Stripe. With billing on it allows: the delete step ends the subscription instead. Yours run after it, and a policy of yours with its id fails at startup.
  • Delete steps: work that must succeed before the delete, after the code (organizationDeleteSteps, OrganizationDeleteStep from @kit/organizations/server). The kit's billing.cancel-subscriptions (same file, kitOrganizationDeleteSteps) ends the organization's subscriptions in Stripe as billingConfig.onDelete says (immediately by default, no refund; or at period end). Unlike a policy a step may write, since only a verified delete reaches it. A denial (deny) stops the delete with its reason, like a policy's; the code is used up by then, so the owner requests a new one. A throw is not caught. A step may also give a warning (a translation key), which the delete dialog shows: the billing step says how the subscription ends. If Stripe cancels but the delete then fails, the organization stays, on the default plan; the retry finds nothing left to cancel.
  • Not covered: a subscription the app has no row for (created in the Stripe dashboard on the organization's customer) isn't canceled by the delete step; the background job cancels it if its webhook arrives after the delete. Cancel those in Stripe.
  • Why not Better Auth's guard: the Stripe plugin adds its own: it lists the customer's subscriptions from Stripe inside the delete request and refuses any that hasn't ended, so a subscription set to cancel at period end would block the delete until the period is over. The kit takes it out (withoutDeleteGuard, packages/billing/src/plugin.ts): the delete step ends them instead.
  • Order: organization and organization:delete permission, policies (a denial sends no code; at confirm time it deletes nothing and doesn't use up the code), the code, the delete steps, then the delete.
  • Message: 409 with message and remediation (translation keys in your messages, e.g. apps/web/messages/en/app.json through the app_translations_update MCP tool), shown in the delete dialog. An unknown key, or a policy that threw, shows the kit's "can't be deleted right now" message. remediationHref turns the remediation into a link: a path in this app only, checked like a redirect; anything else is dropped. Only the delete dialog renders the link for now; invitation and member messages show the text.
  • Logs: organization.refused (warn, error when a policy threw) with the policy's id and code.

Account Policies

The kit runs these before a user deletes their own account: when they ask for the deletion code, and again when they confirm. The Profile page also runs them on every load, to list the dialog's blockers, so a policy must be cheap and read-only. Register yours in apps/web/config/account-hooks.config.server.ts (yours to edit, empty by default), with defineAccountPolicy from @kit/organizations/server; the shape is the same as an organization policy's (Exit Hooks).

  • Stages: delete only. Context: stage, userId.
  • The kit's own: billing.live-account-subscription (apps/web/config/kit-account-policies.server.ts, kit-owned): with billing off, refuses while the user's own subscription could still bill. The session rule (a sign-in from the last 10 minutes, no impersonation), the only-owner rule and the last-admin rule are checked by the service itself, before any policy, and can't be dropped.
  • Organizations deleted with the account also run your organization policies and delete steps, for each of them.
  • Account delete steps (accountDeleteSteps, AccountDeleteStep): like an organization's, they run after the code and before the delete transaction, may write, and a denial stops the delete. The kit's billing.cancel-account-subscriptions ends the user's own subscription first.
  • Message: the dialog lists every blocker with its message and remediation, in the app or kit namespace; a blocker the dialog can't translate shows "can't be deleted right now".
  • Logs: account.deletion.blocked (the blockers' codes and reasons, when a code or the delete is refused), account.deletion.refused, account.deletion.failed.

Common Mistakes

  • Returning the whole result to the browser. results[].metadata.error is raw. Return reasons[0] or your own message.
  • Querying inside every policy. Load once and pass it in the context.
  • Relying on an empty ALL to deny. It allows. Use ANY, or make sure the right policies are registered.
  • Mutating the context. It's frozen at the top level; nested objects are shared, so don't change them either.