@krutai/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.
@@ -0,0 +1,242 @@
1
+ # @krutai/auth - AI Assistant Reference Guide
2
+
3
+ ## Package Overview
4
+
5
+ `@krutai/auth` is an authentication package for KrutAI that wraps Better Auth with mandatory API key validation. This package requires users to provide a valid API key to access authentication features.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ npm install @krutai/auth
11
+ ```
12
+
13
+ ## Core Concepts
14
+
15
+ ### API Key Requirement
16
+ - **MANDATORY**: All users must provide a valid API key
17
+ - API key is validated on initialization (can be disabled with `validateOnInit: false`)
18
+ - Throws `ApiKeyValidationError` if API key is missing or invalid
19
+
20
+ ### Better Auth Integration
21
+ - Wraps the Better Auth library
22
+ - Provides access to full Better Auth API via `getBetterAuth()`
23
+ - See Better Auth docs: https://www.better-auth.com/docs
24
+
25
+ ## Main Exports
26
+
27
+ ### Classes
28
+
29
+ #### `KrutAuth`
30
+ Main authentication client class.
31
+
32
+ **Constructor:**
33
+ ```typescript
34
+ new KrutAuth(config: KrutAuthConfig)
35
+ ```
36
+
37
+ **Methods:**
38
+ - `initialize(): Promise<void>` - Validates API key and initializes Better Auth
39
+ - `getBetterAuth(): ReturnType<typeof betterAuth>` - Returns Better Auth instance
40
+ - `isInitialized(): boolean` - Check if initialized
41
+ - `getApiKey(): string` - Get the API key
42
+ - `signIn()` - Convenience method (returns Better Auth instance)
43
+ - `signOut()` - Convenience method (returns Better Auth instance)
44
+ - `getSession()` - Convenience method (returns Better Auth instance)
45
+
46
+ ### Types
47
+
48
+ #### `KrutAuthConfig`
49
+ ```typescript
50
+ interface KrutAuthConfig {
51
+ apiKey: string; // REQUIRED
52
+ betterAuthOptions?: Partial<BetterAuthOptions>;
53
+ validateOnInit?: boolean; // default: true
54
+ validationEndpoint?: string;
55
+ }
56
+ ```
57
+
58
+ #### `AuthSession`
59
+ ```typescript
60
+ interface AuthSession {
61
+ user: {
62
+ id: string;
63
+ email: string;
64
+ name?: string;
65
+ [key: string]: unknown;
66
+ };
67
+ session: {
68
+ id: string;
69
+ expiresAt: Date;
70
+ [key: string]: unknown;
71
+ };
72
+ }
73
+ ```
74
+
75
+ ### Errors
76
+
77
+ #### `ApiKeyValidationError`
78
+ Thrown when API key validation fails.
79
+
80
+ **Common causes:**
81
+ - API key is missing or empty
82
+ - API key is too short (< 10 characters)
83
+ - API key validation fails against backend
84
+
85
+ ## Usage Examples
86
+
87
+ ### Example 1: Basic Usage with Async Validation
88
+
89
+ ```typescript
90
+ import { KrutAuth } from '@krutai/auth';
91
+
92
+ const auth = new KrutAuth({
93
+ apiKey: 'your-api-key-here',
94
+ betterAuthOptions: {
95
+ database: {
96
+ // your database config
97
+ }
98
+ }
99
+ });
100
+
101
+ // Initialize and validate API key
102
+ await auth.initialize();
103
+
104
+ // Get Better Auth instance
105
+ const betterAuth = auth.getBetterAuth();
106
+ ```
107
+
108
+ ### Example 2: Skip Async Validation
109
+
110
+ ```typescript
111
+ import { KrutAuth } from '@krutai/auth';
112
+
113
+ const auth = new KrutAuth({
114
+ apiKey: 'your-api-key-here',
115
+ validateOnInit: false,
116
+ betterAuthOptions: {
117
+ // config
118
+ }
119
+ });
120
+
121
+ // No need to call initialize()
122
+ const betterAuth = auth.getBetterAuth();
123
+ ```
124
+
125
+ ### Example 3: Error Handling
126
+
127
+ ```typescript
128
+ import { KrutAuth, ApiKeyValidationError } from '@krutai/auth';
129
+
130
+ try {
131
+ const auth = new KrutAuth({
132
+ apiKey: 'invalid-key'
133
+ });
134
+ await auth.initialize();
135
+ } catch (error) {
136
+ if (error instanceof ApiKeyValidationError) {
137
+ console.error('API key validation failed:', error.message);
138
+ }
139
+ }
140
+ ```
141
+
142
+ ### Example 4: Using Better Auth Features
143
+
144
+ ```typescript
145
+ import { KrutAuth } from '@krutai/auth';
146
+
147
+ const auth = new KrutAuth({
148
+ apiKey: process.env.KRUTAI_API_KEY!,
149
+ betterAuthOptions: {
150
+ database: {
151
+ provider: 'postgres',
152
+ url: process.env.DATABASE_URL
153
+ },
154
+ emailAndPassword: {
155
+ enabled: true
156
+ }
157
+ }
158
+ });
159
+
160
+ await auth.initialize();
161
+
162
+ // Access full Better Auth API
163
+ const betterAuth = auth.getBetterAuth();
164
+
165
+ // Use Better Auth methods directly
166
+ // See: https://www.better-auth.com/docs
167
+ ```
168
+
169
+ ## Common Patterns
170
+
171
+ ### Pattern 1: Environment Variable API Key
172
+
173
+ ```typescript
174
+ const auth = new KrutAuth({
175
+ apiKey: process.env.KRUTAI_API_KEY || '',
176
+ betterAuthOptions: {
177
+ // config
178
+ }
179
+ });
180
+ ```
181
+
182
+ ### Pattern 2: Singleton Instance
183
+
184
+ ```typescript
185
+ // auth.ts
186
+ let authInstance: KrutAuth | null = null;
187
+
188
+ export async function getAuth(): Promise<KrutAuth> {
189
+ if (!authInstance) {
190
+ authInstance = new KrutAuth({
191
+ apiKey: process.env.KRUTAI_API_KEY!,
192
+ betterAuthOptions: {
193
+ // config
194
+ }
195
+ });
196
+ await authInstance.initialize();
197
+ }
198
+ return authInstance;
199
+ }
200
+ ```
201
+
202
+ ### Pattern 3: Conditional Initialization
203
+
204
+ ```typescript
205
+ const auth = new KrutAuth({
206
+ apiKey: process.env.KRUTAI_API_KEY!,
207
+ validateOnInit: process.env.NODE_ENV === 'production'
208
+ });
209
+
210
+ if (process.env.NODE_ENV === 'production') {
211
+ await auth.initialize();
212
+ }
213
+ ```
214
+
215
+ ## TypeScript Support
216
+
217
+ Full TypeScript support with exported types:
218
+
219
+ ```typescript
220
+ import type {
221
+ KrutAuthConfig,
222
+ AuthSession,
223
+ BetterAuthOptions
224
+ } from '@krutai/auth';
225
+ ```
226
+
227
+ ## Important Notes
228
+
229
+ 1. **API Key is Required**: The package will not work without a valid API key
230
+ 2. **Better Auth Wrapper**: This is a wrapper around Better Auth, not a replacement
231
+ 3. **Validation**: By default, API key is validated on `initialize()` call
232
+ 4. **Error Handling**: Always catch `ApiKeyValidationError` for proper error handling
233
+
234
+ ## Related Packages
235
+
236
+ - `krutai` - Main KrutAI package with core utilities
237
+ - Future packages: `@krutai/analytics`, `@krutai/roles`, `@krutai/llm`
238
+
239
+ ## Links
240
+
241
+ - Better Auth Documentation: https://www.better-auth.com/docs
242
+ - GitHub Repository: https://github.com/yourusername/krut_packages
package/README.md ADDED
@@ -0,0 +1,177 @@
1
+ # @krutai/auth
2
+
3
+ Authentication package for KrutAI powered by [Better Auth](https://www.better-auth.com/).
4
+
5
+ ## Features
6
+
7
+ - 🔐 **API Key Protection** - Requires valid API key for access
8
+ - 🚀 **Better Auth Integration** - Built on top of Better Auth
9
+ - 📦 **TypeScript First** - Full type safety and IntelliSense support
10
+ - 🎯 **Simple API** - Easy to use authentication client
11
+ - ⚡ **Dual Format** - Supports both ESM and CommonJS
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ npm install @krutai/auth
17
+ ```
18
+
19
+ ## Quick Start
20
+
21
+ ### Basic Usage
22
+
23
+ ```typescript
24
+ import { KrutAuth } from '@krutai/auth';
25
+
26
+ // Initialize with your API key
27
+ const auth = new KrutAuth({
28
+ apiKey: 'your-krutai-api-key',
29
+ betterAuthOptions: {
30
+ // Better Auth configuration
31
+ database: {
32
+ // Your database configuration
33
+ },
34
+ },
35
+ });
36
+
37
+ // Initialize the client (validates API key)
38
+ await auth.initialize();
39
+
40
+ // Use authentication features
41
+ const session = await auth.getSession();
42
+ ```
43
+
44
+ ### Without Async Initialization
45
+
46
+ If you want to skip async validation on initialization:
47
+
48
+ ```typescript
49
+ const auth = new KrutAuth({
50
+ apiKey: 'your-krutai-api-key',
51
+ validateOnInit: false,
52
+ betterAuthOptions: {
53
+ // Better Auth configuration
54
+ },
55
+ });
56
+
57
+ // No need to call initialize()
58
+ const betterAuth = auth.getBetterAuth();
59
+ ```
60
+
61
+ ## API Reference
62
+
63
+ ### `KrutAuth`
64
+
65
+ Main authentication client class.
66
+
67
+ #### Constructor
68
+
69
+ ```typescript
70
+ new KrutAuth(config: KrutAuthConfig)
71
+ ```
72
+
73
+ **Parameters:**
74
+
75
+ - `config.apiKey` (required): Your KrutAI API key
76
+ - `config.betterAuthOptions` (optional): Better Auth configuration options
77
+ - `config.validateOnInit` (optional): Whether to validate API key on initialization (default: `true`)
78
+ - `config.validationEndpoint` (optional): Custom API validation endpoint
79
+
80
+ **Throws:**
81
+
82
+ - `ApiKeyValidationError` if the API key format is invalid
83
+
84
+ #### Methods
85
+
86
+ ##### `initialize()`
87
+
88
+ Validates the API key and initializes the Better Auth instance.
89
+
90
+ ```typescript
91
+ await auth.initialize();
92
+ ```
93
+
94
+ **Returns:** `Promise<void>`
95
+
96
+ **Throws:** `ApiKeyValidationError` if validation fails
97
+
98
+ ##### `getBetterAuth()`
99
+
100
+ Gets the underlying Better Auth instance for advanced usage.
101
+
102
+ ```typescript
103
+ const betterAuth = auth.getBetterAuth();
104
+ ```
105
+
106
+ **Returns:** `BetterAuth`
107
+
108
+ **Throws:** `Error` if not initialized
109
+
110
+ ##### `isInitialized()`
111
+
112
+ Checks if the client is initialized.
113
+
114
+ ```typescript
115
+ const ready = auth.isInitialized();
116
+ ```
117
+
118
+ **Returns:** `boolean`
119
+
120
+ ##### `getApiKey()`
121
+
122
+ Gets the API key (useful for making authenticated requests).
123
+
124
+ ```typescript
125
+ const apiKey = auth.getApiKey();
126
+ ```
127
+
128
+ **Returns:** `string`
129
+
130
+ ## Error Handling
131
+
132
+ The package throws `ApiKeyValidationError` when:
133
+
134
+ - API key is not provided
135
+ - API key is empty or invalid format
136
+ - API key validation fails (if `validateOnInit` is `true`)
137
+
138
+ ```typescript
139
+ import { KrutAuth, ApiKeyValidationError } from '@krutai/auth';
140
+
141
+ try {
142
+ const auth = new KrutAuth({
143
+ apiKey: 'invalid-key',
144
+ });
145
+ await auth.initialize();
146
+ } catch (error) {
147
+ if (error instanceof ApiKeyValidationError) {
148
+ console.error('API key validation failed:', error.message);
149
+ }
150
+ }
151
+ ```
152
+
153
+ ## Better Auth Integration
154
+
155
+ This package wraps [Better Auth](https://www.better-auth.com/) and adds API key validation. You can access the full Better Auth API through the `getBetterAuth()` method:
156
+
157
+ ```typescript
158
+ const auth = new KrutAuth({ apiKey: 'your-key' });
159
+ await auth.initialize();
160
+
161
+ const betterAuth = auth.getBetterAuth();
162
+ // Use Better Auth features directly
163
+ ```
164
+
165
+ For Better Auth documentation, visit: https://www.better-auth.com/docs
166
+
167
+ ## TypeScript Support
168
+
169
+ Full TypeScript support with exported types:
170
+
171
+ ```typescript
172
+ import type { KrutAuthConfig, AuthSession, BetterAuthOptions } from '@krutai/auth';
173
+ ```
174
+
175
+ ## License
176
+
177
+ MIT
@@ -0,0 +1,155 @@
1
+ import * as better_auth from 'better-auth';
2
+ import { BetterAuthOptions, betterAuth } from 'better-auth';
3
+ export { BetterAuthOptions } from 'better-auth';
4
+
5
+ /**
6
+ * Configuration options for KrutAuth
7
+ */
8
+ interface KrutAuthConfig {
9
+ /**
10
+ * API key for authentication with KrutAI services
11
+ * @required
12
+ */
13
+ apiKey: string;
14
+ /**
15
+ * Better Auth configuration options
16
+ * @see https://www.better-auth.com/docs
17
+ */
18
+ betterAuthOptions?: Partial<BetterAuthOptions>;
19
+ /**
20
+ * Whether to validate the API key on initialization
21
+ * @default true
22
+ */
23
+ validateOnInit?: boolean;
24
+ /**
25
+ * Custom API validation endpoint
26
+ */
27
+ validationEndpoint?: string;
28
+ }
29
+ /**
30
+ * Authentication session interface
31
+ */
32
+ interface AuthSession {
33
+ user: {
34
+ id: string;
35
+ email: string;
36
+ name?: string;
37
+ [key: string]: unknown;
38
+ };
39
+ session: {
40
+ id: string;
41
+ expiresAt: Date;
42
+ [key: string]: unknown;
43
+ };
44
+ }
45
+
46
+ /**
47
+ * KrutAuth - Authentication client for KrutAI
48
+ *
49
+ * This class wraps Better Auth and adds API key validation
50
+ * to ensure only authorized users can access authentication features.
51
+ *
52
+ * @example
53
+ * ```typescript
54
+ * import { KrutAuth } from '@krutai/auth';
55
+ *
56
+ * const auth = new KrutAuth({
57
+ * apiKey: 'your-api-key-here',
58
+ * betterAuthOptions: {
59
+ * // Better Auth configuration
60
+ * }
61
+ * });
62
+ *
63
+ * // Initialize the client (validates API key)
64
+ * await auth.initialize();
65
+ *
66
+ * // Use authentication features
67
+ * const betterAuth = auth.getBetterAuth();
68
+ * ```
69
+ */
70
+ declare class KrutAuth {
71
+ private config;
72
+ private apiKey;
73
+ private betterAuthInstance;
74
+ private initialized;
75
+ /**
76
+ * Creates a new KrutAuth instance
77
+ * @param config - Configuration options
78
+ * @throws {ApiKeyValidationError} If API key is invalid
79
+ */
80
+ constructor(config: KrutAuthConfig);
81
+ /**
82
+ * Initialize the authentication client
83
+ * Validates the API key and sets up Better Auth
84
+ * @throws {ApiKeyValidationError} If API key validation fails
85
+ */
86
+ initialize(): Promise<void>;
87
+ /**
88
+ * Initialize Better Auth instance
89
+ * @private
90
+ */
91
+ private initializeBetterAuth;
92
+ /**
93
+ * Get the Better Auth instance
94
+ * @throws {Error} If not initialized
95
+ */
96
+ getBetterAuth(): ReturnType<typeof betterAuth>;
97
+ /**
98
+ * Check if the client is initialized
99
+ */
100
+ isInitialized(): boolean;
101
+ /**
102
+ * Get the API key (useful for making authenticated requests)
103
+ * @returns The API key
104
+ */
105
+ getApiKey(): string;
106
+ /**
107
+ * Sign in a user
108
+ * This is a convenience method that wraps Better Auth
109
+ * You can access the full Better Auth API via getBetterAuth()
110
+ */
111
+ signIn(): Promise<better_auth.Auth<better_auth.BetterAuthOptions>>;
112
+ /**
113
+ * Sign out the current user
114
+ * You can access the full Better Auth API via getBetterAuth()
115
+ */
116
+ signOut(): Promise<better_auth.Auth<better_auth.BetterAuthOptions>>;
117
+ /**
118
+ * Get the current session
119
+ * You can access the full Better Auth API via getBetterAuth()
120
+ */
121
+ getSession(): Promise<better_auth.Auth<better_auth.BetterAuthOptions>>;
122
+ }
123
+
124
+ /**
125
+ * Custom error class for API key validation failures
126
+ */
127
+ declare class ApiKeyValidationError extends Error {
128
+ constructor(message: string);
129
+ }
130
+ /**
131
+ * Validates the format of an API key
132
+ * @param apiKey - The API key to validate
133
+ * @throws {ApiKeyValidationError} If the API key is invalid
134
+ */
135
+ declare function validateApiKeyFormat(apiKey: string | undefined): void;
136
+ /**
137
+ * Validates an API key against a backend service (optional)
138
+ * This is a placeholder for actual API validation logic
139
+ * @param _apiKey - The API key to validate (currently unused in mock implementation)
140
+ * @returns Promise that resolves if valid, rejects if invalid
141
+ */
142
+ declare function validateApiKeyWithService(_apiKey: string): Promise<boolean>;
143
+
144
+ /**
145
+ * @krutai/auth - Authentication package for KrutAI
146
+ *
147
+ * This package provides authentication functionality powered by Better Auth
148
+ * with API key validation to ensure secure access.
149
+ *
150
+ * @packageDocumentation
151
+ */
152
+
153
+ declare const VERSION = "0.1.0";
154
+
155
+ export { ApiKeyValidationError, type AuthSession, KrutAuth, type KrutAuthConfig, VERSION, validateApiKeyFormat, validateApiKeyWithService };
@@ -0,0 +1,155 @@
1
+ import * as better_auth from 'better-auth';
2
+ import { BetterAuthOptions, betterAuth } from 'better-auth';
3
+ export { BetterAuthOptions } from 'better-auth';
4
+
5
+ /**
6
+ * Configuration options for KrutAuth
7
+ */
8
+ interface KrutAuthConfig {
9
+ /**
10
+ * API key for authentication with KrutAI services
11
+ * @required
12
+ */
13
+ apiKey: string;
14
+ /**
15
+ * Better Auth configuration options
16
+ * @see https://www.better-auth.com/docs
17
+ */
18
+ betterAuthOptions?: Partial<BetterAuthOptions>;
19
+ /**
20
+ * Whether to validate the API key on initialization
21
+ * @default true
22
+ */
23
+ validateOnInit?: boolean;
24
+ /**
25
+ * Custom API validation endpoint
26
+ */
27
+ validationEndpoint?: string;
28
+ }
29
+ /**
30
+ * Authentication session interface
31
+ */
32
+ interface AuthSession {
33
+ user: {
34
+ id: string;
35
+ email: string;
36
+ name?: string;
37
+ [key: string]: unknown;
38
+ };
39
+ session: {
40
+ id: string;
41
+ expiresAt: Date;
42
+ [key: string]: unknown;
43
+ };
44
+ }
45
+
46
+ /**
47
+ * KrutAuth - Authentication client for KrutAI
48
+ *
49
+ * This class wraps Better Auth and adds API key validation
50
+ * to ensure only authorized users can access authentication features.
51
+ *
52
+ * @example
53
+ * ```typescript
54
+ * import { KrutAuth } from '@krutai/auth';
55
+ *
56
+ * const auth = new KrutAuth({
57
+ * apiKey: 'your-api-key-here',
58
+ * betterAuthOptions: {
59
+ * // Better Auth configuration
60
+ * }
61
+ * });
62
+ *
63
+ * // Initialize the client (validates API key)
64
+ * await auth.initialize();
65
+ *
66
+ * // Use authentication features
67
+ * const betterAuth = auth.getBetterAuth();
68
+ * ```
69
+ */
70
+ declare class KrutAuth {
71
+ private config;
72
+ private apiKey;
73
+ private betterAuthInstance;
74
+ private initialized;
75
+ /**
76
+ * Creates a new KrutAuth instance
77
+ * @param config - Configuration options
78
+ * @throws {ApiKeyValidationError} If API key is invalid
79
+ */
80
+ constructor(config: KrutAuthConfig);
81
+ /**
82
+ * Initialize the authentication client
83
+ * Validates the API key and sets up Better Auth
84
+ * @throws {ApiKeyValidationError} If API key validation fails
85
+ */
86
+ initialize(): Promise<void>;
87
+ /**
88
+ * Initialize Better Auth instance
89
+ * @private
90
+ */
91
+ private initializeBetterAuth;
92
+ /**
93
+ * Get the Better Auth instance
94
+ * @throws {Error} If not initialized
95
+ */
96
+ getBetterAuth(): ReturnType<typeof betterAuth>;
97
+ /**
98
+ * Check if the client is initialized
99
+ */
100
+ isInitialized(): boolean;
101
+ /**
102
+ * Get the API key (useful for making authenticated requests)
103
+ * @returns The API key
104
+ */
105
+ getApiKey(): string;
106
+ /**
107
+ * Sign in a user
108
+ * This is a convenience method that wraps Better Auth
109
+ * You can access the full Better Auth API via getBetterAuth()
110
+ */
111
+ signIn(): Promise<better_auth.Auth<better_auth.BetterAuthOptions>>;
112
+ /**
113
+ * Sign out the current user
114
+ * You can access the full Better Auth API via getBetterAuth()
115
+ */
116
+ signOut(): Promise<better_auth.Auth<better_auth.BetterAuthOptions>>;
117
+ /**
118
+ * Get the current session
119
+ * You can access the full Better Auth API via getBetterAuth()
120
+ */
121
+ getSession(): Promise<better_auth.Auth<better_auth.BetterAuthOptions>>;
122
+ }
123
+
124
+ /**
125
+ * Custom error class for API key validation failures
126
+ */
127
+ declare class ApiKeyValidationError extends Error {
128
+ constructor(message: string);
129
+ }
130
+ /**
131
+ * Validates the format of an API key
132
+ * @param apiKey - The API key to validate
133
+ * @throws {ApiKeyValidationError} If the API key is invalid
134
+ */
135
+ declare function validateApiKeyFormat(apiKey: string | undefined): void;
136
+ /**
137
+ * Validates an API key against a backend service (optional)
138
+ * This is a placeholder for actual API validation logic
139
+ * @param _apiKey - The API key to validate (currently unused in mock implementation)
140
+ * @returns Promise that resolves if valid, rejects if invalid
141
+ */
142
+ declare function validateApiKeyWithService(_apiKey: string): Promise<boolean>;
143
+
144
+ /**
145
+ * @krutai/auth - Authentication package for KrutAI
146
+ *
147
+ * This package provides authentication functionality powered by Better Auth
148
+ * with API key validation to ensure secure access.
149
+ *
150
+ * @packageDocumentation
151
+ */
152
+
153
+ declare const VERSION = "0.1.0";
154
+
155
+ export { ApiKeyValidationError, type AuthSession, KrutAuth, type KrutAuthConfig, VERSION, validateApiKeyFormat, validateApiKeyWithService };
package/dist/index.js ADDED
@@ -0,0 +1,141 @@
1
+ 'use strict';
2
+
3
+ var betterAuth = require('better-auth');
4
+
5
+ // src/client.ts
6
+
7
+ // src/validator.ts
8
+ var ApiKeyValidationError = class _ApiKeyValidationError extends Error {
9
+ constructor(message) {
10
+ super(message);
11
+ this.name = "ApiKeyValidationError";
12
+ Object.setPrototypeOf(this, _ApiKeyValidationError.prototype);
13
+ }
14
+ };
15
+ function validateApiKeyFormat(apiKey) {
16
+ if (!apiKey) {
17
+ throw new ApiKeyValidationError(
18
+ "API key is required. Please provide a valid API key to use @krutai/auth."
19
+ );
20
+ }
21
+ if (typeof apiKey !== "string") {
22
+ throw new ApiKeyValidationError("API key must be a string.");
23
+ }
24
+ if (apiKey.trim().length === 0) {
25
+ throw new ApiKeyValidationError("API key cannot be empty.");
26
+ }
27
+ if (apiKey.length < 10) {
28
+ throw new ApiKeyValidationError(
29
+ "API key appears to be invalid. Please check your API key."
30
+ );
31
+ }
32
+ }
33
+ async function validateApiKeyWithService(_apiKey) {
34
+ return Promise.resolve(true);
35
+ }
36
+
37
+ // src/client.ts
38
+ var KrutAuth = class {
39
+ /**
40
+ * Creates a new KrutAuth instance
41
+ * @param config - Configuration options
42
+ * @throws {ApiKeyValidationError} If API key is invalid
43
+ */
44
+ constructor(config) {
45
+ this.config = config;
46
+ validateApiKeyFormat(config.apiKey);
47
+ this.apiKey = config.apiKey;
48
+ if (config.validateOnInit === false) {
49
+ this.initializeBetterAuth();
50
+ }
51
+ }
52
+ apiKey;
53
+ betterAuthInstance = null;
54
+ initialized = false;
55
+ /**
56
+ * Initialize the authentication client
57
+ * Validates the API key and sets up Better Auth
58
+ * @throws {ApiKeyValidationError} If API key validation fails
59
+ */
60
+ async initialize() {
61
+ if (this.initialized) {
62
+ return;
63
+ }
64
+ if (this.config.validateOnInit !== false) {
65
+ await validateApiKeyWithService(this.apiKey);
66
+ }
67
+ this.initializeBetterAuth();
68
+ this.initialized = true;
69
+ }
70
+ /**
71
+ * Initialize Better Auth instance
72
+ * @private
73
+ */
74
+ initializeBetterAuth() {
75
+ this.betterAuthInstance = betterAuth.betterAuth({
76
+ ...this.config.betterAuthOptions
77
+ // Add any custom configuration here
78
+ });
79
+ }
80
+ /**
81
+ * Get the Better Auth instance
82
+ * @throws {Error} If not initialized
83
+ */
84
+ getBetterAuth() {
85
+ if (!this.betterAuthInstance) {
86
+ throw new Error(
87
+ "KrutAuth not initialized. Call initialize() first or set validateOnInit to false."
88
+ );
89
+ }
90
+ return this.betterAuthInstance;
91
+ }
92
+ /**
93
+ * Check if the client is initialized
94
+ */
95
+ isInitialized() {
96
+ return this.initialized;
97
+ }
98
+ /**
99
+ * Get the API key (useful for making authenticated requests)
100
+ * @returns The API key
101
+ */
102
+ getApiKey() {
103
+ return this.apiKey;
104
+ }
105
+ /**
106
+ * Sign in a user
107
+ * This is a convenience method that wraps Better Auth
108
+ * You can access the full Better Auth API via getBetterAuth()
109
+ */
110
+ async signIn() {
111
+ const auth = this.getBetterAuth();
112
+ return auth;
113
+ }
114
+ /**
115
+ * Sign out the current user
116
+ * You can access the full Better Auth API via getBetterAuth()
117
+ */
118
+ async signOut() {
119
+ const auth = this.getBetterAuth();
120
+ return auth;
121
+ }
122
+ /**
123
+ * Get the current session
124
+ * You can access the full Better Auth API via getBetterAuth()
125
+ */
126
+ async getSession() {
127
+ const auth = this.getBetterAuth();
128
+ return auth;
129
+ }
130
+ };
131
+
132
+ // src/index.ts
133
+ var VERSION = "0.1.0";
134
+
135
+ exports.ApiKeyValidationError = ApiKeyValidationError;
136
+ exports.KrutAuth = KrutAuth;
137
+ exports.VERSION = VERSION;
138
+ exports.validateApiKeyFormat = validateApiKeyFormat;
139
+ exports.validateApiKeyWithService = validateApiKeyWithService;
140
+ //# sourceMappingURL=index.js.map
141
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/validator.ts","../src/client.ts","../src/index.ts"],"names":["betterAuth"],"mappings":";;;;;;;AAGO,IAAM,qBAAA,GAAN,MAAM,sBAAA,SAA8B,KAAA,CAAM;AAAA,EAC7C,YAAY,OAAA,EAAiB;AACzB,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,uBAAA;AACZ,IAAA,MAAA,CAAO,cAAA,CAAe,IAAA,EAAM,sBAAA,CAAsB,SAAS,CAAA;AAAA,EAC/D;AACJ;AAOO,SAAS,qBAAqB,MAAA,EAAkC;AACnE,EAAA,IAAI,CAAC,MAAA,EAAQ;AACT,IAAA,MAAM,IAAI,qBAAA;AAAA,MACN;AAAA,KACJ;AAAA,EACJ;AAEA,EAAA,IAAI,OAAO,WAAW,QAAA,EAAU;AAC5B,IAAA,MAAM,IAAI,sBAAsB,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A,qBAAA,CAAW;AAAA,MACjC,GAAG,KAAK,MAAA,CAAO;AAAA;AAAA,KAElB,CAAA;AAAA,EACL;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,aAAA,GAA+C;AAC3C,IAAA,IAAI,CAAC,KAAK,kBAAA,EAAoB;AAC1B,MAAA,MAAM,IAAI,KAAA;AAAA,QACN;AAAA,OACJ;AAAA,IACJ;AACA,IAAA,OAAO,IAAA,CAAK,kBAAA;AAAA,EAChB;AAAA;AAAA;AAAA;AAAA,EAKA,aAAA,GAAyB;AACrB,IAAA,OAAO,IAAA,CAAK,WAAA;AAAA,EAChB;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,SAAA,GAAoB;AAChB,IAAA,OAAO,IAAA,CAAK,MAAA;AAAA,EAChB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,MAAA,GAAS;AACX,IAAA,MAAM,IAAA,GAAO,KAAK,aAAA,EAAc;AAGhC,IAAA,OAAO,IAAA;AAAA,EACX;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,OAAA,GAAU;AACZ,IAAA,MAAM,IAAA,GAAO,KAAK,aAAA,EAAc;AAChC,IAAA,OAAO,IAAA;AAAA,EACX;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,UAAA,GAAa;AACf,IAAA,MAAM,IAAA,GAAO,KAAK,aAAA,EAAc;AAChC,IAAA,OAAO,IAAA;AAAA,EACX;AACJ;;;ACpHO,IAAM,OAAA,GAAU","file":"index.js","sourcesContent":["/**\n * Custom error class for API key validation failures\n */\nexport class ApiKeyValidationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ApiKeyValidationError';\n Object.setPrototypeOf(this, ApiKeyValidationError.prototype);\n }\n}\n\n/**\n * Validates the format of an API key\n * @param apiKey - The API key to validate\n * @throws {ApiKeyValidationError} If the API key is invalid\n */\nexport function validateApiKeyFormat(apiKey: string | undefined): void {\n if (!apiKey) {\n throw new ApiKeyValidationError(\n 'API key is required. Please provide a valid API key to use @krutai/auth.'\n );\n }\n\n if (typeof apiKey !== 'string') {\n throw new ApiKeyValidationError('API key must be a string.');\n }\n\n if (apiKey.trim().length === 0) {\n throw new ApiKeyValidationError('API key cannot be empty.');\n }\n\n // Basic format validation - adjust based on your API key format\n if (apiKey.length < 10) {\n throw new ApiKeyValidationError(\n 'API key appears to be invalid. Please check your API key.'\n );\n }\n}\n\n/**\n * Validates an API key against a backend service (optional)\n * This is a placeholder for actual API validation logic\n * @param _apiKey - The API key to validate (currently unused in mock implementation)\n * @returns Promise that resolves if valid, rejects if invalid\n */\nexport async function validateApiKeyWithService(\n _apiKey: string\n): Promise<boolean> {\n // TODO: Implement actual API validation against your backend\n // For now, this is a mock implementation\n\n // Example implementation:\n // const response = await fetch('https://api.krutai.com/validate', {\n // headers: { 'Authorization': `Bearer ${_apiKey}` }\n // });\n // if (!response.ok) {\n // throw new ApiKeyValidationError('Invalid API key');\n // }\n // return true;\n\n // Mock validation - accepts any key that passes format validation\n return Promise.resolve(true);\n}\n","import { betterAuth } from 'better-auth';\nimport type { KrutAuthConfig } from './types';\nimport {\n validateApiKeyFormat,\n validateApiKeyWithService,\n} from './validator';\n\n/**\n * KrutAuth - Authentication client for KrutAI\n * \n * This class wraps Better Auth and adds API key validation\n * to ensure only authorized users can access authentication features.\n * \n * @example\n * ```typescript\n * import { KrutAuth } from '@krutai/auth';\n * \n * const auth = new KrutAuth({\n * apiKey: 'your-api-key-here',\n * betterAuthOptions: {\n * // Better Auth configuration\n * }\n * });\n * \n * // Initialize the client (validates API key)\n * await auth.initialize();\n * \n * // Use authentication features\n * const betterAuth = auth.getBetterAuth();\n * ```\n */\nexport class KrutAuth {\n private apiKey: string;\n private betterAuthInstance: ReturnType<typeof betterAuth> | null = null;\n private initialized = false;\n\n /**\n * Creates a new KrutAuth instance\n * @param config - Configuration options\n * @throws {ApiKeyValidationError} If API key is invalid\n */\n constructor(private config: KrutAuthConfig) {\n // Validate API key format immediately\n validateApiKeyFormat(config.apiKey);\n this.apiKey = config.apiKey;\n\n // Initialize if validation is not required on init\n if (config.validateOnInit === false) {\n this.initializeBetterAuth();\n }\n }\n\n /**\n * Initialize the authentication client\n * Validates the API key and sets up Better Auth\n * @throws {ApiKeyValidationError} If API key validation fails\n */\n async initialize(): Promise<void> {\n if (this.initialized) {\n return;\n }\n\n // Validate API key with service if needed\n if (this.config.validateOnInit !== false) {\n await validateApiKeyWithService(this.apiKey);\n }\n\n this.initializeBetterAuth();\n this.initialized = true;\n }\n\n /**\n * Initialize Better Auth instance\n * @private\n */\n private initializeBetterAuth(): void {\n this.betterAuthInstance = betterAuth({\n ...this.config.betterAuthOptions,\n // Add any custom configuration here\n });\n }\n\n /**\n * Get the Better Auth instance\n * @throws {Error} If not initialized\n */\n getBetterAuth(): ReturnType<typeof betterAuth> {\n if (!this.betterAuthInstance) {\n throw new Error(\n 'KrutAuth not initialized. Call initialize() first or set validateOnInit to false.'\n );\n }\n return this.betterAuthInstance;\n }\n\n /**\n * Check if the client is initialized\n */\n isInitialized(): boolean {\n return this.initialized;\n }\n\n /**\n * Get the API key (useful for making authenticated requests)\n * @returns The API key\n */\n getApiKey(): string {\n return this.apiKey;\n }\n\n /**\n * Sign in a user\n * This is a convenience method that wraps Better Auth\n * You can access the full Better Auth API via getBetterAuth()\n */\n async signIn() {\n const auth = this.getBetterAuth();\n // Return the Better Auth instance for further operations\n // Users can call methods on it directly\n return auth;\n }\n\n /**\n * Sign out the current user\n * You can access the full Better Auth API via getBetterAuth()\n */\n async signOut() {\n const auth = this.getBetterAuth();\n return auth;\n }\n\n /**\n * Get the current session\n * You can access the full Better Auth API via getBetterAuth()\n */\n async getSession() {\n const auth = this.getBetterAuth();\n return auth;\n }\n}\n","/**\n * @krutai/auth - Authentication package for KrutAI\n * \n * This package provides authentication functionality powered by Better Auth\n * with API key validation to ensure secure access.\n * \n * @packageDocumentation\n */\n\n// Export main client\nexport { KrutAuth } from './client';\n\n// Export types\nexport type { KrutAuthConfig, AuthSession, BetterAuthOptions } from './types';\n\n// Export validator utilities\nexport {\n validateApiKeyFormat,\n validateApiKeyWithService,\n ApiKeyValidationError,\n} from './validator';\n\n// Package metadata\nexport const VERSION = '0.1.0';\n"]}
package/dist/index.mjs ADDED
@@ -0,0 +1,135 @@
1
+ import { betterAuth } from 'better-auth';
2
+
3
+ // src/client.ts
4
+
5
+ // src/validator.ts
6
+ var ApiKeyValidationError = class _ApiKeyValidationError extends Error {
7
+ constructor(message) {
8
+ super(message);
9
+ this.name = "ApiKeyValidationError";
10
+ Object.setPrototypeOf(this, _ApiKeyValidationError.prototype);
11
+ }
12
+ };
13
+ function validateApiKeyFormat(apiKey) {
14
+ if (!apiKey) {
15
+ throw new ApiKeyValidationError(
16
+ "API key is required. Please provide a valid API key to use @krutai/auth."
17
+ );
18
+ }
19
+ if (typeof apiKey !== "string") {
20
+ throw new ApiKeyValidationError("API key must be a string.");
21
+ }
22
+ if (apiKey.trim().length === 0) {
23
+ throw new ApiKeyValidationError("API key cannot be empty.");
24
+ }
25
+ if (apiKey.length < 10) {
26
+ throw new ApiKeyValidationError(
27
+ "API key appears to be invalid. Please check your API key."
28
+ );
29
+ }
30
+ }
31
+ async function validateApiKeyWithService(_apiKey) {
32
+ return Promise.resolve(true);
33
+ }
34
+
35
+ // src/client.ts
36
+ var KrutAuth = class {
37
+ /**
38
+ * Creates a new KrutAuth instance
39
+ * @param config - Configuration options
40
+ * @throws {ApiKeyValidationError} If API key is invalid
41
+ */
42
+ constructor(config) {
43
+ this.config = config;
44
+ validateApiKeyFormat(config.apiKey);
45
+ this.apiKey = config.apiKey;
46
+ if (config.validateOnInit === false) {
47
+ this.initializeBetterAuth();
48
+ }
49
+ }
50
+ apiKey;
51
+ betterAuthInstance = null;
52
+ initialized = false;
53
+ /**
54
+ * Initialize the authentication client
55
+ * Validates the API key and sets up Better Auth
56
+ * @throws {ApiKeyValidationError} If API key validation fails
57
+ */
58
+ async initialize() {
59
+ if (this.initialized) {
60
+ return;
61
+ }
62
+ if (this.config.validateOnInit !== false) {
63
+ await validateApiKeyWithService(this.apiKey);
64
+ }
65
+ this.initializeBetterAuth();
66
+ this.initialized = true;
67
+ }
68
+ /**
69
+ * Initialize Better Auth instance
70
+ * @private
71
+ */
72
+ initializeBetterAuth() {
73
+ this.betterAuthInstance = betterAuth({
74
+ ...this.config.betterAuthOptions
75
+ // Add any custom configuration here
76
+ });
77
+ }
78
+ /**
79
+ * Get the Better Auth instance
80
+ * @throws {Error} If not initialized
81
+ */
82
+ getBetterAuth() {
83
+ if (!this.betterAuthInstance) {
84
+ throw new Error(
85
+ "KrutAuth not initialized. Call initialize() first or set validateOnInit to false."
86
+ );
87
+ }
88
+ return this.betterAuthInstance;
89
+ }
90
+ /**
91
+ * Check if the client is initialized
92
+ */
93
+ isInitialized() {
94
+ return this.initialized;
95
+ }
96
+ /**
97
+ * Get the API key (useful for making authenticated requests)
98
+ * @returns The API key
99
+ */
100
+ getApiKey() {
101
+ return this.apiKey;
102
+ }
103
+ /**
104
+ * Sign in a user
105
+ * This is a convenience method that wraps Better Auth
106
+ * You can access the full Better Auth API via getBetterAuth()
107
+ */
108
+ async signIn() {
109
+ const auth = this.getBetterAuth();
110
+ return auth;
111
+ }
112
+ /**
113
+ * Sign out the current user
114
+ * You can access the full Better Auth API via getBetterAuth()
115
+ */
116
+ async signOut() {
117
+ const auth = this.getBetterAuth();
118
+ return auth;
119
+ }
120
+ /**
121
+ * Get the current session
122
+ * You can access the full Better Auth API via getBetterAuth()
123
+ */
124
+ async getSession() {
125
+ const auth = this.getBetterAuth();
126
+ return auth;
127
+ }
128
+ };
129
+
130
+ // src/index.ts
131
+ var VERSION = "0.1.0";
132
+
133
+ export { ApiKeyValidationError, KrutAuth, VERSION, validateApiKeyFormat, validateApiKeyWithService };
134
+ //# sourceMappingURL=index.mjs.map
135
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/validator.ts","../src/client.ts","../src/index.ts"],"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AAO,IAAA;AAAA,EACX;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,UAAA,GAAa;AACf,IAAA,MAAM,IAAA,GAAO,KAAK,aAAA,EAAc;AAChC,IAAA,OAAO,IAAA;AAAA,EACX;AACJ;;;ACpHO,IAAM,OAAA,GAAU","file":"index.mjs","sourcesContent":["/**\n * Custom error class for API key validation failures\n */\nexport class ApiKeyValidationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ApiKeyValidationError';\n Object.setPrototypeOf(this, ApiKeyValidationError.prototype);\n }\n}\n\n/**\n * Validates the format of an API key\n * @param apiKey - The API key to validate\n * @throws {ApiKeyValidationError} If the API key is invalid\n */\nexport function validateApiKeyFormat(apiKey: string | undefined): void {\n if (!apiKey) {\n throw new ApiKeyValidationError(\n 'API key is required. Please provide a valid API key to use @krutai/auth.'\n );\n }\n\n if (typeof apiKey !== 'string') {\n throw new ApiKeyValidationError('API key must be a string.');\n }\n\n if (apiKey.trim().length === 0) {\n throw new ApiKeyValidationError('API key cannot be empty.');\n }\n\n // Basic format validation - adjust based on your API key format\n if (apiKey.length < 10) {\n throw new ApiKeyValidationError(\n 'API key appears to be invalid. Please check your API key.'\n );\n }\n}\n\n/**\n * Validates an API key against a backend service (optional)\n * This is a placeholder for actual API validation logic\n * @param _apiKey - The API key to validate (currently unused in mock implementation)\n * @returns Promise that resolves if valid, rejects if invalid\n */\nexport async function validateApiKeyWithService(\n _apiKey: string\n): Promise<boolean> {\n // TODO: Implement actual API validation against your backend\n // For now, this is a mock implementation\n\n // Example implementation:\n // const response = await fetch('https://api.krutai.com/validate', {\n // headers: { 'Authorization': `Bearer ${_apiKey}` }\n // });\n // if (!response.ok) {\n // throw new ApiKeyValidationError('Invalid API key');\n // }\n // return true;\n\n // Mock validation - accepts any key that passes format validation\n return Promise.resolve(true);\n}\n","import { betterAuth } from 'better-auth';\nimport type { KrutAuthConfig } from './types';\nimport {\n validateApiKeyFormat,\n validateApiKeyWithService,\n} from './validator';\n\n/**\n * KrutAuth - Authentication client for KrutAI\n * \n * This class wraps Better Auth and adds API key validation\n * to ensure only authorized users can access authentication features.\n * \n * @example\n * ```typescript\n * import { KrutAuth } from '@krutai/auth';\n * \n * const auth = new KrutAuth({\n * apiKey: 'your-api-key-here',\n * betterAuthOptions: {\n * // Better Auth configuration\n * }\n * });\n * \n * // Initialize the client (validates API key)\n * await auth.initialize();\n * \n * // Use authentication features\n * const betterAuth = auth.getBetterAuth();\n * ```\n */\nexport class KrutAuth {\n private apiKey: string;\n private betterAuthInstance: ReturnType<typeof betterAuth> | null = null;\n private initialized = false;\n\n /**\n * Creates a new KrutAuth instance\n * @param config - Configuration options\n * @throws {ApiKeyValidationError} If API key is invalid\n */\n constructor(private config: KrutAuthConfig) {\n // Validate API key format immediately\n validateApiKeyFormat(config.apiKey);\n this.apiKey = config.apiKey;\n\n // Initialize if validation is not required on init\n if (config.validateOnInit === false) {\n this.initializeBetterAuth();\n }\n }\n\n /**\n * Initialize the authentication client\n * Validates the API key and sets up Better Auth\n * @throws {ApiKeyValidationError} If API key validation fails\n */\n async initialize(): Promise<void> {\n if (this.initialized) {\n return;\n }\n\n // Validate API key with service if needed\n if (this.config.validateOnInit !== false) {\n await validateApiKeyWithService(this.apiKey);\n }\n\n this.initializeBetterAuth();\n this.initialized = true;\n }\n\n /**\n * Initialize Better Auth instance\n * @private\n */\n private initializeBetterAuth(): void {\n this.betterAuthInstance = betterAuth({\n ...this.config.betterAuthOptions,\n // Add any custom configuration here\n });\n }\n\n /**\n * Get the Better Auth instance\n * @throws {Error} If not initialized\n */\n getBetterAuth(): ReturnType<typeof betterAuth> {\n if (!this.betterAuthInstance) {\n throw new Error(\n 'KrutAuth not initialized. Call initialize() first or set validateOnInit to false.'\n );\n }\n return this.betterAuthInstance;\n }\n\n /**\n * Check if the client is initialized\n */\n isInitialized(): boolean {\n return this.initialized;\n }\n\n /**\n * Get the API key (useful for making authenticated requests)\n * @returns The API key\n */\n getApiKey(): string {\n return this.apiKey;\n }\n\n /**\n * Sign in a user\n * This is a convenience method that wraps Better Auth\n * You can access the full Better Auth API via getBetterAuth()\n */\n async signIn() {\n const auth = this.getBetterAuth();\n // Return the Better Auth instance for further operations\n // Users can call methods on it directly\n return auth;\n }\n\n /**\n * Sign out the current user\n * You can access the full Better Auth API via getBetterAuth()\n */\n async signOut() {\n const auth = this.getBetterAuth();\n return auth;\n }\n\n /**\n * Get the current session\n * You can access the full Better Auth API via getBetterAuth()\n */\n async getSession() {\n const auth = this.getBetterAuth();\n return auth;\n }\n}\n","/**\n * @krutai/auth - Authentication package for KrutAI\n * \n * This package provides authentication functionality powered by Better Auth\n * with API key validation to ensure secure access.\n * \n * @packageDocumentation\n */\n\n// Export main client\nexport { KrutAuth } from './client';\n\n// Export types\nexport type { KrutAuthConfig, AuthSession, BetterAuthOptions } from './types';\n\n// Export validator utilities\nexport {\n validateApiKeyFormat,\n validateApiKeyWithService,\n ApiKeyValidationError,\n} from './validator';\n\n// Package metadata\nexport const VERSION = '0.1.0';\n"]}
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "@krutai/auth",
3
+ "version": "0.1.0",
4
+ "description": "Authentication package for KrutAI powered by Better Auth",
5
+ "main": "./dist/index.js",
6
+ "module": "./dist/index.mjs",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.mjs",
12
+ "require": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "README.md",
18
+ "AI_REFERENCE.md"
19
+ ],
20
+ "scripts": {
21
+ "build": "tsup",
22
+ "dev": "tsup --watch",
23
+ "clean": "rm -rf dist *.tsbuildinfo",
24
+ "typecheck": "tsc --noEmit"
25
+ },
26
+ "keywords": [
27
+ "krutai",
28
+ "auth",
29
+ "authentication",
30
+ "better-auth"
31
+ ],
32
+ "author": "",
33
+ "license": "MIT",
34
+ "dependencies": {
35
+ "better-auth": "^1.1.7"
36
+ },
37
+ "devDependencies": {
38
+ "@types/node": "^20.11.0",
39
+ "tsup": "^8.0.1",
40
+ "typescript": "^5.3.3"
41
+ },
42
+ "publishConfig": {
43
+ "access": "public"
44
+ },
45
+ "repository": {
46
+ "type": "git",
47
+ "url": "https://github.com/AccountantAIOrg/krut_packages.git",
48
+ "directory": "packages/auth"
49
+ }
50
+ }