@mframework/adapter-betterauth 0.0.10 → 0.0.11

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/dist/auth.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ import type { AuthAdapter, TransportAdapter } from '@mframework/core';
2
+ export declare const createAuthAdapter: (transport: TransportAdapter) => AuthAdapter;
package/dist/auth.js ADDED
@@ -0,0 +1,31 @@
1
+ import { unwrap } from './utils.js';
2
+ export const createAuthAdapter = (transport) => ({
3
+ async login(input) {
4
+ const res = await transport.request('POST', '/login', {
5
+ body: input
6
+ });
7
+ return unwrap(res);
8
+ },
9
+ async register(input) {
10
+ const res = await transport.request('POST', '/register', {
11
+ body: input
12
+ });
13
+ return unwrap(res);
14
+ },
15
+ async logout() {
16
+ const res = await transport.request('POST', '/logout');
17
+ return unwrap({ ...res, data: true });
18
+ },
19
+ async getSession() {
20
+ const res = await transport.request('GET', '/session');
21
+ return unwrap(res);
22
+ },
23
+ async refresh() {
24
+ const res = await transport.request('POST', '/refresh');
25
+ return unwrap(res);
26
+ },
27
+ async getUser() {
28
+ const res = await transport.request('GET', '/user');
29
+ return unwrap(res);
30
+ }
31
+ });
@@ -0,0 +1,11 @@
1
+ import "dotenv/config";
2
+ export declare const auth: import("better-auth").Auth<{
3
+ experimental: {
4
+ joins: true;
5
+ };
6
+ database: (options: import("better-auth").BetterAuthOptions) => import("better-auth").DBAdapter<import("better-auth").BetterAuthOptions>;
7
+ emailAndPassword: {
8
+ enabled: true;
9
+ };
10
+ }>;
11
+ export type Auth = typeof auth;
@@ -0,0 +1,12 @@
1
+ import "dotenv/config";
2
+ import { betterAuth } from "better-auth";
3
+ import { prismaAdapter } from "better-auth/adapters/prisma";
4
+ import { prisma } from "@mframework/core";
5
+ // Create and export the BetterAuth runtime instance using the centralized
6
+ // Prisma client exported from packages/modules/api. Layers can import `auth`
7
+ // from this package to get the configured auth instance.
8
+ export const auth = betterAuth({
9
+ experimental: { joins: true },
10
+ database: prismaAdapter(prisma, { provider: 'postgresql' }),
11
+ emailAndPassword: { enabled: true }
12
+ });
@@ -0,0 +1,8 @@
1
+ export interface AuthConfig {
2
+ baseUrl: any;
3
+ authProvider: string;
4
+ authUrl?: string;
5
+ sessionCookieName?: string;
6
+ }
7
+ export declare function setAuthConfig(newConfig: Partial<AuthConfig>): void;
8
+ export declare function getAuthConfig(): AuthConfig;
package/dist/config.js ADDED
@@ -0,0 +1,12 @@
1
+ let config = {
2
+ authProvider: 'better-auth',
3
+ authUrl: '',
4
+ sessionCookieName: 'session',
5
+ baseUrl: undefined
6
+ };
7
+ export function setAuthConfig(newConfig) {
8
+ config = { ...config, ...newConfig };
9
+ }
10
+ export function getAuthConfig() {
11
+ return config;
12
+ }
@@ -0,0 +1,17 @@
1
+ export interface FrameworkContext {
2
+ getRequestURL?(): string;
3
+ getRequestHeaders?(): Record<string, string>;
4
+ getConfig?(): any;
5
+ reloadApp?(): void;
6
+ state?<T>(key: string, init: () => T): {
7
+ value: T;
8
+ };
9
+ }
10
+ /**
11
+ * Frameworks (Nuxt, React, etc.) call this once during initialization.
12
+ */
13
+ export declare function setFrameworkContext(newCtx: FrameworkContext): void;
14
+ /**
15
+ * Auth providers use this to access framework-specific helpers.
16
+ */
17
+ export declare function getFrameworkContext(): FrameworkContext;
@@ -0,0 +1,13 @@
1
+ let ctx = {};
2
+ /**
3
+ * Frameworks (Nuxt, React, etc.) call this once during initialization.
4
+ */
5
+ export function setFrameworkContext(newCtx) {
6
+ ctx = { ...ctx, ...newCtx };
7
+ }
8
+ /**
9
+ * Auth providers use this to access framework-specific helpers.
10
+ */
11
+ export function getFrameworkContext() {
12
+ return ctx;
13
+ }
package/dist/index.d.ts CHANGED
@@ -2,24 +2,24 @@ export declare const installAuthAdapter: (config: {
2
2
  baseUrl: string;
3
3
  apiKey?: string;
4
4
  }) => void;
