@krutai/auth 0.2.3 → 0.4.1

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
@@ -3,203 +3,273 @@
3
3
  ## Package Overview
4
4
 
5
5
  - **Name**: `@krutai/auth`
6
- - **Version**: `0.1.9`
7
- - **Purpose**: Authentication package for KrutAI — wraps Better Auth with a `krutAuth` function and optional API key validation via `KrutAuth` class
6
+ - **Version**: `0.4.0`
7
+ - **Purpose**: Fetch-based authentication client for KrutAI — calls your server's `/lib-auth` routes (powered by better-auth + PostgreSQL on the server side)
8
8
  - **Entry**: `src/index.ts` → `dist/index.{js,mjs,d.ts}`
9
- - **Build**: `tsup` (CJS + ESM, all deps external)
9
+ - **Build**: `tsup` (CJS + ESM, `krutai` external)
10
+
11
+ ## ⚠️ Critical Architecture Note for AI
12
+
13
+ > All auth logic and database connectivity (PostgreSQL, etc.) lives on the server.
14
+ > This package is a **pure HTTP client** that calls the server's `/lib-auth` routes.
15
+
16
+ **Do NOT suggest any of the following for this package — they do not exist:**
17
+ - `@krutai/auth/react`
18
+ - `@krutai/auth/next-js`
19
+ - `createAuthClient()`
20
+ - `toNextJsHandler()`
21
+ - `getBetterAuth()`
22
+ - `betterAuthOptions` config key
23
+ - `database` config key
24
+ - Passing `new Database(...)` or `new Pool(...)` to `krutAuth()`
25
+
26
+ **Do NOT suggest SQLite (`better-sqlite3`) usage.** The server side should use PostgreSQL.
10
27
 
11
28
  ## Dependency Architecture
12
29
 
13
30
  ```
14
- @krutai/auth@0.1.9
15
- ├── dependency: krutai ← API key validation (also peerDep)
16
- ├── dependency: better-auth ← auth engine (external in tsup)
17
- ├── dependency: better-sqlite3 ← default SQLite adapter
18
- └── dependency: @types/better-sqlite3
31
+ @krutai/auth@0.4.0
32
+ └── dependency: krutai ← API key validation (also peerDep)
33
+
34
+ Your Server (separate codebase)
35
+ ├── better-auth ← Auth engine
36
+ └── pg / postgres ← PostgreSQL adapter
19
37
  ```
20
38
 
21
- > **Important for AI**: Do NOT bundle `better-auth` or `krutai` inline (no `noExternal`). They are real dependencies and must stay external in tsup.
39
+ ## Full System Flow
40
+
41
+ ```mermaid
42
+ sequenceDiagram
43
+ participant App as Consumer App (@krutai/auth)
44
+ participant Server as Your Server (/lib-auth)
45
+ participant BA as better-auth (server)
46
+ participant PG as PostgreSQL
47
+
48
+ App->>Server: POST /lib-auth/api/auth/sign-up/email<br/>Headers: Authorization: Bearer <apiKey>
49
+ Server->>Server: Validate API key
50
+ Server->>BA: Forward to better-auth handler
51
+ BA->>PG: INSERT user + session
52
+ PG-->>BA: OK
53
+ BA-->>Server: User + session
54
+ Server-->>App: JSON response { token, user }
55
+ ```
22
56
 
23
57
  ## File Structure
24
58
 
25
59
  ```
26
60
  packages/auth/
27
61
  ├── src/
28
- │ ├── index.ts # Exports krutAuth function + KrutAuth class + validator re-exports
29
- │ ├── client.ts # KrutAuth class (API-key-protected wrapper)
30
- ├── types.ts # KrutAuthConfig, AuthSession, BetterAuthOptions
31
- │ ├── react.ts # re-exports better-auth/react (createAuthClient, hooks)
32
- │ └── next-js.ts # re-exports better-auth/next-js (toNextJsHandler)
33
- ├── scripts/
34
- │ └── migrate.js # postinstall: auto-migrates SQLite tables via better-auth
62
+ │ ├── index.ts # Exports krutAuth factory + KrutAuth class + types + validators
63
+ │ ├── client.ts # KrutAuth class (fetch-based auth client)
64
+ └── types.ts # KrutAuthConfig, auth params, auth response types
35
65
  ├── package.json
36
66
  ├── tsconfig.json
37
67
  └── tsup.config.ts
38
68
  ```
39
69
 
40
- ## Sub-path Exports
41
-
42
- | Import | File | Purpose |
43
- |---|---|---|
44
- | `@krutai/auth` | `dist/index.js` | `krutAuth`, `KrutAuth`, validator re-exports |
45
- | `@krutai/auth/react` | `dist/react.js` | `createAuthClient`, hooks |
46
- | `@krutai/auth/next-js` | `dist/next-js.js` | `toNextJsHandler` |
47
-
48
70
  ## Main Exports
