@krutai/auth 0.1.3 → 0.1.5

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/AI_REFERENCE.md CHANGED
@@ -1,33 +1,53 @@
1
- # @krutai/auth - AI Assistant Reference Guide
1
+ # @krutai/auth AI Assistant Reference Guide
2
2
 
3
3
  ## Package Overview
4
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.
5
+ - **Name**: `@krutai/auth`
6
+ - **Version**: `0.1.4`
7
+ - **Purpose**: Authentication package for KrutAI — wraps Better Auth with mandatory API key validation
8
+ - **Entry**: `src/index.ts` → `dist/index.{js,mjs,d.ts}`
9
+ - **Build**: `tsup` (CJS + ESM, `better-auth` bundled, `krutai` external peer dep)
6
10
 
7
- ## Installation
11
+ ## Dependency Architecture
8
12
 
9
- ```bash
10
- npm install @krutai/auth
11
13
  ```
14
+ @krutai/auth@0.1.4
15
+ ├── peerDependency: krutai >=0.1.2 ← auto-installed, provides API validation
16
+ ├── dependency: better-sqlite3 ← auto-installed
17
+ └── bundled: better-auth ← included in dist (noExternal)
18
+ ```
19
+
20
+ > **Important for AI**: The validator (`validateApiKeyFormat`, `ApiKeyValidationError`, etc.) is NOT defined in this package. It is imported from `krutai` and re-exported. Do NOT add a local `validator.ts` here.
12
21
 
13
- ## Core Concepts
22
+ ## File Structure
23
+
24
+ ```
25
+ packages/auth/
26
+ ├── src/
27
+ │ ├── index.ts # Barrel export — re-exports from krutai for validator
28
+ │ ├── client.ts # KrutAuth class
29
+ │ ├── types.ts # KrutAuthConfig, AuthSession, BetterAuthOptions
30
+ │ ├── react.ts # createAuthClient (better-auth/react)
31
+ │ └── next-js.ts # toNextJsHandler (better-auth/next-js)
32
+ ├── package.json
33
+ ├── tsconfig.json
34
+ └── tsup.config.ts
35
+ ```
14
36
 
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
37
+ ## Sub-path Exports
19
38
 
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
39
+ | Import | File | Purpose |
40
+ |---|---|---|
41
+ | `@krutai/auth` | `dist/index.js` | Server-side: `betterAuth`, `KrutAuth`, validator re-exports |
42
+ | `@krutai/auth/react` | `dist/react.js` | Client-side: `createAuthClient`, hooks |
43
+ | `@krutai/auth/next-js` | `dist/next-js.js` | Next.js handler: `toNextJsHandler` |
24
44
 
25
45
  ## Main Exports
26
46
 
27
47
  ### Classes
28
48
 
29
49
  #### `KrutAuth`
30
- Main authentication client class.
50
+ Main authentication client.
31
51
 
32
52
  **Constructor:**
33
53
  ```typescript
@@ -35,13 +55,11 @@ new KrutAuth(config: KrutAuthConfig)
35
55
  ```
36
56
 
37
57
  **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)
58
+ - `initialize(): Promise<void>` validates API key + initializes Better Auth
59
+ - `getBetterAuth()` returns the Better Auth instance
60
+ - `isInitialized(): boolean`
61
+ - `getApiKey(): string`
62
+ - `signIn()`, `signOut()`, `getSession()` convenience wrappers
45
63
 
46
64
  ### Types
47
65
 
@@ -58,185 +76,115 @@ interface KrutAuthConfig {
58
76
  #### `AuthSession`
59
77
  ```typescript
60
78
  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
- };
79
+ user: { id: string; email: string; name?: string; [key: string]: unknown };
80
+ session: { id: string; expiresAt: Date; [key: string]: unknown };
72
81
  }
