@bitakit/better-auth 0.3.0 → 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.
package/AGENTS.md CHANGED
@@ -80,11 +80,20 @@ For HTTP requests and server `auth.api.*` calls alike, on top of Better Auth's o
80
80
  `organization:update`); domains are stored as IDNA ASCII and returned with a Unicode `display`.
81
81
  Matching is by whole labels; subdomains only with `includeSubdomains`. Each app builds its own
82
82
  settings screen; a policy change never removes members.
83
+ - Security policy on the organization record (`securityPolicy`, default `{ twoFactor: 'optional' }`):
84
+ the organization's sign-in rule. Read it (any member) with `GET /organization/get-security-policy`
85
+ and write it with `POST /organization/set-security-policy` (needs `organization:update`; error
86
+ `INVALID_SECURITY_POLICY`). Requiring two-factor needs the actor's own two-factor sign-in
87
+ (`ENABLE_TWO_FACTOR_FIRST`), so nobody locks themselves out. The guard only stores it: the app
88
+ enforces it on its server – read the organization's value with `storedSecurityPolicy` and check
89
+ the person with `securityPolicyMet(policy, user)` (`./server`; `user.twoFactorEnabled` comes from
90
+ Better Auth's `twoFactor` plugin) – and sends a member who does not meet it to turn two-factor on.
91
+ In the browser it is the `securityPolicy` capability of `@bitakit/organizations`.
83
92
  - Better Auth's errors stay for missing management permission, expired invitations and
84
93
  unverified addresses. Stable codes and messages: `membershipGuardErrors` (`./server`).
85
94
  - Apps that suspend members declare `member.disabled` (boolean) in the organization schema; the
86
95
  guard treats a disabled member as having no authority. Add the `organization.invitationPolicy`
87
- (json) column with the app's Better Auth migration.
96
+ and `organization.securityPolicy` (json) columns with the app's Better Auth migration.
88
97
  - Server-only `auth.api.addMember` (no HTTP route) is trusted server code and not actor-checked.
89
98
 
90
99
  Check capabilities on the server with `hasOrganizationPermission(auth, { headers, permissions })`
package/dist/guard.d.ts CHANGED
@@ -5,6 +5,8 @@ export declare const membershipGuardErrors: Readonly<{
5
5
  INVITATION_NO_LONGER_AUTHORIZED: "This invitation can no longer grant its membership or role. Ask for a new invitation.";
6
6
  EMAIL_DOMAIN_NOT_ALLOWED: "The email address's domain is not allowed in this organization.";
7
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.";
8
10
  }>;
9
11
  type Access = ReturnType<typeof betterAuthAccess>;
10
12
  export type MembershipGuardOptions = {
@@ -26,6 +28,12 @@ export declare function membershipGuard(access: Access, guardOptions?: Membershi
26
28
  required: false;
27
29
  input: false;
28
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
+ };
29
37
  };
30
38
  };
31
39
  };
@@ -100,6 +108,64 @@ export declare function membershipGuard(access: Access, guardOptions?: Membershi
100
108
  })[];
101
109
  organizationId: string;
102
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
+ }>;
103
169
  };
104
170
  };
105
171
  export {};
package/dist/guard.js CHANGED
@@ -1,13 +1,15 @@
1
1
  import { APIError, createAuthEndpoint, createAuthMiddleware, getSessionFromCtx, sessionMiddleware, } from 'better-auth/api';
2
2
  import { hasPermission } from 'better-auth/plugins/organization';
3
3
  import { InvitationPolicyError, invitationPolicyAllows, invitationPolicyView, parseInvitationPolicy, storedInvitationPolicy, } from './domain-policy.js';
4
+ import { parseSecurityPolicy, SecurityPolicyError, storedSecurityPolicy, } from './security-policy.js';
4
5
  // The membership guard: BitaKit's server-side invariants on Better Auth's own organization
5
6
  // operations. Better Auth still runs all of its checks (member management permission, creator role,
6
7
  // last owner, expiry, verified address); this only adds:
7
8
  // - the role ceiling: an actor may only invite, assign or change roles whose effective permissions
8
9
  // (all roles of the member combined, static and custom) the actor holds;
9
10
  // - 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
+ // - 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.
11
13
  // It runs for HTTP requests and server `auth.api.*` calls alike (Better Auth's hook pipeline).
12
14
  /** Stable codes; user-facing messages are separate and may be translated by the app. */
