@bitakit/better-auth 0.2.5 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +66 -2
- package/README.md +2 -0
- package/dist/access.d.ts +70 -0
- package/dist/access.js +97 -0
- package/dist/client.d.ts +15 -12
- package/dist/client.js +9 -4
- package/dist/domain-policy.d.ts +34 -0
- package/dist/domain-policy.js +76 -0
- package/dist/guard.d.ts +171 -0
- package/dist/guard.js +286 -0
- package/dist/organization-session.js +19 -0
- package/dist/organizations.d.ts +45 -2
- package/dist/organizations.js +99 -6
- package/dist/security-policy.d.ts +15 -0
- package/dist/security-policy.js +36 -0
- package/dist/server.d.ts +756 -0
- package/dist/server.js +46 -0
- package/package.json +18 -9
package/AGENTS.md
CHANGED
|
@@ -31,11 +31,75 @@ Connects an existing Better Auth client to BitaKit: it provides the shared `auth
|
|
|
31
31
|
|
|
32
32
|
- Read the session with `useAuth()` from `@bitakit/ui` or `getService(services, authService)`;
|
|
33
33
|
check `app.has('auth')` when it is optional.
|
|
34
|
-
- Organizations: `betterAuthOrganizations(client
|
|
35
|
-
`@bitakit/organizations`, provided as
|
|
34
|
+
- Organizations: `betterAuthOrganizations(client, { access: accessConfiguration })`
|
|
35
|
+
(`./organizations`) is the backend for `@bitakit/organizations`, provided as
|
|
36
|
+
`organizationBackend`. With `access` it reports the declared roles (labels, permissions), the
|
|
37
|
+
organization's custom roles and the viewer's permissions, and offers custom roles and the
|
|
38
|
+
invitation policy of `createOrganizationPlugin`'s guard.
|
|
36
39
|
- E-mail: `betterAuthEmail(emailService, { invitationURL })` (`./email`) gives the server
|
|
37
40
|
callbacks for verification, reset and invitation mail on the `@bitakit/email` contract.
|
|
38
41
|
|
|
42
|
+
## Roles and permissions
|
|
43
|
+
|
|
44
|
+
Plugins declare permissions (`permissions.ts`) and the app its base roles (`src/roles.ts`) with
|
|
45
|
+
`@bitakit/core`; `bitakit generate` writes the checked `accessConfiguration` to
|
|
46
|
+
`src/bitakit.gen.access.ts`. This package translates it; Better Auth decides.
|
|
47
|
+
|
|
48
|
+
```ts
|
|
49
|
+
// server: Better Auth's organization plugin with roles and the membership guard
|
|
50
|
+
import { createOrganizationPlugin } from '@bitakit/better-auth/server';
|
|
51
|
+
import { accessConfiguration } from '@/bitakit.gen.access';
|
|
52
|
+
betterAuth({ plugins: [createOrganizationPlugin(accessConfiguration, { sendInvitationEmail })] });
|
|
53
|
+
|
|
54
|
+
// browser
|
|
55
|
+
createBetterAuthClient({ access: accessConfiguration });
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
- Use `createOrganizationPlugin` instead of Better Auth's `organization()`; all other
|
|
59
|
+
organization options pass through. `ac`, `roles`, `creatorRole` and `dynamicAccessControl` come
|
|
60
|
+
from the declarations and are refused as options.
|
|
61
|
+
- `standard` roles extend Better Auth's `owner`/`admin`/`member` with their grants; other roles get
|
|
62
|
+
exactly their grants; the `standard: 'owner'` role is the creator role (required when roles are
|
|
63
|
+
declared); `customRoles: true` enables Better Auth's dynamic roles (`organizationRole` table).
|
|
64
|
+
- Better Auth's own resources (`organization`, `member`, `invitation`, `team`, `ac`) cannot be
|
|
65
|
+
declared by plugins. Custom roles cannot reuse a base role's name; base roles cannot be deleted.
|
|
66
|
+
|
|
67
|
+
### Membership guard (installed by `createOrganizationPlugin`)
|
|
68
|
+
|
|
69
|
+
For HTTP requests and server `auth.api.*` calls alike, on top of Better Auth's own checks:
|
|
70
|
+
|
|
71
|
+
- Role ceiling: inviting with a role, or changing a member's role, needs the actor to hold every
|
|
72
|
+
permission of that role (all roles of the value combined, custom roles included); a change also
|
|
73
|
+
needs the member's current role. Error `ROLE_EXCEEDS_YOUR_PERMISSIONS`.
|
|
74
|
+
- Acceptance re-checks current data: the inviter must still be a member (not disabled) able to
|
|
75
|
+
grant the invited role, which must still exist. Error `INVITATION_NO_LONGER_AUTHORIZED`; the
|
|
76
|
+
invitation has to be re-issued.
|
|
77
|
+
- Invitation domain policy on the organization record (`invitationPolicy`, default any domain),
|
|
78
|
+
checked at creation and acceptance. Error `EMAIL_DOMAIN_NOT_ALLOWED`. Read and write it through
|
|
79
|
+
`GET /organization/get-invitation-policy` and `POST /organization/set-invitation-policy` (needs
|
|
80
|
+
`organization:update`); domains are stored as IDNA ASCII and returned with a Unicode `display`.
|
|
81
|
+
Matching is by whole labels; subdomains only with `includeSubdomains`. Each app builds its own
|
|
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`.
|
|
92
|
+
- Better Auth's errors stay for missing management permission, expired invitations and
|
|
93
|
+
unverified addresses. Stable codes and messages: `membershipGuardErrors` (`./server`).
|
|
94
|
+
- Apps that suspend members declare `member.disabled` (boolean) in the organization schema; the
|
|
95
|
+
guard treats a disabled member as having no authority. Add the `organization.invitationPolicy`
|
|
96
|
+
and `organization.securityPolicy` (json) columns with the app's Better Auth migration.
|
|
97
|
+
- Server-only `auth.api.addMember` (no HTTP route) is trusted server code and not actor-checked.
|
|
98
|
+
|
|
99
|
+
Check capabilities on the server with `hasOrganizationPermission(auth, { headers, permissions })`
|
|
100
|
+
(`./access`): it re-reads the active membership (missing or disabled grants nothing) and asks
|
|
101
|
+
Better Auth, including custom roles. Client checks only shape the UI.
|
|
102
|
+
|
|
39
103
|
## Rules
|
|
40
104
|
|
|
41
105
|
- Authorization happens on the server (Better Auth access control and the app's routes); the
|
package/README.md
CHANGED
|
@@ -88,6 +88,8 @@ Native client options such as `baseURL` are supported; `plugins` append further
|
|
|
88
88
|
- `src/index.ts`: the `auth` service on the client session, `betterAuthClient`, `betterAuthPlugin`.
|
|
89
89
|
- `src/plugin.ts` (`./plugin`): the package plugin entry the manifest names.
|
|
90
90
|
- `src/organizations.ts`, `src/organization-session.ts` (`./organizations`): organization backend.
|
|
91
|
+
- `src/access.ts` (`./access`): roles and permissions for Better Auth (`betterAuthAccess`), server capability check (`hasOrganizationPermission`).
|
|
92
|
+
- `src/server.ts`, `src/guard.ts`, `src/domain-policy.ts` (`./server`, server-only): `createOrganizationPlugin` with the membership guard and the invitation domain policy. Needs `@bitakit/organizations` installed (domains are checked with its `normalizeInvitationDomain`, the same check settings screens use).
|
|
91
93
|
- `src/email.ts` (`./email`), `src/client.ts` (`./client`).
|
|
92
94
|
|
|
93
95
|
### Native session display compatibility
|
package/dist/access.d.ts
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import type { AccessConfiguration, PermissionMap } from '@bitakit/core';
|
|
2
|
+
import { type AccessControl, type Role } from 'better-auth/plugins/access';
|
|
3
|
+
import { defaultStatements } from 'better-auth/plugins/organization/access';
|
|
4
|
+
/** Resources Better Auth's organization plugin owns; an app cannot declare them. */
|
|
5
|
+
export declare const betterAuthResources: readonly string[];
|
|
6
|
+
export declare class BetterAuthAccessError extends Error {
|
|
7
|
+
constructor(message: string);
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Better Auth organization options from the app's declarations, for the server
|
|
11
|
+
* (`createOrganizationPlugin` from `./server` installs them with the membership guard) and the
|
|
12
|
+
* browser (`createBetterAuthClient({ access })`). Without declared roles Better Auth's standard
|
|
13
|
+
* `owner`, `admin` and `member` remain.
|
|
14
|
+
*/
|
|
15
|
+
export declare function betterAuthAccess(configuration: AccessConfiguration): {
|
|
16
|
+
/** Options for Better Auth's server `organization(...)`; `createOrganizationPlugin` uses them. */
|
|
17
|
+
organization: {
|
|
18
|
+
dynamicAccessControl?: {
|
|
19
|
+
enabled: boolean;
|
|
20
|
+
} | undefined;
|
|
21
|
+
ac: AccessControl;
|
|
22
|
+
roles: Record<string, Role>;
|
|
23
|
+
creatorRole: string;
|
|
24
|
+
};
|
|
25
|
+
/** The same access control for `organizationClient(...)`; client checks only shape the UI. */
|
|
26
|
+
client: {
|
|
27
|
+
dynamicAccessControl?: {
|
|
28
|
+
enabled: boolean;
|
|
29
|
+
} | undefined;
|
|
30
|
+
ac: AccessControl;
|
|
31
|
+
roles: Record<string, Role>;
|
|
32
|
+
};
|
|
33
|
+
};
|
|
34
|
+
/** Operations per resource: the app's declared permissions plus Better Auth's own. */
|
|
35
|
+
export type PermissionRequest = {
|
|
36
|
+
readonly [Resource in keyof PermissionMap]?: readonly PermissionMap[Resource][];
|
|
37
|
+
} & {
|
|
38
|
+
readonly [Resource in keyof typeof defaultStatements]?: readonly (typeof defaultStatements)[Resource][number][];
|
|
39
|
+
};
|
|
40
|
+
type PermissionApi = {
|
|
41
|
+
api: {
|
|
42
|
+
getActiveMember(input: {
|
|
43
|
+
headers: Headers;
|
|
44
|
+
}): Promise<{
|
|
45
|
+
organizationId: string;
|
|
46
|
+
disabled?: boolean | null;
|
|
47
|
+
} | null>;
|
|
48
|
+
hasPermission(input: {
|
|
49
|
+
headers: Headers;
|
|
50
|
+
body: {
|
|
51
|
+
organizationId?: string;
|
|
52
|
+
permissions: Record<string, string[]>;
|
|
53
|
+
};
|
|
54
|
+
}): Promise<{
|
|
55
|
+
success: boolean;
|
|
56
|
+
}>;
|
|
57
|
+
};
|
|
58
|
+
};
|
|
59
|
+
/**
|
|
60
|
+
* The server-side capability check: may the signed-in member do this in their active
|
|
61
|
+
* organization? The membership is read again (missing or disabled grants nothing; with
|
|
62
|
+
* `organizationId` it must be that organization), then Better Auth's `hasPermission` decides,
|
|
63
|
+
* including the organization's custom roles.
|
|
64
|
+
*/
|
|
65
|
+
export declare function hasOrganizationPermission(auth: PermissionApi, input: {
|
|
66
|
+
headers: Headers;
|
|
67
|
+
organizationId?: string;
|
|
68
|
+
permissions: PermissionRequest;
|
|
69
|
+
}): Promise<boolean>;
|
|
70
|
+
export {};
|
package/dist/access.js
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { createAccessControl, } from 'better-auth/plugins/access';
|
|
2
|
+
import { adminAc, defaultStatements, memberAc, ownerAc, } from 'better-auth/plugins/organization/access';
|
|
3
|
+
// Roles and permissions declared with BitaKit (`permissions.ts`, `src/roles.ts`), translated into
|
|
4
|
+
// Better Auth's access control. Better Auth stays the authority: it stores custom roles, checks
|
|
5
|
+
// every permission on the server and protects the creator role. This module only builds its
|
|
6
|
+
// configuration from the trusted, generated `accessConfiguration` (`bitakit.gen.access.ts`).
|
|
7
|
+
/** Resources Better Auth's organization plugin owns; an app cannot declare them. */
|
|
8
|
+
export const betterAuthResources = Object.freeze(Object.keys(defaultStatements));
|
|
9
|
+
const standard = {
|
|
10
|
+
owner: ownerAc,
|
|
11
|
+
admin: adminAc,
|
|
12
|
+
member: memberAc,
|
|
13
|
+
};
|
|
14
|
+
const union = (...sets) => {
|
|
15
|
+
const merged = {};
|
|
16
|
+
for (const set of sets)
|
|
17
|
+
for (const [resource, actions] of Object.entries(set))
|
|
18
|
+
merged[resource] = [...new Set([...(merged[resource] ?? []), ...actions])];
|
|
19
|
+
return merged;
|
|
20
|
+
};
|
|
21
|
+
export class BetterAuthAccessError extends Error {
|
|
22
|
+
constructor(message) {
|
|
23
|
+
super(message);
|
|
24
|
+
this.name = 'BetterAuthAccessError';
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Better Auth organization options from the app's declarations, for the server
|
|
29
|
+
* (`createOrganizationPlugin` from `./server` installs them with the membership guard) and the
|
|
30
|
+
* browser (`createBetterAuthClient({ access })`). Without declared roles Better Auth's standard
|
|
31
|
+
* `owner`, `admin` and `member` remain.
|
|
32
|
+
*/
|
|
33
|
+
export function betterAuthAccess(configuration) {
|
|
34
|
+
const clashes = Object.entries(configuration.permissions).filter(([resource]) => betterAuthResources.includes(resource));
|
|
35
|
+
if (clashes.length)
|
|
36
|
+
throw new BetterAuthAccessError(`${clashes
|
|
37
|
+
.map(([resource, declared]) => `Permission resource "${resource}" (${declared.source ?? `plugin "${declared.owner}"`})`)
|
|
38
|
+
.join('; ')} reuses a Better Auth resource (${betterAuthResources.join(', ')}). Rename it; Better Auth owns organization, membership and role management.`);
|
|
39
|
+
const statements = union(defaultStatements, Object.fromEntries(Object.entries(configuration.permissions).map(([resource, { actions }]) => [
|
|
40
|
+
resource,
|
|
41
|
+
actions,
|
|
42
|
+
])));
|
|
43
|
+
// Typed as Better Auth's general access control, so server and client options accept it.
|
|
44
|
+
const ac = createAccessControl(statements);
|
|
45
|
+
const declared = configuration.roles;
|
|
46
|
+
const specs = declared
|
|
47
|
+
? Object.entries(declared.roles).map(([id, spec]) => [
|
|
48
|
+
id,
|
|
49
|
+
union(spec.standard ? standard[spec.standard].statements : {}, (spec.grants ?? {})),
|
|
50
|
+
])
|
|
51
|
+
: Object.keys(standard).map((id) => [id, standard[id].statements]);
|
|
52
|
+
const creator = declared
|
|
53
|
+
? Object.entries(declared.roles).find(([, spec]) => spec.standard === 'owner')?.[0]
|
|
54
|
+
: 'owner';
|
|
55
|
+
if (!creator)
|
|
56
|
+
throw new BetterAuthAccessError(`${declared?.source ?? 'src/roles.ts'} declares no organization creator. Add a role with standard: 'owner'; Better Auth gives it to whoever creates an organization and protects it.`);
|
|
57
|
+
const roles = Object.fromEntries(specs.map(([id, granted]) => [id, ac.newRole(granted)]));
|
|
58
|
+
const dynamicAccessControl = declared?.options.customRoles ? { enabled: true } : undefined;
|
|
59
|
+
return {
|
|
60
|
+
/** Options for Better Auth's server `organization(...)`; `createOrganizationPlugin` uses them. */
|
|
61
|
+
organization: {
|
|
62
|
+
ac,
|
|
63
|
+
roles,
|
|
64
|
+
creatorRole: creator,
|
|
65
|
+
...(dynamicAccessControl ? { dynamicAccessControl } : {}),
|
|
66
|
+
},
|
|
67
|
+
/** The same access control for `organizationClient(...)`; client checks only shape the UI. */
|
|
68
|
+
client: { ac, roles, ...(dynamicAccessControl ? { dynamicAccessControl } : {}) },
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* The server-side capability check: may the signed-in member do this in their active
|
|
73
|
+
* organization? The membership is read again (missing or disabled grants nothing; with
|
|
74
|
+
* `organizationId` it must be that organization), then Better Auth's `hasPermission` decides,
|
|
75
|
+
* including the organization's custom roles.
|
|
76
|
+
*/
|
|
77
|
+
export async function hasOrganizationPermission(auth, input) {
|
|
78
|
+
try {
|
|
79
|
+
const member = await auth.api.getActiveMember({ headers: input.headers });
|
|
80
|
+
if (!member || member.disabled)
|
|
81
|
+
return false;
|
|
82
|
+
if (input.organizationId && member.organizationId !== input.organizationId)
|
|
83
|
+
return false;
|
|
84
|
+
const result = await auth.api.hasPermission({
|
|
85
|
+
headers: input.headers,
|
|
86
|
+
body: {
|
|
87
|
+
organizationId: member.organizationId,
|
|
88
|
+
permissions: Object.fromEntries(Object.entries(input.permissions).map(([resource, actions]) => [resource, [...actions]])),
|
|
89
|
+
},
|
|
90
|
+
});
|
|
91
|
+
return result.success === true;
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
// No session or no active organization: no permission.
|
|
95
|
+
return false;
|
|
96
|
+
}
|
|
97
|
+
}
|
package/dist/client.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { type ReactAuthClient } from 'better-auth/react';
|
|
2
2
|
import type { BetterAuthClientOptions, BetterAuthClientPlugin } from 'better-auth/client';
|
|
3
|
-
|
|
3
|
+
import type { AccessConfiguration } from '@bitakit/core';
|
|
4
|
+
declare const standardPlugins: (access?: AccessConfiguration) => readonly [{
|
|
4
5
|
id: "organization";
|
|
5
6
|
version: string;
|
|
6
7
|
$InferServerPlugin: import("better-auth/client").OrganizationPlugin<{
|
|
@@ -30,7 +31,7 @@ declare const standardPlugins: () => readonly [{
|
|
|
30
31
|
members: {
|
|
31
32
|
id: string;
|
|
32
33
|
organizationId: string;
|
|
33
|
-
role: "
|
|
34
|
+
role: "owner" | "admin" | "member";
|
|
34
35
|
createdAt: Date;
|
|
35
36
|
userId: string;
|
|
36
37
|
teamId?: string | undefined | undefined;
|
|
@@ -45,7 +46,7 @@ declare const standardPlugins: () => readonly [{
|
|
|
45
46
|
id: string;
|
|
46
47
|
organizationId: string;
|
|
47
48
|
email: string;
|
|
48
|
-
role: "
|
|
49
|
+
role: "owner" | "admin" | "member";
|
|
49
50
|
status: import("better-auth/client").InvitationStatus;
|
|
50
51
|
inviterId: string;
|
|
51
52
|
expiresAt: Date;
|
|
@@ -79,7 +80,7 @@ declare const standardPlugins: () => readonly [{
|
|
|
79
80
|
id: string;
|
|
80
81
|
organizationId: string;
|
|
81
82
|
email: string;
|
|
82
|
-
role: "
|
|
83
|
+
role: "owner" | "admin" | "member";
|
|
83
84
|
status: import("better-auth/client").InvitationStatus;
|
|
84
85
|
inviterId: string;
|
|
85
86
|
expiresAt: Date;
|
|
@@ -89,7 +90,7 @@ declare const standardPlugins: () => readonly [{
|
|
|
89
90
|
Member: {
|
|
90
91
|
id: string;
|
|
91
92
|
organizationId: string;
|
|
92
|
-
role: "
|
|
93
|
+
role: "owner" | "admin" | "member";
|
|
93
94
|
createdAt: Date;
|
|
94
95
|
userId: string;
|
|
95
96
|
teamId?: string | undefined | undefined;
|
|
@@ -109,13 +110,13 @@ declare const standardPlugins: () => readonly [{
|
|
|
109
110
|
};
|
|
110
111
|
};
|
|
111
112
|
organization: {
|
|
112
|
-
checkRolePermission: <R extends "
|
|
113
|
+
checkRolePermission: <R extends "owner" | "admin" | "member">(data: {
|
|
113
114
|
permissions: {
|
|
114
115
|
readonly organization?: ("update" | "delete")[] | undefined;
|
|
115
|
-
readonly member?: ("
|
|
116
|
+
readonly member?: ("update" | "delete" | "create")[] | undefined;
|
|
116
117
|
readonly invitation?: ("create" | "cancel")[] | undefined;
|
|
117
|
-
readonly team?: ("
|
|
118
|
-
readonly ac?: ("
|
|
118
|
+
readonly team?: ("update" | "delete" | "create")[] | undefined;
|
|
119
|
+
readonly ac?: ("update" | "delete" | "create" | "read")[] | undefined;
|
|
119
120
|
};
|
|
120
121
|
} & {
|
|
121
122
|
role: R;
|
|
@@ -138,7 +139,7 @@ declare const standardPlugins: () => readonly [{
|
|
|
138
139
|
members: {
|
|
139
140
|
id: string;
|
|
140
141
|
organizationId: string;
|
|
141
|
-
role: "
|
|
142
|
+
role: "owner" | "admin" | "member";
|
|
142
143
|
createdAt: Date;
|
|
143
144
|
userId: string;
|
|
144
145
|
teamId?: string | undefined | undefined;
|
|
@@ -153,7 +154,7 @@ declare const standardPlugins: () => readonly [{
|
|
|
153
154
|
id: string;
|
|
154
155
|
organizationId: string;
|
|
155
156
|
email: string;
|
|
156
|
-
role: "
|
|
157
|
+
role: "owner" | "admin" | "member";
|
|
157
158
|
status: import("better-auth/client").InvitationStatus;
|
|
158
159
|
inviterId: string;
|
|
159
160
|
expiresAt: Date;
|
|
@@ -2319,7 +2320,9 @@ type ClientOptions<Extensions extends BetterAuthClientPlugin[]> = Omit<BetterAut
|
|
|
2319
2320
|
plugins: [...ReturnType<typeof standardPlugins>, ...Extensions];
|
|
2320
2321
|
};
|
|
2321
2322
|
/** Standard client preset. The server must enable the corresponding native extensions. */
|
|
2322
|
-
export declare function createBetterAuthClient<const Extensions extends BetterAuthClientPlugin[] = []>(options?: Omit<BetterAuthClientOptions, 'plugins'> & {
|
|
2323
|
+
export declare function createBetterAuthClient<const Extensions extends BetterAuthClientPlugin[] = []>({ access, ...options }?: Omit<BetterAuthClientOptions, 'plugins'> & {
|
|
2323
2324
|
plugins?: Extensions;
|
|
2325
|
+
/** The generated `accessConfiguration`; the server's `organization()` uses the same. */
|
|
2326
|
+
access?: AccessConfiguration;
|
|
2324
2327
|
}): ReactAuthClient<ClientOptions<Extensions>>;
|
|
2325
2328
|
export {};
|
package/dist/client.js
CHANGED
|
@@ -2,14 +2,19 @@
|
|
|
2
2
|
import { createAuthClient } from 'better-auth/react';
|
|
3
3
|
import { organizationClient, multiSessionClient, twoFactorClient, } from 'better-auth/client/plugins';
|
|
4
4
|
import { apiKeyClient } from '@better-auth/api-key/client';
|
|
5
|
-
|
|
6
|
-
|
|
5
|
+
import { betterAuthAccess } from './access.js';
|
|
6
|
+
const standardPlugins = (access) => [
|
|
7
|
+
organizationClient({
|
|
8
|
+
teams: { enabled: true },
|
|
9
|
+
// The app's declared roles (bitakit.gen.access.ts); without them Better Auth's standard roles.
|
|
10
|
+
...(access ? betterAuthAccess(access).client : {}),
|
|
11
|
+
}),
|
|
7
12
|
multiSessionClient(),
|
|
8
13
|
apiKeyClient(),
|
|
9
14
|
twoFactorClient(),
|
|
10
15
|
];
|
|
11
16
|
/** Standard client preset. The server must enable the corresponding native extensions. */
|
|
12
|
-
export function createBetterAuthClient(options = {}) {
|
|
17
|
+
export function createBetterAuthClient({ access, ...options } = {}) {
|
|
13
18
|
return createAuthClient({
|
|
14
19
|
...options,
|
|
15
20
|
fetchOptions: {
|
|
@@ -30,7 +35,7 @@ export function createBetterAuthClient(options = {}) {
|
|
|
30
35
|
},
|
|
31
36
|
},
|
|
32
37
|
plugins: [
|
|
33
|
-
...standardPlugins(),
|
|
38
|
+
...standardPlugins(access),
|
|
34
39
|
...(options.plugins ?? []),
|
|
35
40
|
],
|
|
36
41
|
});
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
export type InvitationPolicyMode = 'any' | 'allowlist' | 'blocklist';
|
|
2
|
+
export type InvitationDomain = {
|
|
3
|
+
readonly domain: string;
|
|
4
|
+
readonly includeSubdomains: boolean;
|
|
5
|
+
};
|
|
6
|
+
/** As stored: ASCII domains, lowercase, without a trailing dot. */
|
|
7
|
+
export type InvitationPolicy = {
|
|
8
|
+
readonly mode: InvitationPolicyMode;
|
|
9
|
+
readonly domains: readonly InvitationDomain[];
|
|
10
|
+
};
|
|
11
|
+
/** As shown: each domain also in Unicode, with the stored ASCII form for review. */
|
|
12
|
+
export type InvitationPolicyView = {
|
|
13
|
+
readonly mode: InvitationPolicyMode;
|
|
14
|
+
readonly domains: readonly (InvitationDomain & {
|
|
15
|
+
readonly display: string;
|
|
16
|
+
})[];
|
|
17
|
+
};
|
|
18
|
+
export declare const anyDomain: InvitationPolicy;
|
|
19
|
+
export declare const invitationPolicyLimits: Readonly<{
|
|
20
|
+
domains: 200;
|
|
21
|
+
}>;
|
|
22
|
+
export declare class InvitationPolicyError extends Error {
|
|
23
|
+
constructor(message: string);
|
|
24
|
+
}
|
|
25
|
+
/** A domain in its stored form (ASCII, lowercase), or `null`: the shared check of `@bitakit/organizations`. */
|
|
26
|
+
export declare const normalizeDomain: (value: string) => string | null;
|
|
27
|
+
/** Validates and normalizes a policy for storage; throws one message per problem found first. */
|
|
28
|
+
export declare function parseInvitationPolicy(input: unknown): InvitationPolicy;
|
|
29
|
+
/** The stored policy, or "any domain" when none is stored or the stored value is unreadable. */
|
|
30
|
+
export declare function storedInvitationPolicy(value: unknown): InvitationPolicy;
|
|
31
|
+
/** Whether the policy allows an email address; the domain is normalized exactly like the list. */
|
|
32
|
+
export declare function invitationPolicyAllows(policy: InvitationPolicy, email: string): boolean;
|
|
33
|
+
/** The policy for screens: Unicode for reading, ASCII for review. */
|
|
34
|
+
export declare function invitationPolicyView(policy: InvitationPolicy): InvitationPolicyView;
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { domainToUnicode } from 'node:url';
|
|
2
|
+
import { normalizeInvitationDomain } from '@bitakit/organizations';
|
|
3
|
+
export const anyDomain = Object.freeze({ mode: 'any', domains: [] });
|
|
4
|
+
export const invitationPolicyLimits = Object.freeze({ domains: 200 });
|
|
5
|
+
export class InvitationPolicyError extends Error {
|
|
6
|
+
constructor(message) {
|
|
7
|
+
super(message);
|
|
8
|
+
this.name = 'InvitationPolicyError';
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
/** A domain in its stored form (ASCII, lowercase), or `null`: the shared check of `@bitakit/organizations`. */
|
|
12
|
+
export const normalizeDomain = (value) => normalizeInvitationDomain(value);
|
|
13
|
+
/** Validates and normalizes a policy for storage; throws one message per problem found first. */
|
|
14
|
+
export function parseInvitationPolicy(input) {
|
|
15
|
+
if (!input || typeof input !== 'object' || Array.isArray(input))
|
|
16
|
+
throw new InvitationPolicyError('The invitation policy must be an object with mode and domains.');
|
|
17
|
+
const { mode, domains = [] } = input;
|
|
18
|
+
if (mode !== 'any' && mode !== 'allowlist' && mode !== 'blocklist')
|
|
19
|
+
throw new InvitationPolicyError('The mode must be "any", "allowlist" or "blocklist".');
|
|
20
|
+
if (!Array.isArray(domains))
|
|
21
|
+
throw new InvitationPolicyError('The domains must be a list.');
|
|
22
|
+
if (domains.length > invitationPolicyLimits.domains)
|
|
23
|
+
throw new InvitationPolicyError(`At most ${invitationPolicyLimits.domains} domains can be listed.`);
|
|
24
|
+
const normalized = [];
|
|
25
|
+
const seen = new Set();
|
|
26
|
+
for (const entry of domains) {
|
|
27
|
+
const raw = typeof entry === 'string' ? { domain: entry } : entry;
|
|
28
|
+
const domain = normalizeDomain(String(raw?.domain ?? ''));
|
|
29
|
+
if (!domain)
|
|
30
|
+
throw new InvitationPolicyError(`"${String(raw?.domain ?? '')}" is not a valid domain. Use a name like example.com (no wildcards; switch on subdomains instead).`);
|
|
31
|
+
if (raw.includeSubdomains !== undefined && typeof raw.includeSubdomains !== 'boolean')
|
|
32
|
+
throw new InvitationPolicyError(`includeSubdomains of "${domain}" must be true or false.`);
|
|
33
|
+
if (seen.has(domain))
|
|
34
|
+
continue;
|
|
35
|
+
seen.add(domain);
|
|
36
|
+
normalized.push(Object.freeze({ domain, includeSubdomains: raw.includeSubdomains === true }));
|
|
37
|
+
}
|
|
38
|
+
if (mode === 'allowlist' && !normalized.length)
|
|
39
|
+
throw new InvitationPolicyError('An allowlist needs at least one domain.');
|
|
40
|
+
return Object.freeze({ mode, domains: mode === 'any' ? [] : Object.freeze(normalized) });
|
|
41
|
+
}
|
|
42
|
+
/** The stored policy, or "any domain" when none is stored or the stored value is unreadable. */
|
|
43
|
+
export function storedInvitationPolicy(value) {
|
|
44
|
+
if (value === null || value === undefined || value === '')
|
|
45
|
+
return anyDomain;
|
|
46
|
+
try {
|
|
47
|
+
return parseInvitationPolicy(typeof value === 'string' ? JSON.parse(value) : value);
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
// A damaged record must not silently open an allowlist: refuse every domain until fixed.
|
|
51
|
+
return Object.freeze({ mode: 'allowlist', domains: [] });
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
/** Whether an entry covers a domain: the same domain, or one of its subdomains when enabled. */
|
|
55
|
+
const covers = (entry, domain) => domain === entry.domain || (entry.includeSubdomains && domain.endsWith(`.${entry.domain}`));
|
|
56
|
+
/** Whether the policy allows an email address; the domain is normalized exactly like the list. */
|
|
57
|
+
export function invitationPolicyAllows(policy, email) {
|
|
58
|
+
if (policy.mode === 'any')
|
|
59
|
+
return true;
|
|
60
|
+
const at = typeof email === 'string' ? email.lastIndexOf('@') : -1;
|
|
61
|
+
const domain = at > 0 ? normalizeDomain(email.slice(at + 1)) : null;
|
|
62
|
+
if (!domain)
|
|
63
|
+
return false;
|
|
64
|
+
const listed = policy.domains.some((entry) => covers(entry, domain));
|
|
65
|
+
return policy.mode === 'allowlist' ? listed : !listed;
|
|
66
|
+
}
|
|
67
|
+
/** The policy for screens: Unicode for reading, ASCII for review. */
|
|
68
|
+
export function invitationPolicyView(policy) {
|
|
69
|
+
return {
|
|
70
|
+
mode: policy.mode,
|
|
71
|
+
domains: policy.domains.map((entry) => ({
|
|
72
|
+
...entry,
|
|
73
|
+
display: domainToUnicode(entry.domain) || entry.domain,
|
|
74
|
+
})),
|
|
75
|
+
};
|
|
76
|
+
}
|