@bitakit/better-auth 0.2.5 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,171 @@
1
+ import type { betterAuthAccess } from './access.js';
2
+ /** Stable codes; user-facing messages are separate and may be translated by the app. */
3
+ export declare const membershipGuardErrors: Readonly<{
4
+ ROLE_EXCEEDS_YOUR_PERMISSIONS: "The current or proposed role exceeds the permissions you may grant in this organization.";
5
+ INVITATION_NO_LONGER_AUTHORIZED: "This invitation can no longer grant its membership or role. Ask for a new invitation.";
6
+ EMAIL_DOMAIN_NOT_ALLOWED: "The email address's domain is not allowed in this organization.";
7
+ INVALID_INVITATION_POLICY: "The invitation policy is invalid.";
8
+ INVALID_SECURITY_POLICY: "The security policy is invalid.";
9
+ ENABLE_TWO_FACTOR_FIRST: "Turn on two-factor sign-in for your own account before you require it for the organization.";
10
+ }>;
11
+ type Access = ReturnType<typeof betterAuthAccess>;
12
+ export type MembershipGuardOptions = {
13
+ /** Mirrors the organization option, so an unverified address keeps Better Auth's own error. */
14
+ requireEmailVerificationOnInvitation?: boolean;
15
+ };
16
+ /**
17
+ * The guard as a Better Auth plugin. Normally installed by `createOrganizationPlugin`; exported
18
+ * for reuse and tests. It needs the same translated access as the organization plugin.
19
+ */
20
+ export declare function membershipGuard(access: Access, guardOptions?: MembershipGuardOptions): {
21
+ id: "bitakit-membership-guard";
22
+ schema: {
23
+ organization: {
24
+ fields: {
25
+ /** The invitation domain policy; written only through set-invitation-policy. */
26
+ invitationPolicy: {
27
+ type: "json";
28
+ required: false;
29
+ input: false;
30
+ };
31
+ /** The security policy (two-factor optional or required); written only through set-security-policy. */
32
+ securityPolicy: {
33
+ type: "json";
34
+ required: false;
35
+ input: false;
36
+ };
37
+ };
38
+ };
39
+ };
40
+ hooks: {
41
+ before: {
42
+ matcher: (ctx: import("better-auth").HookEndpointContext) => boolean;
43
+ handler: import("better-call").Middleware<import("better-call").MiddlewareOptions, (inputContext: import("better-call").MiddlewareInputContext<import("better-call").MiddlewareOptions>) => Promise<void>>;
44
+ }[];
45
+ };
46
+ endpoints: {
47
+ getInvitationPolicy: import("better-call").StrictEndpoint<"/organization/get-invitation-policy", {
48
+ method: "GET";
49
+ use: import("better-call").Middleware<import("better-call").MiddlewareOptions, (inputContext: import("better-call").MiddlewareInputContext<import("better-call").MiddlewareOptions>) => Promise<{
50
+ session: {
51
+ session: Record<string, any> & {
52
+ id: string;
53
+ createdAt: Date;
54
+ updatedAt: Date;
55
+ userId: string;
56
+ expiresAt: Date;
57
+ token: string;
58
+ ipAddress?: string | null | undefined;
59
+ userAgent?: string | null | undefined;
60
+ };
61
+ user: Record<string, any> & {
62
+ id: string;
63
+ createdAt: Date;
64
+ updatedAt: Date;
65
+ email: string;
66
+ emailVerified: boolean;
67
+ name: string;
68
+ image?: string | null | undefined;
69
+ };
70
+ };
71
+ }>>[];
72
+ }, {
73
+ mode: import("./domain-policy.js").InvitationPolicyMode;
74
+ domains: readonly (import("./domain-policy.js").InvitationDomain & {
75
+ readonly display: string;
76
+ })[];
77
+ organizationId: string;
78
+ }>;
79
+ setInvitationPolicy: import("better-call").StrictEndpoint<"/organization/set-invitation-policy", {
80
+ method: "POST";
81
+ use: import("better-call").Middleware<import("better-call").MiddlewareOptions, (inputContext: import("better-call").MiddlewareInputContext<import("better-call").MiddlewareOptions>) => Promise<{
82
+ session: {
83
+ session: Record<string, any> & {
84
+ id: string;
85
+ createdAt: Date;
86
+ updatedAt: Date;
87
+ userId: string;
88
+ expiresAt: Date;
89
+ token: string;
90
+ ipAddress?: string | null | undefined;
91
+ userAgent?: string | null | undefined;
92
+ };
93
+ user: Record<string, any> & {
94
+ id: string;
95
+ createdAt: Date;
96
+ updatedAt: Date;
97
+ email: string;
98
+ emailVerified: boolean;
99
+ name: string;
100
+ image?: string | null | undefined;
101
+ };
102
+ };
103
+ }>>[];
104
+ }, {
105
+ mode: import("./domain-policy.js").InvitationPolicyMode;
106
+ domains: readonly (import("./domain-policy.js").InvitationDomain & {
107
+ readonly display: string;
108
+ })[];
109
+ organizationId: string;
110
+ }>;
111
+ getSecurityPolicy: import("better-call").StrictEndpoint<"/organization/get-security-policy", {
112
+ method: "GET";
113
+ use: import("better-call").Middleware<import("better-call").MiddlewareOptions, (inputContext: import("better-call").MiddlewareInputContext<import("better-call").MiddlewareOptions>) => Promise<{
114
+ session: {
115
+ session: Record<string, any> & {
116
+ id: string;
117
+ createdAt: Date;
118
+ updatedAt: Date;
119
+ userId: string;
120
+ expiresAt: Date;
121
+ token: string;
122
+ ipAddress?: string | null | undefined;
123
+ userAgent?: string | null | undefined;
124
+ };
125
+ user: Record<string, any> & {
126
+ id: string;
127
+ createdAt: Date;
128
+ updatedAt: Date;
129
+ email: string;
130
+ emailVerified: boolean;
131
+ name: string;
132
+ image?: string | null | undefined;
133
+ };
134
+ };
135
+ }>>[];
136
+ }, {
137
+ twoFactor: "optional" | "required";
138
+ organizationId: string;
139
+ }>;
140
+ setSecurityPolicy: import("better-call").StrictEndpoint<"/organization/set-security-policy", {
141
+ method: "POST";
142
+ use: import("better-call").Middleware<import("better-call").MiddlewareOptions, (inputContext: import("better-call").MiddlewareInputContext<import("better-call").MiddlewareOptions>) => Promise<{
143
+ session: {
144
+ session: Record<string, any> & {
145
+ id: string;
146
+ createdAt: Date;
147
+ updatedAt: Date;
148
+ userId: string;
149
+ expiresAt: Date;
150
+ token: string;
151
+ ipAddress?: string | null | undefined;
152
+ userAgent?: string | null | undefined;
153
+ };
154
+ user: Record<string, any> & {
155
+ id: string;
156
+ createdAt: Date;
157
+ updatedAt: Date;
158
+ email: string;
159
+ emailVerified: boolean;
160
+ name: string;
161
+ image?: string | null | undefined;
162
+ };
163
+ };
164
+ }>>[];
165
+ }, {
166
+ twoFactor: "optional" | "required";
167
+ organizationId: string;
168
+ }>;
169
+ };
170
+ };
171
+ export {};
package/dist/guard.js ADDED
@@ -0,0 +1,286 @@
1
+ import { APIError, createAuthEndpoint, createAuthMiddleware, getSessionFromCtx, sessionMiddleware, } from 'better-auth/api';
2
+ import { hasPermission } from 'better-auth/plugins/organization';
3
+ import { InvitationPolicyError, invitationPolicyAllows, invitationPolicyView, parseInvitationPolicy, storedInvitationPolicy, } from './domain-policy.js';
4
+ import { parseSecurityPolicy, SecurityPolicyError, storedSecurityPolicy, } from './security-policy.js';
5
+ // The membership guard: BitaKit's server-side invariants on Better Auth's own organization
6
+ // operations. Better Auth still runs all of its checks (member management permission, creator role,
7
+ // last owner, expiry, verified address); this only adds:
8
+ // - the role ceiling: an actor may only invite, assign or change roles whose effective permissions
9
+ // (all roles of the member combined, static and custom) the actor holds;
10
+ // - re-validation at acceptance: the inviter must still be able to grant the invited role;
11
+ // - the organization's invitation domain policy, at creation and acceptance;
12
+ // - the organization's security policy (two-factor optional or required): stored here, enforced by the app.
13
+ // It runs for HTTP requests and server `auth.api.*` calls alike (Better Auth's hook pipeline).
14
+ /** Stable codes; user-facing messages are separate and may be translated by the app. */
15
+ export const membershipGuardErrors = Object.freeze({
16
+ ROLE_EXCEEDS_YOUR_PERMISSIONS: 'The current or proposed role exceeds the permissions you may grant in this organization.',
17
+ INVITATION_NO_LONGER_AUTHORIZED: 'This invitation can no longer grant its membership or role. Ask for a new invitation.',
18
+ EMAIL_DOMAIN_NOT_ALLOWED: "The email address's domain is not allowed in this organization.",
19
+ INVALID_INVITATION_POLICY: 'The invitation policy is invalid.',
20
+ INVALID_SECURITY_POLICY: 'The security policy is invalid.',
21
+ ENABLE_TWO_FACTOR_FIRST: 'Turn on two-factor sign-in for your own account before you require it for the organization.',
22
+ });
23
+ const refuse = (code, status = 'FORBIDDEN', message) => APIError.fromStatus(status, { code, message: message ?? membershipGuardErrors[code] });
24
+ const notMember = () => APIError.fromStatus('FORBIDDEN', {
25
+ code: 'USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION',
26
+ message: 'User is not a member of the organization',
27
+ });
28
+ const roleList = (role) => (Array.isArray(role) ? role : String(role ?? '').split(','))
29
+ .map((part) => String(part).trim())
30
+ .filter(Boolean);
31
+ const merge = (target, source) => {
32
+ for (const [resource, actions] of Object.entries(source))
33
+ target[resource] = [...new Set([...(target[resource] ?? []), ...actions])];
34
+ return target;
35
+ };
36
+ /**
37
+ * The guard as a Better Auth plugin. Normally installed by `createOrganizationPlugin`; exported
38
+ * for reuse and tests. It needs the same translated access as the organization plugin.
39
+ */
40
+ export function membershipGuard(access, guardOptions = {}) {
41
+ const options = access.organization;
42
+ const adapter = (ctx) => ctx.context.adapter;
43
+ const memberOf = (ctx, organizationId, userId) => adapter(ctx).findOne({
44
+ model: 'member',
45
+ where: [
46
+ { field: 'organizationId', value: organizationId },
47
+ { field: 'userId', value: userId },
48
+ ],
49
+ });
50
+ const policyOf = async (ctx, organizationId) => {
51
+ const organization = await adapter(ctx).findOne({
52
+ model: 'organization',
53
+ where: [{ field: 'id', value: organizationId }],
54
+ });
55
+ return storedInvitationPolicy(organization?.invitationPolicy);
56
+ };
57
+ const securityOf = async (ctx, organizationId) => {
58
+ const organization = await adapter(ctx).findOne({
59
+ model: 'organization',
60
+ where: [{ field: 'id', value: organizationId }],
61
+ });
62
+ return storedSecurityPolicy(organization?.securityPolicy);
63
+ };
64
+ /** Effective statements of a stored role value (several roles combined, custom roles included). */
65
+ const statementsOf = async (ctx, organizationId, role) => {
66
+ const custom = new Map();
67
+ if (options.dynamicAccessControl?.enabled)
68
+ for (const row of await adapter(ctx).findMany({
69
+ model: 'organizationRole',
70
+ where: [{ field: 'organizationId', value: organizationId }],
71
+ }))
72
+ custom.set(row.role, typeof row.permission === 'string' ? JSON.parse(row.permission) : row.permission);
73
+ const statements = {};
74
+ const unknown = [];
75
+ for (const name of roleList(role)) {
76
+ const base = access.organization.roles[name]?.statements;
77
+ const extra = custom.get(name);
78
+ if (!base && !extra)
79
+ unknown.push(name);
80
+ if (base)
81
+ merge(statements, base);
82
+ if (extra)
83
+ merge(statements, extra);
84
+ }
85
+ for (const [resource, actions] of Object.entries(statements))
86
+ if (!actions.length)
87
+ delete statements[resource];
88
+ return { statements, unknown };
89
+ };
90
+ /** Whether a role value's own permissions cover the statements (Better Auth decides). */
91
+ const covers = async (ctx, organizationId, role, statements) => !Object.keys(statements).length ||
92
+ (await hasPermission({ role, options, permissions: statements, organizationId }, ctx));
93
+ /** The signed-in actor's membership in the organization; null leaves the refusal to Better Auth. */
94
+ const actorIn = async (ctx, organizationId) => {
95
+ const session = await getSessionFromCtx(ctx);
96
+ if (!session || !organizationId)
97
+ return null;
98
+ const member = await memberOf(ctx, organizationId, session.user.id);
99
+ if (member?.disabled)
100
+ throw refuse('ROLE_EXCEEDS_YOUR_PERMISSIONS');
101
+ return member ? { member, session } : null;
102
+ };
103
+ /** The creator role keeps Better Auth's own protection and error; the guard steps aside for it. */
104
+ const creatorRole = access.organization.creatorRole;
105
+ const touchesCreator = (actorRole, ...values) => !roleList(actorRole).includes(creatorRole) &&
106
+ values.some((value) => roleList(value).includes(creatorRole));
107
+ const organizationIdOf = async (ctx, explicit) => {
108
+ if (typeof explicit === 'string' && explicit)
109
+ return explicit;
110
+ const session = await getSessionFromCtx(ctx);
111
+ return session?.session
112
+ ?.activeOrganizationId;
113
+ };
114
+ const inviting = createAuthMiddleware(async (ctx) => {
115
+ const body = (ctx.body ?? {});
116
+ const organizationId = await organizationIdOf(ctx, body.organizationId);
117
+ if (!organizationId)
118
+ return;
119
+ if (typeof body.email === 'string' &&
120
+ !invitationPolicyAllows(await policyOf(ctx, organizationId), body.email))
121
+ throw refuse('EMAIL_DOMAIN_NOT_ALLOWED');
122
+ const actor = await actorIn(ctx, organizationId);
123
+ // Without the management permission itself Better Auth refuses with its own error.
124
+ if (!actor ||
125
+ !(await covers(ctx, organizationId, actor.member.role, { invitation: ['create'] })))
126
+ return;
127
+ if (touchesCreator(actor.member.role, body.role))
128
+ return;
129
+ const requested = await statementsOf(ctx, organizationId, body.role);
130
+ if (requested.unknown.length)
131
+ return; // Better Auth answers ROLE_NOT_FOUND.
132
+ if (!(await covers(ctx, organizationId, actor.member.role, requested.statements)))
133
+ throw refuse('ROLE_EXCEEDS_YOUR_PERMISSIONS');
134
+ });
135
+ const changingRole = createAuthMiddleware(async (ctx) => {
136
+ const body = (ctx.body ?? {});
137
+ const organizationId = await organizationIdOf(ctx, body.organizationId);
138
+ if (!organizationId || typeof body.memberId !== 'string')
139
+ return;
140
+ const target = await adapter(ctx).findOne({
141
+ model: 'member',
142
+ where: [{ field: 'id', value: body.memberId }],
143
+ });
144
+ if (!target || target.organizationId !== organizationId)
145
+ return; // Better Auth refuses.
146
+ const actor = await actorIn(ctx, organizationId);
147
+ if (!actor || !(await covers(ctx, organizationId, actor.member.role, { member: ['update'] })))
148
+ return;
149
+ if (touchesCreator(actor.member.role, body.role, target.role))
150
+ return;
151
+ const proposed = await statementsOf(ctx, organizationId, body.role);
152
+ if (proposed.unknown.length)
153
+ return; // Better Auth answers ROLE_NOT_FOUND.
154
+ const current = await statementsOf(ctx, organizationId, target.role);
155
+ const both = merge(merge({}, current.statements), proposed.statements);
156
+ if (!(await covers(ctx, organizationId, actor.member.role, both)))
157
+ throw refuse('ROLE_EXCEEDS_YOUR_PERMISSIONS');
158
+ });
159
+ const accepting = createAuthMiddleware(async (ctx) => {
160
+ const { invitationId } = (ctx.body ?? {});
161
+ if (typeof invitationId !== 'string')
162
+ return;
163
+ const invitation = await adapter(ctx).findOne({ model: 'invitation', where: [{ field: 'id', value: invitationId }] });
164
+ // Not pending, expired, someone else's address or unverified: Better Auth's own errors.
165
+ if (!invitation || invitation.status !== 'pending')
166
+ return;
167
+ if (new Date(invitation.expiresAt).getTime() <= Date.now())
168
+ return;
169
+ const session = await getSessionFromCtx(ctx);
170
+ if (!session || session.user.email.toLowerCase() !== invitation.email.toLowerCase())
171
+ return;
172
+ if (guardOptions.requireEmailVerificationOnInvitation && !session.user.emailVerified)
173
+ return;
174
+ const { organizationId } = invitation;
175
+ if (!invitationPolicyAllows(await policyOf(ctx, organizationId), invitation.email))
176
+ throw refuse('EMAIL_DOMAIN_NOT_ALLOWED');
177
+ const inviter = await memberOf(ctx, organizationId, invitation.inviterId);
178
+ if (!inviter || inviter.disabled)
179
+ throw refuse('INVITATION_NO_LONGER_AUTHORIZED');
180
+ const invited = await statementsOf(ctx, organizationId, invitation.role);
181
+ if (invited.unknown.length)
182
+ throw refuse('INVITATION_NO_LONGER_AUTHORIZED');
183
+ if (!(await covers(ctx, organizationId, inviter.role, invited.statements)))
184
+ throw refuse('INVITATION_NO_LONGER_AUTHORIZED');
185
+ });
186
+ return {
187
+ id: 'bitakit-membership-guard',
188
+ schema: {
189
+ organization: {
190
+ fields: {
191
+ /** The invitation domain policy; written only through set-invitation-policy. */
192
+ invitationPolicy: { type: 'json', required: false, input: false },
193
+ /** The security policy (two-factor optional or required); written only through set-security-policy. */
194
+ securityPolicy: { type: 'json', required: false, input: false },
195
+ },
196
+ },
197
+ },
198
+ hooks: {
199
+ before: [
200
+ { matcher: (ctx) => ctx.path === '/organization/invite-member', handler: inviting },
201
+ {
202
+ matcher: (ctx) => ctx.path === '/organization/update-member-role',
203
+ handler: changingRole,
204
+ },
205
+ { matcher: (ctx) => ctx.path === '/organization/accept-invitation', handler: accepting },
206
+ ],
207
+ },
208
+ endpoints: {
209
+ getInvitationPolicy: createAuthEndpoint('/organization/get-invitation-policy', { method: 'GET', use: [sessionMiddleware] }, async (ctx) => {
210
+ const organizationId = await organizationIdOf(ctx, ctx.query?.organizationId);
211
+ const actor = await actorIn(ctx, organizationId);
212
+ if (!organizationId || !actor)
213
+ throw notMember();
214
+ return ctx.json({
215
+ organizationId,
216
+ ...invitationPolicyView(await policyOf(ctx, organizationId)),
217
+ });
218
+ }),
219
+ setInvitationPolicy: createAuthEndpoint('/organization/set-invitation-policy', { method: 'POST', use: [sessionMiddleware] }, async (ctx) => {
220
+ const body = (ctx.body ?? {});
221
+ const organizationId = await organizationIdOf(ctx, body.organizationId);
222
+ const actor = await actorIn(ctx, organizationId);
223
+ if (!organizationId || !actor)
224
+ throw notMember();
225
+ if (!(await covers(ctx, organizationId, actor.member.role, { organization: ['update'] })))
226
+ throw APIError.fromStatus('FORBIDDEN', {
227
+ code: 'YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION',
228
+ message: 'You are not allowed to update this organization',
229
+ });
230
+ let policy;
231
+ try {
232
+ policy = parseInvitationPolicy(body.policy);
233
+ }
234
+ catch (error) {
235
+ if (error instanceof InvitationPolicyError)
236
+ throw refuse('INVALID_INVITATION_POLICY', 'BAD_REQUEST', error.message);
237
+ throw error;
238
+ }
239
+ await adapter(ctx).update({
240
+ model: 'organization',
241
+ where: [{ field: 'id', value: organizationId }],
242
+ update: { invitationPolicy: policy },
243
+ });
244
+ return ctx.json({ organizationId, ...invitationPolicyView(policy) });
245
+ }),
246
+ getSecurityPolicy: createAuthEndpoint('/organization/get-security-policy', { method: 'GET', use: [sessionMiddleware] }, async (ctx) => {
247
+ const organizationId = await organizationIdOf(ctx, ctx.query?.organizationId);
248
+ const actor = await actorIn(ctx, organizationId);
249
+ if (!organizationId || !actor)
250
+ throw notMember();
251
+ return ctx.json({ organizationId, ...(await securityOf(ctx, organizationId)) });
252
+ }),
253
+ setSecurityPolicy: createAuthEndpoint('/organization/set-security-policy', { method: 'POST', use: [sessionMiddleware] }, async (ctx) => {
254
+ const body = (ctx.body ?? {});
255
+ const organizationId = await organizationIdOf(ctx, body.organizationId);
256
+ const actor = await actorIn(ctx, organizationId);
257
+ if (!organizationId || !actor)
258
+ throw notMember();
259
+ if (!(await covers(ctx, organizationId, actor.member.role, { organization: ['update'] })))
260
+ throw APIError.fromStatus('FORBIDDEN', {
261
+ code: 'YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION',
262
+ message: 'You are not allowed to update this organization',
263
+ });
264
+ let policy;
265
+ try {
266
+ policy = parseSecurityPolicy(body.policy);
267
+ }
268
+ catch (error) {
269
+ if (error instanceof SecurityPolicyError)
270
+ throw refuse('INVALID_SECURITY_POLICY', 'BAD_REQUEST', error.message);
271
+ throw error;
272
+ }
273
+ // Nobody requires what they do not have themselves: it would lock them out of their own organization.
274
+ const user = actor.session.user;
275
+ if (policy.twoFactor === 'required' && user.twoFactorEnabled !== true)
276
+ throw refuse('ENABLE_TWO_FACTOR_FIRST');
277
+ await adapter(ctx).update({
278
+ model: 'organization',
279
+ where: [{ field: 'id', value: organizationId }],
280
+ update: { securityPolicy: policy },
281
+ });
282
+ return ctx.json({ organizationId, ...policy });
283
+ }),
284
+ },
285
+ };
286
+ }
@@ -63,6 +63,25 @@ export function sessionOrganizationBackend(client, authenticated, signedOut = au
63
63
  },