13
15
  export const membershipGuardErrors = Object.freeze({
@@ -15,6 +17,8 @@ export const membershipGuardErrors = Object.freeze({
15
17
  INVITATION_NO_LONGER_AUTHORIZED: 'This invitation can no longer grant its membership or role. Ask for a new invitation.',
16
18
  EMAIL_DOMAIN_NOT_ALLOWED: "The email address's domain is not allowed in this organization.",
17
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.',
18
22
  });
19
23
  const refuse = (code, status = 'FORBIDDEN', message) => APIError.fromStatus(status, { code, message: message ?? membershipGuardErrors[code] });
20
24
  const notMember = () => APIError.fromStatus('FORBIDDEN', {
@@ -50,6 +54,13 @@ export function membershipGuard(access, guardOptions = {}) {
50
54
  });
51
55
  return storedInvitationPolicy(organization?.invitationPolicy);
52
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
+ };
53
64
  /** Effective statements of a stored role value (several roles combined, custom roles included). */
54
65
  const statementsOf = async (ctx, organizationId, role) => {
55
66
  const custom = new Map();
@@ -179,6 +190,8 @@ export function membershipGuard(access, guardOptions = {}) {
179
190
  fields: {
180
191
  /** The invitation domain policy; written only through set-invitation-policy. */
181
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 },
182
195
  },
183
196
  },
184
197
  },
@@ -230,6 +243,44 @@ export function membershipGuard(access, guardOptions = {}) {
230
243
  });
231
244
  return ctx.json({ organizationId, ...invitationPolicyView(policy) });
232
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
+ }),
233
284
  },
234
285
  };
235
286
  }
@@ -64,7 +64,7 @@ export function sessionOrganizationBackend(client, authenticated, signedOut = au
64
64
  });
65
65
  }
66
66
  // Capability objects: the same account check before every operation.
