@bitakit/better-auth 0.2.4 → 0.3.0

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.
package/dist/guard.js ADDED
@@ -0,0 +1,235 @@
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
+ // The membership guard: BitaKit's server-side invariants on Better Auth's own organization
5
+ // operations. Better Auth still runs all of its checks (member management permission, creator role,
6
+ // last owner, expiry, verified address); this only adds:
7
+ // - the role ceiling: an actor may only invite, assign or change roles whose effective permissions
8
+ // (all roles of the member combined, static and custom) the actor holds;
9
+ // - re-validation at acceptance: the inviter must still be able to grant the invited role;
10
+ // - the organization's invitation domain policy, at creation and acceptance.
11
+ // It runs for HTTP requests and server `auth.api.*` calls alike (Better Auth's hook pipeline).
12
+ /** Stable codes; user-facing messages are separate and may be translated by the app. */
13
+ export const membershipGuardErrors = Object.freeze({
14
+ ROLE_EXCEEDS_YOUR_PERMISSIONS: 'The current or proposed role exceeds the permissions you may grant in this organization.',
15
+ INVITATION_NO_LONGER_AUTHORIZED: 'This invitation can no longer grant its membership or role. Ask for a new invitation.',
16
+ EMAIL_DOMAIN_NOT_ALLOWED: "The email address's domain is not allowed in this organization.",
17
+ INVALID_INVITATION_POLICY: 'The invitation policy is invalid.',
18
+ });
19
+ const refuse = (code, status = 'FORBIDDEN', message) => APIError.fromStatus(status, { code, message: message ?? membershipGuardErrors[code] });
20
+ const notMember = () => APIError.fromStatus('FORBIDDEN', {
21
+ code: 'USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION',
22
+ message: 'User is not a member of the organization',
23
+ });
24
+ const roleList = (role) => (Array.isArray(role) ? role : String(role ?? '').split(','))
25
+ .map((part) => String(part).trim())
26
+ .filter(Boolean);
27
+ const merge = (target, source) => {
28
+ for (const [resource, actions] of Object.entries(source))
29
+ target[resource] = [...new Set([...(target[resource] ?? []), ...actions])];
30
+ return target;
31
+ };
32
+ /**
33
+ * The guard as a Better Auth plugin. Normally installed by `createOrganizationPlugin`; exported
34
+ * for reuse and tests. It needs the same translated access as the organization plugin.
35
+ */
36
+ export function membershipGuard(access, guardOptions = {}) {
37
+ const options = access.organization;
38
+ const adapter = (ctx) => ctx.context.adapter;
39
+ const memberOf = (ctx, organizationId, userId) => adapter(ctx).findOne({
40
+ model: 'member',
41
+ where: [
42
+ { field: 'organizationId', value: organizationId },
43
+ { field: 'userId', value: userId },
44
+ ],
45
+ });
46
+ const policyOf = async (ctx, organizationId) => {
47
+ const organization = await adapter(ctx).findOne({
48
+ model: 'organization',
49
+ where: [{ field: 'id', value: organizationId }],
50
+ });
51
+ return storedInvitationPolicy(organization?.invitationPolicy);
52
+ };
53
+ /** Effective statements of a stored role value (several roles combined, custom roles included). */
54
+ const statementsOf = async (ctx, organizationId, role) => {
55
+ const custom = new Map();
56
+ if (options.dynamicAccessControl?.enabled)
57
+ for (const row of await adapter(ctx).findMany({
58
+ model: 'organizationRole',
59
+ where: [{ field: 'organizationId', value: organizationId }],
60
+ }))
61
+ custom.set(row.role, typeof row.permission === 'string' ? JSON.parse(row.permission) : row.permission);
62
+ const statements = {};
63
+ const unknown = [];
64
+ for (const name of roleList(role)) {
65
+ const base = access.organization.roles[name]?.statements;
66
+ const extra = custom.get(name);
67
+ if (!base && !extra)
68
+ unknown.push(name);
69
+ if (base)
70
+ merge(statements, base);
71
+ if (extra)
72
+ merge(statements, extra);
73
+ }
74
+ for (const [resource, actions] of Object.entries(statements))
75
+ if (!actions.length)
76
+ delete statements[resource];
77
+ return { statements, unknown };
78
+ };
79
+ /** Whether a role value's own permissions cover the statements (Better Auth decides). */
80
+ const covers = async (ctx, organizationId, role, statements) => !Object.keys(statements).length ||
81
+ (await hasPermission({ role, options, permissions: statements, organizationId }, ctx));
82
+ /** The signed-in actor's membership in the organization; null leaves the refusal to Better Auth. */
83
+ const actorIn = async (ctx, organizationId) => {
84
+ const session = await getSessionFromCtx(ctx);
85
+ if (!session || !organizationId)
86
+ return null;
87
+ const member = await memberOf(ctx, organizationId, session.user.id);
88
+ if (member?.disabled)
89
+ throw refuse('ROLE_EXCEEDS_YOUR_PERMISSIONS');
90
+ return member ? { member, session } : null;
91
+ };
92
+ /** The creator role keeps Better Auth's own protection and error; the guard steps aside for it. */
93
+ const creatorRole = access.organization.creatorRole;
94
+ const touchesCreator = (actorRole, ...values) => !roleList(actorRole).includes(creatorRole) &&
95
+ values.some((value) => roleList(value).includes(creatorRole));
96
+ const organizationIdOf = async (ctx, explicit) => {
97
+ if (typeof explicit === 'string' && explicit)
98
+ return explicit;
99
+ const session = await getSessionFromCtx(ctx);
100
+ return session?.session
101
+ ?.activeOrganizationId;
102
+ };
103
+ const inviting = createAuthMiddleware(async (ctx) => {
104
+ const body = (ctx.body ?? {});
105
+ const organizationId = await organizationIdOf(ctx, body.organizationId);
106
+ if (!organizationId)
107
+ return;
108
+ if (typeof body.email === 'string' &&
109
+ !invitationPolicyAllows(await policyOf(ctx, organizationId), body.email))
110
+ throw refuse('EMAIL_DOMAIN_NOT_ALLOWED');
111
+ const actor = await actorIn(ctx, organizationId);
112
+ // Without the management permission itself Better Auth refuses with its own error.
113
+ if (!actor ||
114
+ !(await covers(ctx, organizationId, actor.member.role, { invitation: ['create'] })))
115
+ return;
116
+ if (touchesCreator(actor.member.role, body.role))
117
+ return;
118
+ const requested = await statementsOf(ctx, organizationId, body.role);
119
+ if (requested.unknown.length)
120
+ return; // Better Auth answers ROLE_NOT_FOUND.
121
+ if (!(await covers(ctx, organizationId, actor.member.role, requested.statements)))
122
+ throw refuse('ROLE_EXCEEDS_YOUR_PERMISSIONS');
123
+ });
124
+ const changingRole = createAuthMiddleware(async (ctx) => {
125
+ const body = (ctx.body ?? {});
126
+ const organizationId = await organizationIdOf(ctx, body.organizationId);
127
+ if (!organizationId || typeof body.memberId !== 'string')
128
+ return;
129
+ const target = await adapter(ctx).findOne({
130
+ model: 'member',
131
+ where: [{ field: 'id', value: body.memberId }],
132
+ });
133
+ if (!target || target.organizationId !== organizationId)
134
+ return; // Better Auth refuses.
135
+ const actor = await actorIn(ctx, organizationId);
136
+ if (!actor || !(await covers(ctx, organizationId, actor.member.role, { member: ['update'] })))
137
+ return;
138
+ if (touchesCreator(actor.member.role, body.role, target.role))
139
+ return;
140
+ const proposed = await statementsOf(ctx, organizationId, body.role);
141
+ if (proposed.unknown.length)
142
+ return; // Better Auth answers ROLE_NOT_FOUND.
143
+ const current = await statementsOf(ctx, organizationId, target.role);
144
+ const both = merge(merge({}, current.statements), proposed.statements);
145
+ if (!(await covers(ctx, organizationId, actor.member.role, both)))
146
+ throw refuse('ROLE_EXCEEDS_YOUR_PERMISSIONS');
147
+ });
148
+ const accepting = createAuthMiddleware(async (ctx) => {
149
+ const { invitationId } = (ctx.body ?? {});
150
+ if (typeof invitationId !== 'string')
151
+ return;
152
+ const invitation = await adapter(ctx).findOne({ model: 'invitation', where: [{ field: 'id', value: invitationId }] });
153
+ // Not pending, expired, someone else's address or unverified: Better Auth's own errors.
154
+ if (!invitation || invitation.status !== 'pending')
155
+ return;
156
+ if (new Date(invitation.expiresAt).getTime() <= Date.now())
157
+ return;
158
+ const session = await getSessionFromCtx(ctx);
159
+ if (!session || session.user.email.toLowerCase() !== invitation.email.toLowerCase())
160
+ return;
161
+ if (guardOptions.requireEmailVerificationOnInvitation && !session.user.emailVerified)
162
+ return;
163
+ const { organizationId } = invitation;
164
+ if (!invitationPolicyAllows(await policyOf(ctx, organizationId), invitation.email))
165
+ throw refuse('EMAIL_DOMAIN_NOT_ALLOWED');
166
+ const inviter = await memberOf(ctx, organizationId, invitation.inviterId);
167
+ if (!inviter || inviter.disabled)
168
+ throw refuse('INVITATION_NO_LONGER_AUTHORIZED');
169
+ const invited = await statementsOf(ctx, organizationId, invitation.role);
170
+ if (invited.unknown.length)
171
+ throw refuse('INVITATION_NO_LONGER_AUTHORIZED');
172
+ if (!(await covers(ctx, organizationId, inviter.role, invited.statements)))
173
+ throw refuse('INVITATION_NO_LONGER_AUTHORIZED');
174
+ });
175
+ return {
176
+ id: 'bitakit-membership-guard',
177
+ schema: {
178
+ organization: {
179
+ fields: {
180
+ /** The invitation domain policy; written only through set-invitation-policy. */
181
+ invitationPolicy: { type: 'json', required: false, input: false },
182
+ },
183
+ },
184
+ },
185
+ hooks: {
186
+ before: [
187
+ { matcher: (ctx) => ctx.path === '/organization/invite-member', handler: inviting },
188
+ {
189
+ matcher: (ctx) => ctx.path === '/organization/update-member-role',
190
+ handler: changingRole,
191
+ },
192
+ { matcher: (ctx) => ctx.path === '/organization/accept-invitation', handler: accepting },
193
+ ],
194
+ },
195
+ endpoints: {
196
+ getInvitationPolicy: createAuthEndpoint('/organization/get-invitation-policy', { method: 'GET', use: [sessionMiddleware] }, async (ctx) => {
197
+ const organizationId = await organizationIdOf(ctx, ctx.query?.organizationId);
198
+ const actor = await actorIn(ctx, organizationId);
199
+ if (!organizationId || !actor)
200
+ throw notMember();
201
+ return ctx.json({
202
+ organizationId,
203
+ ...invitationPolicyView(await policyOf(ctx, organizationId)),
204
+ });
205
+ }),
206
+ setInvitationPolicy: createAuthEndpoint('/organization/set-invitation-policy', { method: 'POST', use: [sessionMiddleware] }, async (ctx) => {
207
+ const body = (ctx.body ?? {});
208
+ const organizationId = await organizationIdOf(ctx, body.organizationId);
209
+ const actor = await actorIn(ctx, organizationId);
210
+ if (!organizationId || !actor)
211
+ throw notMember();
212
+ if (!(await covers(ctx, organizationId, actor.member.role, { organization: ['update'] })))
213
+ throw APIError.fromStatus('FORBIDDEN', {
214
+ code: 'YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION',
215
+ message: 'You are not allowed to update this organization',
216
+ });
217
+ let policy;
218
+ try {
219
+ policy = parseInvitationPolicy(body.policy);
220
+ }
221
+ catch (error) {
222
+ if (error instanceof InvitationPolicyError)
223
+ throw refuse('INVALID_INVITATION_POLICY', 'BAD_REQUEST', error.message);
224
+ throw error;
225
+ }
226
+ await adapter(ctx).update({
227
+ model: 'organization',
228
+ where: [{ field: 'id', value: organizationId }],
229
+ update: { invitationPolicy: policy },
230
+ });
231
+ return ctx.json({ organizationId, ...invitationPolicyView(policy) });
232
+ }),
233
+ },
234
+ };
235
+ }
@@ -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']) {
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;
@@ -1,5 +1,6 @@
1
1
  import { isOrganizationWebsite, organizationWebsiteError } from '@bitakit/organizations';
