@bitakit/better-auth 0.3.1 → 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 +12 -0
- package/dist/guard.d.ts +57 -0
- package/dist/guard.js +77 -2
- package/dist/organizations.js +15 -4
- package/dist/security-policy.d.ts +7 -0
- package/dist/security-policy.js +19 -3
- package/dist/server.d.ts +38 -3
- package/dist/server.js +14 -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
|
@@ -88,6 +88,18 @@ For HTTP requests and server `auth.api.*` calls alike, on top of Better Auth's o
|
|
|
88
88
|
enforces it on its server – read the organization's value with `storedSecurityPolicy` and check
|
|
89
89
|
the person with `securityPolicyMet(policy, user)` (`./server`; `user.twoFactorEnabled` comes from
|
|
90
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`.
|
|
91
103
|
In the browser it is the `securityPolicy` capability of `@bitakit/organizations`.
|
|
92
104
|
- Better Auth's errors stay for missing management permission, expired invitations and
|
|
93
105
|
unverified addresses. Stable codes and messages: `membershipGuardErrors` (`./server`).
|
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<{
|
|
@@ -6,12 +7,25 @@ export declare const membershipGuardErrors: Readonly<{
|
|
|
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.";
|
|
8
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.";
|
|
9
15
|
ENABLE_TWO_FACTOR_FIRST: "Turn on two-factor sign-in for your own account before you require it for the organization.";
|
|
10
16
|
}>;
|
|
11
17
|
type Access = ReturnType<typeof betterAuthAccess>;
|
|
12
18
|
export type MembershipGuardOptions = {
|
|
13
19
|
/** Mirrors the organization option, so an unverified address keeps Better Auth's own error. */
|
|
14
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;
|
|
15
29
|
};
|
|
16
30
|
/**
|
|
17
31
|
* The guard as a Better Auth plugin. Normally installed by `createOrganizationPlugin`; exported
|
|
@@ -19,6 +33,7 @@ export type MembershipGuardOptions = {
|
|
|
19
33
|
*/
|
|
20
34
|
export declare function membershipGuard(access: Access, guardOptions?: MembershipGuardOptions): {
|
|
21
35
|
id: "bitakit-membership-guard";
|
|
36
|
+
init: () => ReturnType<NonNullable<BetterAuthPlugin["init"]>>;
|
|
22
37
|
schema: {
|
|
23
38
|
organization: {
|
|
24
39
|
fields: {
|
|
@@ -36,6 +51,15 @@ export declare function membershipGuard(access: Access, guardOptions?: Membershi
|
|
|
36
51
|
};
|
|
37
52
|
};
|
|
38
53
|
};
|
|
54
|
+
session: {
|
|
55
|
+
readonly fields: {
|
|
56
|
+
readonly signInMethod: {
|
|
57
|
+
readonly type: "string";
|
|
58
|
+
readonly required: false;
|
|
59
|
+
readonly input: false;
|
|
60
|
+
};
|
|
61
|
+
};
|
|
62
|
+
};
|
|
39
63
|
};
|
|
40
64
|
hooks: {
|
|
41
65
|
before: {
|
|
@@ -135,7 +159,39 @@ export declare function membershipGuard(access: Access, guardOptions?: Membershi
|
|
|
135
159
|
}>>[];
|
|
136
160
|
}, {
|
|
137
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
|
+
}, {
|
|
138
191
|
organizationId: string;
|
|
192
|
+
memberId: string;
|
|
193
|
+
userId: string;
|
|
194
|
+
actorUserId: string;
|
|
139
195
|
}>;
|
|
140
196
|
setSecurityPolicy: import("better-call").StrictEndpoint<"/organization/set-security-policy", {
|
|
141
197
|
method: "POST";
|
|
@@ -164,6 +220,7 @@ export declare function membershipGuard(access: Access, guardOptions?: Membershi
|
|
|
164
220
|
}>>[];
|
|
165
221
|
}, {
|
|
166
222
|
twoFactor: "optional" | "required";
|
|
223
|
+
signInMethods?: string[];
|
|
167
224
|
organizationId: string;
|
|
168
225
|
}>;
|
|
169
226
|
};
|
package/dist/guard.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
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
|
+
import { parseSecurityPolicy, SecurityPolicyError, signInMethodAllowed, storedSecurityPolicy, } from './security-policy.js';
|
|
5
|
+
import { signInMethodRecording } from './sign-in-method.js';
|
|
5
6
|
// The membership guard: BitaKit's server-side invariants on Better Auth's own organization
|
|
6
7
|
// operations. Better Auth still runs all of its checks (member management permission, creator role,
|
|
7
8
|
// last owner, expiry, verified address); this only adds:
|
|
@@ -9,7 +10,8 @@ import { parseSecurityPolicy, SecurityPolicyError, storedSecurityPolicy, } from
|
|
|
9
10
|
// (all roles of the member combined, static and custom) the actor holds;
|
|
10
11
|
// - re-validation at acceptance: the inviter must still be able to grant the invited role;
|
|
11
12
|
// - the organization's invitation domain policy, at creation and acceptance;
|
|
12
|
-
// - the organization's security policy (two-factor optional or required): stored here, enforced
|
|
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).
|
|
13
15
|
// It runs for HTTP requests and server `auth.api.*` calls alike (Better Auth's hook pipeline).
|
|
14
16
|
/** Stable codes; user-facing messages are separate and may be translated by the app. */
|
|
15
17
|
export const membershipGuardErrors = Object.freeze({
|
|
@@ -18,6 +20,11 @@ export const membershipGuardErrors = Object.freeze({
|
|
|
18
20
|
EMAIL_DOMAIN_NOT_ALLOWED: "The email address's domain is not allowed in this organization.",
|
|
19
21
|
INVALID_INVITATION_POLICY: 'The invitation policy is invalid.',
|
|
20
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.',
|
|
21
28
|
ENABLE_TWO_FACTOR_FIRST: 'Turn on two-factor sign-in for your own account before you require it for the organization.',
|
|
22
29
|
});
|
|
23
30
|
const refuse = (code, status = 'FORBIDDEN', message) => APIError.fromStatus(status, { code, message: message ?? membershipGuardErrors[code] });
|
|
@@ -183,9 +190,12 @@ export function membershipGuard(access, guardOptions = {}) {
|
|
|
183
190
|
if (!(await covers(ctx, organizationId, inviter.role, invited.statements)))
|
|
184
191
|
throw refuse('INVITATION_NO_LONGER_AUTHORIZED');
|
|
185
192
|
});
|
|
193
|
+
const recording = signInMethodRecording();
|
|
186
194
|
return {
|
|
187
195
|
id: 'bitakit-membership-guard',
|
|
196
|
+
init: recording.init,
|
|
188
197
|
schema: {
|
|
198
|
+
...recording.schema,
|
|
189
199
|
organization: {
|
|
190
200
|
fields: {
|
|
191
201
|
/** The invitation domain policy; written only through set-invitation-policy. */
|
|
@@ -250,6 +260,68 @@ export function membershipGuard(access, guardOptions = {}) {
|
|
|
250
260
|
throw notMember();
|
|
251
261
|
return ctx.json({ organizationId, ...(await securityOf(ctx, organizationId)) });
|
|
252
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
|
+
}),
|
|
253
325
|
setSecurityPolicy: createAuthEndpoint('/organization/set-security-policy', { method: 'POST', use: [sessionMiddleware] }, async (ctx) => {
|
|
254
326
|
const body = (ctx.body ?? {});
|
|
255
327
|
const organizationId = await organizationIdOf(ctx, body.organizationId);
|
|
@@ -274,6 +346,9 @@ export function membershipGuard(access, guardOptions = {}) {
|
|
|
274
346
|
const user = actor.session.user;
|
|
275
347
|
if (policy.twoFactor === 'required' && user.twoFactorEnabled !== true)
|
|
276
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');
|
|
277
352
|
await adapter(ctx).update({
|
|
278
353
|
model: 'organization',
|
|
279
354
|
where: [{ field: 'id', value: organizationId }],
|
package/dist/organizations.js
CHANGED
|
@@ -256,15 +256,26 @@ export function betterAuthOrganizations(client, extensions = {}) {
|
|
|
256
256
|
securityPolicy: declared && client.$fetch
|
|
257
257
|
? {
|
|
258
258
|
load: async (organizationId) => {
|
|
259
|
-
const {
|
|
260
|
-
return
|
|
259
|
+
const { organizationId: _, ...policy } = await guardRequest('/organization/get-security-policy', { method: 'GET', query: { organizationId } });
|
|
260
|
+
return policy;
|
|
261
261
|
},
|
|
262
262
|
save: async ({ organizationId, policy }) => {
|
|
263
|
-
const {
|
|
264
|
-
|
|
263
|
+
const { organizationId: _, ...saved } = await guardRequest('/organization/set-security-policy', {
|
|
264
|
+
method: 'POST',
|
|
265
|
+
body: { organizationId, policy },
|
|
266
|
+
});
|
|
267
|
+
return saved;
|
|
265
268
|
},
|
|
266
269
|
}
|
|
267
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,
|
|
268
279
|
updateRole: (input) => completed(api.updateMemberRole({ ...input, role: input.role })),
|
|
269
280
|
removeMember: ({ organizationId, memberId }) => completed(api.removeMember({ organizationId, memberIdOrEmail: memberId })),
|
|
270
281
|
};
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
/** Same shape as `SecurityPolicy` of `@bitakit/organizations`. */
|
|
2
2
|
export type SecurityPolicy = {
|
|
3
3
|
twoFactor: 'optional' | 'required';
|
|
4
|
+
/** Sign-in methods the organization accepts (`signInMethodOf` names: `email`, `passkey`, `google`, …); absent = all. */
|
|
5
|
+
signInMethods?: string[];
|
|
4
6
|
};
|
|
5
7
|
export declare const defaultSecurityPolicy: SecurityPolicy;
|
|
6
8
|
export declare class SecurityPolicyError extends Error {
|
|
@@ -13,3 +15,8 @@ export declare function storedSecurityPolicy(value: unknown): SecurityPolicy;
|
|
|
13
15
|
export declare function securityPolicyMet(policy: SecurityPolicy, user: {
|
|
14
16
|
twoFactorEnabled?: boolean | null;
|
|
15
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;
|
package/dist/security-policy.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
// The organization's sign-in rule (security policy): whether its members must use two-factor sign-in
|
|
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
|
|
2
3
|
// organization by the membership guard (`securityPolicy`, written only through set-security-policy); enforced by the app on
|
|
3
4
|
// its server with `securityPolicyMet`, because only the app knows which of its requests belong to an organization.
|
|
4
5
|
// Browser- and server-safe.
|
|
@@ -7,10 +8,18 @@ export class SecurityPolicyError extends Error {
|
|
|
7
8
|
}
|
|
8
9
|
/** A policy sent by a client: refused unless it is exactly a known rule. */
|
|
9
10
|
export function parseSecurityPolicy(value) {
|
|
10
|
-
const twoFactor = value
|
|
11
|
+
const { twoFactor, signInMethods } = (value ?? {});
|
|
11
12
|
if (twoFactor !== 'optional' && twoFactor !== 'required')
|
|
12
13
|
throw new SecurityPolicyError('twoFactor must be "optional" or "required".');
|
|
13
|
-
|
|
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)] };
|
|
14
23
|
}
|
|
15
24
|
/** The stored value (JSON text or object, possibly absent or from an older version): never throws, defaults to optional. */
|
|
16
25
|
export function storedSecurityPolicy(value) {
|
|
@@ -34,3 +43,10 @@ export function storedSecurityPolicy(value) {
|
|
|
34
43
|
export function securityPolicyMet(policy, user) {
|
|
35
44
|
return policy.twoFactor !== 'required' || user.twoFactorEnabled === true;
|
|
36
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,11 +1,13 @@
|
|
|
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';
|
|
5
|
-
export { defaultSecurityPolicy, parseSecurityPolicy, securityPolicyMet, storedSecurityPolicy, SecurityPolicyError, type SecurityPolicy, } from './security-policy.js';
|
|
7
|
+
export { defaultSecurityPolicy, parseSecurityPolicy, securityPolicyMet, signInMethodAllowed, storedSecurityPolicy, SecurityPolicyError, type SecurityPolicy, } from './security-policy.js';
|
|
6
8
|
/** Organization options BitaKit derives from `accessConfiguration`; the app must not set them. */
|
|
7
9
|
declare const derived: readonly ["ac", "roles", "creatorRole", "dynamicAccessControl"];
|
|
8
|
-
type AppOrganizationOptions = Omit<OrganizationOptions, (typeof derived)[number]>;
|
|
10
|
+
type AppOrganizationOptions = Omit<OrganizationOptions, (typeof derived)[number]> & Pick<MembershipGuardOptions, 'afterResetTwoFactor'>;
|
|
9
11
|
/**
|
|
10
12
|
* Better Auth's server `organization` plugin for a BitaKit app: the roles and permissions from the
|
|
11
13
|
* generated `accessConfiguration`, and the membership guard (role ceiling, invitation re-validation,
|
|
@@ -721,8 +723,40 @@ export declare function createOrganizationPlugin(configuration: AccessConfigurat
|
|
|
721
723
|
}>>[];
|
|
722
724
|
}, {
|
|
723
725
|
twoFactor: "optional" | "required";
|
|
726
|
+
signInMethods?: string[];
|
|
724
727
|
organizationId: string;
|
|
725
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
|
+
}>;
|
|
726
760
|
setSecurityPolicy: import("better-call").StrictEndpoint<"/organization/set-security-policy", {
|
|
727
761
|
method: "POST";
|
|
728
762
|
use: import("better-call").Middleware<import("better-call").MiddlewareOptions, (inputContext: import("better-call").MiddlewareInputContext<import("better-call").MiddlewareOptions>) => Promise<{
|
|
@@ -750,6 +784,7 @@ export declare function createOrganizationPlugin(configuration: AccessConfigurat
|
|
|
750
784
|
}>>[];
|
|
751
785
|
}, {
|
|
752
786
|
twoFactor: "optional" | "required";
|
|
787
|
+
signInMethods?: string[];
|
|
753
788
|
organizationId: string;
|
|
754
789
|
}>;
|
|
755
790
|
};
|
package/dist/server.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
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';
|
|
6
|
-
export { defaultSecurityPolicy, parseSecurityPolicy, securityPolicyMet, storedSecurityPolicy, SecurityPolicyError, } from './security-policy.js';
|
|
7
|
+
export { defaultSecurityPolicy, parseSecurityPolicy, securityPolicyMet, signInMethodAllowed, storedSecurityPolicy, SecurityPolicyError, } from './security-policy.js';
|
|
7
8
|
/** Organization options BitaKit derives from `accessConfiguration`; the app must not set them. */
|
|
8
9
|
const derived = ['ac', 'roles', 'creatorRole', 'dynamicAccessControl'];
|
|
9
10
|
/**
|
|
@@ -21,17 +22,27 @@ export function createOrganizationPlugin(configuration, options = {}) {
|
|
|
21
22
|
if (conflicting.length)
|
|
22
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.`);
|
|
23
24
|
const access = betterAuthAccess(configuration);
|
|
24
|
-
const
|
|
25
|
+
const { afterResetTwoFactor, ...organizationOptions } = options;
|
|
26
|
+
const base = organization({ ...organizationOptions, ...access.organization });
|
|
25
27
|
const guard = membershipGuard(access, {
|
|
26
28
|
requireEmailVerificationOnInvitation: options.requireEmailVerificationOnInvitation,
|
|
29
|
+
afterResetTwoFactor,
|
|
27
30
|
});
|
|
28
31
|
// One plugin: Better Auth's organization plugin with the guard's field, hooks and endpoints.
|
|
29
32
|
const plugin = base;
|
|
30
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.');
|
|
31
36
|
return {
|
|
32
37
|
...plugin,
|
|
38
|
+
// The guard's init records each session's sign-in method (sign-in-method.ts).
|
|
39
|
+
init: guard.init,
|
|
33
40
|
schema: {
|
|
34
41
|
...schema,
|
|
42
|
+
session: {
|
|
43
|
+
...schema.session,
|
|
44
|
+
fields: { ...schema.session?.fields, ...guard.schema.session.fields },
|
|
45
|
+
},
|
|
35
46
|
organization: {
|
|
36
47
|
...schema.organization,
|
|
37
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"
|