@bitakit/better-auth 0.1.0
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/LICENSE +21 -0
- package/README.md +56 -0
- package/dist/client.d.ts +2324 -0
- package/dist/client.js +15 -0
- package/dist/email.d.ts +23 -0
- package/dist/email.js +27 -0
- package/dist/index.d.ts +40 -0
- package/dist/index.js +38 -0
- package/dist/organization-session.d.ts +4 -0
- package/dist/organization-session.js +69 -0
- package/dist/organizations.d.ts +130 -0
- package/dist/organizations.js +214 -0
- package/package.json +69 -0
package/dist/client.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { createAuthClient } from 'better-auth/react';
|
|
3
|
+
import { organizationClient, multiSessionClient, twoFactorClient } from 'better-auth/client/plugins';
|
|
4
|
+
import { apiKeyClient } from '@better-auth/api-key/client';
|
|
5
|
+
const standardPlugins = () => [
|
|
6
|
+
organizationClient({ teams: { enabled: true } }),
|
|
7
|
+
multiSessionClient(), apiKeyClient(), twoFactorClient(),
|
|
8
|
+
];
|
|
9
|
+
/** Standard client preset. The server must enable the corresponding native extensions. */
|
|
10
|
+
export function createBetterAuthClient(options = {}) {
|
|
11
|
+
return createAuthClient({
|
|
12
|
+
...options,
|
|
13
|
+
plugins: [...standardPlugins(), ...(options.plugins ?? [])],
|
|
14
|
+
});
|
|
15
|
+
}
|
package/dist/email.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { EmailService } from '@bitakit/email';
|
|
2
|
+
type AccountEmail = {
|
|
3
|
+
user: {
|
|
4
|
+
email: string;
|
|
5
|
+
};
|
|
6
|
+
url: string;
|
|
7
|
+
};
|
|
8
|
+
type OrganizationInvitation = {
|
|
9
|
+
id: string;
|
|
10
|
+
email: string;
|
|
11
|
+
organization: {
|
|
12
|
+
name: string;
|
|
13
|
+
};
|
|
14
|
+
};
|
|
15
|
+
/** Server-side callbacks for Better Auth. The host owns its actual invitation route. */
|
|
16
|
+
export declare function betterAuthEmail(service: EmailService, options: {
|
|
17
|
+
invitationURL(id: string): string;
|
|
18
|
+
}): {
|
|
19
|
+
sendVerificationEmail({ user, url }: AccountEmail): Promise<void>;
|
|
20
|
+
sendResetPassword({ user, url }: AccountEmail): Promise<void>;
|
|
21
|
+
sendInvitationEmail({ id, email, organization }: OrganizationInvitation): Promise<void>;
|
|
22
|
+
};
|
|
23
|
+
export {};
|
package/dist/email.js
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/** Server-side callbacks for Better Auth. The host owns its actual invitation route. */
|
|
2
|
+
export function betterAuthEmail(service, options) {
|
|
3
|
+
return {
|
|
4
|
+
async sendVerificationEmail({ user, url }) {
|
|
5
|
+
await service.send({
|
|
6
|
+
to: user.email,
|
|
7
|
+
subject: 'E-Mail-Adresse bestätigen',
|
|
8
|
+
text: `Bitte bestätige deine E-Mail-Adresse:\n\n${url}`,
|
|
9
|
+
});
|
|
10
|
+
},
|
|
11
|
+
async sendResetPassword({ user, url }) {
|
|
12
|
+
await service.send({
|
|
13
|
+
to: user.email,
|
|
14
|
+
subject: 'Passwort zurücksetzen',
|
|
15
|
+
text: `Hier kannst du dein Passwort zurücksetzen:\n\n${url}`,
|
|
16
|
+
});
|
|
17
|
+
},
|
|
18
|
+
async sendInvitationEmail({ id, email, organization }) {
|
|
19
|
+
const url = options.invitationURL(id);
|
|
20
|
+
await service.send({
|
|
21
|
+
to: email,
|
|
22
|
+
subject: 'Einladung zu einer Organisation',
|
|
23
|
+
text: `Du wurdest zu ${organization.name} eingeladen:\n\n${url}`,
|
|
24
|
+
});
|
|
25
|
+
},
|
|
26
|
+
};
|
|
27
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { type AuthService, type AuthPaths, type AuthSignInOptions } from '@bitakit/core';
|
|
2
|
+
type SessionState = {
|
|
3
|
+
data: {
|
|
4
|
+
user: {
|
|
5
|
+
id: string;
|
|
6
|
+
name?: string;
|
|
7
|
+
email?: string;
|
|
8
|
+
emailVerified?: boolean;
|
|
9
|
+
};
|
|
10
|
+
session?: {
|
|
11
|
+
id?: string;
|
|
12
|
+
activeOrganizationId?: string | null;
|
|
13
|
+
};
|
|
14
|
+
} | null;
|
|
15
|
+
isPending: boolean;
|
|
16
|
+
error: unknown;
|
|
17
|
+
};
|
|
18
|
+
/** Structural client contract: preserves the host's Better Auth plugins and configuration. */
|
|
19
|
+
export type BetterAuthClient = {
|
|
20
|
+
$store: {
|
|
21
|
+
atoms: Record<string, {
|
|
22
|
+
get(): SessionState;
|
|
23
|
+
subscribe(listener: (value: SessionState) => void): () => void;
|
|
24
|
+
}>;
|
|
25
|
+
};
|
|
26
|
+
signOut(): Promise<{
|
|
27
|
+
error: unknown;
|
|
28
|
+
}>;
|
|
29
|
+
};
|
|
30
|
+
export declare function betterAuthPlugin(client: BetterAuthClient, options?: {
|
|
31
|
+
paths?: AuthPaths;
|
|
32
|
+
signIn?: (options?: AuthSignInOptions) => Promise<void>;
|
|
33
|
+
signOut?: () => Promise<void>;
|
|
34
|
+
}): {
|
|
35
|
+
readonly id: "better-auth";
|
|
36
|
+
readonly services: readonly [import("@bitakit/core").ServiceDefinition<AuthService> & {
|
|
37
|
+
id: import("@bitakit/core").ServiceKey<AuthService>;
|
|
38
|
+
}];
|
|
39
|
+
};
|
|
40
|
+
export {};
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { definePlugin, provideService, authService, configureAuthPaths, } from '@bitakit/core';
|
|
2
|
+
export function betterAuthPlugin(client, options = {}) {
|
|
3
|
+
const sessionAtom = client.$store.atoms.session;
|
|
4
|
+
if (!sessionAtom)
|
|
5
|
+
throw new Error('Better Auth client has no session atom.');
|
|
6
|
+
let previous;
|
|
7
|
+
let snapshot;
|
|
8
|
+
const auth = {
|
|
9
|
+
paths: options.paths ? configureAuthPaths(options.paths) : undefined,
|
|
10
|
+
signIn: options.signIn,
|
|
11
|
+
getSnapshot() {
|
|
12
|
+
const session = sessionAtom.get();
|
|
13
|
+
if (session !== previous) {
|
|
14
|
+
previous = session;
|
|
15
|
+
snapshot = {
|
|
16
|
+
user: session.data?.user ?? null,
|
|
17
|
+
pending: session.isPending,
|
|
18
|
+
error: session.error,
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
return snapshot;
|
|
22
|
+
},
|
|
23
|
+
subscribe(listener) {
|
|
24
|
+
return sessionAtom.subscribe(listener);
|
|
25
|
+
},
|
|
26
|
+
async signOut() {
|
|
27
|
+
if (options.signOut)
|
|
28
|
+
return options.signOut();
|
|
29
|
+
const result = await client.signOut();
|
|
30
|
+
if (result.error)
|
|
31
|
+
throw result.error;
|
|
32
|
+
},
|
|
33
|
+
};
|
|
34
|
+
return definePlugin({
|
|
35
|
+
id: 'better-auth',
|
|
36
|
+
services: [provideService(authService, { create: () => auth })],
|
|
37
|
+
});
|
|
38
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { BetterAuthClient } from './index.js';
|
|
2
|
+
import type { OrganizationBackend } from '@bitakit/organizations';
|
|
3
|
+
/** Optional explicit demo mode. Never fall back to demo data after a real API failure. */
|
|
4
|
+
export declare function sessionOrganizationBackend(client: BetterAuthClient, authenticated: OrganizationBackend, signedOut?: OrganizationBackend): OrganizationBackend;
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/** Optional explicit demo mode. Never fall back to demo data after a real API failure. */
|
|
2
|
+
export function sessionOrganizationBackend(client, authenticated, signedOut = authenticated) {
|
|
3
|
+
const atom = client.$store.atoms.session;
|
|
4
|
+
let loadedUser;
|
|
5
|
+
const user = () => {
|
|
6
|
+
const state = atom.get();
|
|
7
|
+
if (state.isPending || state.error)
|
|
8
|
+
throw new Error('Authentication is not ready.');
|
|
9
|
+
return state.data?.user.id ?? null;
|
|
10
|
+
};
|
|
11
|
+
const selected = () => (atom.get().data?.user ? authenticated : signedOut);
|
|
12
|
+
const backend = {
|
|
13
|
+
subscribe(listener) {
|
|
14
|
+
let previous = atom.get();
|
|
15
|
+
return atom.subscribe((current) => {
|
|
16
|
+
if (current.data?.user.id === previous.data?.user.id &&
|
|
17
|
+
current.data?.user.emailVerified === previous.data?.user.emailVerified &&
|
|
18
|
+
current.data?.session?.id === previous.data?.session?.id &&
|
|
19
|
+
current.data?.session?.activeOrganizationId === previous.data?.session?.activeOrganizationId &&
|
|
20
|
+
current.isPending === previous.isPending &&
|
|
21
|
+
current.error === previous.error)
|
|
22
|
+
return;
|
|
23
|
+
previous = current;
|
|
24
|
+
listener();
|
|
25
|
+
});
|
|
26
|
+
},
|
|
27
|
+
async load() {
|
|
28
|
+
const identity = user();
|
|
29
|
+
const result = await selected().load();
|
|
30
|
+
if (identity !== user())
|
|
31
|
+
throw new Error('Account changed during loading.');
|
|
32
|
+
loadedUser = identity;
|
|
33
|
+
return result;
|
|
34
|
+
},
|
|
35
|
+
};
|
|
36
|
+
for (const key of [
|
|
37
|
+
'create',
|
|
38
|
+
'setActive',
|
|
39
|
+
'invite',
|
|
40
|
+
'cancelInvitation',
|
|
41
|
+
'updateRole',
|
|
42
|
+
'removeMember',
|
|
43
|
+
'update',
|
|
44
|
+
'delete',
|
|
45
|
+
'acceptInvitation',
|
|
46
|
+
'rejectInvitation',
|
|
47
|
+
'setMemberDisabled',
|
|
48
|
+
]) {
|
|
49
|
+
Object.defineProperty(backend, key, {
|
|
50
|
+
enumerable: true,
|
|
51
|
+
get() {
|
|
52
|
+
if (!selected()[key])
|
|
53
|
+
return undefined;
|
|
54
|
+
return async (input) => {
|
|
55
|
+
if (user() !== loadedUser)
|
|
56
|
+
throw new Error('Account changed. Reload before writing.');
|
|
57
|
+
const operation = selected()[key];
|
|
58
|
+
if (!operation)
|
|
59
|
+
throw new Error('Operation unavailable.');
|
|
60
|
+
await operation(input);
|
|
61
|
+
};
|
|
62
|
+
},
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
Object.defineProperty(backend, 'customInvitationExpiry', {
|
|
66
|
+
get: () => selected().customInvitationExpiry,
|
|
67
|
+
});
|
|
68
|
+
return backend;
|
|
69
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
export { sessionOrganizationBackend } from './organization-session.js';
|
|
2
|
+
import type { BetterAuthClient } from './index.js';
|
|
3
|
+
import type { OrganizationBackend, Organization } from '@bitakit/organizations';
|
|
4
|
+
type Result<T> = Promise<{
|
|
5
|
+
data: T | null;
|
|
6
|
+
error: unknown;
|
|
7
|
+
}>;
|
|
8
|
+
type AuthMember = {
|
|
9
|
+
id: string;
|
|
10
|
+
role: string;
|
|
11
|
+
disabled?: boolean;
|
|
12
|
+
createdAt?: Date | string;
|
|
13
|
+
user: {
|
|
14
|
+
name: string;
|
|
15
|
+
email: string;
|
|
16
|
+
image?: string | null;
|
|
17
|
+
};
|
|
18
|
+
};
|
|
19
|
+
/** Structural boundary supports an existing client configured with Better Auth's organization plugin. */
|
|
20
|
+
export interface BetterAuthOrganizationClient {
|
|
21
|
+
$store?: BetterAuthClient['$store'];
|
|
22
|
+
organization: {
|
|
23
|
+
list(): Result<Array<Organization & {
|
|
24
|
+
metadata?: unknown;
|
|
25
|
+
}>>;
|
|
26
|
+
getOrganization?(): Result<{
|
|
27
|
+
id: string;
|
|
28
|
+
}>;
|
|
29
|
+
getFullOrganization(): Result<{
|
|
30
|
+
id: string;
|
|
31
|
+
}>;
|
|
32
|
+
getActiveMember(): Result<{
|
|
33
|
+
id?: string;
|
|
34
|
+
role: string;
|
|
35
|
+
disabled?: boolean;
|
|
36
|
+
}>;
|
|
37
|
+
listMembers(input: {
|
|
38
|
+
query: {
|
|
39
|
+
organizationId: string;
|
|
40
|
+
limit: number;
|
|
41
|
+
offset: number;
|
|
42
|
+
};
|
|
43
|
+
}): Result<{
|
|
44
|
+
members: AuthMember[];
|
|
45
|
+
total: number;
|
|
46
|
+
}>;
|
|
47
|
+
listInvitations(input: {
|
|
48
|
+
query: {
|
|
49
|
+
organizationId: string;
|
|
50
|
+
};
|
|
51
|
+
}): Result<Array<{
|
|
52
|
+
id: string;
|
|
53
|
+
email: string;
|
|
54
|
+
role: string | null;
|
|
55
|
+
status: string;
|
|
56
|
+
createdAt?: Date | string;
|
|
57
|
+
expiresAt?: Date | string;
|
|
58
|
+
}>>;
|
|
59
|
+
listUserInvitations?(): Result<Array<{
|
|
60
|
+
id: string;
|
|
61
|
+
email: string;
|
|
62
|
+
role: string | null;
|
|
63
|
+
status: string;
|
|
64
|
+
organizationName: string;
|
|
65
|
+
organizationId?: string;
|
|
66
|
+
organizationLogo?: string | null;
|
|
67
|
+
createdAt?: Date | string;
|
|
68
|
+
expiresAt?: Date | string;
|
|
69
|
+
}>>;
|
|
70
|
+
acceptInvitation?(input: {
|
|
71
|
+
invitationId: string;
|
|
72
|
+
}): Result<unknown>;
|
|
73
|
+
rejectInvitation?(input: {
|
|
74
|
+
invitationId: string;
|
|
75
|
+
}): Result<unknown>;
|
|
76
|
+
setActive(input: {
|
|
77
|
+
organizationId: string;
|
|
78
|
+
}): Result<unknown>;
|
|
79
|
+
create(input: {
|
|
80
|
+
name: string;
|
|
81
|
+
slug: string;
|
|
82
|
+
logo?: string;
|
|
83
|
+
metadata?: Record<string, unknown>;
|
|
84
|
+
}): Result<{
|
|
85
|
+
id: string;
|
|
86
|
+
}>;
|
|
87
|
+
update?(input: {
|
|
88
|
+
organizationId: string;
|
|
89
|
+
data: {
|
|
90
|
+
name: string;
|
|
91
|
+
slug: string;
|
|
92
|
+
logo?: string | null;
|
|
93
|
+
metadata?: Record<string, unknown>;
|
|
94
|
+
};
|
|
95
|
+
}): Result<unknown>;
|
|
96
|
+
delete?(input: {
|
|
97
|
+
organizationId: string;
|
|
98
|
+
}): Result<unknown>;
|
|
99
|
+
inviteMember(input: {
|
|
100
|
+
organizationId: string;
|
|
101
|
+
email: string;
|
|
102
|
+
role: 'member' | 'admin';
|
|
103
|
+
resend?: boolean;
|
|
104
|
+
}): Result<unknown>;
|
|
105
|
+
cancelInvitation(input: {
|
|
106
|
+
invitationId: string;
|
|
107
|
+
}): Result<unknown>;
|
|
108
|
+
updateMemberRole(input: {
|
|
109
|
+
organizationId: string;
|
|
110
|
+
memberId: string;
|
|
111
|
+
role: 'member' | 'admin';
|
|
112
|
+
}): Result<unknown>;
|
|
113
|
+
removeMember(input: {
|
|
114
|
+
organizationId: string;
|
|
115
|
+
memberIdOrEmail: string;
|
|
116
|
+
}): Result<unknown>;
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
/** No HTTP routes or credentials are invented. The server must enforce membership and permissions. */
|
|
120
|
+
export type OrganizationExtensions = {
|
|
121
|
+
/** Host-supplied, authenticated server operation; never a client-side DB write. */
|
|
122
|
+
setMemberDisabled?: OrganizationBackend['setMemberDisabled'];
|
|
123
|
+
/** Optional server endpoint supporting per-invitation expiry. */
|
|
124
|
+
invite?: OrganizationBackend['invite'];
|
|
125
|
+
create?: OrganizationBackend['create'];
|
|
126
|
+
update?: OrganizationBackend['update'];
|
|
127
|
+
delete?: OrganizationBackend['delete'];
|
|
128
|
+
list?: () => Promise<Organization[]>;
|
|
129
|
+
};
|
|
130
|
+
export declare function betterAuthOrganizations(client: BetterAuthOrganizationClient, extensions?: OrganizationExtensions): OrganizationBackend;
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
import { isOrganizationWebsite, organizationWebsiteError } from '@bitakit/organizations';
|
|
2
|
+
export { sessionOrganizationBackend } from './organization-session.js';
|
|
3
|
+
async function value(request) {
|
|
4
|
+
const result = await request;
|
|
5
|
+
if (result.error)
|
|
6
|
+
throw result.error;
|
|
7
|
+
if (result.data === null)
|
|
8
|
+
throw new Error('Better Auth returned no data.');
|
|
9
|
+
return result.data;
|
|
10
|
+
}
|
|
11
|
+
async function completed(request) {
|
|
12
|
+
const result = await request;
|
|
13
|
+
if (result.error)
|
|
14
|
+
throw result.error;
|
|
15
|
+
}
|
|
16
|
+
export function betterAuthOrganizations(client, extensions = {}) {
|
|
17
|
+
const api = client.organization;
|
|
18
|
+
const activeOrganization = () => api.getOrganization ? api.getOrganization() : api.getFullOrganization();
|
|
19
|
+
return {
|
|
20
|
+
setMemberDisabled: extensions.setMemberDisabled,
|
|
21
|
+
customInvitationExpiry: !!extensions.invite,
|
|
22
|
+
update: extensions.update ??
|
|
23
|
+
(api.update
|
|
24
|
+
? async ({ organizationId, ...input }) => {
|
|
25
|
+
const existing = (await value(api.list())).find((org) => org.id === organizationId);
|
|
26
|
+
if (!existing)
|
|
27
|
+
throw new Error('Organization is not accessible.');
|
|
28
|
+
await completed(api.update({
|
|
29
|
+
organizationId,
|
|
30
|
+
data: {
|
|
31
|
+
...(await organizationDetails(input)),
|
|
32
|
+
metadata: { ...metadata(existing.metadata), website: input.website ?? '' },
|
|
33
|
+
},
|
|
34
|
+
}));
|
|
35
|
+
}
|
|
36
|
+
: undefined),
|
|
37
|
+
delete: extensions.delete ??
|
|
38
|
+
(api.delete ? (id) => completed(api.delete({ organizationId: id })) : undefined),
|
|
39
|
+
acceptInvitation: api.acceptInvitation
|
|
40
|
+
? (invitationId) => completed(api.acceptInvitation({ invitationId }))
|
|
41
|
+
: undefined,
|
|
42
|
+
rejectInvitation: api.rejectInvitation
|
|
43
|
+
? (invitationId) => completed(api.rejectInvitation({ invitationId }))
|
|
44
|
+
: undefined,
|
|
45
|
+
subscribe(listener) {
|
|
46
|
+
const session = client.$store?.atoms.session;
|
|
47
|
+
if (!session)
|
|
48
|
+
return () => { };
|
|
49
|
+
let previous = session.get();
|
|
50
|
+
return session.subscribe((current) => {
|
|
51
|
+
if (current.data === previous.data && current.isPending === previous.isPending)
|
|
52
|
+
return;
|
|
53
|
+
previous = current;
|
|
54
|
+
listener();
|
|
55
|
+
});
|
|
56
|
+
},
|
|
57
|
+
async load() {
|
|
58
|
+
const [organizations, incomingResult, active] = await Promise.all([
|
|
59
|
+
extensions.list
|
|
60
|
+
? extensions.list()
|
|
61
|
+
: value(api.list()).then((items) => items.map((org) => ({
|
|
62
|
+
...org,
|
|
63
|
+
website: String(metadata(org.metadata).website ?? ''),
|
|
64
|
+
}))),
|
|
65
|
+
api.listUserInvitations?.(),
|
|
66
|
+
activeOrganization(),
|
|
67
|
+
]);
|
|
68
|
+
const verificationRequired = incomingResult?.error?.code ===
|
|
69
|
+
'EMAIL_VERIFICATION_REQUIRED_FOR_INVITATION';
|
|
70
|
+
if (incomingResult?.error && !verificationRequired)
|
|
71
|
+
throw incomingResult.error;
|
|
72
|
+
const incomingInvitations = (incomingResult?.data ?? []).map((item) => ({
|
|
73
|
+
...item,
|
|
74
|
+
role: item.role ?? 'member',
|
|
75
|
+
createdAt: item.createdAt instanceof Date ? item.createdAt.toISOString() : item.createdAt,
|
|
76
|
+
expiresAt: item.expiresAt instanceof Date ? item.expiresAt.toISOString() : item.expiresAt,
|
|
77
|
+
}));
|
|
78
|
+
if (active.error)
|
|
79
|
+
throw active.error;
|
|
80
|
+
const empty = {
|
|
81
|
+
organizations,
|
|
82
|
+
activeId: null,
|
|
83
|
+
members: [],
|
|
84
|
+
invitations: [],
|
|
85
|
+
canManage: false,
|
|
86
|
+
incomingInvitations,
|
|
87
|
+
incomingInvitationsError: verificationRequired
|
|
88
|
+
? 'Bitte bestätige deine E-Mail-Adresse, um Einladungen zu sehen.'
|
|
89
|
+
: undefined,
|
|
90
|
+
};
|
|
91
|
+
if (!active.data)
|
|
92
|
+
return empty;
|
|
93
|
+
const activeId = active.data.id;
|
|
94
|
+
if (!organizations.some((org) => org.id === activeId))
|
|
95
|
+
throw new Error('Active organization is not accessible.');
|
|
96
|
+
const current = await value(api.getActiveMember());
|
|
97
|
+
if (current.disabled)
|
|
98
|
+
throw new Error('Membership is disabled.');
|
|
99
|
+
const canManage = current.role
|
|
100
|
+
.split(',')
|
|
101
|
+
.some((role) => role === 'owner' || role === 'admin');
|
|
102
|
+
const [members, invitations] = await Promise.all([
|
|
103
|
+
(async () => {
|
|
104
|
+
const members = [];
|
|
105
|
+
for (let offset = 0;;) {
|
|
106
|
+
const page = await value(api.listMembers({ query: { organizationId: activeId, limit: 100, offset } }));
|
|
107
|
+
members.push(...page.members.map((member) => ({
|
|
108
|
+
id: member.id,
|
|
109
|
+
role: member.role,
|
|
110
|
+
disabled: member.disabled,
|
|
111
|
+
createdAt: member.createdAt instanceof Date
|
|
112
|
+
? member.createdAt.toISOString()
|
|
113
|
+
: member.createdAt,
|
|
114
|
+
name: member.user.name,
|
|
115
|
+
image: member.user.image,
|
|
116
|
+
email: member.user.email,
|
|
117
|
+
})));
|
|
118
|
+
offset += page.members.length;
|
|
119
|
+
if (offset >= page.total)
|
|
120
|
+
break;
|
|
121
|
+
if (!page.members.length)
|
|
122
|
+
throw new Error('Incomplete member list.');
|
|
123
|
+
}
|
|
124
|
+
return members;
|
|
125
|
+
})(),
|
|
126
|
+
canManage
|
|
127
|
+
? value(api.listInvitations({ query: { organizationId: activeId } })).then((items) => items.map((item) => ({
|
|
128
|
+
...item,
|
|
129
|
+
role: item.role ?? 'member',
|
|
130
|
+
createdAt: item.createdAt instanceof Date ? item.createdAt.toISOString() : item.createdAt,
|
|
131
|
+
expiresAt: item.expiresAt instanceof Date ? item.expiresAt.toISOString() : item.expiresAt,
|
|
132
|
+
})))
|
|
133
|
+
: Promise.resolve([]),
|
|
134
|
+
]);
|
|
135
|
+
// Another tab may have changed the active workspace during the requests.
|
|
136
|
+
const latest = await activeOrganization();
|
|
137
|
+
if (latest.error)
|
|
138
|
+
throw latest.error;
|
|
139
|
+
if (latest.data?.id !== activeId)
|
|
140
|
+
throw new Error('Active organization changed during loading.');
|
|
141
|
+
return {
|
|
142
|
+
organizations,
|
|
143
|
+
activeId,
|
|
144
|
+
members,
|
|
145
|
+
invitations,
|
|
146
|
+
canManage,
|
|
147
|
+
canDelete: current.role.split(',').includes('owner'),
|
|
148
|
+
viewerMemberId: current.id,
|
|
149
|
+
incomingInvitations,
|
|
150
|
+
incomingInvitationsError: verificationRequired
|
|
151
|
+
? 'Bitte bestätige deine E-Mail-Adresse, um Einladungen zu sehen.'
|
|
152
|
+
: undefined,
|
|
153
|
+
};
|
|
154
|
+
},
|
|
155
|
+
setActive: (id) => completed(api.setActive({ organizationId: id })),
|
|
156
|
+
create: extensions.create ??
|
|
157
|
+
(async (input) => {
|
|
158
|
+
const created = await value(api.create(await organizationDetails(input)));
|
|
159
|
+
await completed(api.setActive({ organizationId: created.id }));
|
|
160
|
+
}),
|
|
161
|
+
invite: extensions.invite ??
|
|
162
|
+
((input) => {
|
|
163
|
+
if (input.expiresInDays !== undefined && input.expiresInDays !== 30)
|
|
164
|
+
throw new Error('Custom invitation expiry requires a server extension.');
|
|
165
|
+
const { expiresInDays: _expiry, ...body } = input;
|
|
166
|
+
return completed(api.inviteMember(body));
|
|
167
|
+
}),
|
|
168
|
+
async cancelInvitation({ organizationId, invitationId }) {
|
|
169
|
+
// Better Auth's cancel API takes only the invitation ID; verify the displayed scope first.
|
|
170
|
+
const invitations = await value(api.listInvitations({ query: { organizationId } }));
|
|
171
|
+
if (!invitations.some((item) => item.id === invitationId))
|
|
172
|
+
throw new Error('Invitation is not in this organization.');
|
|
173
|
+
await completed(api.cancelInvitation({ invitationId }));
|
|
174
|
+
},
|
|
175
|
+
updateRole: (input) => completed(api.updateMemberRole(input)),
|
|
176
|
+
removeMember: ({ organizationId, memberId }) => completed(api.removeMember({ organizationId, memberIdOrEmail: memberId })),
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
function metadata(value) {
|
|
180
|
+
if (typeof value === 'string') {
|
|
181
|
+
try {
|
|
182
|
+
return metadata(JSON.parse(value));
|
|
183
|
+
}
|
|
184
|
+
catch {
|
|
185
|
+
return {};
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
return value && typeof value === 'object' && !Array.isArray(value)
|
|
189
|
+
? value
|
|
190
|
+
: {};
|
|
191
|
+
}
|
|
192
|
+
async function organizationDetails(input) {
|
|
193
|
+
if (!isOrganizationWebsite(input.website ?? ''))
|
|
194
|
+
throw new Error(organizationWebsiteError);
|
|
195
|
+
let logo;
|
|
196
|
+
if (input.logo) {
|
|
197
|
+
if (input.logo.size > 2 * 1024 * 1024 ||
|
|
198
|
+
!['image/png', 'image/jpeg', 'image/webp'].includes(input.logo.type))
|
|
199
|
+
throw new Error('Invalid organization logo.');
|
|
200
|
+
const bytes = new Uint8Array(await input.logo.arrayBuffer());
|
|
201
|
+
let binary = '';
|
|
202
|
+
for (const byte of bytes)
|
|
203
|
+
binary += String.fromCharCode(byte);
|
|
204
|
+
logo = `data:${input.logo.type};base64,${btoa(binary)}`;
|
|
205
|
+
}
|
|
206
|
+
else if (input.removeLogo)
|
|
207
|
+
logo = '';
|
|
208
|
+
return {
|
|
209
|
+
name: input.name,
|
|
210
|
+
slug: input.slug,
|
|
211
|
+
...(logo !== undefined ? { logo } : {}),
|
|
212
|
+
metadata: { website: input.website ?? '' },
|
|
213
|
+
};
|
|
214
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@bitakit/better-auth",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"sideEffects": false,
|
|
6
|
+
"files": [
|
|
7
|
+
"dist",
|
|
8
|
+
"README.md"
|
|
9
|
+
],
|
|
10
|
+
"exports": {
|
|
11
|
+
".": {
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"default": "./dist/index.js"
|
|
14
|
+
},
|
|
15
|
+
"./organizations": {
|
|
16
|
+
"types": "./dist/organizations.d.ts",
|
|
17
|
+
"default": "./dist/organizations.js"
|
|
18
|
+
},
|
|
19
|
+
"./email": {
|
|
20
|
+
"types": "./dist/email.d.ts",
|
|
21
|
+
"default": "./dist/email.js"
|
|
22
|
+
},
|
|
23
|
+
"./client": {
|
|
24
|
+
"types": "./dist/client.d.ts",
|
|
25
|
+
"default": "./dist/client.js"
|
|
26
|
+
}
|
|
27
|
+
},
|
|
28
|
+
"scripts": {
|
|
29
|
+
"build": "tsc -p tsconfig.json",
|
|
30
|
+
"test": "npm run build && node --test tests/*.test.mjs"
|
|
31
|
+
},
|
|
32
|
+
"dependencies": {
|
|
33
|
+
"@bitakit/core": "0.1.1",
|
|
34
|
+
"@better-auth/api-key": "1.7.5"
|
|
35
|
+
},
|
|
36
|
+
"peerDependencies": {
|
|
37
|
+
"better-auth": "^1.7.5",
|
|
38
|
+
"react": "^19.0.0",
|
|
39
|
+
"@bitakit/organizations": "0.1.0",
|
|
40
|
+
"@bitakit/email": "0.1.0"
|
|
41
|
+
},
|
|
42
|
+
"devDependencies": {
|
|
43
|
+
"typescript": "^5",
|
|
44
|
+
"@types/react": "^19",
|
|
45
|
+
"@bitakit/organizations": "0.1.0",
|
|
46
|
+
"@bitakit/email": "0.1.0"
|
|
47
|
+
},
|
|
48
|
+
"peerDependenciesMeta": {
|
|
49
|
+
"better-auth": {
|
|
50
|
+
"optional": true
|
|
51
|
+
},
|
|
52
|
+
"@bitakit/organizations": {
|
|
53
|
+
"optional": true
|
|
54
|
+
},
|
|
55
|
+
"@bitakit/email": {
|
|
56
|
+
"optional": true
|
|
57
|
+
}
|
|
58
|
+
},
|
|
59
|
+
"description": "Better Auth plugin, organization adapter and server email callbacks for SaaS Foundation.",
|
|
60
|
+
"license": "MIT",
|
|
61
|
+
"repository": {
|
|
62
|
+
"type": "git",
|
|
63
|
+
"url": "git+https://github.com/mvavesal/bitakit.git",
|
|
64
|
+
"directory": "packages/better-auth"
|
|
65
|
+
},
|
|
66
|
+
"publishConfig": {
|
|
67
|
+
"access": "public"
|
|
68
|
+
}
|
|
69
|
+
}
|