@bitakit/better-auth 0.1.0 → 0.2.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/README.md CHANGED
@@ -1,56 +1,100 @@
1
1
  # @bitakit/better-auth
2
2
 
3
- Optionales Foundation-Plugin für einen bereits konfigurierten Better-Auth-Client.
4
- `betterAuthPlugin(client, { signOut? })` liefert ein normales Plugin für die Foundation-Liste.
5
- Es stellt den allgemeinen `authService` bereit: Sitzung, Änderungen und Abmelden.
6
-
7
- Die Foundation übernimmt Beobachtung und Cleanup. Der Client und die Serverkonfiguration
8
- bleiben beim Host. Die Basis-Anbindung implementiert keine Anmeldeoberfläche; Organisationen und E-Mail-Hooks
9
- sind separate optionale Einstiegspunkte desselben Pakets. Es darf nicht als vollständiges Auth-Setup
10
- oder Ersatz für serverseitige Rechteprüfungen verstanden werden.
11
-
12
- ## Organisationsanbindung
13
-
14
- `@bitakit/better-auth/organizations` exportiert `betterAuthOrganizations(client)`.
15
- Es implementiert den allgemeinen Organisationsvertrag mit den SDK-Methoden des bereits
16
- konfigurierten Organization-Clients, einschließlich paginierter Mitgliederlisten.
17
- Die UI kommt optional aus `@bitakit/organizations/react`.
18
-
19
- Die aktuelle UI-Berechtigungsprojektion unterstützt die Standardrollen owner/admin/member.
20
- Ein deaktiviertes Mitglied wird beim Laden abgewiesen. Eigene Rollen benötigen eine
21
- angepasste Fähigkeitenprojektion. Backend-Policies und Suspension-Hooks bleiben Pflicht;
22
- der Client-Adapter ist keine Sicherheitsgrenze. Eine bestehende Web-App wird nicht automatisch migriert.
23
-
24
- ## E-Mail (Server)
25
-
26
- `@bitakit/better-auth/email` exportiert `betterAuthEmail(emailService, { invitationURL })`.
27
- Das liefert die Better-Auth-Callbacks `sendVerificationEmail`, `sendResetPassword` und
28
- `sendInvitationEmail`. Die ersten beiden gehören in die jeweiligen Auth-Optionen,
29
- der dritte in die Organization-Plugin-Konfiguration. Der Host bestimmt seine echte
30
- Einladungsroute. Texte sind derzeit deutsche Standardtexte; für andere Templates können
31
- Host-Callbacks denselben E-Mail-Service direkt verwenden.
32
-
33
- Die Callbacks hängen ausschließlich vom allgemeinen E-Mail-Vertrag ab, nicht von Nodemailer.
34
- Sie werden nicht automatisch in eine bereits erzeugte Server-Auth-Instanz injiziert.
35
-
36
- ### Organisationsverwaltung
37
-
38
- `betterAuthOrganizations(client)` unterstützt native Erstellung mit anschließendem Aktivieren, Profiländerung, Logo, Website-Metadata und Löschen. Die vorhandenen serverseitigen Better-Auth-Regeln gelten weiterhin. Optional können explizite Server-Erweiterungen diese Operationen übernehmen. `sessionOrganizationBackend(client, authenticated, signedOut)` trennt einen ausdrücklich lokalen Demo-Einstieg von echten Konten; Fehler des echten Backends werden nie mit Demo-Daten beantwortet. Host-Apps komponieren nur die Adapter, die Logik bleibt im Paket. Ohne Einladungserweiterung gilt die serverseitige Standardlaufzeit; Mitgliedssperren benötigen eine explizite Erweiterung.
3
+ Optional BitaKit plugin for an existing, configured Better Auth client. It provides the general
4
+ `auth` service (session snapshot, changes, sign-out) on the client's session atom. It has no
5
+ sign-in UI and is no replacement for server-side permission checks; organizations and e-mail
6
+ hooks are separate optional entry points of the same package.
7
+
8
+ ## Install and provide the client
9
+
10
+ The package manifest declares `bitakit: { plugin: './plugin', configuration: 'better-auth' }`,
11
+ so a generated app composes the plugin without host code. The plugin takes no host objects:
12
+ the client arrives through the `betterAuthClient` contract (`better-auth-client`). Provide it
13
+ once in the app:
14
+
15
+ ```ts
16
+ // src/services/better-auth-client.ts
17
+ import { defineService } from '@bitakit/core';
18
+ import { betterAuthClient } from '@bitakit/better-auth';
19
+ import { authClient } from '../lib/auth-client';
20
+
21
+ export default defineService(() => ({ client: authClient }), { provides: betterAuthClient });
22
+ ```
23
+
24
+ The client is wrapped in `{ client }`: a Better Auth client answers every property, `subscribe`
25
+ included, so the runtime would observe a bare client as a service and call it. Without that
26
+ service, startup fails with a named error. The contract is not called
27
+ `auth.client`: `auth` is the authentication service itself and cannot also be a namespace.
28
+
29
+ Options live in `src/configs/better-auth.ts`:
30
+
31
+ ```ts
32
+ export default defineConfig({
33
+ defaults: { paths: { signIn: '/login', afterSignIn: '/', afterSignOut: '/' } },
34
+ });
35
+ ```
36
+
37
+ `betterAuthPlugin(options?)` accepts `{ paths?, signIn?, signOut? }`. `paths` are validated
38
+ when the configuration is created. An optional `signIn(options)` delegates a native login
39
+ flow; without it, `useAuth().signIn()` opens `paths.signIn`. `signOut` replaces the client's
40
+ sign-out; use the shared UI hook for post-logout navigation instead of redirecting inside it.
41
+ Manual composition passes the same options and provides the client through
42
+ `createRuntime(config, { services: { [betterAuthClient]: { client: authClient } } })`, the
43
+ `BitaKitRuntimeProvider` `services` prop or any plugin service with `provides: betterAuthClient`.
44
+
45
+ See the [client authentication guide](../../apps/docs/content/docs/reference/authentication.mdx) for `AuthBoundary`, safe return
46
+ destinations and a provider adapter template.
47
+
48
+ ## Organizations
49
+
50
+ `@bitakit/better-auth/organizations` exports `betterAuthOrganizations(client, extensions?)`, the
51
+ general organization backend on the SDK methods of a client configured with Better Auth's
52
+ organization plugin (including paginated member lists, native creation and activation, profile,
53
+ logo, website metadata and deletion). Explicit server extensions may take over operations;
54
+ member suspension needs one. `sessionOrganizationBackend(client, authenticated, signedOut)`
55
+ separates an explicit local demo entry from real accounts; failures of the real backend are
56
+ never answered with demo data. Provide the result as the `organizationBackend` contract of
57
+ `@bitakit/organizations`:
58
+
59
+ ```ts
60
+ // src/services/organization-backend.ts
61
+ export default defineService(
62
+ () => sessionOrganizationBackend(authClient, betterAuthOrganizations(authClient)),
63
+ { provides: organizationBackend },
64
+ );
65
+ ```
66
+
67
+ The UI permission projection supports the standard roles owner/admin/member; a disabled member
68
+ is rejected when loading. Backend policies and suspension hooks remain mandatory; the client
69
+ adapter is not a security boundary. The UI comes from `@bitakit/better-auth-ui/organizations`.
70
+
71
+ ## E-mail (server)
72
+
73
+ `@bitakit/better-auth/email` exports `betterAuthEmail(emailService, { invitationURL })`, the
74
+ Better Auth callbacks `sendVerificationEmail`, `sendResetPassword` and `sendInvitationEmail`.
75
+ The first two belong in the auth options, the third in the organization plugin configuration.
76
+ The host decides its real invitation route. They depend only on the general e-mail contract,
77
+ not on Nodemailer, and are never injected into an existing server auth instance.
39
78
 