5
- export { auth, Auth } from './src/betterauth';
6
- export { default as BetterAuthProvider } from './src/provider';
7
- export { getAuthPlugins } from './src/plugins';
8
- export * from './src/types';
9
- export * from './src/auth';
10
- export * from './src/utils';
11
- export * from './src/transport';
12
- export * from './src/framework';
13
- export * from './src/registry';
14
- export * from './src/validation';
15
- export * from './src/config';
5
+ export { auth, Auth } from './betterauth';
6
+ export { default as BetterAuthProvider } from './provider';
7
+ export { getAuthPlugins } from './plugins';
8
+ export * from './types';
9
+ export * from './auth';
10
+ export * from './utils';
11
+ export * from './transport';
12
+ export * from './framework';
13
+ export * from './registry';
14
+ export * from './validation';
15
+ export * from './config';
16
16
  export * from 'better-auth/client/plugins';
17
17
  export * from '@polar-sh/better-auth';
18
18
  export * as BetterAuth from 'better-auth';
19
- export { getAuthConfig } from './src/config';
20
- export { getFrameworkContext } from './src/framework';
21
- export type { AuthProvider } from './src/types';
22
- export { registerAuthProvider } from './src/registry';
19
+ export { getAuthConfig } from './config';
20
+ export { getFrameworkContext } from './framework';
21
+ export type { AuthProvider } from './types';
22
+ export { registerAuthProvider } from './registry';
23
23
  export { polarClient } from '@polar-sh/better-auth';
24
24
  export { adminClient, inferAdditionalFields } from 'better-auth/client/plugins';
