hylekit 1.0.0 → 1.0.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.
Files changed (44) hide show
  1. package/README.md +402 -0
  2. package/dist/bff/index.cjs +338 -0
  3. package/dist/bff/index.cjs.map +1 -0
  4. package/dist/bff/index.d.cts +2 -0
  5. package/dist/bff/index.d.ts +2 -0
  6. package/dist/bff/index.js +316 -0
  7. package/dist/bff/index.js.map +1 -0
  8. package/dist/client/nextjs.cjs +250 -0
  9. package/dist/client/nextjs.cjs.map +1 -0
  10. package/dist/client/nextjs.d.cts +868 -0
  11. package/dist/client/nextjs.d.ts +868 -0
  12. package/dist/client/nextjs.js +230 -0
  13. package/dist/client/nextjs.js.map +1 -0
  14. package/dist/client/sveltekit.cjs +237 -0
  15. package/dist/client/sveltekit.cjs.map +1 -0
  16. package/dist/client/sveltekit.d.cts +844 -0
  17. package/dist/client/sveltekit.d.ts +844 -0
  18. package/dist/client/sveltekit.js +217 -0
  19. package/dist/client/sveltekit.js.map +1 -0
  20. package/dist/index-DYW73KK3.d.cts +58 -0
  21. package/dist/index-DYW73KK3.d.ts +58 -0
  22. package/dist/index.cjs +502 -553
  23. package/dist/index.cjs.map +1 -1
  24. package/dist/index.d.cts +3266 -1897
  25. package/dist/index.d.ts +3266 -1897
  26. package/dist/index.js +488 -535
  27. package/dist/index.js.map +1 -1
  28. package/dist/lib/schema.cjs +118 -0
  29. package/dist/lib/schema.cjs.map +1 -0
  30. package/dist/lib/schema.d.cts +3 -0
  31. package/dist/lib/schema.d.ts +3 -0
  32. package/dist/lib/schema.js +87 -0
  33. package/dist/lib/schema.js.map +1 -0
  34. package/dist/schema-ph9L8QMm.d.cts +674 -0
  35. package/dist/schema-ph9L8QMm.d.ts +674 -0
  36. package/dist/server/express.cjs +243 -0
  37. package/dist/server/express.cjs.map +1 -0
  38. package/dist/server/express.d.cts +85 -0
  39. package/dist/server/express.d.ts +85 -0
  40. package/dist/server/express.js +219 -0
  41. package/dist/server/express.js.map +1 -0
  42. package/dist/types-BHiK1JUX.d.cts +32 -0
  43. package/dist/types-GOn9sn7-.d.ts +32 -0
  44. package/package.json +45 -10