49
71
 
50
- ### `krutAuth(options)` ← PRIMARY API
51
-
52
- Drop-in replacement for `betterAuth`. Users should always use this.
53
-
54
- **Always include `baseURL`** to avoid Better Auth base URL warnings:
72
+ ### `krutAuth(config)` ← FACTORY (recommended)
55
73
 
56
74
  ```typescript
57
75
  import { krutAuth } from "@krutai/auth";
58
- import Database from "better-sqlite3";
59
76
 
60
- export const auth = krutAuth({
61
- database: new Database("./sqlite.db"),
62
- emailAndPassword: { enabled: true },
63
- baseURL: process.env.BETTER_AUTH_BASE_URL ?? "http://localhost:3000",
77
+ const auth = krutAuth({
78
+ apiKey: process.env.KRUTAI_API_KEY!, // or set KRUTAI_API_KEY env var
79
+ serverUrl: "https://krut.ai", // your server URL
64
80
  });
65
- ```
66
81
 
67
- ### `KrutAuth` class API-KEY-PROTECTED WRAPPER
82
+ await auth.initialize(); // validates API key against server
83
+ ```
68
84
 
69
- For when you need API key validation before initializing auth.
85
+ ### `KrutAuth` class CORE CLIENT
70
86
 
71
- ```typescript
72
- import { KrutAuth } from "@krutai/auth";
87
+ | Method | HTTP Call | Description |
88
+ |---|---|---|
89
+ | `initialize()` | validates API key | Must be called before other methods |
90
+ | `signUpEmail(params)` | `POST /lib-auth/api/auth/sign-up/email` | Register a new user |
91
+ | `signInEmail(params)` | `POST /lib-auth/api/auth/sign-in/email` | Authenticate a user |
92
+ | `getSession(token)` | `GET /lib-auth/api/auth/get-session` | Retrieve session info |
93
+ | `signOut(token)` | `POST /lib-auth/api/auth/sign-out` | Invalidate a session |
94
+ | `request(method, path, body?)` | Any | Generic helper for custom endpoints |
95
+ | `isInitialized()` | — | Returns `boolean` |
73
96
 
74
- const auth = new KrutAuth({
75
- apiKey: process.env.KRUTAI_API_KEY!,
76
- betterAuthOptions: {
77
- database: { provider: 'postgres', url: process.env.DATABASE_URL },
78
- emailAndPassword: { enabled: true },
79
- },
80
- });
97
+ ### Types
81
98
 
82
- await auth.initialize();
83
- const betterAuthInstance = auth.getBetterAuth();
99
+ #### `KrutAuthConfig`
100
+ ```typescript
101
+ interface KrutAuthConfig {
102
+ apiKey?: string; // defaults to process.env.KRUTAI_API_KEY
103
+ serverUrl?: string; // default: "http://localhost:8000"
104
+ authPrefix?: string; // default: "/lib-auth"
105
+ validateOnInit?: boolean; // default: true
106
+ }
84
107
  ```
85
108
 
86
- **Methods:**
87
- - `initialize(): Promise<void>` — validates API key + initializes Better Auth
88
- - `getBetterAuth(): Auth` returns the Better Auth `Auth` instance
89
- - `isInitialized(): boolean`
90
- - `getApiKey(): string`
109
+ #### `SignUpEmailParams` / `SignInEmailParams`
110
+ ```typescript
111
+ interface SignUpEmailParams { email: string; password: string; name: string; }
112
+ interface SignInEmailParams { email: string; password: string; }
113
+ ```
91
114
 
92
- ### Types
115
+ #### `AuthResponse`
116
+ ```typescript
117
+ interface AuthResponse { token: string; user: AuthUser; [key: string]: unknown; }
118
+ ```
93
119
 
94
- #### `KrutAuthConfig`
120
+ #### `AuthUser`
95
121
  ```typescript
96
- interface KrutAuthConfig {
97
- apiKey: string; // REQUIRED
98
- betterAuthOptions?: Partial<BetterAuthOptions>;
99
- validateOnInit?: boolean; // default: true
100
- validationEndpoint?: string;
122
+ interface AuthUser {
123
+ id: string;
124
+ email: string;
125
+ name?: string;
126
+ emailVerified: boolean;
127
+ createdAt: string;
128
+ updatedAt: string;
129
+ [key: string]: unknown;
101
130
  }
102
131
  ```
103
132
 
104
- ### Validator Re-exports (from `krutai`)
133
+ #### `AuthSession`
134
+ ```typescript
135
+ interface AuthSession { user: AuthUser; session: AuthSessionRecord; }
136
+ interface AuthSessionRecord { id: string; userId: string; token: string; expiresAt: string; }
137
+ ```
105
138
 
