hylekit 1.0.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.
package/dist/index.js ADDED
@@ -0,0 +1,666 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __export = (target, all) => {
3
+ for (var name in all)
4
+ __defProp(target, name, { get: all[name], enumerable: true });
5
+ };
6
+
7
+ // src/auth.ts
8
+ import { betterAuth } from "better-auth";
9
+ import { drizzleAdapter } from "better-auth/adapters/drizzle";
10
+
11
+ // src/schema.ts
12
+ var schema_exports = {};
13
+ __export(schema_exports, {
14
+ account: () => account,
15
+ accountRelations: () => accountRelations,
16
+ oauthAccessToken: () => oauthAccessToken,
17
+ oauthAccessTokenRelations: () => oauthAccessTokenRelations,
18
+ oauthApplication: () => oauthApplication,
19
+ oauthApplicationRelations: () => oauthApplicationRelations,
20
+ oauthConsent: () => oauthConsent,
21
+ oauthConsentRelations: () => oauthConsentRelations,
22
+ session: () => session,
23
+ sessionRelations: () => sessionRelations,
24
+ user: () => user,
25
+ userRelations: () => userRelations,
26
+ verification: () => verification
27
+ });
28
+ import { relations, sql } from "drizzle-orm";
29
+ import { sqliteTable, text, integer, index } from "drizzle-orm/sqlite-core";
30
+ var user = sqliteTable("user", {
31
+ id: text("id").primaryKey(),
32
+ name: text("name").notNull(),
33
+ email: text("email").notNull().unique(),
34
+ emailVerified: integer("email_verified", { mode: "boolean" }).default(false).notNull(),
35
+ image: text("image"),
36
+ createdAt: integer("created_at", { mode: "timestamp_ms" }).default(sql`(cast(unixepoch('subsecond') * 1000 as integer))`).notNull(),
37
+ updatedAt: integer("updated_at", { mode: "timestamp_ms" }).default(sql`(cast(unixepoch('subsecond') * 1000 as integer))`).$onUpdate(() => /* @__PURE__ */ new Date()).notNull()
38
+ });
39
+ var session = sqliteTable(
40
+ "session",
41
+ {
42
+ id: text("id").primaryKey(),
43
+ expiresAt: integer("expires_at", { mode: "timestamp_ms" }).notNull(),
44
+ token: text("token").notNull().unique(),
45
+ createdAt: integer("created_at", { mode: "timestamp_ms" }).default(sql`(cast(unixepoch('subsecond') * 1000 as integer))`).notNull(),
46
+ updatedAt: integer("updated_at", { mode: "timestamp_ms" }).$onUpdate(() => /* @__PURE__ */ new Date()).notNull(),
47
+ ipAddress: text("ip_address"),
48
+ userAgent: text("user_agent"),
49
+ userId: text("user_id").notNull().references(() => user.id, { onDelete: "cascade" })
50
+ },
51
+ (table) => [index("session_userId_idx").on(table.userId)]
52
+ );
53
+ var account = sqliteTable(
54
+ "account",
55
+ {
56
+ id: text("id").primaryKey(),
57
+ accountId: text("account_id").notNull(),
58
+ providerId: text("provider_id").notNull(),
59
+ userId: text("user_id").notNull().references(() => user.id, { onDelete: "cascade" }),
60
+ accessToken: text("access_token"),
61
+ refreshToken: text("refresh_token"),
62
+ idToken: text("id_token"),
63
+ accessTokenExpiresAt: integer("access_token_expires_at", {
64
+ mode: "timestamp_ms"
65
+ }),
66
+ refreshTokenExpiresAt: integer("refresh_token_expires_at", {
67
+ mode: "timestamp_ms"
68
+ }),
69
+ scope: text("scope"),
70
+ password: text("password"),
71
+ createdAt: integer("created_at", { mode: "timestamp_ms" }).default(sql`(cast(unixepoch('subsecond') * 1000 as integer))`).notNull(),
72
+ updatedAt: integer("updated_at", { mode: "timestamp_ms" }).$onUpdate(() => /* @__PURE__ */ new Date()).notNull()
73
+ },
74
+ (table) => [index("account_userId_idx").on(table.userId)]
75
+ );
76
+ var verification = sqliteTable(
77
+ "verification",
78
+ {
79
+ id: text("id").primaryKey(),
80
+ identifier: text("identifier").notNull(),
81
+ value: text("value").notNull(),
82
+ expiresAt: integer("expires_at", { mode: "timestamp_ms" }).notNull(),
83
+ createdAt: integer("created_at", { mode: "timestamp_ms" }).default(sql`(cast(unixepoch('subsecond') * 1000 as integer))`).notNull(),
84
+ updatedAt: integer("updated_at", { mode: "timestamp_ms" }).default(sql`(cast(unixepoch('subsecond') * 1000 as integer))`).$onUpdate(() => /* @__PURE__ */ new Date()).notNull()
85
+ },
86
+ (table) => [index("verification_identifier_idx").on(table.identifier)]
87
+ );
88
+ var oauthApplication = sqliteTable(
89
+ "oauth_application",
90
+ {
91
+ id: text("id").primaryKey(),
92
+ name: text("name"),
93
+ icon: text("icon"),
94
+ metadata: text("metadata"),
95
+ clientId: text("client_id").unique(),
96
+ clientSecret: text("client_secret"),
97
+ redirectUrls: text("redirect_urls"),
98
+ type: text("type"),
99
+ disabled: integer("disabled", { mode: "boolean" }).default(false),
100
+ userId: text("user_id").references(() => user.id, { onDelete: "cascade" }),
101
+ createdAt: integer("created_at", { mode: "timestamp_ms" }),
102
+ updatedAt: integer("updated_at", { mode: "timestamp_ms" })
103
+ },
104
+ (table) => [index("oauthApplication_userId_idx").on(table.userId)]
105
+ );
106
+ var oauthAccessToken = sqliteTable(
107
+ "oauth_access_token",
108
+ {
109
+ id: text("id").primaryKey(),
110
+ accessToken: text("access_token").unique(),
111
+ refreshToken: text("refresh_token").unique(),
112
+ accessTokenExpiresAt: integer("access_token_expires_at", {
113
+ mode: "timestamp_ms"
114
+ }),
115
+ refreshTokenExpiresAt: integer("refresh_token_expires_at", {
116
+ mode: "timestamp_ms"
117
+ }),
118
+ clientId: text("client_id").references(() => oauthApplication.clientId, {
119
+ onDelete: "cascade"
120
+ }),
121
+ userId: text("user_id").references(() => user.id, { onDelete: "cascade" }),
122
+ scopes: text("scopes"),
123
+ createdAt: integer("created_at", { mode: "timestamp_ms" }),
124
+ updatedAt: integer("updated_at", { mode: "timestamp_ms" })
125
+ },
126
+ (table) => [
127
+ index("oauthAccessToken_clientId_idx").on(table.clientId),
128
+ index("oauthAccessToken_userId_idx").on(table.userId)
129
+ ]
130
+ );
131
+ var oauthConsent = sqliteTable(
132
+ "oauth_consent",
133
+ {
134
+ id: text("id").primaryKey(),
135
+ clientId: text("client_id").references(() => oauthApplication.clientId, {
136
+ onDelete: "cascade"
137
+ }),
138
+ userId: text("user_id").references(() => user.id, { onDelete: "cascade" }),
139
+ scopes: text("scopes"),
140
+ createdAt: integer("created_at", { mode: "timestamp_ms" }),
141
+ updatedAt: integer("updated_at", { mode: "timestamp_ms" }),
142
+ consentGiven: integer("consent_given", { mode: "boolean" })
143
+ },
144
+ (table) => [
145
+ index("oauthConsent_clientId_idx").on(table.clientId),
146
+ index("oauthConsent_userId_idx").on(table.userId)
147
+ ]
148
+ );
149
+ var userRelations = relations(user, ({ many }) => ({
150
+ sessions: many(session),
151
+ accounts: many(account),
152
+ oauthApplications: many(oauthApplication),
153
+ oauthAccessTokens: many(oauthAccessToken),
154
+ oauthConsents: many(oauthConsent)
155
+ }));
156
+ var sessionRelations = relations(session, ({ one }) => ({
157
+ user: one(user, {
158
+ fields: [session.userId],
159
+ references: [user.id]
160
+ })
161
+ }));
162
+ var accountRelations = relations(account, ({ one }) => ({
163
+ user: one(user, {
164
+ fields: [account.userId],
165
+ references: [user.id]
166
+ })
167
+ }));
168
+ var oauthApplicationRelations = relations(
169
+ oauthApplication,
170
+ ({ one, many }) => ({
171
+ user: one(user, {
172
+ fields: [oauthApplication.userId],
173
+ references: [user.id]
174
+ }),
175
+ oauthAccessTokens: many(oauthAccessToken),
176
+ oauthConsents: many(oauthConsent)
177
+ })
178
+ );
179
+ var oauthAccessTokenRelations = relations(
180
+ oauthAccessToken,
181
+ ({ one }) => ({
182
+ oauthApplication: one(oauthApplication, {
183
+ fields: [oauthAccessToken.clientId],
184
+ references: [oauthApplication.clientId]
185
+ }),
186
+ user: one(user, {
187
+ fields: [oauthAccessToken.userId],
188
+ references: [user.id]
189
+ })
190
+ })
191
+ );
192
+ var oauthConsentRelations = relations(oauthConsent, ({ one }) => ({
193
+ oauthApplication: one(oauthApplication, {
194
+ fields: [oauthConsent.clientId],
195
+ references: [oauthApplication.clientId]
196
+ }),
197
+ user: one(user, {
198
+ fields: [oauthConsent.userId],
199
+ references: [user.id]
200
+ })
201
+ }));
202
+
203
+ // src/auth.ts
204
+ var createAuth = (db, config) => {
205
+ return betterAuth({
206
+ database: drizzleAdapter(db, {
207
+ provider: "sqlite",
208
+ schema: {
209
+ ...schema_exports
210
+ }
211
+ }),
212
+ socialProviders: {
213
+ google: {
214
+ enabled: true,
215
+ clientId: process.env.GOOGLE_CLIENT_ID ?? "",
216
+ clientSecret: process.env.GOOGLE_CLIENT_SECRET ?? ""
217
+ }
218
+ },
219
+ ...config
220
+ });
221
+ };
222
+
223
+ // src/client/types.ts
224
+ var DEFAULT_CONFIG = {
225
+ authorizeEndpoint: "/api/auth/oauth2/authorize",
226
+ tokenEndpoint: "/api/auth/oauth2/token",
227
+ userEndpoint: "/api/auth/oauth2/userinfo",
228
+ cookieName: "access_token",
229
+ cookieMaxAge: 60 * 60 * 24 * 7
230
+ // 7 Days
231
+ };
232
+ function resolveConfig(config) {
233
+ return {
234
+ ...DEFAULT_CONFIG,
235
+ ...config
236
+ };
237
+ }
238
+ function buildAuthorizationUrl(config, clientConfig, options) {
239
+ const targetUrl = new URL(config.url + config.authorizeEndpoint);
240
+ const scopes = ["openid", "profile", "email"];
241
+ if (options?.additionalScopes) {
242
+ scopes.push(...options.additionalScopes);
243
+ }
244
+ targetUrl.searchParams.set("response_type", "code");
245
+ targetUrl.searchParams.set("client_id", clientConfig.clientId);
246
+ targetUrl.searchParams.set("redirect_uri", clientConfig.redirectUri);
247
+ targetUrl.searchParams.set("scope", scopes.join(" "));
248
+ if (options?.state) {
249
+ targetUrl.searchParams.set("state", options.state);
250
+ }
251
+ return targetUrl.toString();
252
+ }
253
+ async function exchangeCodeForTokens(config, clientConfig, code) {
254
+ const response = await fetch(config.url + config.tokenEndpoint, {
255
+ method: "POST",
256
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
257
+ body: new URLSearchParams({
258
+ grant_type: "authorization_code",
259
+ client_id: clientConfig.clientId,
260
+ client_secret: clientConfig.clientSecret,
261
+ redirect_uri: clientConfig.redirectUri,
262
+ code
263
+ })
264
+ });
265
+ if (!response.ok) {
266
+ const errorText = await response.text();
267
+ throw new Error(`Token exchange failed (${response.status}): ${errorText}`);
268
+ }
269
+ const tokens = await response.json();
270
+ if (!tokens.access_token) {
271
+ throw new Error("No access token in response");
272
+ }
273
+ return tokens;
274
+ }
275
+ async function fetchUserInfo(config, accessToken) {
276
+ try {
277
+ const response = await fetch(config.url + config.userEndpoint, {
278
+ headers: {
279
+ "Authorization": `Bearer ${accessToken}`
280
+ }
281
+ });
282
+ if (!response.ok) {
283
+ return null;
284
+ }
285
+ return await response.json();
286
+ } catch {
287
+ return null;
288
+ }
289
+ }
290
+
291
+ // src/client/sveltekit.ts
292
+ import { redirect } from "@sveltejs/kit";
293
+ function createSvelteKitClient(centralAuthConfig) {
294
+ const config = resolveConfig(centralAuthConfig);
295
+ return {
296
+ /**
297
+ * Get the current Central Auth configuration.
298
+ */
299
+ getConfig: () => ({ ...config }),
300
+ /**
301
+ * Initiates the OAuth2 sign-in flow by redirecting to the Central Auth Server.
302
+ * Uses SvelteKit's redirect() which throws a redirect response.
303
+ *
304
+ * @param clientConfig - OAuth2 client configuration
305
+ * @param options - Optional sign-in options
306
+ * @throws Redirect to the Central Auth authorization endpoint
307
+ */
308
+ signIn: (clientConfig, options) => {
309
+ const authUrl = buildAuthorizationUrl(config, clientConfig, options);
310
+ redirect(302, authUrl);
311
+ },
312
+ /**
313
+ * Builds the authorization URL without redirecting.
314
+ * Useful when you need to return the URL for client-side navigation.
315
+ *
316
+ * @param clientConfig - OAuth2 client configuration
317
+ * @param options - Optional sign-in options
318
+ * @returns The authorization URL string
319
+ */
320
+ getSignInUrl: (clientConfig, options) => {
321
+ return buildAuthorizationUrl(config, clientConfig, options);
322
+ },
323
+ /**
324
+ * Handles the OAuth2 callback, exchanges the code for tokens, and sets the session cookie.
325
+ * Uses SvelteKit's cookies API for cookie management.
326
+ *
327
+ * @param event - SvelteKit RequestEvent
328
+ * @param clientConfig - OAuth2 client configuration
329
+ * @param options - Optional callback options
330
+ * @throws Redirect on success, throws error on failure
331
+ */
332
+ handleSignInCallback: async (event, clientConfig, options) => {
333
+ const { url, cookies: cookies2 } = event;
334
+ const code = url.searchParams.get("code");
335
+ const error = url.searchParams.get("error");
336
+ const errorDescription = url.searchParams.get("error_description");
337
+ if (error) {
338
+ throw new Error(`Authentication failed: ${errorDescription || error}`);
339
+ }
340
+ if (!code) {
341
+ throw new Error("Missing authorization code");
342
+ }
343
+ try {
344
+ const tokens = await exchangeCodeForTokens(config, clientConfig, code);
345
+ cookies2.set(config.cookieName, tokens.access_token, {
346
+ httpOnly: true,
347
+ secure: event.url.protocol === "https:",
348
+ sameSite: "lax",
349
+ path: "/",
350
+ maxAge: config.cookieMaxAge
351
+ });
352
+ const successPath = options?.successRedirectPath || "/";
353
+ redirect(302, successPath);
354
+ } catch (err) {
355
+ if (err && typeof err === "object" && "status" in err) {
356
+ throw err;
357
+ }
358
+ console.error("Auth callback error:", err);
359
+ throw new Error("Authentication failed");
360
+ }
361
+ },
362
+ /**
363
+ * Signs out the user by clearing the session cookie.
364
+ *
365
+ * @param cookies - SvelteKit Cookies object
366
+ * @param redirectPath - Path to redirect to after sign out (default: "/")
367
+ * @throws Redirect to the specified path
368
+ */
369
+ signOut: (cookies2, redirectPath = "/") => {
370
+ cookies2.delete(config.cookieName, { path: "/" });
371
+ redirect(302, redirectPath);
372
+ },
373
+ /**
374
+ * Clears the session cookie without redirecting.
375
+ * Useful when you need more control over the response.
376
+ *
377
+ * @param cookies - SvelteKit Cookies object
378
+ */
379
+ clearSession: (cookies2) => {
380
+ cookies2.delete(config.cookieName, { path: "/" });
381
+ },
382
+ /**
383
+ * Retrieves the access token from cookies.
384
+ *
385
+ * @param cookies - SvelteKit Cookies object
386
+ * @returns The access token or null if not found
387
+ */
388
+ getAccessToken: (cookies2) => {
389
+ return cookies2.get(config.cookieName) ?? null;
390
+ },
391
+ /**
392
+ * Fetches user information from the Central Auth Server.
393
+ *
394
+ * @param accessToken - The access token to use for authentication
395
+ * @returns The user information or null if the request fails
396
+ */
397
+ getUser: async (accessToken) => {
398
+ return fetchUserInfo(config, accessToken);
399
+ },
400
+ /**
401
+ * Gets the current user session from cookies.
402
+ * Combines getAccessToken and getUser for convenience.
403
+ *
404
+ * @param cookies - SvelteKit Cookies object
405
+ * @returns The user information or null if not authenticated
406
+ */
407
+ getSession: async (cookies2) => {
408
+ const accessToken = cookies2.get(config.cookieName);
409
+ if (!accessToken) return null;
410
+ return fetchUserInfo(config, accessToken);
411
+ },
412
+ /**
413
+ * Checks if the user is authenticated (has access token in cookies).
414
+ * Note: This only checks for token presence, not validity.
415
+ *
416
+ * @param cookies - SvelteKit Cookies object
417
+ * @returns true if an access token is present
418
+ */
419
+ isAuthenticated: (cookies2) => {
420
+ return !!cookies2.get(config.cookieName);
421
+ },
422
+ /**
423
+ * Protects a route by checking authentication and redirecting if needed.
424
+ * Use in +page.server.ts or +layout.server.ts load functions.
425
+ *
426
+ * @param cookies - SvelteKit Cookies object
427
+ * @param loginPath - Path to redirect to for login (default: "/login")
428
+ * @throws Redirect to login path if not authenticated
429
+ */
430
+ requireAuth: (cookies2, loginPath = "/login") => {
431
+ if (!cookies2.get(config.cookieName)) {
432
+ redirect(302, loginPath);
433
+ }
434
+ }
435
+ };
436
+ }
437
+ var svelteClient = createSvelteKitClient;
438
+
439
+ // src/client/nextjs.ts
440
+ import { cookies } from "next/headers";
441
+ import { redirect as redirect2 } from "next/navigation";
442
+ import { NextResponse } from "next/server";
443
+ function createNextClient(centralAuthConfig) {
444
+ const config = resolveConfig(centralAuthConfig);
445
+ return {
446
+ /**
447
+ * Get the current Central Auth configuration.
448
+ */
449
+ getConfig: () => ({ ...config }),
450
+ /**
451
+ * Initiates the OAuth2 sign-in flow by returning a redirect Response.
452
+ * Use in Route Handlers (App Router).
453
+ *
454
+ * @param clientConfig - OAuth2 client configuration
455
+ * @param options - Optional sign-in options
456
+ * @returns NextResponse redirect to the Central Auth authorization endpoint
457
+ */
458
+ signIn: (clientConfig, options) => {
459
+ const authUrl = buildAuthorizationUrl(config, clientConfig, options);
460
+ return NextResponse.redirect(authUrl);
461
+ },
462
+ /**
463
+ * Builds the authorization URL without redirecting.
464
+ * Useful for client-side navigation or custom redirect logic.
465
+ *
466
+ * @param clientConfig - OAuth2 client configuration
467
+ * @param options - Optional sign-in options
468
+ * @returns The authorization URL string
469
+ */
470
+ getSignInUrl: (clientConfig, options) => {
471
+ return buildAuthorizationUrl(config, clientConfig, options);
472
+ },
473
+ /**
474
+ * Handles the OAuth2 callback in Route Handlers.
475
+ * Exchanges the code for tokens and sets the session cookie.
476
+ *
477
+ * @param request - NextRequest object
478
+ * @param clientConfig - OAuth2 client configuration
479
+ * @param options - Optional callback options
480
+ * @returns NextResponse with redirect and cookie set
481
+ */
482
+ handleSignInCallback: async (request, clientConfig, options) => {
483
+ const { searchParams } = new URL(request.url);
484
+ const code = searchParams.get("code");
485
+ const error = searchParams.get("error");
486
+ const errorDescription = searchParams.get("error_description");
487
+ if (error) {
488
+ return NextResponse.json(
489
+ { error: errorDescription || error },
490
+ { status: 400 }
491
+ );
492
+ }
493
+ if (!code) {
494
+ return NextResponse.json(
495
+ { error: "Missing authorization code" },
496
+ { status: 400 }
497
+ );
498
+ }
499
+ try {
500
+ const tokens = await exchangeCodeForTokens(config, clientConfig, code);
501
+ const successPath = options?.successRedirectPath || "/";
502
+ const successUrl = new URL(successPath, clientConfig.appUrl);
503
+ const response = NextResponse.redirect(successUrl);
504
+ response.cookies.set(config.cookieName, tokens.access_token, {
505
+ httpOnly: true,
506
+ secure: process.env.NODE_ENV === "production",
507
+ sameSite: "lax",
508
+ path: "/",
509
+ maxAge: config.cookieMaxAge
510
+ });
511
+ return response;
512
+ } catch (err) {
513
+ console.error("Auth callback error:", err);
514
+ return NextResponse.json(
515
+ { error: "Authentication failed" },
516
+ { status: 500 }
517
+ );
518
+ }
519
+ },
520
+ /**
521
+ * Signs out the user by clearing the session cookie.
522
+ * Use in Route Handlers.
523
+ *
524
+ * @param clientConfig - OAuth2 client configuration
525
+ * @param redirectPath - Path to redirect to after sign out (default: "/")
526
+ * @returns NextResponse with redirect and cookie cleared
527
+ */
528
+ signOut: (clientConfig, redirectPath = "/") => {
529
+ const redirectUrl = new URL(redirectPath, clientConfig.appUrl);
530
+ const response = NextResponse.redirect(redirectUrl);
531
+ response.cookies.set(config.cookieName, "", {
532
+ httpOnly: true,
533
+ secure: process.env.NODE_ENV === "production",
534
+ sameSite: "lax",
535
+ path: "/",
536
+ maxAge: 0
537
+ });
538
+ return response;
539
+ },
540
+ /**
541
+ * Retrieves the access token from cookies.
542
+ * Use in Server Components or Route Handlers.
543
+ *
544
+ * @returns The access token or null if not found
545
+ */
546
+ getAccessToken: async () => {
547
+ const cookieStore = await cookies();
548
+ return cookieStore.get(config.cookieName)?.value ?? null;
549
+ },
550
+ /**
551
+ * Retrieves the access token from a NextRequest.
552
+ * Use in middleware or Route Handlers when you have the request object.
553
+ *
554
+ * @param request - NextRequest object
555
+ * @returns The access token or null if not found
556
+ */
557
+ getAccessTokenFromRequest: (request) => {
558
+ return request.cookies.get(config.cookieName)?.value ?? null;
559
+ },
560
+ /**
561
+ * Fetches user information from the Central Auth Server.
562
+ *
563
+ * @param accessToken - The access token to use for authentication
564
+ * @returns The user information or null if the request fails
565
+ */
566
+ getUser: async (accessToken) => {
567
+ return fetchUserInfo(config, accessToken);
568
+ },
569
+ /**
570
+ * Gets the current user session.
571
+ * Use in Server Components.
572
+ *
573
+ * @returns The user information or null if not authenticated
574
+ */
575
+ getSession: async () => {
576
+ const cookieStore = await cookies();
577
+ const accessToken = cookieStore.get(config.cookieName)?.value;
578
+ if (!accessToken) return null;
579
+ return fetchUserInfo(config, accessToken);
580
+ },
581
+ /**
582
+ * Gets the current user session from a request.
583
+ * Use in middleware or Route Handlers.
584
+ *
585
+ * @param request - NextRequest object
586
+ * @returns The user information or null if not authenticated
587
+ */
588
+ getSessionFromRequest: async (request) => {
589
+ const accessToken = request.cookies.get(config.cookieName)?.value;
590
+ if (!accessToken) return null;
591
+ return fetchUserInfo(config, accessToken);
592
+ },
593
+ /**
594
+ * Checks if the user is authenticated.
595
+ * Use in Server Components.
596
+ *
597
+ * @returns true if an access token is present
598
+ */
599
+ isAuthenticated: async () => {
600
+ const cookieStore = await cookies();
601
+ return !!cookieStore.get(config.cookieName)?.value;
602
+ },
603
+ /**
604
+ * Checks if the request is authenticated.
605
+ * Use in middleware.
606
+ *
607
+ * @param request - NextRequest object
608
+ * @returns true if an access token is present
609
+ */
610
+ isAuthenticatedRequest: (request) => {
611
+ return !!request.cookies.get(config.cookieName)?.value;
612
+ },
613
+ /**
614
+ * Protects a route by checking authentication and redirecting if needed.
615
+ * Use in Server Components.
616
+ *
617
+ * @param loginPath - Path to redirect to for login (default: "/login")
618
+ * @throws Redirect to login path if not authenticated
619
+ */
620
+ requireAuth: async (loginPath = "/login") => {
621
+ const cookieStore = await cookies();
622
+ if (!cookieStore.get(config.cookieName)?.value) {
623
+ redirect2(loginPath);
624
+ }
625
+ },
626
+ /**
627
+ * Creates a middleware-compatible auth check.
628
+ * Returns a NextResponse redirect if not authenticated.
629
+ *
630
+ * @param request - NextRequest object
631
+ * @param loginPath - Path to redirect to for login (default: "/login")
632
+ * @returns NextResponse redirect if not authenticated, null otherwise
633
+ */
634
+ middlewareAuth: (request, loginPath = "/login") => {
635
+ if (!request.cookies.get(config.cookieName)?.value) {
636
+ const loginUrl = new URL(loginPath, request.url);
637
+ loginUrl.searchParams.set("from", request.nextUrl.pathname);
638
+ return NextResponse.redirect(loginUrl);
639
+ }
640
+ return null;
641
+ }
642
+ };
643
+ }
644
+ var nextClient = createNextClient;
645
+ export {
646
+ DEFAULT_CONFIG,
647
+ account,
648
+ accountRelations,
649
+ createAuth,
650
+ createNextClient,
651
+ createSvelteKitClient,
652
+ nextClient,
653
+ oauthAccessToken,
654
+ oauthAccessTokenRelations,
655
+ oauthApplication,
656
+ oauthApplicationRelations,
657
+ oauthConsent,
658
+ oauthConsentRelations,
659
+ session,
660
+ sessionRelations,
661
+ svelteClient,
662
+ user,
663
+ userRelations,
664
+ verification
665
+ };
666
+ //# sourceMappingURL=index.js.map