25
25
  export { stripeClient } from '@better-auth/stripe/client';
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { setAuthAdapter } from '@mframework/core';
2
- import { createAuthTransport } from './src/transport';
3
- import { createAuthAdapter } from './src/auth';
2
+ import { createAuthTransport } from './transport';
3
+ import { createAuthAdapter } from './auth';
4
4
  export const installAuthAdapter = (config) => {
5
5
  const transport = createAuthTransport(config);
6
6
  setAuthAdapter(createAuthAdapter(transport));
@@ -8,23 +8,23 @@ export const installAuthAdapter = (config) => {
8
8
  // Export the server-side BetterAuth instance (if present) so other layers can
9
9
  // import the runtime `auth` instance from this package. The file is optional
10
10
  // and will only exist when BetterAuth is configured for the adapter.
11
- export { auth } from './src/betterauth';
12
- export { default as BetterAuthProvider } from './src/provider';
13
- export { getAuthPlugins } from './src/plugins';
14
- export * from './src/types';
15
- export * from './src/auth';
16
- export * from './src/utils';
17
- export * from './src/transport';
18
- export * from './src/framework';
19
- export * from './src/registry';
20
- export * from './src/validation';
21
- export * from './src/config';
11
+ export { auth } from './betterauth';
12
+ export { default as BetterAuthProvider } from './provider';
13
+ export { getAuthPlugins } from './plugins';
14
+ export * from './types';
15
+ export * from './auth';
16
+ export * from './utils';
17
+ export * from './transport';
18
+ export * from './framework';
19
+ export * from './registry';
20
+ export * from './validation';
21
+ export * from './config';
22
22
  export * from 'better-auth/client/plugins';
23
23
  export * from '@polar-sh/better-auth';
24
24
  export * as BetterAuth from 'better-auth';
25
- export { getAuthConfig } from './src/config';
26
- export { getFrameworkContext } from './src/framework';
27
- export { registerAuthProvider } from './src/registry';
25
+ export { getAuthConfig } from './config';
26
+ export { getFrameworkContext } from './framework';
27
+ export { registerAuthProvider } from './registry';
28
28
  export { polarClient } from '@polar-sh/better-auth';
29
29
  export { adminClient, inferAdditionalFields } from 'better-auth/client/plugins';
30
30
  export { stripeClient } from '@better-auth/stripe/client';
@@ -0,0 +1,5 @@
1
+ export type AuthPluginOptions = {
2
+ subscription?: boolean;
3
+ };
4
+ export declare function getAuthPlugins(opts?: AuthPluginOptions): any[];
5
+ export default getAuthPlugins;
@@ -0,0 +1,19 @@
1
+ import { stripeClient } from '@better-auth/stripe/client';
2
+ import { polarClient } from '@polar-sh/better-auth';
3
+ import { adminClient, inferAdditionalFields } from 'better-auth/client/plugins';
4
+ export function getAuthPlugins(opts = {}) {
5
+ const { subscription = true } = opts;
6
+ return [
7
+ inferAdditionalFields({
8
+ user: {
9
+ polarCustomerId: {
10
+ type: 'string'
11
+ }
12
+ }
13
+ }),
14
+ adminClient(),
15
+ polarClient(),
16
+ stripeClient({ subscription })
17
+ ];
18
+ }
19
+ export default getAuthPlugins;
@@ -0,0 +1,2 @@
1
+ declare const BetterAuthProvider: any;
2
+ export default BetterAuthProvider;
@@ -0,0 +1,84 @@
1
+ import * as BetterAuth from 'better-auth';
2
+ import { getAuthConfig } from './config.js';
3
+ import { getFrameworkContext } from './framework.js';
4
+ // Create a single shared Better Auth client instance
5
+ let client = null;
6
+ function resolveClientFactory() {
7
+ return BetterAuth.Client ?? BetterAuth.default ?? BetterAuth;
8
+ }
9
+ function getClient() {
10
+ if (client)
11
+ return client;
12
+ const config = getAuthConfig();
13
+ const ctx = getFrameworkContext();
14
+ const Client = resolveClientFactory();
15
+ client = Client({
16
+ baseURL: config.baseUrl,
17
+ fetch: async (url, options = {}) => {
18
+ const baseHeaders = ctx.getRequestHeaders?.() || {};
19
+ let optionHeaders = {};
20
+ if (options.headers instanceof Headers) {
21
+ options.headers.forEach((value, key) => {
22
+ optionHeaders[key] = value;
23
+ });
24
+ }
25
+ else if (Array.isArray(options.headers)) {
26
+ for (const [k, v] of options.headers) {
27
+ optionHeaders[k] = v;
28
+ }
29
+ }
30
+ else if (typeof options.headers === 'object' && options.headers !== null) {
31
+ optionHeaders = options.headers;
32
+ }
33
+ const headers = {
34
+ ...baseHeaders,
35
+ ...optionHeaders
36
+ };
37
+ return fetch(url, { ...options, headers });
38
+ }
39
+ });
40
+ return client;
41
+ }
42
+ const BetterAuthProvider = {
43
+ async login(credentials) {
44
+ const client = getClient();
45
+ const result = await client.signIn(credentials);
46
+ if (result.error) {
47
+ throw new Error(result.error.message || 'Login failed');
48
+ }
49
+ return result.data;
50
+ },
51
+ async logout() {
52
+ const client = getClient();
53
+ await client.signOut();
54
+ const ctx = getFrameworkContext();
55
+ ctx.reloadApp?.();
56
+ },
57
+ async session() {
58
+ const client = getClient();
59
+ const result = await client.session();
60
+ if (result.error) {
61
+ return null;
62
+ }
63
+ return result.data;
64
+ },
65
+ async register(data) {
66
+ const client = getClient();
67
+ const result = await client.signUp(data);
68
+ if (result.error) {
69
+ throw new Error(result.error.message || 'Registration failed');
70
+ }
71
+ return result.data;
72
+ },
73
+ async refresh() {
74
+ const client = getClient();
75
+ const result = await client.refresh();
76
+ if (result.error) {
77
+ throw new Error(result.error.message || 'Session refresh failed');
78
+ }
79
+ return result.data;
80
+ }
81
+ };
82
+ // Register the provider under the canonical name so other layers can discover
83
+ // it using the existing registry mechanism.
84
+ export default BetterAuthProvider;
@@ -0,0 +1,4 @@
1
+ import type { AuthProvider } from './types.js';
2
+ export declare function registerAuthProvider(name: string, provider: AuthProvider): void;
3
+ export declare function setActiveAuthProvider(name: string): void;
4
+ export declare function getAuthProvider(): AuthProvider;
@@ -0,0 +1,21 @@
1
+ // allow missing entries in the map so TypeScript understands runtime checks
2
+ const providers = {};
3
+ let activeProvider = null;
4
+ export function registerAuthProvider(name, provider) {
5
+ providers[name] = provider;
6
+ }
7
+ export function setActiveAuthProvider(name) {
8
+ if (!providers[name]) {
9
+ throw new Error(`Auth provider "${name}" is not registered`);
10
+ }
11
+ activeProvider = name;
12
+ }
13
+ export function getAuthProvider() {
14
+ if (!activeProvider) {
15
+ throw new Error('No active auth provider has been set');
16
+ }
17
+ const prov = providers[activeProvider];
18
+ if (!prov)
19
+ throw new Error(`Auth provider "${activeProvider}" not found`);
20
+ return prov;
21
+ }
@@ -0,0 +1,5 @@
1
+ import type { TransportAdapter } from '@mframework/core';
2
+ export declare const createAuthTransport: (config: {
3
+ baseUrl: string;
4
+ apiKey?: string;
5
+ }) => TransportAdapter;
@@ -0,0 +1,42 @@
1
+ export const createAuthTransport = (config) => {
2
+ return {
3
+ async request(method, path, options = {}) {
4
+ try {
5
+ const url = new URL(path, config.baseUrl);
6
+ if (options.query) {
7
+ Object.entries(options.query).forEach(([key, value]) => {
8
+ url.searchParams.set(key, String(value));
9
+ });
10
+ }
11
+ const res = await fetch(url.toString(), {
12
+ method,
13
+ headers: {
14
+ 'Content-Type': 'application/json',
15
+ ...(config.apiKey ? { Authorization: `Bearer ${config.apiKey}` } : {}),
16
+ ...(options.headers || {})
17
+ },
18
+ body: options.body ? JSON.stringify(options.body) : undefined
19
+ });
20
+ const data = await res.json().catch(() => null);
21
+ if (!res.ok) {
22
+ return {
23
+ status: res.status,
24
+ data: null,
25
+ error: data?.message || 'Unknown error'
26
+ };
27
+ }
28
+ return {
29
+ status: res.status,
30
+ data
31
+ };
32
+ }
33
+ catch (err) {
34
+ return {
35
+ status: 500,
36
+ data: null,
37
+ error: err.message || 'Transport error'
38
+ };
39
+ }
40
+ }
41
+ };
42
+ };
@@ -0,0 +1,29 @@
1
+ export interface AuthSession {
2
+ user: {
3
+ id: string;
4
+ email?: string;
5
+ name?: string;
6
+ avatarUrl?: string;
7
+ [key: string]: any;
8
+ };
9
+ expiresAt?: string;
10
+ [key: string]: any;
11
+ }
12
+ export interface AuthCredentials {
13
+ email: string;
14
+ password: string;
15
+ [key: string]: any;
16
+ }
17
+ export interface AuthRegistration {
18
+ email: string;
19
+ password: string;
20
+ name?: string;
21
+ [key: string]: any;
22
+ }
23
+ export interface AuthProvider {
24
+ login(credentials: AuthCredentials): Promise<AuthSession>;
25
+ logout(): Promise<void>;
26
+ session(): Promise<AuthSession | null>;
27
+ register?(data: AuthRegistration): Promise<AuthSession>;
28
+ refresh?(): Promise<AuthSession>;
29
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,2 @@
1
+ import type { APIResponse, Result } from '@mframework/core';
2
+ export declare const unwrap: <T>(response: APIResponse<T>) => Result<T>;
package/dist/utils.js ADDED
@@ -0,0 +1,12 @@
1
+ export const unwrap = (response) => {
2
+ if (response.error) {
3
+ return {
4
+ ok: false,
5
+ error: response.error
6
+ };
7
+ }
8
+ return {
9
+ ok: true,
10
+ data: response.data
11
+ };
12
+ };
@@ -0,0 +1,22 @@
1
+ import { z } from 'zod';
2
+ export declare const loginSchema: z.ZodObject<{
3
+ email: z.ZodString;
4
+ password: z.ZodString;
5
+ }, z.core.$strip>;
6
+ export type LoginInput = z.infer<typeof loginSchema>;
7
+ export declare const registerSchema: z.ZodObject<{
8
+ email: z.ZodString;
9
+ password: z.ZodString;
10
+ confirmPassword: z.ZodString;
11
+ }, z.core.$strip>;
12
+ export type RegisterInput = z.infer<typeof registerSchema>;
13
+ export declare const forgotPasswordSchema: z.ZodObject<{
14
+ email: z.ZodString;
15
+ }, z.core.$strip>;
16
+ export type ForgotPasswordInput = z.infer<typeof forgotPasswordSchema>;
17
+ export declare const resetPasswordSchema: z.ZodObject<{
18
+ token: z.ZodString;
19
+ password: z.ZodString;
20
+ confirmPassword: z.ZodString;
21
+ }, z.core.$strip>;
22
+ export type ResetPasswordInput = z.infer<typeof resetPasswordSchema>;
@@ -0,0 +1,21 @@
1
+ import { z } from 'zod';
2
+ export const loginSchema = z.object({
3
+ email: z.string().email(),
4
+ password: z.string().min(8)
5
+ });
6
+ export const registerSchema = z.object({
7
+ email: z.string().email(),
8
+ password: z.string().min(8),
9
+ confirmPassword: z.string().min(8)
10
+ }).refine((data) => data.password === data.confirmPassword, {
11
+ message: 'Passwords do not match',
12
+ path: ['confirmPassword']
13
+ });
14
+ export const forgotPasswordSchema = z.object({
15
+ email: z.string().email()
16
+ });
17
+ export const resetPasswordSchema = z.object({
18
+ token: z.string(),
19
+ password: z.string().min(8),
20
+ confirmPassword: z.string().min(8)
21
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mframework/adapter-betterauth",
3
- "version": "0.0.10",
3
+ "version": "0.0.11",
4
4
  "description": "Official Better-Auth adapter for M Framework Auth Layer",
5
5
  "main": "dist/src/index.js",
6
6
  "types": "dist/src/index.d.ts",