106
- > **Note for AI assistants**: Only `validateApiKeyFormat`, `validateApiKeyWithService`, and `ApiKeyValidationError` are exported. `createApiKeyChecker` is **NOT exported**. Do not suggest it.
107
- > The API key validation is **format/length only** (not null, minimum length). There is no external API check call.
139
+ ### Validator Re-exports (from `krutai`)
108
140
 
109
141
  ```typescript
110
- // These are re-exported from krutai — NOT defined here
111
- export { validateApiKeyFormat, validateApiKeyWithService, ApiKeyValidationError } from 'krutai';
142
+ export { validateApiKeyFormat, validateApiKey } from 'krutai';
112
143
  ```
113
144
 
114
145
  ## Usage Examples
115
146
 
116
- ### Example 1: Standard Server Setup (recommended)
147
+ ### Example 1: Sign Up + Sign In
117
148
  ```typescript
118
149
  import { krutAuth } from "@krutai/auth";
119
- import Database from "better-sqlite3";
120
150
 
121
- export const auth = krutAuth({
122
- database: new Database("./sqlite.db"),
123
- emailAndPassword: { enabled: true },
124
- baseURL: process.env.BETTER_AUTH_BASE_URL ?? "http://localhost:3000",
151
+ const auth = krutAuth({
152
+ apiKey: process.env.KRUTAI_API_KEY!,
153
+ serverUrl: "https://krut.ai",
125
154
  });
126
- ```
155
+ await auth.initialize();
127
156
 
128
- ### Example 2: Next.js Route Handler
129
- ```typescript
130
- // app/api/auth/[...all]/route.ts
131
- import { auth } from "@/lib/auth";
132
- import { toNextJsHandler } from "@krutai/auth/next-js";
157
+ // Sign up
158
+ const { token, user } = await auth.signUpEmail({
159
+ email: "user@example.com",
160
+ password: "secret123",
161
+ name: "Alice",
162
+ });
133
163
 
134
- export const { GET, POST } = toNextJsHandler(auth);
164
+ // Sign in
165
+ const result = await auth.signInEmail({
166
+ email: "user@example.com",
167
+ password: "secret123",
168
+ });
169
+ console.log("Token:", result.token);
135
170
  ```
136
171
 
137
- ### Example 3: React Client
172
+ ### Example 2: Session Management
138
173
  ```typescript
139
- import { createAuthClient } from "@krutai/auth/react";
174
+ // Get session
175
+ const session = await auth.getSession(token);
176
+ console.log("User:", session.user.email);
140
177
 
141
- export const authClient = createAuthClient({
142
- baseURL: process.env.NEXT_PUBLIC_APP_URL ?? "http://localhost:3000",
143
- });
144
- export const { signIn, signUp, signOut, useSession } = authClient;
178
+ // Sign out
179
+ await auth.signOut(token);
145
180
  ```
146
181
 
147
- ### Example 4: KrutAuth with API Key Validation
182
+ ### Example 3: Custom Endpoint
148
183
  ```typescript
149
- import { KrutAuth } from "@krutai/auth";
150
-
151
- const auth = new KrutAuth({
152
- apiKey: process.env.KRUTAI_API_KEY!,
153
- betterAuthOptions: { emailAndPassword: { enabled: true } },
184
+ const data = await auth.request("POST", "/api/auth/some-custom-endpoint", {
185
+ someParam: "value",
154
186
  });
155
- await auth.initialize();
156
187
  ```
157
188
 
158
- ### Example 5: Error Handling
189
+ ### Example 4: Error Handling
159
190
  ```typescript
160
- import { KrutAuth, ApiKeyValidationError } from "@krutai/auth";
191
+ import { krutAuth, KrutAuthKeyValidationError } from "@krutai/auth";
161
192
 
162
193
  try {
163
- const auth = new KrutAuth({ apiKey: "bad" });
194
+ const auth = krutAuth({ apiKey: "bad-key" });
164
195
  await auth.initialize();
165
196
  } catch (e) {
166
- if (e instanceof ApiKeyValidationError) {
197
+ if (e instanceof KrutAuthKeyValidationError) {
167
198
  console.error("Invalid API key:", e.message);
168
199
  }
169
200
  }
170
201
  ```
171
202
 