package/README.md ADDED
@@ -0,0 +1,402 @@
1
+ # HyleKit
2
+
3
+ Distributed BetterAuth library for SvelteKit and Next.js with Google OAuth and Turso cloud database.
4
+
5
+ ## Features
6
+
7
+ - 🔐 **Google OAuth** - Simple Google login integration
8
+ - 🌐 **Distributed Auth** - Each app runs auth locally, sharing a Turso cloud database
9
+ - 📦 **Framework Adapters** - First-class support for SvelteKit and Next.js
10
+ - 🗄️ **Turso/LibSQL** - Edge-friendly SQLite database
11
+ - 🔄 **Session Management** - Automatic session handling with cookies
12
+ - 🚀 **BFF Pattern** - Built-in support for Backend-For-Frontend architecture with Express
13
+
14
+ ## Installation
15
+
16
+ ```bash
17
+ npm install hylekit
18
+ ```
19
+
20
+ ## Environment Variables
21
+
22
+ ```bash
23
+ # Turso Database
24
+ DATABASE_URL=libsql://[db-name]-[org].turso.io
25
+ DATABASE_AUTH_TOKEN=your-turso-token
26
+
27
+ # Google OAuth
28
+ GOOGLE_CLIENT_ID=your-google-client-id
29
+ GOOGLE_CLIENT_SECRET=your-google-client-secret
30
+
31
+ # App URL
32
+ PUBLIC_APP_URL=http://localhost:5173 # or your production URL
33
+ ```
34
+
35
+ ## Architecture
36
+
37
+ HyleKit supports a BFF (Backend-For-Frontend) architecture:
38
+
39
+ ```
40
+ ┌─────────────────────────────────────────────────────────────────┐
41
+ │ Browser (Client FE) │
42
+ │ └── Uses: hyle.client (signIn, signOut, etc.) │
43
+ └─────────────────────────────────┬───────────────────────────────┘
44
+
45
+
46
+ ┌─────────────────────────────────────────────────────────────────┐
47
+ │ Next.js / SvelteKit Backend (BFF) │
48
+ │ ├── Auth: hyle.server (getSession, handler, etc.) │
49
+ │ └── Calls Express via: hyle.bff (BffClient) │
50
+ │ └── Attaches session as x-hyle-user/x-hyle-session headers │
51
+ └─────────────────────────────────┬───────────────────────────────┘
52
+
53
+
54
+ ┌─────────────────────────────────────────────────────────────────┐
55
+ │ Express Backend │
56
+ │ └── Uses: hyle.server.express.middleware() │
57
+ │ └── Parses headers → req.authUser, req.authSession │
58
+ │ └── Optional: DB verification for service-to-service calls │
59
+ └─────────────────────────────────────────────────────────────────┘
60
+ ```
61
+
62
+ ---
63
+
64
+ ## SvelteKit Setup
65
+
66
+ ### 1. Create Auth Route Handler
67
+
68
+ Create the auth API route to handle authentication requests:
69
+
70
+ ```typescript
71
+ // src/routes/api/auth/[...auth]/+server.ts
72
+ import hyle from "hylekit";
73
+
74
+ export const { GET, POST } = hyle.server.sveltekit.handler;
75
+ ```
76
+
77
+ ### 2. Add Session Hook
78
+
79
+ Add the handle hook to populate session data in `event.locals`:
80
+
81
+ ```typescript
82
+ // src/hooks.server.ts
83
+ import hyle from "hylekit";
84
+
85
+ export const handle = hyle.server.sveltekit.createHandle();
86
+ ```
87
+
88
+ ### 3. Extend App.Locals Types
89
+
90
+ Update your type definitions to include session data:
91
+
92
+ ```typescript
93
+ // src/app.d.ts
94
+ import type { SessionResult, UserInfo } from "hylekit";
95
+
96
+ declare global {
97
+ namespace App {
98
+ interface Locals {
99
+ session: SessionResult;
100
+ user: UserInfo | null;
101
+ }
102
+ }
103
+ }
104
+
105
+ export {};
106
+ ```
107
+
108
+ ### 4. Use in Pages
109
+
110
+ Access session data in your server load functions:
111
+
112
+ ```typescript
113
+ // src/routes/+page.server.ts
114
+ import type { PageServerLoad } from "./$types";
115
+
116
+ export const load: PageServerLoad = async ({ locals }) => {
117
+ return {
118
+ user: locals.user,
119
+ };
120
+ };
121
+ ```
122
+
123
+ ```svelte
124
+ <!-- src/routes/+page.svelte -->
125
+ <script lang="ts">
126
+ export let data;
127
+ </script>
128
+
129
+ {#if data.user}
130
+ <p>Welcome, {data.user.name}!</p>
131
+ <a href="/api/auth/sign-out">Sign out</a>
132
+ {:else}
133
+ <a href="/api/auth/sign-in/google">Sign in with Google</a>
134
+ {/if}
135
+ ```
136
+
137
+ ---
138
+
139
+ ## Next.js Setup (App Router)
140
+
141
+ ### 1. Create Auth Route Handler
142
+
143
+ Create the auth API route to handle authentication requests:
144
+
145
+ ```typescript
146
+ // app/api/auth/[...auth]/route.ts
147
+ import hyle from "hylekit";
148
+
149
+ export const { GET, POST } = hyle.server.nextjs.handler;
150
+ ```
151
+
152
+ ### 2. Use in Server Components
153
+
154
+ Access session data directly in your server components:
155
+
156
+ ```typescript
157
+ // app/page.tsx
158
+ import hyle from "hylekit";
159
+
160
+ export default async function Page() {
161
+ const session = await hyle.server.nextjs.getSession();
162
+
163
+ if (!session) {
164
+ return (
165
+ <a href="/api/auth/sign-in/google">Sign in with Google</a>
166
+ );
167
+ }
168
+
169
+ return (
170
+ <div>
171
+ <p>Welcome, {session.user.name}!</p>
172
+ <a href="/api/auth/sign-out">Sign out</a>
173
+ </div>
174
+ );
175
+ }
176
+ ```
177
+
178
+ ### 3. Protected Routes
179
+
180
+ Use the auth helpers to protect routes:
181
+
182
+ ```typescript
183
+ // app/dashboard/page.tsx
184
+ import hyle from "hylekit";
185
+ import { redirect } from "next/navigation";
186
+
187
+ export default async function DashboardPage() {
188
+ const isAuth = await hyle.server.nextjs.isAuthenticated();
189
+
190
+ if (!isAuth) {
191
+ redirect("/api/auth/sign-in/google");
192
+ }
193
+
194
+ const user = await hyle.server.nextjs.getUser();
195
+
196
+ return <p>Dashboard for {user?.name}</p>;
197
+ }
198
+ ```
199
+
200
+ ---
201
+
202
+ ## BFF Pattern with Express
203
+
204
+ ### 1. Setup Express Middleware
205
+
206
+ Configure the Express middleware to parse authenticated requests:
207
+
208
+ ```typescript
209
+ // express-app/src/app.ts
210
+ import express from "express";
211
+ import hyle from "hylekit";
212
+
213
+ const app = express();
214
+
215
+ // Option 1: Trust headers from BFF (internal calls only)
216
+ app.use(hyle.server.express.middleware({
217
+ unauthenticatedRoutes: ["/health", "/public/*"],
218
+ }));
219
+
220
+ // Option 2: Verify sessions against DB (for service-to-service calls)
221
+ app.use(hyle.server.express.middleware({
222
+ unauthenticatedRoutes: ["/health", "/public/*"],
223
+ verifySession: true, // Checks session in Turso DB
224
+ }));
225
+ ```
226
+
227
+ ### 2. Access Auth Context in Routes
228
+
229
+ Use `req.authUser` and `req.authSession` in your route handlers:
230
+
231
+ ```typescript
232
+ import type { AuthenticatedRequest } from "hylekit";
233
+
234
+ app.get("/api/profile", (req: AuthenticatedRequest, res) => {
235
+ // authUser is always available on authenticated routes
236
+ res.json({
237
+ userId: req.authUser.id,
238
+ email: req.authUser.email,
239
+ name: req.authUser.name,
240
+ });
241
+ });
242
+
243
+ app.post("/api/settings", (req: AuthenticatedRequest, res) => {
244
+ // Access full session data
245
+ console.log("Session expires:", req.authSession.expiresAt);
246
+
247
+ // Your business logic here
248
+ res.json({ success: true });
249
+ });
250
+ ```
251
+
252
+ ### 3. Using Helper Functions
253
+
254
+ ```typescript
255
+ import { isAuthenticated, getAuthContext } from "hylekit";
256
+
257
+ // Type guard for optional auth routes
258
+ app.get("/api/greeting", (req, res) => {
259
+ if (isAuthenticated(req)) {
260
+ res.json({ message: `Hello, ${req.authUser.name}!` });
261
+ } else {
262
+ res.json({ message: "Hello, guest!" });
263
+ }
264
+ });
265
+
266
+ // Get auth context with error handling
267
+ app.post("/api/order", (req, res) => {
268
+ try {
269
+ const { user, session } = getAuthContext(req);
270
+ // Proceed with authenticated user
271
+ } catch (e) {
272
+ res.status(401).json({ error: "Not authenticated" });
273
+ }
274
+ });
275
+ ```
276
+
277
+ ### 4. Call Express from Next.js/SvelteKit
278
+
279
+ Use the BFF client to make authenticated calls from your frontend backend:
280
+
281
+ ```typescript
282
+ // Next.js: app/api/data/route.ts
283
+ import { createNextJsBff } from "hylekit";
284
+
285
+ const bff = createNextJsBff(process.env.EXPRESS_API_URL!);
286
+
287
+ export async function GET() {
288
+ // Session is automatically attached to the request
289
+ const data = await bff.get("/api/profile");
290
+ return Response.json(data);
291
+ }
292
+ ```
293
+
294
+ ```typescript
295
+ // SvelteKit: src/routes/api/data/+server.ts
296
+ import { createSvelteKitBff } from "hylekit";
297
+ import type { RequestHandler } from "./$types";
298
+
299
+ const bff = createSvelteKitBff(process.env.EXPRESS_API_URL!);
300
+
301
+ export const GET: RequestHandler = async (event) => {
302
+ // Use .with(event) to bind the request context
303
+ const data = await bff.with(event).get("/api/profile");
304
+ return new Response(JSON.stringify(data));
305
+ };
306
+ ```
307
+
308
+ ### Middleware Options
309
+
310
+ | Option | Type | Default | Description |
311
+ |--------|------|---------|-------------|
312
+ | `unauthenticatedRoutes` | `string[]` | `[]` | Routes that skip authentication |
313
+ | `verifySession` | `boolean` | `false` | Verify session against DB (for service-to-service) |
314
+ | `required` | `boolean` | `true` | Return 401 for unauthenticated requests |
315
+
316
+ ### Route Pattern Examples
317
+
318
+ ```typescript
319
+ unauthenticatedRoutes: [
320
+ "/health", // Exact match
321
+ "/public/*", // Matches /public/anything (single level)
322
+ "/api/webhooks/**", // Matches /api/webhooks/a/b/c (deep)
323
+ ]
324
+ ```
325
+
326
+ ---
327
+
328
+ ## Database Schema
329
+
330
+ HyleKit uses Drizzle ORM. You can import the schema definitions for use with Drizzle Kit or migration tools.
331
+
332
+ ```typescript
333
+ // Import all schema definitions
334
+ import hyle from "hylekit";
335
+
336
+ const { user, session, account, verification } = hyle.schema;
337
+ ```
338
+
339
+ ---
340
+
341
+ ## API Reference
342
+
343
+ The library exports a default `hyle` object containing:
344
+
345
+ ### `hyle.server`
346
+
347
+ #### `hyle.server.sveltekit`
348
+ - `handler`: `{ GET, POST }` route handlers.
349
+ - `createHandle()`: Creates a SvelteKit handle hook.
350
+ - `getSession(event)`: Get session from request event.
351
+ - `isAuthenticated(event)`: Check if user is authenticated.
352
+ - `makeAuthenticatedCall(fn)`: Wrapper to ensure authentication.
353
+
354
+ #### `hyle.server.nextjs`
355
+ - `handler`: `{ GET, POST }` route handlers.
356
+ - `getSession()`: Get session from current request headers.
357
+ - `isAuthenticated()`: Check if user is authenticated.
358
+ - `getUser()`: Get current user object.
359
+ - `makeAuthenticatedCall(fn)`: Wrapper to ensure authentication.
360
+
361
+ #### `hyle.server.express`
362
+ - `middleware(options)`: Express middleware for session verification.
363
+ - `isAuthenticated(req)`: Type guard to check if request is authenticated.
364
+ - `getAuthContext(req)`: Get `{ user, session }` from request (throws if not authenticated).
365
+
366
+ ### `hyle.client`
367
+
368
+ #### `hyle.client.sveltekit`
369
+ - `login`: Alias for `signIn`.
370
+ - All `better-auth/svelte` client methods.
371
+
372
+ #### `hyle.client.nextjs`
373
+ - `login`: Alias for `signIn`.
374
+ - All `better-auth/react` client methods.
375
+
376
+ ### `hyle.bff`
377
+
378
+ #### `hyle.bff.createNextJsBff(config)`
379
+ Creates a BFF client for Next.js that automatically attaches session headers.
380
+
381
+ #### `hyle.bff.createSvelteKitBff(config)`
382
+ Creates a BFF client for SvelteKit that automatically attaches session headers.
383
+
384
+ ### Types
385
+
386
+ ```typescript
387
+ import type {
388
+ SessionResult,
389
+ SessionData,
390
+ UserInfo,
391
+ Session,
392
+ User,
393
+ BffClientConfig,
394
+ RequestOptions,
395
+ AuthenticatedRequest,
396
+ MiddlewareOptions,
397
+ } from "hylekit";
398
+ ```
399
+
400
+ ## License
401
+
402
+ ISC