64
64
  });
65
65
  }
66
+ // Capability objects: the same account check before every operation.
67
+ for (const key of ['customRoles', 'invitationPolicy', 'securityPolicy']) {
68
+ Object.defineProperty(backend, key, {
69
+ enumerable: true,
70
+ get() {
71
+ const capability = selected()[key];
72
+ if (!capability)
73
+ return undefined;
74
+ return Object.fromEntries(Object.entries(capability).map(([name, operation]) => [
75
+ name,
76
+ async (input) => {
77
+ if (user() !== loadedUser)
78
+ throw new Error('Account changed. Reload before writing.');
79
+ return operation(input);
80
+ },
81
+ ]));
82
+ },
83
+ });
84
+ }
66
85
  Object.defineProperty(backend, 'customInvitationExpiry', {
67
86
  get: () => selected().customInvitationExpiry,
68
87
  });
@@ -1,6 +1,7 @@
1
1
  export { sessionOrganizationBackend } from './organization-session.js';
2
2
  import type { BetterAuthClient } from './index.js';
3
3
  import type { OrganizationBackend, Organization } from '@bitakit/organizations';
4
+ import type { AccessConfiguration } from '@bitakit/core';
4
5
  type Result<T> = Promise<{
5
6
  data: T | null;
6
7
  error: unknown;
@@ -16,6 +17,11 @@ type AuthMember = {
16
17
  image?: string | null;
17
18
  };
18
19
  };