67
- for (const key of ['customRoles', 'invitationPolicy']) {
67
+ for (const key of ['customRoles', 'invitationPolicy', 'securityPolicy']) {
68
68
  Object.defineProperty(backend, key, {
69
69
  enumerable: true,
70
70
  get() {
@@ -60,7 +60,7 @@ export function betterAuthOrganizations(client, extensions = {}) {
60
60
  }
61
61
  const guardRequest = async (path, options) => {
62
62
  if (!client.$fetch)
63
- throw new Error('This client cannot reach the invitation policy.');
63
+ throw new Error('This client cannot reach the organization policies.');
64
64
  return (await value(client.$fetch(path, options)));
65
65
  };
66
66
  const activeOrganization = () => api.getOrganization ? api.getOrganization() : api.getFullOrganization();
@@ -253,6 +253,18 @@ export function betterAuthOrganizations(client, extensions = {}) {
253
253
  }),
254
254
  }
255
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,
256
268
  updateRole: (input) => completed(api.updateMemberRole({ ...input, role: input.role })),
257
269
  removeMember: ({ organizationId, memberId }) => completed(api.removeMember({ organizationId, memberIdOrEmail: memberId })),
258
270
  };
@@ -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
+ }
package/dist/server.d.ts CHANGED
@@ -2,13 +2,14 @@ import type { AccessConfiguration } from '@bitakit/core';
2
2
  import { type OrganizationOptions } from 'better-auth/plugins/organization';
3
3
  export { membershipGuard, membershipGuardErrors, type MembershipGuardOptions } from './guard.js';
4
4
  export { anyDomain, invitationPolicyAllows, invitationPolicyView, normalizeDomain, parseInvitationPolicy, storedInvitationPolicy, InvitationPolicyError, type InvitationDomain, type InvitationPolicy, type InvitationPolicyMode, type InvitationPolicyView, } from './domain-policy.js';
5
+ export { defaultSecurityPolicy, parseSecurityPolicy, securityPolicyMet, storedSecurityPolicy, SecurityPolicyError, type SecurityPolicy, } from './security-policy.js';
5
6
  /** Organization options BitaKit derives from `accessConfiguration`; the app must not set them. */
6
7
  declare const derived: readonly ["ac", "roles", "creatorRole", "dynamicAccessControl"];
7
8
  type AppOrganizationOptions = Omit<OrganizationOptions, (typeof derived)[number]>;
8
9
  /**
9
10
  * Better Auth's server `organization` plugin for a BitaKit app: the roles and permissions from the
10
11
  * generated `accessConfiguration`, and the membership guard (role ceiling, invitation re-validation,
11
- * invitation domain policy) installed in the same plugin, so it cannot be left out. Every other
12
+ * invitation domain policy, the stored security policy) installed in the same plugin, so it cannot be left out. Every other
12
13
  * organization option (invitation e-mail, hooks, teams, limits) is the app's, unchanged.
13
14
  *
14
15
  * ```ts
@@ -693,5 +694,63 @@ export declare function createOrganizationPlugin(configuration: AccessConfigurat
693
694
  })[];
694
695
  organizationId: string;
695
696
  }>;
697
+ getSecurityPolicy: import("better-call").StrictEndpoint<"/organization/get-security-policy", {
698
+ method: "GET";
699
+ use: import("better-call").Middleware<import("better-call").MiddlewareOptions, (inputContext: import("better-call").MiddlewareInputContext<import("better-call").MiddlewareOptions>) => Promise<{
700
+ session: {
701
+ session: Record<string, any> & {
702
+ id: string;
703
+ createdAt: Date;
704
+ updatedAt: Date;
705
+ userId: string;
706
+ expiresAt: Date;
707
+ token: string;
708
+ ipAddress?: string | null | undefined;
709
+ userAgent?: string | null | undefined;
710
+ };
711
+ user: Record<string, any> & {
712
+ id: string;
713
+ createdAt: Date;
714
+ updatedAt: Date;
715
+ email: string;
716
+ emailVerified: boolean;
717
+ name: string;
718
+ image?: string | null | undefined;
719
+ };
720
+ };
721
+ }>>[];
722
+ }, {
723
+ twoFactor: "optional" | "required";
724
+ organizationId: string;
725
+ }>;
726
+ setSecurityPolicy: import("better-call").StrictEndpoint<"/organization/set-security-policy", {
727
+ method: "POST";
728
+ use: import("better-call").Middleware<import("better-call").MiddlewareOptions, (inputContext: import("better-call").MiddlewareInputContext<import("better-call").MiddlewareOptions>) => Promise<{
729
+ session: {
730
+ session: Record<string, any> & {
731
+ id: string;
732
+ createdAt: Date;
733
+ updatedAt: Date;
734
+ userId: string;
735
+ expiresAt: Date;
736
+ token: string;
737
+ ipAddress?: string | null | undefined;
738
+ userAgent?: string | null | undefined;
739
+ };
740
+ user: Record<string, any> & {
741
+ id: string;
742
+ createdAt: Date;
743
+ updatedAt: Date;
744
+ email: string;
745
+ emailVerified: boolean;
746
+ name: string;
747
+ image?: string | null | undefined;
748
+ };
749
+ };
750
+ }>>[];
751
+ }, {
752
+ twoFactor: "optional" | "required";
753
+ organizationId: string;
754
+ }>;
696
755
  };
697
756
  };
package/dist/server.js CHANGED
@@ -3,12 +3,13 @@ import { betterAuthAccess } from './access.js';
3
3
  import { membershipGuard } from './guard.js';
4
4
  export { membershipGuard, membershipGuardErrors } from './guard.js';
5
5
  export { anyDomain, invitationPolicyAllows, invitationPolicyView, normalizeDomain, parseInvitationPolicy, storedInvitationPolicy, InvitationPolicyError, } from './domain-policy.js';
6
+ export { defaultSecurityPolicy, parseSecurityPolicy, securityPolicyMet, storedSecurityPolicy, SecurityPolicyError, } from './security-policy.js';
6
7
  /** Organization options BitaKit derives from `accessConfiguration`; the app must not set them. */
7
8
  const derived = ['ac', 'roles', 'creatorRole', 'dynamicAccessControl'];
8
9
  /**
9
10
  * Better Auth's server `organization` plugin for a BitaKit app: the roles and permissions from the
10
11
  * generated `accessConfiguration`, and the membership guard (role ceiling, invitation re-validation,
11
- * invitation domain policy) installed in the same plugin, so it cannot be left out. Every other
12
+ * invitation domain policy, the stored security policy) installed in the same plugin, so it cannot be left out. Every other
12
13
  * organization option (invitation e-mail, hooks, teams, limits) is the app's, unchanged.
13
14
  *
14
15
  * ```ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bitakit/better-auth",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "type": "module",
5
5
  "bitakit": {
6
6
  "plugin": "./plugin",
@@ -54,13 +54,13 @@
54
54
  },
55
55
  "peerDependencies": {
56
56
  "@bitakit/email": "^0.3.0",
57
- "@bitakit/organizations": "^0.3.0",
57
+ "@bitakit/organizations": "^0.3.1",
58
58
  "better-auth": "^1.7.5",
59
59
  "react": "^19.0.0"
60
60
  },
61
61
  "devDependencies": {
62
62
  "@bitakit/email": "^0.3.0",
63
- "@bitakit/organizations": "^0.3.0",
63
+ "@bitakit/organizations": "^0.3.1",
64
64
  "@types/node": "^24.19.2",
65
65
  "@types/react": "^19",
66
66
  "typescript": "^5"