73
82
  ```
74
83
 
75
- ### Errors
84
+ ### Validator Re-exports (from `krutai`)
76
85
 
77
- #### `ApiKeyValidationError`
78
- Thrown when API key validation fails.
86
+ ```typescript
87
+ // These are re-exported from krutai — NOT defined here
88
+ export { validateApiKeyFormat, validateApiKeyWithService, createApiKeyChecker, ApiKeyValidationError } from 'krutai';
89
+ ```
79
90
 
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
91
+ ### Other Re-exports
92
+
93
+ ```typescript
94
+ export { betterAuth } from 'better-auth';
95
+ ```
84
96
 
85
97
  ## Usage Examples
86
98
 
87
- ### Example 1: Basic Usage with Async Validation
99
+ ### Example 1: Basic Server Setup
100
+ ```typescript
101
+ import { betterAuth } from '@krutai/auth';
88
102
 
103
+ export const auth = betterAuth({
104
+ database: { /* config */ },
105
+ });
106
+ ```
107
+
108
+ ### Example 2: KrutAuth with API Key
89
109
  ```typescript
90
110
  import { KrutAuth } from '@krutai/auth';
91
111
 
92
112
  const auth = new KrutAuth({
93
- apiKey: 'your-api-key-here',
113
+ apiKey: process.env.KRUTAI_API_KEY!,
94
114
  betterAuthOptions: {
95
- database: {
96
- // your database config
97
- }
98
- }
115
+ database: { provider: 'postgres', url: process.env.DATABASE_URL },
116
+ emailAndPassword: { enabled: true },
117
+ },
99
118
  });
100
119
 
101
- // Initialize and validate API key
102
120
  await auth.initialize();
103
-
104
- // Get Better Auth instance
105
121
  const betterAuth = auth.getBetterAuth();
106
122
  ```
107
123
 
108
- ### Example 2: Skip Async Validation
109
-
124
+ ### Example 3: Skip Async Validation
110
125
  ```typescript
111
- import { KrutAuth } from '@krutai/auth';
112
-
113
126
  const auth = new KrutAuth({
114
- apiKey: 'your-api-key-here',
127
+ apiKey: process.env.KRUTAI_API_KEY!,
115
128
  validateOnInit: false,
116
- betterAuthOptions: {
117
- // config
118
- }
129
+ betterAuthOptions: { /* config */ },
119
130
  });
120
-
121
131
  // No need to call initialize()
122
132
  const betterAuth = auth.getBetterAuth();
123
133
  ```
124
134
 
125
- ### Example 3: Error Handling
126
-
135
+ ### Example 4: Error Handling
127
136
  ```typescript
128
137
  import { KrutAuth, ApiKeyValidationError } from '@krutai/auth';
129
138
 
130
139
  try {
131
- const auth = new KrutAuth({
132
- apiKey: 'invalid-key'
133
- });
140
+ const auth = new KrutAuth({ apiKey: 'bad' });
134
141
  await auth.initialize();
135
- } catch (error) {
136
- if (error instanceof ApiKeyValidationError) {
137
- console.error('API key validation failed:', error.message);
142
+ } catch (e) {
143
+ if (e instanceof ApiKeyValidationError) {
144
+ console.error('Invalid API key:', e.message);
138
145
  }
139
146
  }
140
147
  ```
141
148
 
142
- ### Example 4: Using Better Auth Features
143
-
149
+ ### Example 5: Next.js Route Handler
144
150
  ```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();
151
+ // app/api/auth/[...all]/route.ts
152
+ import { auth } from '@/lib/auth';
153
+ import { toNextJsHandler } from '@krutai/auth/next-js';
164
154
 
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
- });
155
+ export const { GET, POST } = toNextJsHandler(auth);
180
156
  ```
181
157
 
182
- ### Pattern 2: Singleton Instance
183
-
158
+ ### Example 6: React Client
184
159
  ```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
160
+ import { createAuthClient } from '@krutai/auth/react';
203
161
 
204
- ```typescript
205
- const auth = new KrutAuth({
206
- apiKey: process.env.KRUTAI_API_KEY!,
207
- validateOnInit: process.env.NODE_ENV === 'production'
162
+ export const authClient = createAuthClient({
163
+ baseURL: process.env.NEXT_PUBLIC_APP_URL ?? 'http://localhost:3000',
208
164
  });
209
-
210
- if (process.env.NODE_ENV === 'production') {
211
- await auth.initialize();
212
- }
165
+ export const { signIn, signUp, signOut, useSession } = authClient;
213
166
  ```