40
79
  ## Standard browser client
41
80
 
42
- `createBetterAuthClient` from `@bitakit/better-auth/client` creates the shared browser client with organization/teams, multi-session, API key, and two-factor extensions. These are client capabilities, not server activation: the server must configure the matching native extensions. Native client options such as baseURL are supported; plugins supplied to this helper append additional client extensions. Use the native createAuthClient and existing betterAuthPlugin directly for a different preset.
81
+ `createBetterAuthClient` from `@bitakit/better-auth/client` creates the shared browser client
82
+ with organization/teams, multi-session, API key and two-factor extensions. These are client
83
+ capabilities, not server activation: the server must configure the matching extensions.
84
+ Native client options such as `baseURL` are supported; `plugins` append further extensions.
43
85
 
44
- The main headless adapter entry remains separate from this browser-only subpath.
86
+ ## Source responsibilities
45
87
 
46
- ## Shared client navigation
88
+ - `src/index.ts`: the `auth` service on the client session, `betterAuthClient`, `betterAuthPlugin`.
89
+ - `src/plugin.ts` (`./plugin`): the package plugin entry the manifest names.
90
+ - `src/organizations.ts`, `src/organization-session.ts` (`./organizations`): organization backend.
91
+ - `src/email.ts` (`./email`), `src/client.ts` (`./client`).
47
92
 
