@krutai/auth 0.2.2 → 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 +184 -114
- package/README.md +154 -74
- package/dist/index.d.mts +214 -84
- package/dist/index.d.ts +214 -84
- package/dist/index.js +151 -63
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +146 -60
- package/dist/index.mjs.map +1 -1
- package/package.json +7 -24
- package/dist/next-js.d.mts +0 -1
- package/dist/next-js.d.ts +0 -1
- package/dist/next-js.js +0 -14
- package/dist/next-js.js.map +0 -1
- package/dist/next-js.mjs +0 -3
- package/dist/next-js.mjs.map +0 -1
- package/dist/react.d.mts +0 -1
- package/dist/react.d.ts +0 -1
- package/dist/react.js +0 -14
- package/dist/react.js.map +0 -1
- package/dist/react.mjs +0 -3
- package/dist/react.mjs.map +0 -1
- package/scripts/migrate.js +0 -53
package/AI_REFERENCE.md
CHANGED
|
@@ -3,203 +3,273 @@
|
|
|
3
3
|
## Package Overview
|
|
4
4
|
|
|
5
5
|
- **Name**: `@krutai/auth`
|
|
6
|
-
- **Version**: `0.
|
|
7
|
-
- **Purpose**:
|
|
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,
|
|
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.
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
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
|
-
|
|
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
|
|
29
|
-
│ ├── client.ts # KrutAuth class (
|
|
30
|
-
│
|
|
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(
|
|
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
|
-
|
|
61
|
-
|
|
62
|
-
|
|
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
|
-
|
|
82
|
+
await auth.initialize(); // validates API key against server
|
|
83
|
+
```
|
|
68
84
|
|
|
69
|
-
|
|
85
|
+
### `KrutAuth` class ← CORE CLIENT
|
|
70
86
|
|
|
71
|
-
|
|
72
|
-
|
|
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
|
-
|
|
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
|
-
|
|
83
|
-
|
|
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
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
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
|
-
|
|
115
|
+
#### `AuthResponse`
|
|
116
|
+
```typescript
|
|
117
|
+
interface AuthResponse { token: string; user: AuthUser; [key: string]: unknown; }
|
|
118
|
+
```
|
|
93
119
|
|
|
94
|
-
#### `
|
|
120
|
+
#### `AuthUser`
|
|
95
121
|
```typescript
|
|
96
|
-
interface
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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:
|
|
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
|
-
|
|
122
|
-
|
|
123
|
-
|
|
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
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
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
|
-
|
|
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
|
|
172
|
+
### Example 2: Session Management
|
|
138
173
|
```typescript
|
|
139
|
-
|
|
174
|
+
// Get session
|
|
175
|
+
const session = await auth.getSession(token);
|
|
176
|
+
console.log("User:", session.user.email);
|
|
140
177
|
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
});
|
|
144
|
-
export const { signIn, signUp, signOut, useSession } = authClient;
|
|
178
|
+
// Sign out
|
|
179
|
+
await auth.signOut(token);
|
|
145
180
|
```
|
|
146
181
|
|
|
147
|
-
### Example
|
|
182
|
+
### Example 3: Custom Endpoint
|
|
148
183
|
```typescript
|
|
149
|
-
|
|
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
|
|
189
|
+
### Example 4: Error Handling
|
|
159
190
|
```typescript
|
|
160
|
-
import {
|
|
191
|
+
import { krutAuth, KrutAuthKeyValidationError } from "@krutai/auth";
|
|
161
192
|
|
|
162
193
|
try {
|
|
163
|
-
const auth =
|
|
194
|
+
const auth = krutAuth({ apiKey: "bad-key" });
|
|
164
195
|
await auth.initialize();
|
|
165
196
|
} catch (e) {
|
|
166
|
-
if (e instanceof
|
|
197
|
+
if (e instanceof KrutAuthKeyValidationError) {
|
|
167
198
|
console.error("Invalid API key:", e.message);
|
|
168
199
|
}
|
|
169
200
|
}
|
|
170
201
|
```
|
|
171
202
|
|
|
172
|
-
|
|
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
|
-
|
|
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
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
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
|
-
##
|
|
250
|
+
## Known Limitations
|
|
182
251
|
|
|
183
|
-
|
|
184
|
-
- `
|
|
185
|
-
|
|
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. **
|
|
191
|
-
2. **
|
|
192
|
-
3. **
|
|
193
|
-
4. **
|
|
194
|
-
5.
|
|
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/
|
|
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
|