2
2
  export { sessionOrganizationBackend } from './organization-session.js';
3
+ import { betterAuthAccess } from './access.js';
3
4
  async function value(request) {
4
5
  const result = await request;
5
6
  if (result.error)
@@ -13,8 +14,55 @@ async function completed(request) {
13
14
  if (result.error)
14
15
  throw result.error;
15
16
  }
17
+ const union = (target, source) => {
18
+ for (const [resource, actions] of Object.entries(source))
19
+ target[resource] = [...new Set([...(target[resource] ?? []), ...actions])];
20
+ return target;
21
+ };
22
+ const holds = (held, needed) => Object.entries(needed).every(([resource, actions]) => actions.every((action) => held[resource]?.includes(action)));
16
23
  export function betterAuthOrganizations(client, extensions = {}) {
17
24
  const api = client.organization;
25
+ const declared = extensions.access;
26
+ const translated = declared ? betterAuthAccess(declared).organization : undefined;
27
+ /** Base roles in the app's order, then custom roles; with the viewer's combined permissions. */
28
+ async function rolesFor(organizationId, viewerRole) {
29
+ if (!declared || !translated)
30
+ return {};
31
+ const custom = translated.dynamicAccessControl && api.listRoles
32
+ ? (await value(api.listRoles({ query: { organizationId } }))).map((row) => ({
33
+ role: row.role,
34
+ permission: (typeof row.permission === 'string'
35
+ ? JSON.parse(row.permission)
36
+ : row.permission),
37
+ }))
38
+ : [];
39
+ const specs = declared.roles?.roles ?? {};
40
+ const roles = [
41
+ ...Object.entries(translated.roles).map(([id, role]) => ({
42
+ id,
43
+ ...(specs[id]?.label ? { label: specs[id].label } : {}),
44
+ ...(specs[id]?.description ? { description: specs[id].description } : {}),
45
+ ...(specs[id]?.standard ? { standard: specs[id].standard } : {}),
46
+ custom: false,
47
+ permissions: role.statements,
48
+ })),
49
+ ...custom
50
+ .filter((row) => !(row.role in translated.roles))
51
+ .map((row) => ({ id: row.role, custom: true, permissions: row.permission })),
52
+ ];
53
+ const viewerPermissions = {};
54
+ for (const name of viewerRole.split(',').map((part) => part.trim())) {
55
+ const role = roles.find((item) => item.id === name);
56
+ if (role)
57
+ union(viewerPermissions, role.permissions);
58
+ }
59
+ return { roles, viewerPermissions };
60
+ }
61
+ const guardRequest = async (path, options) => {
62
+ if (!client.$fetch)
63
+ throw new Error('This client cannot reach the invitation policy.');
64
+ return (await value(client.$fetch(path, options)));
65
+ };
18
66
  const activeOrganization = () => api.getOrganization ? api.getOrganization() : api.getFullOrganization();
19
67
  return {
20
68
  setMemberDisabled: extensions.setMemberDisabled,
@@ -96,9 +144,12 @@ export function betterAuthOrganizations(client, extensions = {}) {
96
144
  const current = await value(api.getActiveMember());
97
145
  if (current.disabled)
98
146
  throw new Error('Membership is disabled.');
99
- const canManage = current.role
100
- .split(',')
101
- .some((role) => role === 'owner' || role === 'admin');
147
+ const access = await rolesFor(activeId, current.role);
148
+ // With declared roles, management follows permissions; otherwise Better Auth's owner/admin.
149
+ const canManage = access.viewerPermissions
150
+ ? holds(access.viewerPermissions, { invitation: ['create'] }) ||
151
+ holds(access.viewerPermissions, { member: ['update'] })
152
+ : current.role.split(',').some((role) => role === 'owner' || role === 'admin');
102
153
  const [members, invitations] = await Promise.all([
103
154
  (async () => {
104
155
  const members = [];
@@ -144,8 +195,11 @@ export function betterAuthOrganizations(client, extensions = {}) {
144
195
  members,
145
196
  invitations,
146
197
  canManage,
147
- canDelete: current.role.split(',').includes('owner'),
198
+ canDelete: access.viewerPermissions
199
+ ? holds(access.viewerPermissions, { organization: ['delete'] })
200
+ : current.role.split(',').includes('owner'),
148
201
  viewerMemberId: current.id,
202
+ ...access,
149
203
  incomingInvitations,
150
204
  incomingInvitationsError: verificationRequired
151
205
  ? 'Verify your email address to see invitations.'
@@ -163,7 +217,7 @@ export function betterAuthOrganizations(client, extensions = {}) {
163
217
  if (input.expiresInDays !== undefined && input.expiresInDays !== 30)
164
218
  throw new Error('Custom invitation expiry requires a server extension.');
165
219
  const { expiresInDays: _expiry, ...body } = input;
166
- return completed(api.inviteMember(body));
220
+ return completed(api.inviteMember({ ...body, role: body.role }));
167
221
  }),
168
222
  async cancelInvitation({ organizationId, invitationId }) {
169
223
  // Better Auth's cancel API takes only the invitation ID; verify the displayed scope first.
@@ -172,7 +226,34 @@ export function betterAuthOrganizations(client, extensions = {}) {
172
226
  throw new Error('Invitation is not in this organization.');
173
227
  await completed(api.cancelInvitation({ invitationId }));
174
228
  },
175
- updateRole: (input) => completed(api.updateMemberRole(input)),
229
+ customRoles: translated?.dynamicAccessControl && api.createRole && api.updateRole && api.deleteRole
230
+ ? {
231
+ create: ({ organizationId, role, permissions }) => completed(api.createRole({
232
+ organizationId,
233
+ role,
234
+ permission: union({}, permissions),
235
+ })),
236
+ update: ({ organizationId, role, permissions }) => completed(api.updateRole({
237
+ organizationId,
238
+ roleName: role,
239
+ data: { permission: union({}, permissions) },
240
+ })),
241
+ delete: ({ organizationId, role }) => completed(api.deleteRole({ organizationId, roleName: role })),
242
+ }
243
+ : undefined,
244
+ invitationPolicy: declared && client.$fetch
245
+ ? {
246
+ load: (organizationId) => guardRequest('/organization/get-invitation-policy', {
247
+ method: 'GET',
248
+ query: { organizationId },
249
+ }),
250
+ save: ({ organizationId, policy }) => guardRequest('/organization/set-invitation-policy', {
251
+ method: 'POST',
252
+ body: { organizationId, policy },
253
+ }),
254
+ }
255
+ : undefined,
256
+ updateRole: (input) => completed(api.updateMemberRole({ ...input, role: input.role })),
176
257
  removeMember: ({ organizationId, memberId }) => completed(api.removeMember({ organizationId, memberIdOrEmail: memberId })),
177
258
  };
178
259
  }