48
- Pass application-owned `paths: { signIn, afterSignIn, afterSignOut }` as the second
49
- argument to `betterAuthPlugin`. An optional `signIn(options)` delegates a native login
50
- flow; without it, `useAuth().signIn()` opens the configured application login page.
51
- The existing `signOut` override remains supported. Use the shared UI hook for configured
52
- post-logout navigation; avoid also redirecting inside the override.
93
+ ### Native session display compatibility
53
94
 
54
- See the [client authentication guide](../core/docs/auth.md) for configuration,
55
- `AuthBoundary`, safe return destinations and a provider adapter template. These additions
56
- are workspace APIs pending release. Native server configuration and login UI remain external.
95
+ `createBetterAuthClient` retains Better Auth's native client and extensions. Its public fetch
96
+ success hook supplies `Unknown` for missing/blank user-agent display values in list-sessions
97
+ responses, because native HeroUI session cards cannot parse an empty user agent. It keeps
98
+ every session/token, delegates the caller's hook and leaves storage, authorization and all
99
+ other endpoint payloads unchanged. Hosts providing a different native client do not receive
100
+ this preset behavior automatically.
package/dist/client.js CHANGED
@@ -1,15 +1,37 @@
1
1
  'use client';
2
2
  import { createAuthClient } from 'better-auth/react';
3
- import { organizationClient, multiSessionClient, twoFactorClient } from 'better-auth/client/plugins';
3
+ import { organizationClient, multiSessionClient, twoFactorClient, } from 'better-auth/client/plugins';
4
4
  import { apiKeyClient } from '@better-auth/api-key/client';
5
5
  const standardPlugins = () => [
6
6
  organizationClient({ teams: { enabled: true } }),
7
- multiSessionClient(), apiKeyClient(), twoFactorClient(),
7
+ multiSessionClient(),
8
+ apiKeyClient(),
9
+ twoFactorClient(),
8
10
  ];
9
11
  /** Standard client preset. The server must enable the corresponding native extensions. */
10
12
  export function createBetterAuthClient(options = {}) {
11
13
  return createAuthClient({
12
14
  ...options,
13
- plugins: [...standardPlugins(), ...(options.plugins ?? [])],
15
+ fetchOptions: {
16
+ ...options.fetchOptions,
17
+ async onSuccess(context) {
18
+ // Native session cards require a nonempty UA even though Better Auth permits null.
19
+ // Preserve every session and permission; only supply an unknown display value.
20
+ if (new URL(context.request.url, 'http://localhost').pathname.endsWith('/list-sessions') &&
21
+ Array.isArray(context.data)) {
22
+ for (const session of context.data) {
23
+ if (session &&
24
+ typeof session === 'object' &&
25
+ (typeof session.userAgent !== 'string' || !session.userAgent.trim()))
26
+ session.userAgent = 'Unknown';
27
+ }
28
+ }
29
+ await options.fetchOptions?.onSuccess?.(context);
30
+ },
31
+ },
32
+ plugins: [
33
+ ...standardPlugins(),
34
+ ...(options.plugins ?? []),
35
+ ],
14
36
  });
15
37
  }
