@bitakit/better-auth 0.3.0 → 0.3.2
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 +22 -1
- package/dist/guard.d.ts +123 -0
- package/dist/guard.js +127 -1
- package/dist/organization-session.js +1 -1
- package/dist/organizations.js +24 -1
- package/dist/security-policy.d.ts +22 -0
- package/dist/security-policy.js +52 -0
- package/dist/server.d.ts +97 -3
- package/dist/server.js +15 -3
- package/dist/sign-in-method.d.ts +46 -0
- package/dist/sign-in-method.js +77 -0
- package/package.json +3 -3
package/AGENTS.md
CHANGED
|
@@ -80,11 +80,32 @@ 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
|
+
- Accepted sign-in methods (`securityPolicy.signInMethods`, absent = every method): each session records how it was signed
|
|
92
|
+
in (`session.signInMethod`; names of Better Auth's last-login-method plugin – `email`, `magic-link`, `passkey`, a
|
|
93
|
+
provider id such as `google` –, also across the two-factor code step; `signInMethodOf`). The app checks a request's
|
|
94
|
+
session with `signInMethodAllowed(policy, session.signInMethod)` (a session without a method is refused while a list
|
|
95
|
+
exists: the person signs in again). Saving a list without the actor's own method is refused (`SIGN_IN_METHOD_IN_USE`).
|
|
96
|
+
Add the `session.signInMethod` (text) column with the app's Better Auth migration.
|
|
97
|
+
- Two-step reset: `POST /organization/reset-member-two-factor` (`{ organizationId?, memberId }`) turns a member's
|
|
98
|
+
two-factor off (lost phone): needs `member:update` and the target's role within the actor's (never the creator role by a
|
|
99
|
+
non-creator, never oneself – `RESET_OWN_TWO_FACTOR`), only for a person in no other organization
|
|
100
|
+
(`MEMBER_OF_OTHER_ORGANIZATIONS`), only with Better Auth's `twoFactor` plugin installed; it removes the secret, sets
|
|
101
|
+
`twoFactorEnabled` false and ends every session of the person. `createOrganizationPlugin(…, { afterResetTwoFactor })`
|
|
102
|
+
is told afterwards (email the person, audit). In the browser: the `resetTwoFactor` capability of `@bitakit/organizations`.
|
|
103
|
+
In the browser it is the `securityPolicy` capability of `@bitakit/organizations`.
|
|
83
104
|
- Better Auth's errors stay for missing management permission, expired invitations and
|
|
84
105
|
unverified addresses. Stable codes and messages: `membershipGuardErrors` (`./server`).
|
|
85
106
|
- Apps that suspend members declare `member.disabled` (boolean) in the organization schema; the
|
|
86
107
|
guard treats a disabled member as having no authority. Add the `organization.invitationPolicy`
|
|
87
|
-
(json)
|
|
108
|
+
and `organization.securityPolicy` (json) columns with the app's Better Auth migration.
|
|
88
109
|
- Server-only `auth.api.addMember` (no HTTP route) is trusted server code and not actor-checked.
|
|
89
110
|
|
|
90
111
|
Check capabilities on the server with `hasOrganizationPermission(auth, { headers, permissions })`
|
package/dist/guard.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { BetterAuthPlugin } from 'better-auth';
|
|
1
2
|
import type { betterAuthAccess } from './access.js';
|
|
2
3
|
/** Stable codes; user-facing messages are separate and may be translated by the app. */
|
|
3
4
|
export declare const membershipGuardErrors: Readonly<{
|
|
@@ -5,11 +6,26 @@ export declare const membershipGuardErrors: Readonly<{
|
|
|
5
6
|
INVITATION_NO_LONGER_AUTHORIZED: "This invitation can no longer grant its membership or role. Ask for a new invitation.";
|
|
6
7
|
EMAIL_DOMAIN_NOT_ALLOWED: "The email address's domain is not allowed in this organization.";
|
|
7
8
|
INVALID_INVITATION_POLICY: "The invitation policy is invalid.";
|
|
9
|
+
INVALID_SECURITY_POLICY: "The security policy is invalid.";
|
|
10
|
+
RESET_OWN_TWO_FACTOR: "Turn your own two-step sign-in off in your account settings.";
|
|
11
|
+
MEMBER_OF_OTHER_ORGANIZATIONS: "This person also belongs to other organizations, so no single organization may reset their two-step sign-in.";
|
|
12
|
+
TWO_FACTOR_NOT_ENABLED: "This member has not turned on two-step sign-in.";
|
|
13
|
+
TWO_FACTOR_NOT_AVAILABLE: "Two-step sign-in is not installed.";
|
|
14
|
+
SIGN_IN_METHOD_IN_USE: "Keep the sign-in method you are signed in with, or sign in with one of the methods you keep first.";
|
|
15
|
+
ENABLE_TWO_FACTOR_FIRST: "Turn on two-factor sign-in for your own account before you require it for the organization.";
|
|
8
16
|
}>;
|
|
9
17
|
type Access = ReturnType<typeof betterAuthAccess>;
|
|
10
18
|
export type MembershipGuardOptions = {
|
|
11
19
|
/** Mirrors the organization option, so an unverified address keeps Better Auth's own error. */
|
|
12
20
|
requireEmailVerificationOnInvitation?: boolean;
|
|
21
|
+
/** After a member's two-step sign-in was reset (tell the person, write the audit log); a failure is logged, not answered. */
|
|
22
|
+
afterResetTwoFactor?: (data: TwoFactorReset) => Promise<void> | void;
|
|
23
|
+
};
|
|
24
|
+
export type TwoFactorReset = {
|
|
25
|
+
organizationId: string;
|
|
26
|
+
memberId: string;
|
|
27
|
+
userId: string;
|
|
28
|
+
actorUserId: string;
|
|
13
29
|
};
|
|
14
30
|
/**
|
|
15
31
|
* The guard as a Better Auth plugin. Normally installed by `createOrganizationPlugin`; exported
|
|
@@ -17,6 +33,7 @@ export type MembershipGuardOptions = {
|
|
|
17
33
|
*/
|
|
18
34
|
export declare function membershipGuard(access: Access, guardOptions?: MembershipGuardOptions): {
|
|
19
35
|
id: "bitakit-membership-guard";
|
|
36
|
+
init: () => ReturnType<NonNullable<BetterAuthPlugin["init"]>>;
|
|
20
37
|
schema: {
|
|
21
38
|
organization: {
|
|
22
39
|
fields: {
|
|
@@ -26,6 +43,21 @@ export declare function membershipGuard(access: Access, guardOptions?: Membershi
|
|
|
26
43
|
required: false;
|
|
27
44
|
input: false;
|
|
28
45
|
};
|
|
46
|
+
/** The security policy (two-factor optional or required); written only through set-security-policy. */
|
|
47
|
+
securityPolicy: {
|
|
48
|
+
type: "json";
|
|
49
|
+
required: false;
|
|
50
|
+
input: false;
|
|
51
|
+
};
|
|
52
|
+
};
|
|
53
|
+
};
|
|
54
|
+
session: {
|
|
55
|
+
readonly fields: {
|
|
56
|
+
readonly signInMethod: {
|
|
57
|
+
readonly type: "string";
|
|
58
|
+
readonly required: false;
|
|
59
|
+
readonly input: false;
|
|
60
|
+
};
|
|
29
61
|
};
|
|
30
62
|
};
|
|
31
63
|
};
|
|
@@ -100,6 +132,97 @@ export declare function membershipGuard(access: Access, guardOptions?: Membershi
|
|
|
100
132
|
})[];
|
|
101
133
|
organizationId: string;
|
|
102
134
|
}>;
|
|
135
|
+
getSecurityPolicy: import("better-call").StrictEndpoint<"/organization/get-security-policy", {
|
|
136
|
+
method: "GET";
|
|
137
|
+
use: import("better-call").Middleware<import("better-call").MiddlewareOptions, (inputContext: import("better-call").MiddlewareInputContext<import("better-call").MiddlewareOptions>) => Promise<{
|
|
138
|
+
session: {
|
|
139
|
+
session: Record<string, any> & {
|
|
140
|
+
id: string;
|
|
141
|
+
createdAt: Date;
|
|
142
|
+
updatedAt: Date;
|
|
143
|
+
userId: string;
|
|
144
|
+
expiresAt: Date;
|
|
145
|
+
token: string;
|
|
146
|
+
ipAddress?: string | null | undefined;
|
|
147
|
+
userAgent?: string | null | undefined;
|
|
148
|
+
};
|
|
149
|
+
user: Record<string, any> & {
|
|
150
|
+
id: string;
|
|
151
|
+
createdAt: Date;
|
|
152
|
+
updatedAt: Date;
|
|
153
|
+
email: string;
|
|
154
|
+
emailVerified: boolean;
|
|
155
|
+
name: string;
|
|
156
|
+
image?: string | null | undefined;
|
|
157
|
+
};
|
|
158
|
+
};
|
|
159
|
+
}>>[];
|
|
160
|
+
}, {
|
|
161
|
+
twoFactor: "optional" | "required";
|
|
162
|
+
signInMethods?: string[];
|
|
163
|
+
organizationId: string;
|
|
164
|
+
}>;
|
|
165
|
+
resetMemberTwoFactor: import("better-call").StrictEndpoint<"/organization/reset-member-two-factor", {
|
|
166
|
+
method: "POST";
|
|
167
|
+
use: import("better-call").Middleware<import("better-call").MiddlewareOptions, (inputContext: import("better-call").MiddlewareInputContext<import("better-call").MiddlewareOptions>) => Promise<{
|
|
168
|
+
session: {
|
|
169
|
+
session: Record<string, any> & {
|
|
170
|
+
id: string;
|
|
171
|
+
createdAt: Date;
|
|
172
|
+
updatedAt: Date;
|
|
173
|
+
userId: string;
|
|
174
|
+
expiresAt: Date;
|
|
175
|
+
token: string;
|
|
176
|
+
ipAddress?: string | null | undefined;
|
|
177
|
+
userAgent?: string | null | undefined;
|
|
178
|
+
};
|
|
179
|
+
user: Record<string, any> & {
|
|
180
|
+
id: string;
|
|
181
|
+
createdAt: Date;
|
|
182
|
+
updatedAt: Date;
|
|
183
|
+
email: string;
|
|
184
|
+
emailVerified: boolean;
|
|
185
|
+
name: string;
|
|
186
|
+
image?: string | null | undefined;
|
|
187
|
+
};
|
|
188
|
+
};
|
|
189
|
+
}>>[];
|
|
190
|
+
}, {
|
|
191
|
+
organizationId: string;
|
|
192
|
+
memberId: string;
|
|
193
|
+
userId: string;
|
|
194
|
+
actorUserId: string;
|
|
195
|
+
}>;
|
|
196
|
+
setSecurityPolicy: import("better-call").StrictEndpoint<"/organization/set-security-policy", {
|
|
197
|
+
method: "POST";
|
|
198
|
+
use: import("better-call").Middleware<import("better-call").MiddlewareOptions, (inputContext: import("better-call").MiddlewareInputContext<import("better-call").MiddlewareOptions>) => Promise<{
|
|
199
|
+
session: {
|
|
200
|
+
session: Record<string, any> & {
|
|
201
|
+
id: string;
|
|
202
|
+
createdAt: Date;
|
|
203
|
+
updatedAt: Date;
|
|
204
|
+
userId: string;
|
|
205
|
+
expiresAt: Date;
|
|
206
|
+
token: string;
|
|
207
|
+
ipAddress?: string | null | undefined;
|
|
208
|
+
userAgent?: string | null | undefined;
|
|
209
|
+
};
|
|
210
|
+
user: Record<string, any> & {
|
|
211
|
+
id: string;
|
|
212
|
+
createdAt: Date;
|
|
213
|
+
updatedAt: Date;
|
|
214
|
+
email: string;
|
|
215
|
+
emailVerified: boolean;
|
|
216
|
+
name: string;
|
|
217
|
+
image?: string | null | undefined;
|
|
218
|
+
};
|
|
219
|
+
};
|
|
220
|
+
}>>[];
|
|
221
|
+
}, {
|
|
222
|
+
twoFactor: "optional" | "required";
|
|
223
|
+
signInMethods?: string[];
|
|
224
|
+
organizationId: string;
|
|
225
|
+
}>;
|
|
103
226
|
};
|
|
104
227
|
};
|
|
105
228
|
export {};
|
package/dist/guard.js
CHANGED
|
@@ -1,13 +1,17 @@
|
|
|
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, signInMethodAllowed, storedSecurityPolicy, } from './security-policy.js';
|
|
5
|
+
import { signInMethodRecording } from './sign-in-method.js';
|
|
4
6
|
// The membership guard: BitaKit's server-side invariants on Better Auth's own organization
|
|
5
7
|
// operations. Better Auth still runs all of its checks (member management permission, creator role,
|
|
6
8
|
// last owner, expiry, verified address); this only adds:
|
|
7
9
|
// - the role ceiling: an actor may only invite, assign or change roles whose effective permissions
|
|
8
10
|
// (all roles of the member combined, static and custom) the actor holds;
|
|
9
11
|
// - 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
|
|
12
|
+
// - the organization's invitation domain policy, at creation and acceptance;
|
|
13
|
+
// - the organization's security policy (two-factor optional or required, accepted sign-in methods): stored here, enforced
|
|
14
|
+
// by the app; each session records how it was signed in (`session.signInMethod`, sign-in-method.ts).
|
|
11
15
|
// It runs for HTTP requests and server `auth.api.*` calls alike (Better Auth's hook pipeline).
|
|
12
16
|
/** Stable codes; user-facing messages are separate and may be translated by the app. */
|
|
13
17
|
export const membershipGuardErrors = Object.freeze({
|
|
@@ -15,6 +19,13 @@ export const membershipGuardErrors = Object.freeze({
|
|
|
15
19
|
INVITATION_NO_LONGER_AUTHORIZED: 'This invitation can no longer grant its membership or role. Ask for a new invitation.',
|
|
16
20
|
EMAIL_DOMAIN_NOT_ALLOWED: "The email address's domain is not allowed in this organization.",
|
|
17
21
|
INVALID_INVITATION_POLICY: 'The invitation policy is invalid.',
|
|
22
|
+
INVALID_SECURITY_POLICY: 'The security policy is invalid.',
|
|
23
|
+
RESET_OWN_TWO_FACTOR: 'Turn your own two-step sign-in off in your account settings.',
|
|
24
|
+
MEMBER_OF_OTHER_ORGANIZATIONS: 'This person also belongs to other organizations, so no single organization may reset their two-step sign-in.',
|
|
25
|
+
TWO_FACTOR_NOT_ENABLED: 'This member has not turned on two-step sign-in.',
|
|
26
|
+
TWO_FACTOR_NOT_AVAILABLE: 'Two-step sign-in is not installed.',
|
|
27
|
+
SIGN_IN_METHOD_IN_USE: 'Keep the sign-in method you are signed in with, or sign in with one of the methods you keep first.',
|
|
28
|
+
ENABLE_TWO_FACTOR_FIRST: 'Turn on two-factor sign-in for your own account before you require it for the organization.',
|
|
18
29
|
});
|
|
19
30
|
const refuse = (code, status = 'FORBIDDEN', message) => APIError.fromStatus(status, { code, message: message ?? membershipGuardErrors[code] });
|
|
20
31
|
const notMember = () => APIError.fromStatus('FORBIDDEN', {
|
|
@@ -50,6 +61,13 @@ export function membershipGuard(access, guardOptions = {}) {
|
|
|
50
61
|
});
|
|
51
62
|
return storedInvitationPolicy(organization?.invitationPolicy);
|
|
52
63
|
};
|
|
64
|
+
const securityOf = async (ctx, organizationId) => {
|
|
65
|
+
const organization = await adapter(ctx).findOne({
|
|
66
|
+
model: 'organization',
|
|
67
|
+
where: [{ field: 'id', value: organizationId }],
|
|
68
|
+
});
|
|
69
|
+
return storedSecurityPolicy(organization?.securityPolicy);
|
|
70
|
+
};
|
|
53
71
|
/** Effective statements of a stored role value (several roles combined, custom roles included). */
|
|
54
72
|
const statementsOf = async (ctx, organizationId, role) => {
|
|
55
73
|
const custom = new Map();
|
|
@@ -172,13 +190,18 @@ export function membershipGuard(access, guardOptions = {}) {
|
|
|
172
190
|
if (!(await covers(ctx, organizationId, inviter.role, invited.statements)))
|
|
173
191
|
throw refuse('INVITATION_NO_LONGER_AUTHORIZED');
|
|
174
192
|
});
|
|
193
|
+
const recording = signInMethodRecording();
|
|
175
194
|
return {
|
|
176
195
|
id: 'bitakit-membership-guard',
|
|
196
|
+
init: recording.init,
|
|
177
197
|
schema: {
|
|
198
|
+
...recording.schema,
|
|
178
199
|
organization: {
|
|
179
200
|
fields: {
|
|
180
201
|
/** The invitation domain policy; written only through set-invitation-policy. */
|
|
181
202
|
invitationPolicy: { type: 'json', required: false, input: false },
|
|
203
|
+
/** The security policy (two-factor optional or required); written only through set-security-policy. */
|
|
204
|
+
securityPolicy: { type: 'json', required: false, input: false },
|
|
182
205
|
},
|
|
183
206
|
},
|
|
184
207
|
},
|
|
@@ -230,6 +253,109 @@ export function membershipGuard(access, guardOptions = {}) {
|
|
|
230
253
|
});
|
|
231
254
|
return ctx.json({ organizationId, ...invitationPolicyView(policy) });
|
|
232
255
|
}),
|
|
256
|
+
getSecurityPolicy: createAuthEndpoint('/organization/get-security-policy', { method: 'GET', use: [sessionMiddleware] }, async (ctx) => {
|
|
257
|
+
const organizationId = await organizationIdOf(ctx, ctx.query?.organizationId);
|
|
258
|
+
const actor = await actorIn(ctx, organizationId);
|
|
259
|
+
if (!organizationId || !actor)
|
|
260
|
+
throw notMember();
|
|
261
|
+
return ctx.json({ organizationId, ...(await securityOf(ctx, organizationId)) });
|
|
262
|
+
}),
|
|
263
|
+
// A member lost their second factor (phone gone, no backup codes): an owner or admin turns it off for them. Only for a
|
|
264
|
+
// person who belongs to this organization alone – otherwise one organization would weaken an account others rely on –
|
|
265
|
+
// and never for oneself or above one's own role. Their sessions end; they sign in with their password and may set it
|
|
266
|
+
// up again (an organization that requires it sends them there).
|
|
267
|
+
resetMemberTwoFactor: createAuthEndpoint('/organization/reset-member-two-factor', { method: 'POST', use: [sessionMiddleware] }, async (ctx) => {
|
|
268
|
+
const body = (ctx.body ?? {});
|
|
269
|
+
const organizationId = await organizationIdOf(ctx, body.organizationId);
|
|
270
|
+
const actor = await actorIn(ctx, organizationId);
|
|
271
|
+
if (!organizationId || !actor)
|
|
272
|
+
throw notMember();
|
|
273
|
+
const target = typeof body.memberId === 'string' && body.memberId
|
|
274
|
+
? await adapter(ctx).findOne({
|
|
275
|
+
model: 'member',
|
|
276
|
+
where: [
|
|
277
|
+
{ field: 'id', value: body.memberId },
|
|
278
|
+
{ field: 'organizationId', value: organizationId },
|
|
279
|
+
],
|
|
280
|
+
})
|
|
281
|
+
: null;
|
|
282
|
+
if (!target)
|
|
283
|
+
throw APIError.fromStatus('BAD_REQUEST', {
|
|
284
|
+
code: 'MEMBER_NOT_FOUND',
|
|
285
|
+
message: 'Member not found',
|
|
286
|
+
});
|
|
287
|
+
if (target.userId === actor.session.user.id)
|
|
288
|
+
throw refuse('RESET_OWN_TWO_FACTOR', 'BAD_REQUEST');
|
|
289
|
+
const { statements } = await statementsOf(ctx, organizationId, target.role);
|
|
290
|
+
if (!(await covers(ctx, organizationId, actor.member.role, { member: ['update'] })) ||
|
|
291
|
+
touchesCreator(actor.member.role, target.role) ||
|
|
292
|
+
!(await covers(ctx, organizationId, actor.member.role, statements)))
|
|
293
|
+
throw refuse('ROLE_EXCEEDS_YOUR_PERMISSIONS');
|
|
294
|
+
if (!ctx.context.options.plugins?.some((plugin) => plugin.id === 'two-factor'))
|
|
295
|
+
throw refuse('TWO_FACTOR_NOT_AVAILABLE', 'BAD_REQUEST');
|
|
296
|
+
const memberships = await adapter(ctx).count({
|
|
297
|
+
model: 'member',
|
|
298
|
+
where: [{ field: 'userId', value: target.userId }],
|
|
299
|
+
});
|
|
300
|
+
if (memberships > 1)
|
|
301
|
+
throw refuse('MEMBER_OF_OTHER_ORGANIZATIONS');
|
|
302
|
+
const user = (await ctx.context.internalAdapter.findUserById(target.userId));
|
|
303
|
+
if (!user?.twoFactorEnabled)
|
|
304
|
+
throw refuse('TWO_FACTOR_NOT_ENABLED', 'BAD_REQUEST');
|
|
305
|
+
await adapter(ctx).deleteMany({
|
|
306
|
+
model: 'twoFactor',
|
|
307
|
+
where: [{ field: 'userId', value: target.userId }],
|
|
308
|
+
});
|
|
309
|
+
await ctx.context.internalAdapter.updateUser(target.userId, { twoFactorEnabled: false });
|
|
310
|
+
await ctx.context.internalAdapter.deleteUserSessions(target.userId);
|
|
311
|
+
const reset = {
|
|
312
|
+
organizationId,
|
|
313
|
+
memberId: target.id,
|
|
314
|
+
userId: target.userId,
|
|
315
|
+
actorUserId: actor.session.user.id,
|
|
316
|
+
};
|
|
317
|
+
try {
|
|
318
|
+
await guardOptions.afterResetTwoFactor?.(reset);
|
|
319
|
+
}
|
|
320
|
+
catch (error) {
|
|
321
|
+
ctx.context.logger.error('afterResetTwoFactor failed', error);
|
|
322
|
+
}
|
|
323
|
+
return ctx.json(reset);
|
|
324
|
+
}),
|
|
325
|
+
setSecurityPolicy: createAuthEndpoint('/organization/set-security-policy', { method: 'POST', use: [sessionMiddleware] }, async (ctx) => {
|
|
326
|
+
const body = (ctx.body ?? {});
|
|
327
|
+
const organizationId = await organizationIdOf(ctx, body.organizationId);
|
|
328
|
+
const actor = await actorIn(ctx, organizationId);
|
|
329
|
+
if (!organizationId || !actor)
|
|
330
|
+
throw notMember();
|
|
331
|
+
if (!(await covers(ctx, organizationId, actor.member.role, { organization: ['update'] })))
|
|
332
|
+
throw APIError.fromStatus('FORBIDDEN', {
|
|
333
|
+
code: 'YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION',
|
|
334
|
+
message: 'You are not allowed to update this organization',
|
|
335
|
+
});
|
|
336
|
+
let policy;
|
|
337
|
+
try {
|
|
338
|
+
policy = parseSecurityPolicy(body.policy);
|
|
339
|
+
}
|
|
340
|
+
catch (error) {
|
|
341
|
+
if (error instanceof SecurityPolicyError)
|
|
342
|
+
throw refuse('INVALID_SECURITY_POLICY', 'BAD_REQUEST', error.message);
|
|
343
|
+
throw error;
|
|
344
|
+
}
|
|
345
|
+
// Nobody requires what they do not have themselves: it would lock them out of their own organization.
|
|
346
|
+
const user = actor.session.user;
|
|
347
|
+
if (policy.twoFactor === 'required' && user.twoFactorEnabled !== true)
|
|
348
|
+
throw refuse('ENABLE_TWO_FACTOR_FIRST');
|
|
349
|
+
const method = actor.session.session.signInMethod;
|
|
350
|
+
if (!signInMethodAllowed(policy, method))
|
|
351
|
+
throw refuse('SIGN_IN_METHOD_IN_USE');
|
|
352
|
+
await adapter(ctx).update({
|
|
353
|
+
model: 'organization',
|
|
354
|
+
where: [{ field: 'id', value: organizationId }],
|
|
355
|
+
update: { securityPolicy: policy },
|
|
356
|
+
});
|
|
357
|
+
return ctx.json({ organizationId, ...policy });
|
|
358
|
+
}),
|
|
233
359
|
},
|
|
234
360
|
};
|
|
235
361
|
}
|
|
@@ -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() {
|
package/dist/organizations.js
CHANGED
|
@@ -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
|
|
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,29 @@ export function betterAuthOrganizations(client, extensions = {}) {
|
|
|
253
253
|
}),
|
|
254
254
|
}
|
|
255
255
|
: undefined,
|
|
256
|
+
securityPolicy: declared && client.$fetch
|
|
257
|
+
? {
|
|
258
|
+
load: async (organizationId) => {
|
|
259
|
+
const { organizationId: _, ...policy } = await guardRequest('/organization/get-security-policy', { method: 'GET', query: { organizationId } });
|
|
260
|
+
return policy;
|
|
261
|
+
},
|
|
262
|
+
save: async ({ organizationId, policy }) => {
|
|
263
|
+
const { organizationId: _, ...saved } = await guardRequest('/organization/set-security-policy', {
|
|
264
|
+
method: 'POST',
|
|
265
|
+
body: { organizationId, policy },
|
|
266
|
+
});
|
|
267
|
+
return saved;
|
|
268
|
+
},
|
|
269
|
+
}
|
|
270
|
+
: undefined,
|
|
271
|
+
resetTwoFactor: declared && client.$fetch
|
|
272
|
+
? async ({ organizationId, memberId }) => {
|
|
273
|
+
await guardRequest('/organization/reset-member-two-factor', {
|
|
274
|
+
method: 'POST',
|
|
275
|
+
body: { organizationId, memberId },
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
: undefined,
|
|
256
279
|
updateRole: (input) => completed(api.updateMemberRole({ ...input, role: input.role })),
|
|
257
280
|
removeMember: ({ organizationId, memberId }) => completed(api.removeMember({ organizationId, memberIdOrEmail: memberId })),
|
|
258
281
|
};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/** Same shape as `SecurityPolicy` of `@bitakit/organizations`. */
|
|
2
|
+
export type SecurityPolicy = {
|
|
3
|
+
twoFactor: 'optional' | 'required';
|
|
4
|
+
/** Sign-in methods the organization accepts (`signInMethodOf` names: `email`, `passkey`, `google`, …); absent = all. */
|
|
5
|
+
signInMethods?: string[];
|
|
6
|
+
};
|
|
7
|
+
export declare const defaultSecurityPolicy: SecurityPolicy;
|
|
8
|
+
export declare class SecurityPolicyError extends Error {
|
|
9
|
+
}
|
|
10
|
+
/** A policy sent by a client: refused unless it is exactly a known rule. */
|
|
11
|
+
export declare function parseSecurityPolicy(value: unknown): SecurityPolicy;
|
|
12
|
+
/** The stored value (JSON text or object, possibly absent or from an older version): never throws, defaults to optional. */
|
|
13
|
+
export declare function storedSecurityPolicy(value: unknown): SecurityPolicy;
|
|
14
|
+
/** Whether a person meets the organization's rule: with `required`, only with two-factor sign-in turned on. */
|
|
15
|
+
export declare function securityPolicyMet(policy: SecurityPolicy, user: {
|
|
16
|
+
twoFactorEnabled?: boolean | null;
|
|
17
|
+
}): boolean;
|
|
18
|
+
/**
|
|
19
|
+
* Whether a session's sign-in method (the session's `signInMethod`, recorded by the membership guard) is accepted. With a
|
|
20
|
+
* list, a session whose method is unknown (signed in before it was recorded) is not: the person signs in again.
|
|
21
|
+
*/
|
|
22
|
+
export declare function signInMethodAllowed(policy: SecurityPolicy, method: string | null | undefined): boolean;
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// The organization's sign-in rule (security policy): whether its members must use two-factor sign-in, and which sign-in
|
|
2
|
+
// methods it accepts (absent = every method the app offers). Stored on the
|
|
3
|
+
// organization by the membership guard (`securityPolicy`, written only through set-security-policy); enforced by the app on
|
|
4
|
+
// its server with `securityPolicyMet`, because only the app knows which of its requests belong to an organization.
|
|
5
|
+
// Browser- and server-safe.
|
|
6
|
+
export const defaultSecurityPolicy = Object.freeze({ twoFactor: 'optional' });
|
|
7
|
+
export class SecurityPolicyError extends Error {
|
|
8
|
+
}
|
|
9
|
+
/** A policy sent by a client: refused unless it is exactly a known rule. */
|
|
10
|
+
export function parseSecurityPolicy(value) {
|
|
11
|
+
const { twoFactor, signInMethods } = (value ?? {});
|
|
12
|
+
if (twoFactor !== 'optional' && twoFactor !== 'required')
|
|
13
|
+
throw new SecurityPolicyError('twoFactor must be "optional" or "required".');
|
|
14
|
+
if (signInMethods === undefined || signInMethods === null)
|
|
15
|
+
return { twoFactor };
|
|
16
|
+
// An empty list would lock every member out; a method is a short lower-case name.
|
|
17
|
+
if (!Array.isArray(signInMethods) ||
|
|
18
|
+
!signInMethods.length ||
|
|
19
|
+
signInMethods.length > 20 ||
|
|
20
|
+
!signInMethods.every((method) => typeof method === 'string' && /^[a-z0-9][a-z0-9-]{0,39}$/.test(method)))
|
|
21
|
+
throw new SecurityPolicyError('signInMethods must be a non-empty list of sign-in method names.');
|
|
22
|
+
return { twoFactor, signInMethods: [...new Set(signInMethods)] };
|
|
23
|
+
}
|
|
24
|
+
/** The stored value (JSON text or object, possibly absent or from an older version): never throws, defaults to optional. */
|
|
25
|
+
export function storedSecurityPolicy(value) {
|
|
26
|
+
let parsed = value;
|
|
27
|
+
if (typeof value === 'string') {
|
|
28
|
+
try {
|
|
29
|
+
parsed = JSON.parse(value);
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
return defaultSecurityPolicy;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
try {
|
|
36
|
+
return parseSecurityPolicy(parsed);
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
return defaultSecurityPolicy;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
/** Whether a person meets the organization's rule: with `required`, only with two-factor sign-in turned on. */
|
|
43
|
+
export function securityPolicyMet(policy, user) {
|
|
44
|
+
return policy.twoFactor !== 'required' || user.twoFactorEnabled === true;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Whether a session's sign-in method (the session's `signInMethod`, recorded by the membership guard) is accepted. With a
|
|
48
|
+
* list, a session whose method is unknown (signed in before it was recorded) is not: the person signs in again.
|
|
49
|
+
*/
|
|
50
|
+
export function signInMethodAllowed(policy, method) {
|
|
51
|
+
return !policy.signInMethods || (!!method && policy.signInMethods.includes(method));
|
|
52
|
+
}
|
package/dist/server.d.ts
CHANGED
|
@@ -1,14 +1,17 @@
|
|
|
1
1
|
import type { AccessConfiguration } from '@bitakit/core';
|
|
2
2
|
import { type OrganizationOptions } from 'better-auth/plugins/organization';
|
|
3
|
-
|
|
3
|
+
import { type MembershipGuardOptions } from './guard.js';
|
|
4
|
+
export { membershipGuard, membershipGuardErrors, type MembershipGuardOptions, type TwoFactorReset, } from './guard.js';
|
|
5
|
+
export { signInMethodOf } from './sign-in-method.js';
|
|
4
6
|
export { anyDomain, invitationPolicyAllows, invitationPolicyView, normalizeDomain, parseInvitationPolicy, storedInvitationPolicy, InvitationPolicyError, type InvitationDomain, type InvitationPolicy, type InvitationPolicyMode, type InvitationPolicyView, } from './domain-policy.js';
|
|
7
|
+
export { defaultSecurityPolicy, parseSecurityPolicy, securityPolicyMet, signInMethodAllowed, storedSecurityPolicy, SecurityPolicyError, type SecurityPolicy, } from './security-policy.js';
|
|
5
8
|
/** Organization options BitaKit derives from `accessConfiguration`; the app must not set them. */
|
|
6
9
|
declare const derived: readonly ["ac", "roles", "creatorRole", "dynamicAccessControl"];
|
|
7
|
-
type AppOrganizationOptions = Omit<OrganizationOptions, (typeof derived)[number]>;
|
|
10
|
+
type AppOrganizationOptions = Omit<OrganizationOptions, (typeof derived)[number]> & Pick<MembershipGuardOptions, 'afterResetTwoFactor'>;
|
|
8
11
|
/**
|
|
9
12
|
* Better Auth's server `organization` plugin for a BitaKit app: the roles and permissions from the
|
|
10
13
|
* 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
|
|
14
|
+
* invitation domain policy, the stored security policy) installed in the same plugin, so it cannot be left out. Every other
|
|
12
15
|
* organization option (invitation e-mail, hooks, teams, limits) is the app's, unchanged.
|
|
13
16
|
*
|
|
14
17
|
* ```ts
|
|
@@ -693,5 +696,96 @@ export declare function createOrganizationPlugin(configuration: AccessConfigurat
|
|
|
693
696
|
})[];
|
|
694
697
|
organizationId: string;
|
|
695
698
|
}>;
|
|
699
|
+
getSecurityPolicy: import("better-call").StrictEndpoint<"/organization/get-security-policy", {
|
|
700
|
+
method: "GET";
|
|
701
|
+
use: import("better-call").Middleware<import("better-call").MiddlewareOptions, (inputContext: import("better-call").MiddlewareInputContext<import("better-call").MiddlewareOptions>) => Promise<{
|
|
702
|
+
session: {
|
|
703
|
+
session: Record<string, any> & {
|
|
704
|
+
id: string;
|
|
705
|
+
createdAt: Date;
|
|
706
|
+
updatedAt: Date;
|
|
707
|
+
userId: string;
|
|
708
|
+
expiresAt: Date;
|
|
709
|
+
token: string;
|
|
710
|
+
ipAddress?: string | null | undefined;
|
|
711
|
+
userAgent?: string | null | undefined;
|
|
712
|
+
};
|
|
713
|
+
user: Record<string, any> & {
|
|
714
|
+
id: string;
|
|
715
|
+
createdAt: Date;
|
|
716
|
+
updatedAt: Date;
|
|
717
|
+
email: string;
|
|
718
|
+
emailVerified: boolean;
|
|
719
|
+
name: string;
|
|
720
|
+
image?: string | null | undefined;
|
|
721
|
+
};
|
|
722
|
+
};
|
|
723
|
+
}>>[];
|
|
724
|
+
}, {
|
|
725
|
+
twoFactor: "optional" | "required";
|
|
726
|
+
signInMethods?: string[];
|
|
727
|
+
organizationId: string;
|
|
728
|
+
}>;
|
|
729
|
+
resetMemberTwoFactor: import("better-call").StrictEndpoint<"/organization/reset-member-two-factor", {
|
|
730
|
+
method: "POST";
|
|
731
|
+
use: import("better-call").Middleware<import("better-call").MiddlewareOptions, (inputContext: import("better-call").MiddlewareInputContext<import("better-call").MiddlewareOptions>) => Promise<{
|
|
732
|
+
session: {
|
|
733
|
+
session: Record<string, any> & {
|
|
734
|
+
id: string;
|
|
735
|
+
createdAt: Date;
|
|
736
|
+
updatedAt: Date;
|
|
737
|
+
userId: string;
|
|
738
|
+
expiresAt: Date;
|
|
739
|
+
token: string;
|
|
740
|
+
ipAddress?: string | null | undefined;
|
|
741
|
+
userAgent?: string | null | undefined;
|
|
742
|
+
};
|
|
743
|
+
user: Record<string, any> & {
|
|
744
|
+
id: string;
|
|
745
|
+
createdAt: Date;
|
|
746
|
+
updatedAt: Date;
|
|
747
|
+
email: string;
|
|
748
|
+
emailVerified: boolean;
|
|
749
|
+
name: string;
|
|
750
|
+
image?: string | null | undefined;
|
|
751
|
+
};
|
|
752
|
+
};
|
|
753
|
+
}>>[];
|
|
754
|
+
}, {
|
|
755
|
+
organizationId: string;
|
|
756
|
+
memberId: string;
|
|
757
|
+
userId: string;
|
|
758
|
+
actorUserId: string;
|
|
759
|
+
}>;
|
|
760
|
+
setSecurityPolicy: import("better-call").StrictEndpoint<"/organization/set-security-policy", {
|
|
761
|
+
method: "POST";
|
|
762
|
+
use: import("better-call").Middleware<import("better-call").MiddlewareOptions, (inputContext: import("better-call").MiddlewareInputContext<import("better-call").MiddlewareOptions>) => Promise<{
|
|
763
|
+
session: {
|
|
764
|
+
session: Record<string, any> & {
|
|
765
|
+
id: string;
|
|
766
|
+
createdAt: Date;
|
|
767
|
+
updatedAt: Date;
|
|
768
|
+
userId: string;
|
|
769
|
+
expiresAt: Date;
|
|
770
|
+
token: string;
|
|
771
|
+
ipAddress?: string | null | undefined;
|
|
772
|
+
userAgent?: string | null | undefined;
|
|
773
|
+
};
|
|
774
|
+
user: Record<string, any> & {
|
|
775
|
+
id: string;
|
|
776
|
+
createdAt: Date;
|
|
777
|
+
updatedAt: Date;
|
|
778
|
+
email: string;
|
|
779
|
+
emailVerified: boolean;
|
|
780
|
+
name: string;
|
|
781
|
+
image?: string | null | undefined;
|
|
782
|
+
};
|
|
783
|
+
};
|
|
784
|
+
}>>[];
|
|
785
|
+
}, {
|
|
786
|
+
twoFactor: "optional" | "required";
|
|
787
|
+
signInMethods?: string[];
|
|
788
|
+
organizationId: string;
|
|
789
|
+
}>;
|
|
696
790
|
};
|
|
697
791
|
};
|
package/dist/server.js
CHANGED
|
@@ -1,14 +1,16 @@
|
|
|
1
1
|
import { organization } from 'better-auth/plugins/organization';
|
|
2
2
|
import { betterAuthAccess } from './access.js';
|
|
3
3
|
import { membershipGuard } from './guard.js';
|
|
4
|
-
export { membershipGuard, membershipGuardErrors } from './guard.js';
|
|
4
|
+
export { membershipGuard, membershipGuardErrors, } from './guard.js';
|
|
5
|
+
export { signInMethodOf } from './sign-in-method.js';
|
|
5
6
|
export { anyDomain, invitationPolicyAllows, invitationPolicyView, normalizeDomain, parseInvitationPolicy, storedInvitationPolicy, InvitationPolicyError, } from './domain-policy.js';
|
|
7
|
+
export { defaultSecurityPolicy, parseSecurityPolicy, securityPolicyMet, signInMethodAllowed, storedSecurityPolicy, SecurityPolicyError, } from './security-policy.js';
|
|
6
8
|
/** Organization options BitaKit derives from `accessConfiguration`; the app must not set them. */
|
|
7
9
|
const derived = ['ac', 'roles', 'creatorRole', 'dynamicAccessControl'];
|
|
8
10
|
/**
|
|
9
11
|
* Better Auth's server `organization` plugin for a BitaKit app: the roles and permissions from the
|
|
10
12
|
* 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
|
|
13
|
+
* invitation domain policy, the stored security policy) installed in the same plugin, so it cannot be left out. Every other
|
|
12
14
|
* organization option (invitation e-mail, hooks, teams, limits) is the app's, unchanged.
|
|
13
15
|
*
|
|
14
16
|
* ```ts
|
|
@@ -20,17 +22,27 @@ export function createOrganizationPlugin(configuration, options = {}) {
|
|
|
20
22
|
if (conflicting.length)
|
|
21
23
|
throw new Error(`createOrganizationPlugin: ${conflicting.join(', ')} come from the app's roles and permissions (src/roles.ts, permissions.ts); remove them from the organization options.`);
|
|
22
24
|
const access = betterAuthAccess(configuration);
|
|
23
|
-
const
|
|
25
|
+
const { afterResetTwoFactor, ...organizationOptions } = options;
|
|
26
|
+
const base = organization({ ...organizationOptions, ...access.organization });
|
|
24
27
|
const guard = membershipGuard(access, {
|
|
25
28
|
requireEmailVerificationOnInvitation: options.requireEmailVerificationOnInvitation,
|
|
29
|
+
afterResetTwoFactor,
|
|
26
30
|
});
|
|
27
31
|
// One plugin: Better Auth's organization plugin with the guard's field, hooks and endpoints.
|
|
28
32
|
const plugin = base;
|
|
29
33
|
const schema = (plugin.schema ?? {});
|
|
34
|
+
if (plugin.init)
|
|
35
|
+
throw new Error('Better Auth’s organization plugin now has an init step: merge it with the guard’s.');
|
|
30
36
|
return {
|
|
31
37
|
...plugin,
|
|
38
|
+
// The guard's init records each session's sign-in method (sign-in-method.ts).
|
|
39
|
+
init: guard.init,
|
|
32
40
|
schema: {
|
|
33
41
|
...schema,
|
|
42
|
+
session: {
|
|
43
|
+
...schema.session,
|
|
44
|
+
fields: { ...schema.session?.fields, ...guard.schema.session.fields },
|
|
45
|
+
},
|
|
34
46
|
organization: {
|
|
35
47
|
...schema.organization,
|
|
36
48
|
fields: { ...schema.organization?.fields, ...guard.schema.organization.fields },
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { BetterAuthPlugin } from 'better-auth';
|
|
2
|
+
type EndpointContext = {
|
|
3
|
+
path?: string;
|
|
4
|
+
params?: Record<string, string | undefined>;
|
|
5
|
+
body?: unknown;
|
|
6
|
+
getSignedCookie?: (name: string, secret: string) => Promise<string | null | false>;
|
|
7
|
+
context?: {
|
|
8
|
+
secret: string;
|
|
9
|
+
session?: {
|
|
10
|
+
session?: {
|
|
11
|
+
signInMethod?: string | null;
|
|
12
|
+
};
|
|
13
|
+
} | null;
|
|
14
|
+
createAuthCookie: (name: string) => {
|
|
15
|
+
name: string;
|
|
16
|
+
};
|
|
17
|
+
internalAdapter: {
|
|
18
|
+
findVerificationValue(identifier: string): Promise<{
|
|
19
|
+
value: string;
|
|
20
|
+
} | null>;
|
|
21
|
+
createVerificationValue(data: {
|
|
22
|
+
identifier: string;
|
|
23
|
+
value: string;
|
|
24
|
+
expiresAt: Date;
|
|
25
|
+
}): Promise<unknown>;
|
|
26
|
+
};
|
|
27
|
+
};
|
|
28
|
+
};
|
|
29
|
+
/** The sign-in method a request signs in with, from its path; null for a request that is no sign-in. */
|
|
30
|
+
export declare function signInMethodOf(ctx: EndpointContext | null | undefined): string | null;
|
|
31
|
+
/** Better Auth plugin options that record `session.signInMethod` (part of the membership guard). */
|
|
32
|
+
export declare function signInMethodRecording(): {
|
|
33
|
+
schema: {
|
|
34
|
+
readonly session: {
|
|
35
|
+
readonly fields: {
|
|
36
|
+
readonly signInMethod: {
|
|
37
|
+
readonly type: "string";
|
|
38
|
+
readonly required: false;
|
|
39
|
+
readonly input: false;
|
|
40
|
+
};
|
|
41
|
+
};
|
|
42
|
+
};
|
|
43
|
+
};
|
|
44
|
+
init: () => ReturnType<NonNullable<BetterAuthPlugin["init"]>>;
|
|
45
|
+
};
|
|
46
|
+
export {};
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
const pendingPrefix = 'sign-in-method-';
|
|
2
|
+
/** The sign-in method a request signs in with, from its path; null for a request that is no sign-in. */
|
|
3
|
+
export function signInMethodOf(ctx) {
|
|
4
|
+
const path = ctx?.path ?? '';
|
|
5
|
+
if (path.startsWith('/callback/'))
|
|
6
|
+
return ctx?.params?.id ?? path.split('/').pop() ?? null;
|
|
7
|
+
if (path.startsWith('/oauth2/callback/'))
|
|
8
|
+
return ctx?.params?.providerId ?? path.split('/').pop() ?? null;
|
|
9
|
+
if (path === '/sign-in/social')
|
|
10
|
+
return ctx?.body?.provider ?? null;
|
|
11
|
+
if (path === '/one-tap/callback')
|
|
12
|
+
return 'google';
|
|
13
|
+
if (path === '/sign-in/email' || path === '/sign-up/email' || path === '/verify-email')
|
|
14
|
+
return 'email';
|
|
15
|
+
if (path === '/sign-in/username')
|
|
16
|
+
return 'username';
|
|
17
|
+
if (path === '/sign-in/phone-number' || path === '/phone-number/verify')
|
|
18
|
+
return 'phone-number';
|
|
19
|
+
if (path.startsWith('/passkey/verify-authentication'))
|
|
20
|
+
return 'passkey';
|
|
21
|
+
if (path.startsWith('/magic-link/verify'))
|
|
22
|
+
return 'magic-link';
|
|
23
|
+
if (path === '/sign-in/email-otp')
|
|
24
|
+
return 'email-otp';
|
|
25
|
+
if (path.includes('siwe'))
|
|
26
|
+
return 'siwe';
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
const codeStep = (path) => !!path?.startsWith('/two-factor/verify-');
|
|
30
|
+
/** Better Auth plugin options that record `session.signInMethod` (part of the membership guard). */
|
|
31
|
+
export function signInMethodRecording() {
|
|
32
|
+
return {
|
|
33
|
+
schema: {
|
|
34
|
+
session: { fields: { signInMethod: { type: 'string', required: false, input: false } } },
|
|
35
|
+
},
|
|
36
|
+
init: () => ({
|
|
37
|
+
options: {
|
|
38
|
+
databaseHooks: {
|
|
39
|
+
session: {
|
|
40
|
+
create: {
|
|
41
|
+
before: async (session, raw) => {
|
|
42
|
+
const ctx = raw;
|
|
43
|
+
let method = signInMethodOf(ctx);
|
|
44
|
+
if (!method && ctx?.context && codeStep(ctx.path) && ctx.getSignedCookie) {
|
|
45
|
+
const challenge = await ctx.getSignedCookie(ctx.context.createAuthCookie('two_factor').name, ctx.context.secret);
|
|
46
|
+
if (challenge)
|
|
47
|
+
method =
|
|
48
|
+
(await ctx.context.internalAdapter.findVerificationValue(`${pendingPrefix}${challenge}`))?.value ?? null;
|
|
49
|
+
}
|
|
50
|
+
method ??= ctx?.context?.session?.session?.signInMethod ?? null;
|
|
51
|
+
return method ? { data: { ...session, signInMethod: method } } : undefined;
|
|
52
|
+
},
|
|
53
|
+
},
|
|
54
|
+
},
|
|
55
|
+
verification: {
|
|
56
|
+
create: {
|
|
57
|
+
// The two-factor challenge of a sign-in (`2fa-<random>`, not its attempt counter): keep the method beside it.
|
|
58
|
+
after: async (verification, raw) => {
|
|
59
|
+
const ctx = raw;
|
|
60
|
+
const { identifier, expiresAt } = verification;
|
|
61
|
+
if (!/^2fa-(?!attempts-)/.test(identifier) || !ctx?.context)
|
|
62
|
+
return;
|
|
63
|
+
const method = signInMethodOf(ctx);
|
|
64
|
+
if (method)
|
|
65
|
+
await ctx.context.internalAdapter.createVerificationValue({
|
|
66
|
+
identifier: `${pendingPrefix}${identifier}`,
|
|
67
|
+
value: method,
|
|
68
|
+
expiresAt,
|
|
69
|
+
});
|
|
70
|
+
},
|
|
71
|
+
},
|
|
72
|
+
},
|
|
73
|
+
},
|
|
74
|
+
},
|
|
75
|
+
}),
|
|
76
|
+
};
|
|
77
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bitakit/better-auth",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.2",
|
|
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.
|
|
57
|
+
"@bitakit/organizations": "^0.3.2",
|
|
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.
|
|
63
|
+
"@bitakit/organizations": "^0.3.2",
|
|
64
64
|
"@types/node": "^24.19.2",
|
|
65
65
|
"@types/react": "^19",
|
|
66
66
|
"typescript": "^5"
|