214
167
 
215
- ## TypeScript Support
168
+ ## tsup Configuration Notes
216
169
 
217
- Full TypeScript support with exported types:
218
-
219
- ```typescript
220
- import type {
221
- KrutAuthConfig,
222
- AuthSession,
223
- BetterAuthOptions
224
- } from '@krutai/auth';
225
- ```
170
+ - `better-auth` `noExternal` (bundled into dist)
171
+ - `krutai` → external (peer dep, NOT bundled)
172
+ - `react`, `react-dom`, `next`, `better-sqlite3` → external
226
173
 
227
174
  ## Important Notes
228
175
 
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
176
+ 1. **Validator lives in `krutai`**: Never add a local `validator.ts` import from `krutai`
177
+ 2. **`krutai` must be external in tsup**: Do NOT add it to `noExternal`
178
+ 3. **`krutai` in devDependencies**: Needed for local TypeScript compilation during development
179
+ 4. **API key validation**: Format check is synchronous (constructor), service check is async (`initialize()`)
233
180
 
234
181
  ## Related Packages
235
182
 
236
- - `krutai` - Main KrutAI package with core utilities
237
- - Future packages: `@krutai/analytics`, `@krutai/roles`, `@krutai/llm`
183
+ - `krutai` Core utilities and API validation (peer dep)
184
+ - `@krutai/rbac` Role-Based Access Control
238
185
 
239
186
  ## Links
240
187
 