package/dist/email.js CHANGED
@@ -4,23 +4,23 @@ export function betterAuthEmail(service, options) {
4
4
  async sendVerificationEmail({ user, url }) {
5
5
  await service.send({
6
6
  to: user.email,
7
- subject: 'E-Mail-Adresse bestätigen',
8
- text: `Bitte bestätige deine E-Mail-Adresse:\n\n${url}`,
7
+ subject: 'Verify your email address',
8
+ text: `Please verify your email address:\n\n${url}`,
9
9
  });
10
10
  },
11
11
  async sendResetPassword({ user, url }) {
12
12
  await service.send({
13
13
  to: user.email,
14
- subject: 'Passwort zurücksetzen',
15
- text: `Hier kannst du dein Passwort zurücksetzen:\n\n${url}`,
14
+ subject: 'Reset your password',
15
+ text: `You can reset your password here:\n\n${url}`,
16
16
  });
17
17
  },
18
18
  async sendInvitationEmail({ id, email, organization }) {
19
19
  const url = options.invitationURL(id);
20
20
  await service.send({
21
21
  to: email,
22
- subject: 'Einladung zu einer Organisation',
23
- text: `Du wurdest zu ${organization.name} eingeladen:\n\n${url}`,
22
+ subject: 'Organization invitation',
23
+ text: `You have been invited to join ${organization.name}:\n\n${url}`,
24
24
  });
25
25
  },
26
26
  };
package/dist/index.d.ts CHANGED
@@ -27,14 +27,46 @@ export type BetterAuthClient = {
27
27
  error: unknown;
28
28
  }>;
29
29
  };
