@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.
@@ -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 organization policies.');
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,46 @@ 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
+ securityPolicy: declared && client.$fetch
257
+ ? {
258
+ load: async (organizationId) => {
259
+ const { twoFactor } = await guardRequest('/organization/get-security-policy', { method: 'GET', query: { organizationId } });
260
+ return { twoFactor };
261
+ },
262
+ save: async ({ organizationId, policy }) => {
263
+ const { twoFactor } = await guardRequest('/organization/set-security-policy', { method: 'POST', body: { organizationId, policy } });
264
+ return { twoFactor };
265
+ },
266
+ }
267
+ : undefined,
268
+ updateRole: (input) => completed(api.updateMemberRole({ ...input, role: input.role })),
176
269
  removeMember: ({ organizationId, memberId }) => completed(api.removeMember({ organizationId, memberIdOrEmail: memberId })),
177
270
  };
178
271
  }
@@ -0,0 +1,15 @@
1
+ /** Same shape as `SecurityPolicy` of `@bitakit/organizations`. */
2
+ export type SecurityPolicy = {
3
+ twoFactor: 'optional' | 'required';
4
+ };
5
+ export declare const defaultSecurityPolicy: SecurityPolicy;
6
+ export declare class SecurityPolicyError extends Error {
7
+ }
8
+ /** A policy sent by a client: refused unless it is exactly a known rule. */
9
+ export declare function parseSecurityPolicy(value: unknown): SecurityPolicy;
10
+ /** The stored value (JSON text or object, possibly absent or from an older version): never throws, defaults to optional. */
11
+ export declare function storedSecurityPolicy(value: unknown): SecurityPolicy;
12
+ /** Whether a person meets the organization's rule: with `required`, only with two-factor sign-in turned on. */
13
+ export declare function securityPolicyMet(policy: SecurityPolicy, user: {
14
+ twoFactorEnabled?: boolean | null;
15
+ }): boolean;
@@ -0,0 +1,36 @@
1
+ // The organization's sign-in rule (security policy): whether its members must use two-factor sign-in. Stored on the
2
+ // organization by the membership guard (`securityPolicy`, written only through set-security-policy); enforced by the app on
3
+ // its server with `securityPolicyMet`, because only the app knows which of its requests belong to an organization.
4
+ // Browser- and server-safe.
5
+ export const defaultSecurityPolicy = Object.freeze({ twoFactor: 'optional' });
6
+ export class SecurityPolicyError extends Error {
7
+ }
8
+ /** A policy sent by a client: refused unless it is exactly a known rule. */
9
+ export function parseSecurityPolicy(value) {
10
+ const twoFactor = value?.twoFactor;
11
+ if (twoFactor !== 'optional' && twoFactor !== 'required')
12
+ throw new SecurityPolicyError('twoFactor must be "optional" or "required".');
13
+ return { twoFactor };
14
+ }
15
+ /** The stored value (JSON text or object, possibly absent or from an older version): never throws, defaults to optional. */
16
+ export function storedSecurityPolicy(value) {
17
+ let parsed = value;
18
+ if (typeof value === 'string') {
19
+ try {
20
+ parsed = JSON.parse(value);
21
+ }
22
+ catch {
23
+ return defaultSecurityPolicy;
24
+ }
25
+ }
26
+ try {
27
+ return parseSecurityPolicy(parsed);
28
+ }
29
+ catch {
30
+ return defaultSecurityPolicy;
31
+ }
32
+ }
33
+ /** Whether a person meets the organization's rule: with `required`, only with two-factor sign-in turned on. */
34
+ export function securityPolicyMet(policy, user) {
35
+ return policy.twoFactor !== 'required' || user.twoFactorEnabled === true;
36
+ }