@onmax/nuxt-better-auth 0.0.1 → 0.0.2-alpha.2

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 (50) hide show
  1. package/README.md +17 -170
  2. package/dist/module.d.mts +20 -2
  3. package/dist/module.json +1 -1
  4. package/dist/module.mjs +363 -14
  5. package/dist/runtime/app/components/BetterAuthState.d.vue.ts +20 -0
  6. package/dist/runtime/app/components/BetterAuthState.vue +8 -0
  7. package/dist/runtime/app/components/BetterAuthState.vue.d.ts +20 -0
  8. package/dist/runtime/app/composables/useUserSession.d.ts +20 -0
  9. package/dist/runtime/app/composables/useUserSession.js +158 -0
  10. package/dist/runtime/app/middleware/auth.global.d.ts +13 -0
  11. package/dist/runtime/app/middleware/auth.global.js +31 -0
  12. package/dist/runtime/app/pages/__better-auth-devtools.d.vue.ts +3 -0
  13. package/dist/runtime/app/pages/__better-auth-devtools.vue +426 -0
  14. package/dist/runtime/app/pages/__better-auth-devtools.vue.d.ts +3 -0
  15. package/dist/runtime/app/plugins/session.client.d.ts +2 -0
  16. package/dist/runtime/app/plugins/session.client.js +16 -0
  17. package/dist/runtime/app/plugins/session.server.d.ts +2 -0
  18. package/dist/runtime/app/plugins/session.server.js +23 -0
  19. package/dist/runtime/config.d.ts +36 -0
  20. package/dist/runtime/config.js +6 -0
  21. package/dist/runtime/server/api/_better-auth/_schema.d.ts +8 -0
  22. package/dist/runtime/server/api/_better-auth/_schema.js +11 -0
  23. package/dist/runtime/server/api/_better-auth/accounts.get.d.ts +14 -0
  24. package/dist/runtime/server/api/_better-auth/accounts.get.js +28 -0
  25. package/dist/runtime/server/api/_better-auth/config.get.d.ts +35 -0
  26. package/dist/runtime/server/api/_better-auth/config.get.js +46 -0
  27. package/dist/runtime/server/api/_better-auth/sessions.delete.d.ts +4 -0
  28. package/dist/runtime/server/api/_better-auth/sessions.delete.js +22 -0
  29. package/dist/runtime/server/api/_better-auth/sessions.get.d.ts +14 -0
  30. package/dist/runtime/server/api/_better-auth/sessions.get.js +34 -0
  31. package/dist/runtime/server/api/_better-auth/users.get.d.ts +14 -0
  32. package/dist/runtime/server/api/_better-auth/users.get.js +34 -0
  33. package/dist/runtime/server/api/auth/[...all].d.ts +2 -0
  34. package/dist/runtime/server/api/auth/[...all].js +6 -0
  35. package/dist/runtime/server/middleware/route-access.d.ts +2 -0
  36. package/dist/runtime/server/middleware/route-access.js +28 -0
  37. package/dist/runtime/server/tsconfig.json +3 -0
  38. package/dist/runtime/server/utils/auth.d.ts +10 -0
  39. package/dist/runtime/server/utils/auth.js +32 -0
  40. package/dist/runtime/server/utils/session.d.ts +9 -0
  41. package/dist/runtime/server/utils/session.js +22 -0
  42. package/dist/runtime/types/augment.d.ts +42 -0
  43. package/dist/runtime/types/augment.js +0 -0
  44. package/dist/runtime/types.d.ts +23 -0
  45. package/dist/runtime/types.js +0 -0
  46. package/dist/runtime/utils/match-user.d.ts +2 -0
  47. package/dist/runtime/utils/match-user.js +13 -0
  48. package/dist/types.d.mts +8 -10
  49. package/package.json +35 -10
  50. package/dist/module.d.cts +0 -2