30
- export declare function betterAuthPlugin(client: BetterAuthClient, options?: {
30
+ /**
31
+ * The host's Better Auth client, wrapped: a Better Auth client answers every property,
32
+ * `subscribe` included, so the runtime would observe a bare client as a service.
33
+ */
34
+ export type BetterAuthClientService = {
35
+ readonly client: BetterAuthClient;
36
+ };
37
+ /**
38
+ * Provide it once, for example in `src/services/better-auth-client.ts`:
39
+ * `export default defineService(() => ({ client: authClient }), { provides: betterAuthClient })`.
40
+ * The name is not `auth.client`: `auth` is already the authentication service itself.
41
+ */
42
+ export declare const betterAuthClient: import("@bitakit/core").ServiceKey<BetterAuthClientService, "better-auth-client">;
43
+ /** Options from `configs/better-auth.ts` (package manifest `configuration: 'better-auth'`). */
44
+ export type BetterAuthOptions = {
31
45
  paths?: AuthPaths;
46
+ /** Optional SDK-native login flow; UI otherwise navigates to `paths.signIn`. */
32
47
  signIn?: (options?: AuthSignInOptions) => Promise<void>;
48
+ /** Replaces the client's `signOut()`, for example to clear host state first. */
33
49
  signOut?: () => Promise<void>;
34
- }): {
50
+ };
51
+ /**
52
+ * Better Auth as the `auth` service. The client arrives through the `betterAuthClient`
53
+ * contract; the options come from `configs/better-auth.ts`. Paths are validated here, so an
54
+ * invalid path fails when the configuration is created.
55
+ */
56
+ export declare function betterAuthPlugin(options?: BetterAuthOptions): {
35
57
  readonly id: "better-auth";
36
- readonly services: readonly [import("@bitakit/core").ServiceDefinition<AuthService> & {
37
- id: import("@bitakit/core").ServiceKey<AuthService>;
38
- }];
58
+ readonly metadata: {
59
+ readonly name: "Better Auth";
60
+ readonly description: "The authentication service on the Better Auth client session.";
61
+ };
62
+ readonly services: {
63
+ readonly session: import("@bitakit/core").ServiceOptions & {
64
+ readonly kind: "service";
65
+ create(context: import("@bitakit/core").ServiceContext): AuthService;
66
+ } & {
67
+ readonly requires: readonly [import("@bitakit/core").ServiceKey<BetterAuthClientService, "better-auth-client">];
68
+ readonly provides: import("@bitakit/core").ServiceKey<AuthService, "auth">;
69
+ };
70
+ };
39
71
  };
40
72
  export {};
package/dist/index.js CHANGED
@@ -1,19 +1,29 @@
1
- import { definePlugin, provideService, authService, configureAuthPaths, } from '@bitakit/core';
2
- export function betterAuthPlugin(client, options = {}) {
1
+ import { definePlugin, defineService, getService, defineContract, authService, configureAuthPaths, } from '@bitakit/core';
2
+ /**
3
+ * Provide it once, for example in `src/services/better-auth-client.ts`:
4
+ * `export default defineService(() => ({ client: authClient }), { provides: betterAuthClient })`.
5
+ * The name is not `auth.client`: `auth` is already the authentication service itself.
6
+ */
7
+ export const betterAuthClient = defineContract('better-auth-client').of();
8
+ /** The `auth` contract on the session atom of the provided Better Auth client. */
9
+ function sessionAuth(client, options, paths) {
3
10
  const sessionAtom = client.$store.atoms.session;
4
11
  if (!sessionAtom)
5
12
  throw new Error('Better Auth client has no session atom.');
6
13
  let previous;
7
14
  let snapshot;
8
- const auth = {
9
- paths: options.paths ? configureAuthPaths(options.paths) : undefined,
15
+ return {
16
+ paths,
10
17
  signIn: options.signIn,
11
18
  getSnapshot() {
12
19
  const session = sessionAtom.get();
13
20
  if (session !== previous) {
14
21
  previous = session;
22
+ // The active organization scopes organization settings; only the organization plugin sets it.
23
+ const active = session.data?.session?.activeOrganizationId;
15
24
  snapshot = {
16
25
  user: session.data?.user ?? null,
26
+ organizationId: active ?? null,
17
27
  pending: session.isPending,
18
28
  error: session.error,
19
29
  };
@@ -31,8 +41,22 @@ export function betterAuthPlugin(client, options = {}) {
31
41
  throw result.error;
32
42
  },
33
43
  };
44
+ }
45
+ /**
46
+ * Better Auth as the `auth` service. The client arrives through the `betterAuthClient`
47
+ * contract; the options come from `configs/better-auth.ts`. Paths are validated here, so an
48
+ * invalid path fails when the configuration is created.
49
+ */
50
+ export function betterAuthPlugin(options = {}) {
51
+ const paths = options.paths ? configureAuthPaths(options.paths) : undefined;
34
52
  return definePlugin({
35
53
  id: 'better-auth',
36
- services: [provideService(authService, { create: () => auth })],
54
+ metadata: {
55
+ name: 'Better Auth',
56
+ description: 'The authentication service on the Better Auth client session.',
57
+ },
58
+ services: {
59
+ session: defineService(({ services }) => sessionAuth(getService(services, betterAuthClient).client, options, paths), { requires: [betterAuthClient], provides: authService }),
60
+ },
37
61
  });
38
62
  }
@@ -16,7 +16,8 @@ export function sessionOrganizationBackend(client, authenticated, signedOut = au
16
16
  if (current.data?.user.id === previous.data?.user.id &&
17
17
  current.data?.user.emailVerified === previous.data?.user.emailVerified &&
18
18
  current.data?.session?.id === previous.data?.session?.id &&
19
- current.data?.session?.activeOrganizationId === previous.data?.session?.activeOrganizationId &&
19
+ current.data?.session?.activeOrganizationId ===
20
+ previous.data?.session?.activeOrganizationId &&
20
21
  current.isPending === previous.isPending &&
21
22
  current.error === previous.error)
22
23
  return;
@@ -85,7 +85,7 @@ export function betterAuthOrganizations(client, extensions = {}) {
85
85
  canManage: false,
86
86
  incomingInvitations,
87
87
  incomingInvitationsError: verificationRequired
88
- ? 'Bitte bestätige deine E-Mail-Adresse, um Einladungen zu sehen.'
88
+ ? 'Verify your email address to see invitations.'
89
89
  : undefined,
90
90
  };
91
91
  if (!active.data)
@@ -148,7 +148,7 @@ export function betterAuthOrganizations(client, extensions = {}) {
148
148
  viewerMemberId: current.id,
149
149
  incomingInvitations,
150
150
  incomingInvitationsError: verificationRequired
151
- ? 'Bitte bestätige deine E-Mail-Adresse, um Einladungen zu sehen.'
151
+ ? 'Verify your email address to see invitations.'
152
152
  : undefined,
153
153
  };
154
154
  },
@@ -0,0 +1,2 @@
1
+ /** Package plugin entry: `bitakit.plugin` in package.json points here. */
2
+ export { betterAuthPlugin as default } from './index.js';
package/dist/plugin.js ADDED
@@ -0,0 +1,2 @@
1
+ /** Package plugin entry: `bitakit.plugin` in package.json points here. */
2
+ export { betterAuthPlugin as default } from './index.js';
package/package.json CHANGED
@@ -1,7 +1,11 @@
1
1
  {
2
2
  "name": "@bitakit/better-auth",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "type": "module",
5
+ "bitakit": {
6
+ "plugin": "./plugin",
7
+ "configuration": "better-auth"
8
+ },
5
9
  "sideEffects": false,
6
10
  "files": [
7
11
  "dist",
@@ -12,6 +16,10 @@
12
16
  "types": "./dist/index.d.ts",
13
17
  "default": "./dist/index.js"
14
18
  },
19
+ "./plugin": {
20
+ "types": "./dist/plugin.d.ts",
21
+ "default": "./dist/plugin.js"
22
+ },
15
23
  "./organizations": {
16
24
  "types": "./dist/organizations.d.ts",
17
25
  "default": "./dist/organizations.js"
@@ -23,27 +31,28 @@
23
31
  "./client": {
24
32
  "types": "./dist/client.d.ts",
25
33
  "default": "./dist/client.js"
26
- }
34
+ },
35
+ "./package.json": "./package.json"
27
36
  },
28
37
  "scripts": {
29
38
  "build": "tsc -p tsconfig.json",
30
39
  "test": "npm run build && node --test tests/*.test.mjs"
31
40
  },
32
41
  "dependencies": {
33
- "@bitakit/core": "0.1.1",
34
- "@better-auth/api-key": "1.7.5"
42
+ "@bitakit/core": "^0.2.0",
43
+ "@better-auth/api-key": "^1.7.5"
35
44
  },
36
45
  "peerDependencies": {
37
46
  "better-auth": "^1.7.5",
38
47
  "react": "^19.0.0",
39
- "@bitakit/organizations": "0.1.0",
40
- "@bitakit/email": "0.1.0"
48
+ "@bitakit/organizations": "^0.2.0",
49
+ "@bitakit/email": "^0.2.0"
41
50
  },
42
51
  "devDependencies": {
43
52
  "typescript": "^5",
44
53
  "@types/react": "^19",
45
- "@bitakit/organizations": "0.1.0",
46
- "@bitakit/email": "0.1.0"
54
+ "@bitakit/organizations": "^0.2.0",
55
+ "@bitakit/email": "^0.2.0"
47
56
  },
48
57
  "peerDependenciesMeta": {
49
58
  "better-auth": {
@@ -56,7 +65,7 @@
56
65
  "optional": true
57
66
  }
58
67
  },
59
- "description": "Better Auth plugin, organization adapter and server email callbacks for SaaS Foundation.",
68
+ "description": "BitaKit plugin for Better Auth: authentication service, organization adapter and server email callbacks.",
60
69
  "license": "MIT",
61
70
  "repository": {
62
71
  "type": "git",
@@ -65,5 +74,12 @@
65
74
  },
66
75
  "publishConfig": {
67
76
  "access": "public"
68
- }
77
+ },
78
+ "keywords": [
79
+ "bitakit",
80
+ "ai-agents",
81
+ "composition",
82
+ "better-auth",
83
+ "authentication"
84
+ ]
69
85
  }