172
- ## Auto-Migration (postinstall)
203
+ ### Example 5: Skip validation in tests
204
+ ```typescript
205
+ const auth = krutAuth({
206
+ apiKey: "test-key-minimum-10-chars",
207
+ serverUrl: "http://localhost:8000",
208
+ validateOnInit: false, // Skip server round-trip
209
+ });
210
+ // Ready to use immediately — no initialize() needed
211
+ ```
212
+
213
+ ## Server-side PostgreSQL Setup (NOT in this package)
214
+
215
+ When a user asks about PostgreSQL + this auth package, the Postgres config goes on the **server**, not here:
216
+
217
+ ```typescript
218
+ // server: lib/auth.ts
219
+ import { betterAuth } from "better-auth";
220
+ import { Pool } from "pg";
173
221
 
174
- `scripts/migrate.js` runs after `npm install` to create all required Better Auth SQLite tables automatically. This means users do NOT need to run any manual migration commands — sign-up and sign-in work out of the box.
222
+ export const auth = betterAuth({
223
+ database: new Pool({ connectionString: process.env.DATABASE_URL }),
224
+ emailAndPassword: { enabled: true },
225
+ basePath: "/lib-auth",
226
+ baseURL: process.env.BETTER_AUTH_BASE_URL,
227
+ secret: process.env.BETTER_AUTH_SECRET,
228
+ });
229
+ ```
175
230
 
176
- The script:
177
- 1. Creates `sqlite.db` in the project root (if not present)
178
- 2. Runs `better-auth migrate` to create all required tables
179
- 3. Skips silently if the DB already exists and tables are up to date
231
+ Required server env vars:
232
+ - `DATABASE_URL` PostgreSQL connection string (e.g. `postgresql://user:pass@host:5432/db`)
233
+ - `BETTER_AUTH_BASE_URL` Server base URL
234
+ - `BETTER_AUTH_SECRET` Session signing secret
235
+
236
+ ## Request Headers
237
+
238
+ Every request from `KrutAuth` sends:
239
+ ```
240
+ Content-Type: application/json
241
+ Authorization: Bearer <apiKey>
242
+ x-api-key: <apiKey>
243
+ ```
244
+
245
+ `getSession` and `signOut` additionally send:
246
+ ```
247
+ Cookie: better-auth.session_token=<sessionToken>
248
+ ```
180
249
 
181
- ## tsup Configuration Notes
250
+ ## Known Limitations
182
251
 
183
- - `better-auth` **external** (real dependency, NOT bundled)
184
- - `krutai` **external** (peer dep, NOT bundled)
185
- - `better-sqlite3` **external** (real dependency)
186
- - `react`, `react-dom`, `next` → external
252
+ 1. **`getSession`/`signOut` use cookie-based auth** may not work in all server-to-server contexts if the server strips cookies
253
+ 2. **`AuthResponse` is missing `session`** — better-auth returns `{ token, user, session }` but the type only declares `{ token, user }`. Access `session` via the `[key: string]: unknown` index signature
254
+ 3. **`dist/index.d.ts` may be missing** Run `npm run build` inside `packages/auth` if TypeScript types are not resolving
187
255
 
188
256
  ## Important Notes
189
257
 
190
- 1. **Always set `baseURL`**: Pass `baseURL: process.env.BETTER_AUTH_BASE_URL` in `krutAuth()` options
191
- 2. **Use `krutAuth` not `betterAuth`**: The public API is `krutAuth`. `betterAuth` is an internal implementation detail
192
- 3. **Validator lives in `krutai`**: Never add a local `validator.ts` import from `krutai`
193
- 4. **No `noExternal` for `better-auth` or `krutai`**: They must stay external in tsup
194
- 5. **`getBetterAuth()` returns `Auth`**: Uses the `Auth` type from `better-auth`, not `ReturnType<typeof betterAuth>`
258
+ 1. **No local database** All auth logic runs on your server — this package is a pure HTTP client
259
+ 2. **No SQLite** Do not use `better-sqlite3` with this package or its server. Use PostgreSQL
260
+ 3. **API key in headers** Every request sends `Authorization: Bearer <key>` and `x-api-key` headers
261
+ 4. **Server prefix** Auth routes are prefixed with `/lib-auth` by default (configurable via `authPrefix`)
262
+ 5. **Call `initialize()` first** Must validate API key before calling auth methods (unless `validateOnInit: false`)
263
+ 6. **Same pattern as ai-provider** — Works identically to `KrutAIProvider` — construct, initialize, call methods
195
264
 
196
265
  ## Related Packages
197
266
 
198
- - `krutai` — Core utilities and API validation (peer dep)
199
- - `@krutai/rbac` — Role-Based Access Control
267
+ - `krutai` — Core utilities and API key validation (peer dep)
268
+ - `@krutai/ai-provider` — AI provider (same fetch-based pattern)
269
+ - `@krutai/db-service` — DB config service client
200
270
 
201
271
  ## Links
202
272
 
203
- - Better Auth Docs: https://www.better-auth.com/docs
204
273
  - GitHub: https://github.com/AccountantAIOrg/krut_packages
205
274
  - npm: https://www.npmjs.com/package/@krutai/auth
275
+ - Better Auth PostgreSQL docs: https://www.better-auth.com/docs/adapters/postgresql