@@ -0,0 +1,16 @@
1
+ import { defineNuxtPlugin } from "#imports";
2
+ import { useUserSession } from "../composables/useUserSession.js";
3
+ export default defineNuxtPlugin(async (nuxtApp) => {
4
+ const { fetchSession } = useUserSession();
5
+ const safeFetch = async () => {
6
+ try {
7
+ await fetchSession();
8
+ } catch {
9
+ }
10
+ };
11
+ if (!nuxtApp.payload.serverRendered) {
12
+ await safeFetch();
13
+ } else if (nuxtApp.payload.prerenderedAt || nuxtApp.payload.isCached) {
14
+ nuxtApp.hook("app:mounted", safeFetch);
15
+ }
16
+ });
@@ -0,0 +1,2 @@
1
+ declare const _default: any;
2
+ export default _default;
@@ -0,0 +1,23 @@
1
+ import { defineNuxtPlugin, useRequestEvent, useRequestHeaders, useState } from "#imports";
2
+ export default defineNuxtPlugin({
3
+ name: "auth:session-init",
4
+ enforce: "pre",
5
+ async setup() {
6
+ const session = useState("auth:session", () => null);
7
+ const user = useState("auth:user", () => null);
8
+ const authReady = useState("auth:ready", () => false);
9
+ const event = useRequestEvent();
10
+ if (event) {
11
+ try {
12
+ const headers = useRequestHeaders(["cookie"]);
13
+ const data = await $fetch("/api/auth/get-session", { headers });
14
+ if (data?.session && data?.user) {
15
+ session.value = data.session;
16
+ user.value = data.user;
17
+ }
18
+ } catch {
19
+ }
20
+ }
21
+ authReady.value = true;
22
+ }
23
+ });
@@ -0,0 +1,36 @@
1
+ import type { BetterAuthOptions } from 'better-auth';
2
+ import type { ClientOptions } from 'better-auth/client';
3
+ import type { ServerAuthContext } from './types/augment.js';
4
+ export type { ServerAuthContext };
5
+ export interface ClientAuthContext {
6
+ siteUrl: string;
7
+ }
8
+ type ServerAuthConfig = Omit<BetterAuthOptions, 'database' | 'secret' | 'baseURL'>;
9
+ type ClientAuthConfig = Omit<ClientOptions, 'baseURL'> & {
10
+ baseURL?: string;
11
+ };
12
+ export type ServerAuthConfigFn = (ctx: ServerAuthContext) => ServerAuthConfig;
13
+ export type ClientAuthConfigFn = (ctx: ClientAuthContext) => ClientAuthConfig;
14
+ export interface BetterAuthModuleOptions {
15
+ /** Server config path relative to rootDir. Default: 'server/auth.config' */
16
+ serverConfig?: string;
17
+ /** Client config path relative to rootDir. Default: 'app/auth.config' */
18
+ clientConfig?: string;
19
+ redirects?: {
20
+ login?: string;
21
+ guest?: string;
22
+ };
23
+ /** Enable KV secondary storage for sessions. Requires hub.kv: true */
24
+ secondaryStorage?: boolean;
25
+ }
26
+ export interface AuthRuntimeConfig {
27
+ redirects: {
28
+ login: string;
29
+ guest: string;
30
+ };
31
+ }
32
+ export interface AuthPrivateRuntimeConfig {
33
+ secondaryStorage: boolean;
34
+ }
35
+ export declare function defineServerAuth<T extends ServerAuthConfig>(config: (ctx: ServerAuthContext) => T): (ctx: ServerAuthContext) => T;
36
+ export declare function defineClientAuth(config: ClientAuthConfigFn): ClientAuthConfigFn;
@@ -0,0 +1,6 @@
1
+ export function defineServerAuth(config) {
2
+ return config;
3
+ }
4
+ export function defineClientAuth(config) {
5
+ return config;
6
+ }
@@ -0,0 +1,8 @@
1
+ import { z } from 'zod';
2
+ export declare const paginationQuerySchema: z.ZodObject<{
3
+ page: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
4
+ limit: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
5
+ search: z.ZodDefault<z.ZodString>;
6
+ }, z.core.$strip>;
7
+ export type PaginationQuery = z.infer<typeof paginationQuerySchema>;
8
+ export declare function sanitizeSearchPattern(search: string): string;
@@ -0,0 +1,11 @@
1
+ import { z } from "zod";
2
+ export const paginationQuerySchema = z.object({
3
+ page: z.coerce.number().int().min(1).default(1),
4
+ limit: z.coerce.number().int().min(1).max(100).default(20),
5
+ search: z.string().max(100).default("")
6
+ });
7
+ export function sanitizeSearchPattern(search) {
8
+ if (!search)
9
+ return "";
10
+ return `%${search.replace(/[%_\\]/g, "\\$&")}%`;
11
+ }
@@ -0,0 +1,14 @@
1
+ declare const _default: import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<{
2
+ accounts: never[];
3
+ total: number;
4
+ error: string;
5
+ page?: undefined;
6
+ limit?: undefined;
7
+ } | {
8
+ accounts: any;
9
+ total: any;
10
+ page: number;
11
+ limit: number;
12
+ error?: undefined;
13
+ }>>;
14
+ export default _default;
@@ -0,0 +1,28 @@
1
+ import { defineEventHandler, getQuery } from "h3";
2
+ import { paginationQuerySchema, sanitizeSearchPattern } from "./_schema.js";
3
+ export default defineEventHandler(async (event) => {
4
+ try {
5
+ const { db, schema } = await import("hub:db");
6
+ if (!schema.account)
7
+ return { accounts: [], total: 0, error: "Account table not found" };
8
+ const query = paginationQuerySchema.parse(getQuery(event));
9
+ const { page, limit, search } = query;
10
+ const offset = (page - 1) * limit;
11
+ const { count, like, desc } = await import("drizzle-orm");
12
+ let dbQuery = db.select().from(schema.account);
13
+ let countQuery = db.select({ count: count() }).from(schema.account);
14
+ if (search) {
15
+ const pattern = sanitizeSearchPattern(search);
16
+ dbQuery = dbQuery.where(like(schema.account.providerId, pattern));
17
+ countQuery = countQuery.where(like(schema.account.providerId, pattern));
18
+ }
19
+ const [accounts, totalResult] = await Promise.all([
20
+ dbQuery.orderBy(desc(schema.account.createdAt)).limit(limit).offset(offset),
21
+ countQuery
22
+ ]);
23
+ return { accounts, total: totalResult[0]?.count ?? 0, page, limit };
24
+ } catch (error) {
25
+ console.error("[DevTools] Fetch accounts failed:", error);
26
+ return { accounts: [], total: 0, error: "Failed to fetch accounts" };
27
+ }
28
+ });
@@ -0,0 +1,35 @@
1
+ declare const _default: import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<{
2
+ config: {
3
+ module: {
4
+ redirects: {
5
+ login?: string;
6
+ guest?: string;
7
+ };
8
+ secondaryStorage: boolean;
9
+ useDatabase: boolean;
10
+ };
11
+ server: {
12
+ baseURL: string | undefined;
13
+ basePath: string;
14
+ socialProviders: string[];
15
+ plugins: any[];
16
+ trustedOrigins: string[] | ((request: Request) => string[] | Promise<string[]>);
17
+ session: {
18
+ expiresIn: string;
19
+ updateAge: string;
20
+ cookieCache: boolean;
21
+ };
22
+ emailAndPassword: boolean;
23
+ rateLimit: boolean;
24
+ advanced: {
25
+ useSecureCookies: string | boolean;
26
+ disableCSRFCheck: boolean;
27
+ };
28
+ };
29
+ };
30
+ error?: undefined;
31
+ } | {
32
+ config: null;
33
+ error: any;
34
+ }>>;
35
+ export default _default;
@@ -0,0 +1,46 @@
1
+ import { defineEventHandler } from "h3";
2
+ import { useRuntimeConfig } from "nitropack/runtime";
3
+ import { serverAuth } from "../../utils/auth.js";
4
+ export default defineEventHandler(async (event) => {
5
+ try {
6
+ const auth = await serverAuth(event);
7
+ const options = auth.options;
8
+ const runtimeConfig = useRuntimeConfig();
9
+ const publicAuth = runtimeConfig.public?.auth;
10
+ const privateAuth = runtimeConfig.auth;
11
+ const sessionConfig = options.session || {};
12
+ const expiresInDays = sessionConfig.expiresIn ? Math.round(sessionConfig.expiresIn / 86400) : 7;
13
+ const updateAgeDays = sessionConfig.updateAge ? Math.round(sessionConfig.updateAge / 86400) : 1;
14
+ return {
15
+ config: {
16
+ // Module config (nuxt.config.ts)
17
+ module: {
18
+ redirects: publicAuth?.redirects || { login: "/login", guest: "/" },
19
+ secondaryStorage: privateAuth?.secondaryStorage ?? false,
20
+ useDatabase: publicAuth?.useDatabase ?? false
21
+ },
22
+ // Server config (server/auth.config.ts)
23
+ server: {
24
+ baseURL: options.baseURL,
25
+ basePath: options.basePath || "/api/auth",
26
+ socialProviders: Object.keys(options.socialProviders || {}),
27
+ plugins: (options.plugins || []).map((p) => p.id || "unknown"),
28
+ trustedOrigins: options.trustedOrigins || [],
29
+ session: {
30
+ expiresIn: `${expiresInDays} days`,
31
+ updateAge: `${updateAgeDays} days`,
32
+ cookieCache: sessionConfig.cookieCache?.enabled ?? false
33
+ },
34
+ emailAndPassword: !!options.emailAndPassword,
35
+ rateLimit: options.rateLimit?.enabled ?? false,
36
+ advanced: {
37
+ useSecureCookies: options.advanced?.useSecureCookies ?? "auto",
38
+ disableCSRFCheck: options.advanced?.disableCSRFCheck ?? false
39
+ }
40
+ }
41
+ }
42
+ };
43
+ } catch (error) {
44
+ return { config: null, error: error.message || "Failed to fetch config" };
45
+ }
46
+ });
@@ -0,0 +1,4 @@
1
+ declare const _default: import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<{
2
+ success: boolean;
3
+ }>>;
4
+ export default _default;
@@ -0,0 +1,22 @@
1
+ import { createError, defineEventHandler, readBody } from "h3";
2
+ import { z } from "zod";
3
+ const deleteSessionSchema = z.object({
4
+ id: z.string().min(1, "Session ID required")
5
+ });
6
+ export default defineEventHandler(async (event) => {
7
+ try {
8
+ const body = deleteSessionSchema.parse(await readBody(event));
9
+ const { db, schema } = await import("hub:db");
10
+ if (!schema.session)
11
+ throw createError({ statusCode: 500, message: "Session table not found" });
12
+ const { eq } = await import("drizzle-orm");
13
+ await db.delete(schema.session).where(eq(schema.session.id, body.id));
14
+ return { success: true };
15
+ } catch (error) {
16
+ if (error instanceof z.ZodError) {
17
+ throw createError({ statusCode: 400, message: error.errors[0]?.message || "Invalid request" });
18
+ }
19
+ console.error("[DevTools] Delete session failed:", error);
20
+ throw createError({ statusCode: 500, message: "Failed to delete session" });
21
+ }
22
+ });
@@ -0,0 +1,14 @@
1
+ declare const _default: import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<{
2
+ sessions: never[];
3
+ total: number;
4
+ error: string;
5
+ page?: undefined;
6
+ limit?: undefined;
7
+ } | {
8
+ sessions: any;
9
+ total: any;
10
+ page: number;
11
+ limit: number;
12
+ error?: undefined;
13
+ }>>;
14
+ export default _default;
@@ -0,0 +1,34 @@
1
+ import { defineEventHandler, getQuery } from "h3";
2
+ import { paginationQuerySchema, sanitizeSearchPattern } from "./_schema.js";
3
+ export default defineEventHandler(async (event) => {
4
+ try {
5
+ const { db, schema } = await import("hub:db");
6
+ if (!schema.session)
7
+ return { sessions: [], total: 0, error: "Session table not found" };
8
+ const query = paginationQuerySchema.parse(getQuery(event));
9
+ const { page, limit, search } = query;
10
+ const offset = (page - 1) * limit;
11
+ const { count, like, or, desc } = await import("drizzle-orm");
12
+ let dbQuery = db.select().from(schema.session);
13
+ let countQuery = db.select({ count: count() }).from(schema.session);
14
+ if (search) {
15
+ const pattern = sanitizeSearchPattern(search);
16
+ const searchCondition = or(
17
+ like(schema.session.userId, pattern),
18
+ schema.session.ipAddress ? like(schema.session.ipAddress, pattern) : void 0
19
+ );
20
+ if (searchCondition) {
21
+ dbQuery = dbQuery.where(searchCondition);
22
+ countQuery = countQuery.where(searchCondition);
23
+ }
24
+ }
25
+ const [sessions, totalResult] = await Promise.all([
26
+ dbQuery.orderBy(desc(schema.session.createdAt)).limit(limit).offset(offset),
27
+ countQuery
28
+ ]);
29
+ return { sessions, total: totalResult[0]?.count ?? 0, page, limit };
30
+ } catch (error) {
31
+ console.error("[DevTools] Fetch sessions failed:", error);
32
+ return { sessions: [], total: 0, error: "Failed to fetch sessions" };
33
+ }
34
+ });
@@ -0,0 +1,14 @@
1
+ declare const _default: import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<{
2
+ users: never[];
3
+ total: number;
4
+ error: string;
5
+ page?: undefined;
6
+ limit?: undefined;
7
+ } | {
8
+ users: any;
9
+ total: any;
10
+ page: number;
11
+ limit: number;
12
+ error?: undefined;
13
+ }>>;
14
+ export default _default;
@@ -0,0 +1,34 @@
1
+ import { defineEventHandler, getQuery } from "h3";
2
+ import { paginationQuerySchema, sanitizeSearchPattern } from "./_schema.js";
3
+ export default defineEventHandler(async (event) => {
4
+ try {
5
+ const { db, schema } = await import("hub:db");
6
+ if (!schema.user)
7
+ return { users: [], total: 0, error: "User table not found" };
8
+ const query = paginationQuerySchema.parse(getQuery(event));
9
+ const { page, limit, search } = query;
10
+ const offset = (page - 1) * limit;
11
+ const { count, like, or, desc } = await import("drizzle-orm");
12
+ let dbQuery = db.select().from(schema.user);
13
+ let countQuery = db.select({ count: count() }).from(schema.user);
14
+ if (search) {
15
+ const pattern = sanitizeSearchPattern(search);
16
+ const searchCondition = or(
17
+ like(schema.user.name, pattern),
18
+ like(schema.user.email, pattern)
19
+ );
20
+ if (searchCondition) {
21
+ dbQuery = dbQuery.where(searchCondition);
22
+ countQuery = countQuery.where(searchCondition);
23
+ }
24
+ }
25
+ const [users, totalResult] = await Promise.all([
26
+ dbQuery.orderBy(desc(schema.user.createdAt)).limit(limit).offset(offset),
27
+ countQuery
28
+ ]);
29
+ return { users, total: totalResult[0]?.count ?? 0, page, limit };
30
+ } catch (error) {
31
+ console.error("[DevTools] Fetch users failed:", error);
32
+ return { users: [], total: 0, error: "Failed to fetch users" };
33
+ }
34
+ });
@@ -0,0 +1,2 @@
1
+ declare const _default: import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<Response>>;
2
+ export default _default;
@@ -0,0 +1,6 @@
1
+ import { defineEventHandler, toWebRequest } from "h3";
2
+ import { serverAuth } from "../../utils/auth.js";
3
+ export default defineEventHandler(async (event) => {
4
+ const auth = await serverAuth(event);
5
+ return auth.handler(toWebRequest(event));
6
+ });
@@ -0,0 +1,2 @@
1
+ declare const _default: import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<void>>;
2
+ export default _default;
@@ -0,0 +1,28 @@
1
+ import { createError, defineEventHandler, getRequestURL } from "h3";
2
+ import { getRouteRules } from "nitropack/runtime";
3
+ import { matchesUser } from "../../utils/match-user.js";
4
+ export default defineEventHandler(async (event) => {
5
+ const path = getRequestURL(event).pathname;
6
+ if (!path.startsWith("/api/"))
7
+ return;
8
+ if (path.startsWith("/api/auth/"))
9
+ return;
10
+ const rules = getRouteRules(event);
11
+ if (!rules.auth)
12
+ return;
13
+ const auth = rules.auth;
14
+ const mode = typeof auth === "string" ? auth : auth?.only ?? "user";
15
+ if (mode === "guest") {
16
+ const session = await getUserSession(event);
17
+ if (session)
18
+ throw createError({ statusCode: 403, statusMessage: "Authenticated users not allowed" });
19
+ return;
20
+ }
21
+ if (mode === "user") {
22
+ const session = await requireUserSession(event);
23
+ if (typeof auth === "object" && auth.user) {
24
+ if (!matchesUser(session.user, auth.user))
25
+ throw createError({ statusCode: 403, statusMessage: "Access denied" });
26
+ }
27
+ }
28
+ });
@@ -0,0 +1,3 @@
1
+ {
2
+ "extends": "../../../.nuxt/tsconfig.server.json"
3
+ }
@@ -0,0 +1,10 @@
1
+ import type { H3Event } from 'h3';
2
+ import { betterAuth } from 'better-auth';
3
+ type AuthInstance = ReturnType<typeof betterAuth>;
4
+ declare module 'h3' {
5
+ interface H3EventContext {
6
+ _betterAuth?: AuthInstance;
7
+ }
8
+ }
9
+ export declare function serverAuth(event: H3Event): Promise<AuthInstance>;
10
+ export {};
@@ -0,0 +1,32 @@
1
+ import { createDatabase, db } from "#auth/database";
2
+ import { createSecondaryStorage } from "#auth/secondary-storage";
3
+ import createServerAuth from "#auth/server";
4
+ import { betterAuth } from "better-auth";
5
+ import { consola } from "consola";
6
+ import { getRequestURL } from "h3";
7
+ import { useRuntimeConfig } from "nitropack/runtime";
8
+ const logger = consola.withTag("nuxt-better-auth");
9
+ function getBaseURL(event, siteUrl) {
10
+ if (siteUrl)
11
+ return siteUrl;
12
+ const origin = getRequestURL(event).origin;
13
+ if (process.env.NODE_ENV === "production")
14
+ throw new Error("siteUrl must be configured in production. Set NUXT_PUBLIC_SITE_URL or configure in nuxt.config.");
15
+ logger.warn("siteUrl not set, auto-detected:", origin);
16
+ return origin;
17
+ }
18
+ export async function serverAuth(event) {
19
+ if (event.context._betterAuth)
20
+ return event.context._betterAuth;
21
+ const runtimeConfig = useRuntimeConfig();
22
+ const database = createDatabase();
23
+ const userConfig = createServerAuth({ runtimeConfig, db });
24
+ event.context._betterAuth = betterAuth({
25
+ ...userConfig,
26
+ ...database && { database },
27
+ secondaryStorage: createSecondaryStorage(),
28
+ secret: runtimeConfig.betterAuthSecret,
29
+ baseURL: getBaseURL(event, runtimeConfig.public.siteUrl)
30
+ });
31
+ return event.context._betterAuth;
32
+ }
@@ -0,0 +1,9 @@
1
+ import type { H3Event } from 'h3';
2
+ import type { AuthSession, AuthUser, RequireSessionOptions } from '../../types.js';
3
+ interface FullSession {
4
+ user: AuthUser;
5
+ session: AuthSession;
6
+ }
7
+ export declare function getUserSession(event: H3Event): Promise<FullSession | null>;
8
+ export declare function requireUserSession(event: H3Event, options?: RequireSessionOptions): Promise<FullSession>;
9
+ export {};
@@ -0,0 +1,22 @@
1
+ import { createError } from "h3";
2
+ import { matchesUser } from "../../utils/match-user.js";
3
+ export async function getUserSession(event) {
4
+ const auth = await serverAuth(event);
5
+ const session = await auth.api.getSession({ headers: event.headers });
6
+ return session;
7
+ }
8
+ export async function requireUserSession(event, options) {
9
+ const session = await getUserSession(event);
10
+ if (!session)
11
+ throw createError({ statusCode: 401, statusMessage: "Authentication required" });
12
+ if (options?.user) {
13
+ if (!matchesUser(session.user, options.user))
14
+ throw createError({ statusCode: 403, statusMessage: "Access denied" });
15
+ }
16
+ if (options?.rule) {
17
+ const allowed = await options.rule({ user: session.user, session: session.session });
18
+ if (!allowed)
19
+ throw createError({ statusCode: 403, statusMessage: "Access denied" });
20
+ }
21
+ return session;
22
+ }
@@ -0,0 +1,42 @@
1
+ import type { ComputedRef, Ref } from 'vue';
2
+ export interface AuthUser {
3
+ id: string;
4
+ createdAt: Date;
5
+ updatedAt: Date;
6
+ email: string;
7
+ emailVerified: boolean;
8
+ name: string;
9
+ image?: string | null;
10
+ }
11
+ export interface AuthSession {
12
+ id: string;
13
+ createdAt: Date;
14
+ updatedAt: Date;
15
+ userId: string;
16
+ expiresAt: Date;
17
+ token: string;
18
+ ipAddress?: string | null;
19
+ userAgent?: string | null;
20
+ }
21
+ export interface ServerAuthContext {
22
+ runtimeConfig: Record<string, unknown>;
23
+ db: unknown;
24
+ }
25
+ export interface UserSessionComposable {
26
+ client: unknown;
27
+ user: Ref<AuthUser | null>;
28
+ session: Ref<AuthSession | null>;
29
+ loggedIn: ComputedRef<boolean>;
30
+ ready: ComputedRef<boolean>;
31
+ signIn: unknown;
32
+ signUp: unknown;
33
+ fetchSession: (options?: {
34
+ headers?: HeadersInit;
35
+ force?: boolean;
36
+ }) => Promise<void>;
37
+ waitForSession: () => Promise<void>;
38
+ signOut: (options?: {
39
+ onSuccess?: () => void | Promise<void>;
40
+ }) => Promise<unknown>;
41
+ updateUser: (updates: Partial<AuthUser>) => void;
42
+ }
File without changes
@@ -0,0 +1,23 @@
1
+ import type { NitroRouteRules } from 'nitropack/types';
2
+ import type { AuthSession, AuthUser } from './types/augment.js';
3
+ export type { AuthSession, AuthUser, ServerAuthContext, UserSessionComposable } from './types/augment.js';
4
+ export type { Auth, InferSession, InferUser } from 'better-auth';
5
+ export type AuthMode = 'guest' | 'user';
6
+ export type UserMatch<T> = {
7
+ [K in keyof T]?: T[K] | T[K][];
8
+ };
9
+ export type AuthMeta = false | AuthMode | {
10
+ only?: AuthMode;
11
+ redirectTo?: string;
12
+ user?: UserMatch<AuthUser>;
13
+ };
14
+ export type AuthRouteRules = NitroRouteRules & {
15
+ auth?: AuthMeta;
16
+ };
17
+ export interface RequireSessionOptions {
18
+ user?: UserMatch<AuthUser>;
19
+ rule?: (ctx: {
20
+ user: AuthUser;
21
+ session: AuthSession;
22
+ }) => boolean | Promise<boolean>;
23
+ }
File without changes
@@ -0,0 +1,2 @@
1
+ import type { UserMatch } from '../types.js';
2
+ export declare function matchesUser<T extends object>(user: T, match: UserMatch<T>): boolean;
@@ -0,0 +1,13 @@
1
+ export function matchesUser(user, match) {
2
+ for (const [key, expected] of Object.entries(match)) {
3
+ const actual = user[key];
4
+ if (Array.isArray(expected)) {
5
+ if (!expected.includes(actual))
6
+ return false;
7
+ } else {
8
+ if (actual !== expected)
9
+ return false;
10
+ }
11
+ }
12
+ return true;
13
+ }
package/dist/types.d.mts CHANGED
@@ -1,13 +1,11 @@
1
- import type { ModuleHooks, ModuleRuntimeHooks, ModuleRuntimeConfig, ModulePublicRuntimeConfig } from './module.mjs'
1
+ import type { NuxtModule } from '@nuxt/schema'
2
2
 
3
- declare module '#app' {
4
- interface RuntimeNuxtHooks extends ModuleRuntimeHooks {}
5
- }
3
+ import type { default as Module } from './module.mjs'
6
4
 
7
- declare module '@nuxt/schema' {
8
- interface NuxtHooks extends ModuleHooks {}
9
- interface RuntimeConfig extends ModuleRuntimeConfig {}
10
- interface PublicRuntimeConfig extends ModulePublicRuntimeConfig {}
11
- }
5
+ export type ModuleOptions = typeof Module extends NuxtModule<infer O> ? Partial<O> : Record<string, any>
12
6
 
13
- export * from "./module.mjs"
7
+ export { type BetterAuthModuleOptions, type defineClientAuth, type defineServerAuth } from '../dist/runtime/config.js'
8
+
9
+ export { type Auth, type AuthMeta, type AuthMode, type AuthRouteRules, type AuthSession, type AuthUser, type InferSession, type InferUser, type RequireSessionOptions, type ServerAuthContext, type UserMatch } from '../dist/runtime/types.js'
10
+
11
+ export { default } from './module.mjs'