241
- - Better Auth Documentation: https://www.better-auth.com/docs
242
- - GitHub Repository: https://github.com/yourusername/krut_packages
188
+ - Better Auth Docs: https://www.better-auth.com/docs
189
+ - GitHub: https://github.com/AccountantAIOrg/krut_packages
190
+ - npm: https://www.npmjs.com/package/@krutai/auth
package/README.md CHANGED
@@ -4,9 +4,9 @@ Authentication package for KrutAI powered by [Better Auth](https://www.better-au
4
4
 
5
5
  ## Features
6
6
 
7
- - 🔐 **API Key Protection** — Requires a valid KrutAI API key
7
+ - 🔐 **API Key Protection** — Requires a valid KrutAI API key (validated via `krutai`)
8
8
  - 🚀 **Better Auth Integration** — Built on top of Better Auth
9
- - 📦 **Self-Contained**No extra installs needed; `better-auth` and `better-sqlite3` are included automatically
9
+ - 📦 **Auto-installs `krutai`** The core `krutai` package is installed automatically as a peer dependency
10
10
  - 🎯 **Next.js Ready** — First-class support via `@krutai/auth/next-js`
11
11
  - ⚡ **Dual Format** — Supports both ESM and CommonJS
12
12
  - 🔷 **TypeScript First** — Full type safety and IntelliSense
@@ -17,7 +17,7 @@ Authentication package for KrutAI powered by [Better Auth](https://www.better-au
17
17
  npm install @krutai/auth
18
18
  ```
19
19
 
20
- > **Note:** Installing `@krutai/auth` automatically installs `better-sqlite3` (the default database adapter) and bundles `better-auth` — no additional packages required.
20
+ > **Note:** `krutai` is automatically installed as a peer dependency. `better-sqlite3` is included as a dependency and `better-auth` is bundled — no additional packages required.
21
21
 
22
22
  ## Quick Start
23
23
 
@@ -76,7 +76,7 @@ await auth.initialize();
76
76
 
77
77
  | Import path | What it provides |
78
78
  |---|---|
79
- | `@krutai/auth` | `betterAuth`, `KrutAuth`, validators |
79
+ | `@krutai/auth` | `betterAuth`, `KrutAuth`, validator re-exports from `krutai` |
80
80
  | `@krutai/auth/react` | `createAuthClient`, `useSession`, etc. |
81
81
  | `@krutai/auth/next-js` | `toNextJsHandler` |
82
82
 
@@ -115,9 +115,18 @@ try {
115
115
  }
116
116
  ```
117
117
 
118
+ > `ApiKeyValidationError` is re-exported from `krutai` — the single source of truth for API validation across the KrutAI ecosystem.
119
+
118
120
  ## Architecture
119
121
 
120
- `@krutai/auth` is fully self-contained `better-auth` is bundled into the output and `better-sqlite3` is auto-installed as a dependency. Each `@krutai/*` sub-library independently includes its own API key validation, so you never need to install the parent `krutai` package separately.
122
+ `@krutai/auth` depends on `krutai` (auto-installed as a peer dependency) for API key validation. `better-auth` is bundled into the output and `better-sqlite3` is auto-installed as a dependency.
123
+
124
+ ```
125
+ @krutai/auth@0.1.4
126
+ ├── peerDependency: krutai >=0.1.2 (auto-installed)
127
+ ├── dependency: better-sqlite3
128
+ └── bundled: better-auth
129
+ ```
121
130
 
122
131
  For Better Auth documentation, visit: https://www.better-auth.com/docs
123
132
 
package/dist/index.d.mts CHANGED
@@ -1,6 +1,7 @@
1
1
  import * as better_auth from 'better-auth';
2
2
  import { BetterAuthOptions, betterAuth } from 'better-auth';
3
- export { BetterAuthOptions, betterAuth } from 'better-auth';
3
+ export { BetterAuthOptions } from 'better-auth';
4
+ export { ApiKeyValidationError, createApiKeyChecker, validateApiKeyFormat, validateApiKeyWithService } from 'krutai';
4
5
 
5
6
  /**
6
7
  * Configuration options for KrutAuth
@@ -121,56 +122,20 @@ declare class KrutAuth {
121
122
  getSession(): Promise<better_auth.Auth<better_auth.BetterAuthOptions>>;
122
123
  }
123
124
 
124
- /**
125
- * API Key Validation Module
126
- *
127
- * Centralized API key validation for @krutai/auth.
128
- * This is bundled directly into @krutai/auth so no separate `krutai` package install is needed.
129
- */
130
- /**
131
- * Custom error for API key validation failures
132
- */
133
- declare class ApiKeyValidationError extends Error {
134
- constructor(message: string);
135
- }
136
- /**
137
- * Validates the format of an API key
138
- * @param apiKey - The API key to validate
139
- * @throws {ApiKeyValidationError} If the API key format is invalid
140
- */
141
- declare function validateApiKeyFormat(apiKey: string): void;
142
- /**
143
- * Validates an API key with the KrutAI service
144
- * @param apiKey - The API key to validate
145
- * @returns Promise that resolves to true if valid, false otherwise
146
- */
147
- declare function validateApiKeyWithService(apiKey: string): Promise<boolean>;
148
- /**
149
- * Creates a validated API key checker function
150
- * @param apiKey - The API key to validate
151
- * @returns A function that checks if the API key is valid
152
- */
153
- declare function createApiKeyChecker(apiKey: string): {
154
- /**
155
- * Validates the API key (cached after first call)
156
- */
157
- validate(): Promise<boolean>;
158
- /**
159
- * Resets the validation cache
160
- */
161
- reset(): void;
162
- };
163
-
164
125
  /**
165
126
  * @krutai/auth - Authentication package for KrutAI
166
127
  *
167
- * Everything is bundled no need to separately install `krutai` or `better-auth`.
128
+ * Requires `krutai` as a peer dependency (installed automatically).
168
129
  *
169
130
  * @example Server-side (Next.js API route / server component)
170
131
  * ```typescript
171
- * import { betterAuth } from "@krutai/auth";
132
+ * import { KrutAuth } from "@krutai/auth";
172
133
  *
173
- * export const auth = betterAuth({ ... });
134
+ * export const auth = new KrutAuth({
135
+ * apiKey: process.env.KRUTAI_API_KEY!,
136
+ * betterAuthOptions: { ... },
137
+ * });
138
+ * await auth.initialize();
174
139
  * ```
175
140
  *
176
141
  * @example Client-side (React / Next.js client component)
@@ -187,6 +152,6 @@ declare function createApiKeyChecker(apiKey: string): {
187
152
  * @packageDocumentation
188
153
  */
189
154
 
190
- declare const VERSION = "0.1.2";
155
+ declare const VERSION = "0.1.5";
191
156
 
192
- export { ApiKeyValidationError, type AuthSession, KrutAuth, type KrutAuthConfig, VERSION, createApiKeyChecker, validateApiKeyFormat, validateApiKeyWithService };
157
+ export { type AuthSession, KrutAuth, type KrutAuthConfig, VERSION };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import * as better_auth from 'better-auth';
2
2
  import { BetterAuthOptions, betterAuth } from 'better-auth';
3
- export { BetterAuthOptions, betterAuth } from 'better-auth';
3
+ export { BetterAuthOptions } from 'better-auth';
4
+ export { ApiKeyValidationError, createApiKeyChecker, validateApiKeyFormat, validateApiKeyWithService } from 'krutai';
4
5
 
5
6
  /**
6
7
  * Configuration options for KrutAuth
@@ -121,56 +122,20 @@ declare class KrutAuth {
121
122
  getSession(): Promise<better_auth.Auth<better_auth.BetterAuthOptions>>;
122
123
  }
123
124
 
124
- /**
125
- * API Key Validation Module
126
- *
127
- * Centralized API key validation for @krutai/auth.
128
- * This is bundled directly into @krutai/auth so no separate `krutai` package install is needed.
129
- */
130
- /**
131
- * Custom error for API key validation failures
132
- */
133
- declare class ApiKeyValidationError extends Error {
134
- constructor(message: string);
135
- }
136
- /**
137
- * Validates the format of an API key
138
- * @param apiKey - The API key to validate
139
- * @throws {ApiKeyValidationError} If the API key format is invalid
140
- */
141
- declare function validateApiKeyFormat(apiKey: string): void;
142
- /**
143
- * Validates an API key with the KrutAI service
144
- * @param apiKey - The API key to validate
145
- * @returns Promise that resolves to true if valid, false otherwise
146
- */
147
- declare function validateApiKeyWithService(apiKey: string): Promise<boolean>;
148
- /**
149
- * Creates a validated API key checker function
150
- * @param apiKey - The API key to validate
151
- * @returns A function that checks if the API key is valid
152
- */
153
- declare function createApiKeyChecker(apiKey: string): {
154
- /**
155
- * Validates the API key (cached after first call)
156
- */
157
- validate(): Promise<boolean>;
158
- /**
159
- * Resets the validation cache
160
- */
161
- reset(): void;
162
- };
163
-
164
125
  /**
165
126
  * @krutai/auth - Authentication package for KrutAI
166
127
  *
167
- * Everything is bundled no need to separately install `krutai` or `better-auth`.
128
+ * Requires `krutai` as a peer dependency (installed automatically).
168
129
  *
169
130
  * @example Server-side (Next.js API route / server component)
170
131
  * ```typescript
171
- * import { betterAuth } from "@krutai/auth";
132
+ * import { KrutAuth } from "@krutai/auth";
172
133
  *
173
- * export const auth = betterAuth({ ... });
134
+ * export const auth = new KrutAuth({
135
+ * apiKey: process.env.KRUTAI_API_KEY!,
136
+ * betterAuthOptions: { ... },
137
+ * });
138
+ * await auth.initialize();
174
139
  * ```
175
140
  *
176
141
  * @example Client-side (React / Next.js client component)
@@ -187,6 +152,6 @@ declare function createApiKeyChecker(apiKey: string): {
187
152
  * @packageDocumentation
188
153
  */
189
154
 
190
- declare const VERSION = "0.1.2";
155
+ declare const VERSION = "0.1.5";
191
156
 
192
- export { ApiKeyValidationError, type AuthSession, KrutAuth, type KrutAuthConfig, VERSION, createApiKeyChecker, validateApiKeyFormat, validateApiKeyWithService };
157
+ export { type AuthSession, KrutAuth, type KrutAuthConfig, VERSION };