20
+ /**
21
+ * Role parameters name Better Auth's built-in roles so every configured client fits; the app's own
22
+ * roles (`createOrganizationPlugin`) pass through at runtime and the server checks them.
23
+ */
24
+ type ClientRole = 'member' | 'admin';
19
25
  /** Structural boundary supports an existing client configured with Better Auth's organization plugin. */
20
26
  export interface BetterAuthOrganizationClient {
21
27
  $store?: BetterAuthClient['$store'];
@@ -99,7 +105,7 @@ export interface BetterAuthOrganizationClient {
99
105
  inviteMember(input: {
100
106
  organizationId: string;
101
107
  email: string;
102
- role: 'member' | 'admin';
108
+ role: ClientRole;
103
109
  resend?: boolean;
104
110
  }): Result<unknown>;
105
111
  cancelInvitation(input: {
@@ -108,13 +114,44 @@ export interface BetterAuthOrganizationClient {
108
114
  updateMemberRole(input: {
109
115
  organizationId: string;
110
116
  memberId: string;
111
- role: 'member' | 'admin';
117
+ role: ClientRole;
112
118
  }): Result<unknown>;
113
119
  removeMember(input: {
114
120
  organizationId: string;
115
121
  memberIdOrEmail: string;
116
122
  }): Result<unknown>;
123
+ /** Better Auth dynamic roles (present with `dynamicAccessControl`). */
124
+ listRoles?(input: {
125
+ query: {
126
+ organizationId: string;
127
+ };
128
+ }): Result<Array<{
129
+ role: string;
130
+ permission: Record<string, string[]> | string;
131
+ }>>;
132
+ createRole?(input: {
133
+ organizationId: string;
134
+ role: string;
135
+ permission: Record<string, string[]>;
136
+ }): Result<unknown>;
137
+ updateRole?(input: {
138
+ organizationId: string;
139
+ roleName: string;
140
+ data: {
141
+ permission: Record<string, string[]>;
142
+ };
143
+ }): Result<unknown>;
144
+ deleteRole?(input: {
145
+ organizationId: string;
146
+ roleName: string;
147
+ }): Result<unknown>;
117
148
  };
149
+ /** Generic request, used for the membership guard's invitation policy endpoints. */
150
+ $fetch?(path: string, options: {
151
+ method: 'GET' | 'POST';
152
+ query?: Record<string, string>;
153
+ body?: unknown;
154
+ }): Result<unknown>;
118
155
  }
119
156
  /** No HTTP routes or credentials are invented. The server must enforce membership and permissions. */
120
157
  export type OrganizationExtensions = {
@@ -126,5 +163,11 @@ export type OrganizationExtensions = {
126
163
  update?: OrganizationBackend['update'];
127
164
  delete?: OrganizationBackend['delete'];
128
165
  list?: () => Promise<Organization[]>;
166
+ /**
167
+ * The app's generated `accessConfiguration`: the backend then reports the base roles (with
168
+ * labels and permissions), the organization's custom roles and the viewer's permissions, and
169
+ * offers custom roles and the invitation policy of `createOrganizationPlugin`'s guard.
170
+ */
171
+ access?: AccessConfiguration;
129
172
  };
130
173
  export declare function betterAuthOrganizations(client: BetterAuthOrganizationClient, extensions?: OrganizationExtensions): OrganizationBackend;