@onmax/nuxt-better-auth 0.0.2-alpha.2 → 0.0.2-alpha.21
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/module.json +1 -1
- package/dist/module.mjs +470 -184
- package/dist/runtime/adapters/convex.d.ts +111 -0
- package/dist/runtime/adapters/convex.js +213 -0
- package/dist/runtime/app/components/BetterAuthState.vue +1 -0
- package/dist/runtime/app/composables/useUserSession.d.ts +13 -11
- package/dist/runtime/app/composables/useUserSession.js +13 -12
- package/dist/runtime/app/middleware/auth.global.js +7 -1
- package/dist/runtime/app/plugins/session.client.js +1 -2
- package/dist/runtime/app/plugins/session.server.js +2 -1
- package/dist/runtime/config.d.ts +18 -5
- package/dist/runtime/config.js +7 -2
- package/dist/runtime/server/api/_better-auth/accounts.get.js +1 -1
- package/dist/runtime/server/api/_better-auth/config.get.d.ts +9 -9
- package/dist/runtime/server/api/_better-auth/config.get.js +3 -2
- package/dist/runtime/server/api/_better-auth/sessions.delete.js +1 -1
- package/dist/runtime/server/api/_better-auth/sessions.get.js +11 -2
- package/dist/runtime/server/api/_better-auth/users.get.js +1 -1
- package/dist/runtime/server/api/auth/[...all].js +1 -1
- package/dist/runtime/server/utils/auth.d.ts +5 -8
- package/dist/runtime/server/utils/auth.js +66 -17
- package/dist/runtime/server/utils/session.js +2 -1
- package/dist/runtime/types/augment.d.ts +1 -1
- package/dist/runtime/types.d.ts +1 -1
- package/package.json +36 -11
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import type { FunctionReference } from 'convex/server';
|
|
2
|
+
interface ConvexCleanedWhere {
|
|
3
|
+
field: string;
|
|
4
|
+
value: string | number | boolean | string[] | number[] | null;
|
|
5
|
+
operator?: 'lt' | 'lte' | 'gt' | 'gte' | 'eq' | 'in' | 'not_in' | 'ne' | 'contains' | 'starts_with' | 'ends_with';
|
|
6
|
+
connector?: 'AND' | 'OR';
|
|
7
|
+
}
|
|
8
|
+
interface PaginationResult<T> {
|
|
9
|
+
page: T[];
|
|
10
|
+
isDone: boolean;
|
|
11
|
+
continueCursor: string | null;
|
|
12
|
+
splitCursor?: string;
|
|
13
|
+
pageStatus?: 'SplitRecommended' | 'SplitRequired' | string;
|
|
14
|
+
count?: number;
|
|
15
|
+
}
|
|
16
|
+
interface ConvexAuthApi {
|
|
17
|
+
create: FunctionReference<'mutation', 'public', {
|
|
18
|
+
input: {
|
|
19
|
+
model: string;
|
|
20
|
+
data: Record<string, unknown>;
|
|
21
|
+
};
|
|
22
|
+
select?: string[];
|
|
23
|
+
}, unknown>;
|
|
24
|
+
findOne: FunctionReference<'query', 'public', {
|
|
25
|
+
model: string;
|
|
26
|
+
where?: ConvexCleanedWhere[];
|
|
27
|
+
select?: string[];
|
|
28
|
+
}, unknown>;
|
|
29
|
+
findMany: FunctionReference<'query', 'public', {
|
|
30
|
+
model: string;
|
|
31
|
+
where?: ConvexCleanedWhere[];
|
|
32
|
+
limit?: number;
|
|
33
|
+
sortBy?: {
|
|
34
|
+
direction: 'asc' | 'desc';
|
|
35
|
+
field: string;
|
|
36
|
+
};
|
|
37
|
+
paginationOpts: {
|
|
38
|
+
numItems: number;
|
|
39
|
+
cursor: string | null;
|
|
40
|
+
};
|
|
41
|
+
}, PaginationResult<unknown>>;
|
|
42
|
+
updateOne: FunctionReference<'mutation', 'public', {
|
|
43
|
+
input: {
|
|
44
|
+
model: string;
|
|
45
|
+
where?: ConvexCleanedWhere[];
|
|
46
|
+
update: Record<string, unknown>;
|
|
47
|
+
};
|
|
48
|
+
}, unknown>;
|
|
49
|
+
updateMany: FunctionReference<'mutation', 'public', {
|
|
50
|
+
input: {
|
|
51
|
+
model: string;
|
|
52
|
+
where?: ConvexCleanedWhere[];
|
|
53
|
+
update: Record<string, unknown>;
|
|
54
|
+
};
|
|
55
|
+
paginationOpts: {
|
|
56
|
+
numItems: number;
|
|
57
|
+
cursor: string | null;
|
|
58
|
+
};
|
|
59
|
+
}, PaginationResult<unknown> & {
|
|
60
|
+
count: number;
|
|
61
|
+
}>;
|
|
62
|
+
deleteOne: FunctionReference<'mutation', 'public', {
|
|
63
|
+
input: {
|
|
64
|
+
model: string;
|
|
65
|
+
where?: ConvexCleanedWhere[];
|
|
66
|
+
};
|
|
67
|
+
}, unknown>;
|
|
68
|
+
deleteMany: FunctionReference<'mutation', 'public', {
|
|
69
|
+
input: {
|
|
70
|
+
model: string;
|
|
71
|
+
where?: ConvexCleanedWhere[];
|
|
72
|
+
};
|
|
73
|
+
paginationOpts: {
|
|
74
|
+
numItems: number;
|
|
75
|
+
cursor: string | null;
|
|
76
|
+
};
|
|
77
|
+
}, PaginationResult<unknown> & {
|
|
78
|
+
count: number;
|
|
79
|
+
}>;
|
|
80
|
+
}
|
|
81
|
+
export interface ConvexHttpAdapterOptions {
|
|
82
|
+
/** Convex deployment URL (e.g., https://your-app.convex.cloud) */
|
|
83
|
+
url: string;
|
|
84
|
+
/** Convex API functions for auth operations - import from your convex/_generated/api */
|
|
85
|
+
api: ConvexAuthApi;
|
|
86
|
+
/** Enable debug logging for adapter operations */
|
|
87
|
+
debugLogs?: boolean;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Creates a Better Auth adapter that communicates with Convex via HTTP.
|
|
91
|
+
* Uses ConvexHttpClient for server-side auth operations.
|
|
92
|
+
*
|
|
93
|
+
* @example
|
|
94
|
+
* ```ts
|
|
95
|
+
* import { api } from '~/convex/_generated/api'
|
|
96
|
+
*
|
|
97
|
+
* export default defineServerAuth(() => ({
|
|
98
|
+
* database: createConvexHttpAdapter({
|
|
99
|
+
* url: process.env.CONVEX_URL!,
|
|
100
|
+
* api: api.auth,
|
|
101
|
+
* }),
|
|
102
|
+
* }))
|
|
103
|
+
* ```
|
|
104
|
+
*
|
|
105
|
+
* @limitations
|
|
106
|
+
* - `update()` only supports AND-connected where clauses (no OR support)
|
|
107
|
+
* - `count()` fetches all documents client-side (Convex limitation)
|
|
108
|
+
* - `offset` pagination not supported in `findMany()`
|
|
109
|
+
*/
|
|
110
|
+
export declare function createConvexHttpAdapter(options: ConvexHttpAdapterOptions): import("better-auth/adapters").AdapterFactory;
|
|
111
|
+
export {};
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
import { createAdapterFactory } from "better-auth/adapters";
|
|
2
|
+
import { ConvexHttpClient } from "convex/browser";
|
|
3
|
+
function parseWhere(where) {
|
|
4
|
+
if (!where)
|
|
5
|
+
return [];
|
|
6
|
+
const whereArray = Array.isArray(where) ? where : [where];
|
|
7
|
+
return whereArray.map((w) => {
|
|
8
|
+
if (w.value instanceof Date)
|
|
9
|
+
return { ...w, value: w.value.getTime() };
|
|
10
|
+
return w;
|
|
11
|
+
});
|
|
12
|
+
}
|
|
13
|
+
async function handlePagination(next, { limit } = {}) {
|
|
14
|
+
const state = { isDone: false, cursor: null, docs: [], count: 0 };
|
|
15
|
+
const onResult = (result) => {
|
|
16
|
+
state.cursor = result.pageStatus === "SplitRecommended" || result.pageStatus === "SplitRequired" ? result.splitCursor ?? result.continueCursor : result.continueCursor;
|
|
17
|
+
if (result.page) {
|
|
18
|
+
state.docs.push(...result.page);
|
|
19
|
+
state.isDone = limit && state.docs.length >= limit || result.isDone;
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
if (result.count) {
|
|
23
|
+
state.count += result.count;
|
|
24
|
+
state.isDone = limit && state.count >= limit || result.isDone;
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
state.isDone = result.isDone;
|
|
28
|
+
};
|
|
29
|
+
do {
|
|
30
|
+
const result = await next({
|
|
31
|
+
paginationOpts: {
|
|
32
|
+
numItems: Math.min(200, (limit ?? 200) - state.docs.length, 200),
|
|
33
|
+
cursor: state.cursor
|
|
34
|
+
}
|
|
35
|
+
});
|
|
36
|
+
onResult(result);
|
|
37
|
+
} while (!state.isDone);
|
|
38
|
+
return state;
|
|
39
|
+
}
|
|
40
|
+
export function createConvexHttpAdapter(options) {
|
|
41
|
+
if (!options.url.startsWith("https://") || !options.url.includes(".convex.")) {
|
|
42
|
+
throw new Error(`Invalid Convex URL: ${options.url}. Expected format: https://your-app.convex.cloud`);
|
|
43
|
+
}
|
|
44
|
+
const client = new ConvexHttpClient(options.url);
|
|
45
|
+
return createAdapterFactory({
|
|
46
|
+
config: {
|
|
47
|
+
adapterId: "convex-http",
|
|
48
|
+
adapterName: "Convex HTTP Adapter",
|
|
49
|
+
debugLogs: options.debugLogs ?? false,
|
|
50
|
+
disableIdGeneration: true,
|
|
51
|
+
transaction: false,
|
|
52
|
+
supportsNumericIds: false,
|
|
53
|
+
supportsJSON: false,
|
|
54
|
+
supportsDates: false,
|
|
55
|
+
supportsArrays: true,
|
|
56
|
+
usePlural: false,
|
|
57
|
+
mapKeysTransformInput: { id: "_id" },
|
|
58
|
+
mapKeysTransformOutput: { _id: "id" },
|
|
59
|
+
customTransformInput: ({ data, fieldAttributes }) => {
|
|
60
|
+
if (data && fieldAttributes.type === "date")
|
|
61
|
+
return new Date(data).getTime();
|
|
62
|
+
return data;
|
|
63
|
+
},
|
|
64
|
+
customTransformOutput: ({ data, fieldAttributes }) => {
|
|
65
|
+
if (data && fieldAttributes.type === "date")
|
|
66
|
+
return new Date(data).getTime();
|
|
67
|
+
return data;
|
|
68
|
+
}
|
|
69
|
+
},
|
|
70
|
+
adapter: ({ options: authOptions }) => {
|
|
71
|
+
authOptions.telemetry = { enabled: false };
|
|
72
|
+
return {
|
|
73
|
+
id: "convex-http",
|
|
74
|
+
create: async ({ model, data, select }) => {
|
|
75
|
+
return client.mutation(options.api.create, {
|
|
76
|
+
input: { model, data },
|
|
77
|
+
select
|
|
78
|
+
});
|
|
79
|
+
},
|
|
80
|
+
findOne: async (data) => {
|
|
81
|
+
if (data.where?.every((w) => w.connector === "OR")) {
|
|
82
|
+
for (const w of data.where) {
|
|
83
|
+
const result = await client.query(options.api.findOne, {
|
|
84
|
+
...data,
|
|
85
|
+
model: data.model,
|
|
86
|
+
where: parseWhere(w)
|
|
87
|
+
});
|
|
88
|
+
if (result)
|
|
89
|
+
return result;
|
|
90
|
+
}
|
|
91
|
+
return null;
|
|
92
|
+
}
|
|
93
|
+
return client.query(options.api.findOne, {
|
|
94
|
+
...data,
|
|
95
|
+
model: data.model,
|
|
96
|
+
where: parseWhere(data.where)
|
|
97
|
+
});
|
|
98
|
+
},
|
|
99
|
+
findMany: async (data) => {
|
|
100
|
+
if (data.offset)
|
|
101
|
+
throw new Error("offset not supported");
|
|
102
|
+
if (data.where?.some((w) => w.connector === "OR")) {
|
|
103
|
+
const results = await Promise.all(
|
|
104
|
+
data.where.map(
|
|
105
|
+
async (w) => handlePagination(async ({ paginationOpts }) => {
|
|
106
|
+
return client.query(options.api.findMany, {
|
|
107
|
+
...data,
|
|
108
|
+
model: data.model,
|
|
109
|
+
where: parseWhere(w),
|
|
110
|
+
paginationOpts
|
|
111
|
+
});
|
|
112
|
+
}, { limit: data.limit })
|
|
113
|
+
)
|
|
114
|
+
);
|
|
115
|
+
const allDocs = results.flatMap((r) => r.docs);
|
|
116
|
+
const uniqueDocs = [...new Map(allDocs.map((d) => [d._id, d])).values()];
|
|
117
|
+
if (data.sortBy) {
|
|
118
|
+
return uniqueDocs.sort((a, b) => {
|
|
119
|
+
const aVal = a[data.sortBy.field];
|
|
120
|
+
const bVal = b[data.sortBy.field];
|
|
121
|
+
const cmp = aVal < bVal ? -1 : aVal > bVal ? 1 : 0;
|
|
122
|
+
return data.sortBy.direction === "asc" ? cmp : -cmp;
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
return uniqueDocs;
|
|
126
|
+
}
|
|
127
|
+
const result = await handlePagination(
|
|
128
|
+
async ({ paginationOpts }) => client.query(options.api.findMany, {
|
|
129
|
+
...data,
|
|
130
|
+
model: data.model,
|
|
131
|
+
where: parseWhere(data.where),
|
|
132
|
+
paginationOpts
|
|
133
|
+
}),
|
|
134
|
+
{ limit: data.limit }
|
|
135
|
+
);
|
|
136
|
+
return result.docs;
|
|
137
|
+
},
|
|
138
|
+
// Note: Convex doesn't have a native count query, so we fetch all docs and count client-side.
|
|
139
|
+
// This is inefficient for large datasets but acceptable for auth tables (typically small).
|
|
140
|
+
count: async (data) => {
|
|
141
|
+
if (data.where?.some((w) => w.connector === "OR")) {
|
|
142
|
+
const results = await Promise.all(
|
|
143
|
+
data.where.map(
|
|
144
|
+
async (w) => handlePagination(async ({ paginationOpts }) => {
|
|
145
|
+
return client.query(options.api.findMany, {
|
|
146
|
+
...data,
|
|
147
|
+
model: data.model,
|
|
148
|
+
where: parseWhere(w),
|
|
149
|
+
paginationOpts
|
|
150
|
+
});
|
|
151
|
+
})
|
|
152
|
+
)
|
|
153
|
+
);
|
|
154
|
+
const allDocs = results.flatMap((r) => r.docs);
|
|
155
|
+
const uniqueDocs = [...new Map(allDocs.map((d) => [d._id, d])).values()];
|
|
156
|
+
return uniqueDocs.length;
|
|
157
|
+
}
|
|
158
|
+
const result = await handlePagination(async ({ paginationOpts }) => client.query(options.api.findMany, {
|
|
159
|
+
...data,
|
|
160
|
+
model: data.model,
|
|
161
|
+
where: parseWhere(data.where),
|
|
162
|
+
paginationOpts
|
|
163
|
+
}));
|
|
164
|
+
return result.docs.length;
|
|
165
|
+
},
|
|
166
|
+
// Supports single eq or multiple AND-connected conditions (Better Auth's common patterns)
|
|
167
|
+
update: async (data) => {
|
|
168
|
+
const hasOrConnector = data.where?.some((w) => w.connector === "OR");
|
|
169
|
+
if (hasOrConnector) {
|
|
170
|
+
throw new Error("update() does not support OR conditions - use updateMany() or split into multiple calls");
|
|
171
|
+
}
|
|
172
|
+
return client.mutation(options.api.updateOne, {
|
|
173
|
+
input: {
|
|
174
|
+
model: data.model,
|
|
175
|
+
where: parseWhere(data.where),
|
|
176
|
+
update: data.update
|
|
177
|
+
}
|
|
178
|
+
});
|
|
179
|
+
},
|
|
180
|
+
updateMany: async (data) => {
|
|
181
|
+
const result = await handlePagination(async ({ paginationOpts }) => client.mutation(options.api.updateMany, {
|
|
182
|
+
input: {
|
|
183
|
+
...data,
|
|
184
|
+
model: data.model,
|
|
185
|
+
where: parseWhere(data.where)
|
|
186
|
+
},
|
|
187
|
+
paginationOpts
|
|
188
|
+
}));
|
|
189
|
+
return result.count;
|
|
190
|
+
},
|
|
191
|
+
delete: async (data) => {
|
|
192
|
+
await client.mutation(options.api.deleteOne, {
|
|
193
|
+
input: {
|
|
194
|
+
model: data.model,
|
|
195
|
+
where: parseWhere(data.where)
|
|
196
|
+
}
|
|
197
|
+
});
|
|
198
|
+
},
|
|
199
|
+
deleteMany: async (data) => {
|
|
200
|
+
const result = await handlePagination(async ({ paginationOpts }) => client.mutation(options.api.deleteMany, {
|
|
201
|
+
input: {
|
|
202
|
+
...data,
|
|
203
|
+
model: data.model,
|
|
204
|
+
where: parseWhere(data.where)
|
|
205
|
+
},
|
|
206
|
+
paginationOpts
|
|
207
|
+
}));
|
|
208
|
+
return result.count;
|
|
209
|
+
}
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
});
|
|
213
|
+
}
|
|
@@ -1,20 +1,22 @@
|
|
|
1
|
-
import type { AuthUser } from '#nuxt-better-auth';
|
|
1
|
+
import type { AppAuthClient, AuthSession, AuthUser } from '#nuxt-better-auth';
|
|
2
|
+
import type { ComputedRef, Ref } from 'vue';
|
|
2
3
|
export interface SignOutOptions {
|
|
3
4
|
onSuccess?: () => void | Promise<void>;
|
|
4
5
|
}
|
|
5
|
-
export
|
|
6
|
-
client:
|
|
7
|
-
session:
|
|
8
|
-
user:
|
|
9
|
-
loggedIn:
|
|
10
|
-
ready:
|
|
11
|
-
signIn:
|
|
12
|
-
signUp:
|
|
13
|
-
signOut: (options?: SignOutOptions) => Promise<
|
|
6
|
+
export interface UseUserSessionReturn {
|
|
7
|
+
client: AppAuthClient | null;
|
|
8
|
+
session: Ref<AuthSession | null>;
|
|
9
|
+
user: Ref<AuthUser | null>;
|
|
10
|
+
loggedIn: ComputedRef<boolean>;
|
|
11
|
+
ready: ComputedRef<boolean>;
|
|
12
|
+
signIn: NonNullable<AppAuthClient>['signIn'];
|
|
13
|
+
signUp: NonNullable<AppAuthClient>['signUp'];
|
|
14
|
+
signOut: (options?: SignOutOptions) => Promise<void>;
|
|
14
15
|
waitForSession: () => Promise<void>;
|
|
15
16
|
fetchSession: (options?: {
|
|
16
17
|
headers?: HeadersInit;
|
|
17
18
|
force?: boolean;
|
|
18
19
|
}) => Promise<void>;
|
|
19
20
|
updateUser: (updates: Partial<AuthUser>) => void;
|
|
20
|
-
}
|
|
21
|
+
}
|
|
22
|
+
export declare function useUserSession(): UseUserSessionReturn;
|
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import
|
|
1
|
+
import createAppAuthClient from "#auth/client";
|
|
2
2
|
import { computed, nextTick, useRequestHeaders, useRequestURL, useRuntimeConfig, useState, watch } from "#imports";
|
|
3
|
-
import { consola } from "consola";
|
|
4
3
|
let _client = null;
|
|
5
4
|
function getClient(baseURL) {
|
|
6
5
|
if (!_client)
|
|
@@ -30,7 +29,8 @@ export function useUserSession() {
|
|
|
30
29
|
() => clientSession.value,
|
|
31
30
|
(newSession) => {
|
|
32
31
|
if (newSession?.data?.session && newSession?.data?.user) {
|
|
33
|
-
|
|
32
|
+
const { token: _, ...safeSession } = newSession.data.session;
|
|
33
|
+
session.value = safeSession;
|
|
34
34
|
user.value = newSession.data.user;
|
|
35
35
|
} else if (!newSession?.isPending) {
|
|
36
36
|
clearSession();
|
|
@@ -82,10 +82,11 @@ export function useUserSession() {
|
|
|
82
82
|
}
|
|
83
83
|
const signIn = client?.signIn ? new Proxy(client.signIn, {
|
|
84
84
|
get(target, prop) {
|
|
85
|
-
const
|
|
85
|
+
const targetRecord = target;
|
|
86
|
+
const method = targetRecord[prop];
|
|
86
87
|
if (typeof method !== "function")
|
|
87
88
|
return method;
|
|
88
|
-
return wrapAuthMethod((...args) =>
|
|
89
|
+
return wrapAuthMethod((...args) => targetRecord[prop](...args));
|
|
89
90
|
}
|
|
90
91
|
}) : new Proxy({}, {
|
|
91
92
|
get: (_, prop) => {
|
|
@@ -94,10 +95,11 @@ export function useUserSession() {
|
|
|
94
95
|
});
|
|
95
96
|
const signUp = client?.signUp ? new Proxy(client.signUp, {
|
|
96
97
|
get(target, prop) {
|
|
97
|
-
const
|
|
98
|
+
const targetRecord = target;
|
|
99
|
+
const method = targetRecord[prop];
|
|
98
100
|
if (typeof method !== "function")
|
|
99
101
|
return method;
|
|
100
|
-
return wrapAuthMethod((...args) =>
|
|
102
|
+
return wrapAuthMethod((...args) => targetRecord[prop](...args));
|
|
101
103
|
}
|
|
102
104
|
}) : new Proxy({}, {
|
|
103
105
|
get: (_, prop) => {
|
|
@@ -118,15 +120,15 @@ export function useUserSession() {
|
|
|
118
120
|
const result = await client.getSession({ query }, fetchOptions);
|
|
119
121
|
const data = result.data;
|
|
120
122
|
if (data?.session && data?.user) {
|
|
121
|
-
|
|
123
|
+
const { token: _, ...safeSession } = data.session;
|
|
124
|
+
session.value = safeSession;
|
|
122
125
|
user.value = data.user;
|
|
123
126
|
} else {
|
|
124
127
|
clearSession();
|
|
125
128
|
}
|
|
126
129
|
} catch (error) {
|
|
127
130
|
clearSession();
|
|
128
|
-
|
|
129
|
-
consola.error("Failed to fetch auth session:", error);
|
|
131
|
+
console.error("[nuxt-better-auth] Failed to fetch session:", error);
|
|
130
132
|
} finally {
|
|
131
133
|
if (!authReady.value)
|
|
132
134
|
authReady.value = true;
|
|
@@ -136,11 +138,10 @@ export function useUserSession() {
|
|
|
136
138
|
async function signOut(options) {
|
|
137
139
|
if (!client)
|
|
138
140
|
throw new Error("signOut can only be called on client-side");
|
|
139
|
-
|
|
141
|
+
await client.signOut();
|
|
140
142
|
clearSession();
|
|
141
143
|
if (options?.onSuccess)
|
|
142
144
|
await options.onSuccess();
|
|
143
|
-
return response;
|
|
144
145
|
}
|
|
145
146
|
return {
|
|
146
147
|
client,
|
|
@@ -1,6 +1,12 @@
|
|
|
1
|
-
import { createError, defineNuxtRouteMiddleware, getRouteRules, navigateTo, useRequestHeaders, useRuntimeConfig } from "#imports";
|
|
1
|
+
import { createError, defineNuxtRouteMiddleware, getRouteRules, navigateTo, useNuxtApp, useRequestHeaders, useRuntimeConfig, useUserSession } from "#imports";
|
|
2
2
|
import { matchesUser } from "../../utils/match-user.js";
|
|
3
3
|
export default defineNuxtRouteMiddleware(async (to) => {
|
|
4
|
+
const nuxtApp = useNuxtApp();
|
|
5
|
+
if (import.meta.client) {
|
|
6
|
+
const isPrerendered = nuxtApp.payload.prerenderedAt || nuxtApp.payload.isCached;
|
|
7
|
+
if (isPrerendered && nuxtApp.isHydrating)
|
|
8
|
+
return;
|
|
9
|
+
}
|
|
4
10
|
if (to.meta.auth === void 0) {
|
|
5
11
|
const rules = await getRouteRules({ path: to.path });
|
|
6
12
|
if (rules.auth !== void 0)
|
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import { defineNuxtPlugin } from "#imports";
|
|
2
|
-
import { useUserSession } from "../composables/useUserSession.js";
|
|
1
|
+
import { defineNuxtPlugin, useUserSession } from "#imports";
|
|
3
2
|
export default defineNuxtPlugin(async (nuxtApp) => {
|
|
4
3
|
const { fetchSession } = useUserSession();
|
|
5
4
|
const safeFetch = async () => {
|
|
@@ -12,7 +12,8 @@ export default defineNuxtPlugin({
|
|
|
12
12
|
const headers = useRequestHeaders(["cookie"]);
|
|
13
13
|
const data = await $fetch("/api/auth/get-session", { headers });
|
|
14
14
|
if (data?.session && data?.user) {
|
|
15
|
-
|
|
15
|
+
const { token: _, ...safeSession } = data.session;
|
|
16
|
+
session.value = safeSession;
|
|
16
17
|
user.value = data.user;
|
|
17
18
|
}
|
|
18
19
|
} catch {
|
package/dist/runtime/config.d.ts
CHANGED
|
@@ -1,17 +1,21 @@
|
|
|
1
1
|
import type { BetterAuthOptions } from 'better-auth';
|
|
2
|
-
import type {
|
|
2
|
+
import type { BetterAuthClientOptions } from 'better-auth/client';
|
|
3
|
+
import type { CasingOption } from '../schema-generator.js';
|
|
3
4
|
import type { ServerAuthContext } from './types/augment.js';
|
|
5
|
+
import { createAuthClient } from 'better-auth/vue';
|
|
4
6
|
export type { ServerAuthContext };
|
|
5
7
|
export interface ClientAuthContext {
|
|
6
8
|
siteUrl: string;
|
|
7
9
|
}
|
|
8
|
-
type ServerAuthConfig = Omit<BetterAuthOptions, 'database' | 'secret' | 'baseURL'>;
|
|
9
|
-
type ClientAuthConfig = Omit<
|
|
10
|
+
export type ServerAuthConfig = Omit<BetterAuthOptions, 'database' | 'secret' | 'baseURL'>;
|
|
11
|
+
export type ClientAuthConfig = Omit<BetterAuthClientOptions, 'baseURL'> & {
|
|
10
12
|
baseURL?: string;
|
|
11
13
|
};
|
|
12
14
|
export type ServerAuthConfigFn = (ctx: ServerAuthContext) => ServerAuthConfig;
|
|
13
15
|
export type ClientAuthConfigFn = (ctx: ClientAuthContext) => ClientAuthConfig;
|
|
14
16
|
export interface BetterAuthModuleOptions {
|
|
17
|
+
/** Client-only mode - skip server setup for external auth backends */
|
|
18
|
+
clientOnly?: boolean;
|
|
15
19
|
/** Server config path relative to rootDir. Default: 'server/auth.config' */
|
|
16
20
|
serverConfig?: string;
|
|
17
21
|
/** Client config path relative to rootDir. Default: 'app/auth.config' */
|
|
@@ -22,15 +26,24 @@ export interface BetterAuthModuleOptions {
|
|
|
22
26
|
};
|
|
23
27
|
/** Enable KV secondary storage for sessions. Requires hub.kv: true */
|
|
24
28
|
secondaryStorage?: boolean;
|
|
29
|
+
/** Schema generation options. Must match drizzleAdapter config. */
|
|
30
|
+
schema?: {
|
|
31
|
+
/** Plural table names: user → users. Default: false */
|
|
32
|
+
usePlural?: boolean;
|
|
33
|
+
/** Column/table name casing. Explicit value takes precedence over hub.db.casing. */
|
|
34
|
+
casing?: CasingOption;
|
|
35
|
+
};
|
|
25
36
|
}
|
|
26
37
|
export interface AuthRuntimeConfig {
|
|
27
38
|
redirects: {
|
|
28
39
|
login: string;
|
|
29
40
|
guest: string;
|
|
30
41
|
};
|
|
42
|
+
useDatabase: boolean;
|
|
43
|
+
clientOnly: boolean;
|
|
31
44
|
}
|
|
32
45
|
export interface AuthPrivateRuntimeConfig {
|
|
33
46
|
secondaryStorage: boolean;
|
|
34
47
|
}
|
|
35
|
-
export declare function defineServerAuth<T extends ServerAuthConfig>(config: (ctx: ServerAuthContext) => T): (ctx: ServerAuthContext) => T;
|
|
36
|
-
export declare function defineClientAuth(config:
|
|
48
|
+
export declare function defineServerAuth<T extends ServerAuthConfig>(config: T | ((ctx: ServerAuthContext) => T)): (ctx: ServerAuthContext) => T;
|
|
49
|
+
export declare function defineClientAuth<T extends ClientAuthConfig>(config: T | ((ctx: ClientAuthContext) => T)): (baseURL: string) => ReturnType<typeof createAuthClient<T>>;
|
package/dist/runtime/config.js
CHANGED
|
@@ -1,6 +1,11 @@
|
|
|
1
|
+
import { createAuthClient } from "better-auth/vue";
|
|
1
2
|
export function defineServerAuth(config) {
|
|
2
|
-
return config;
|
|
3
|
+
return typeof config === "function" ? config : () => config;
|
|
3
4
|
}
|
|
4
5
|
export function defineClientAuth(config) {
|
|
5
|
-
return
|
|
6
|
+
return (baseURL) => {
|
|
7
|
+
const ctx = { siteUrl: baseURL };
|
|
8
|
+
const resolved = typeof config === "function" ? config(ctx) : config;
|
|
9
|
+
return createAuthClient({ ...resolved, baseURL });
|
|
10
|
+
};
|
|
6
11
|
}
|
|
@@ -2,7 +2,7 @@ import { defineEventHandler, getQuery } from "h3";
|
|
|
2
2
|
import { paginationQuerySchema, sanitizeSearchPattern } from "./_schema.js";
|
|
3
3
|
export default defineEventHandler(async (event) => {
|
|
4
4
|
try {
|
|
5
|
-
const { db, schema } = await import("
|
|
5
|
+
const { db, schema } = await import("@nuxthub/db");
|
|
6
6
|
if (!schema.account)
|
|
7
7
|
return { accounts: [], total: 0, error: "Account table not found" };
|
|
8
8
|
const query = paginationQuerySchema.parse(getQuery(event));
|
|
@@ -9,27 +9,27 @@ declare const _default: import("h3").EventHandler<import("h3").EventHandlerReque
|
|
|
9
9
|
useDatabase: boolean;
|
|
10
10
|
};
|
|
11
11
|
server: {
|
|
12
|
-
baseURL:
|
|
13
|
-
basePath:
|
|
12
|
+
baseURL: any;
|
|
13
|
+
basePath: any;
|
|
14
14
|
socialProviders: string[];
|
|
15
|
-
plugins: any
|
|
16
|
-
trustedOrigins:
|
|
15
|
+
plugins: any;
|
|
16
|
+
trustedOrigins: any;
|
|
17
17
|
session: {
|
|
18
18
|
expiresIn: string;
|
|
19
19
|
updateAge: string;
|
|
20
|
-
cookieCache:
|
|
20
|
+
cookieCache: any;
|
|
21
21
|
};
|
|
22
22
|
emailAndPassword: boolean;
|
|
23
|
-
rateLimit:
|
|
23
|
+
rateLimit: any;
|
|
24
24
|
advanced: {
|
|
25
|
-
useSecureCookies:
|
|
26
|
-
disableCSRFCheck:
|
|
25
|
+
useSecureCookies: any;
|
|
26
|
+
disableCSRFCheck: any;
|
|
27
27
|
};
|
|
28
28
|
};
|
|
29
29
|
};
|
|
30
30
|
error?: undefined;
|
|
31
31
|
} | {
|
|
32
32
|
config: null;
|
|
33
|
-
error:
|
|
33
|
+
error: string;
|
|
34
34
|
}>>;
|
|
35
35
|
export default _default;
|
|
@@ -3,7 +3,7 @@ import { useRuntimeConfig } from "nitropack/runtime";
|
|
|
3
3
|
import { serverAuth } from "../../utils/auth.js";
|
|
4
4
|
export default defineEventHandler(async (event) => {
|
|
5
5
|
try {
|
|
6
|
-
const auth =
|
|
6
|
+
const auth = serverAuth(event);
|
|
7
7
|
const options = auth.options;
|
|
8
8
|
const runtimeConfig = useRuntimeConfig();
|
|
9
9
|
const publicAuth = runtimeConfig.public?.auth;
|
|
@@ -41,6 +41,7 @@ export default defineEventHandler(async (event) => {
|
|
|
41
41
|
}
|
|
42
42
|
};
|
|
43
43
|
} catch (error) {
|
|
44
|
-
|
|
44
|
+
console.error("[DevTools] Config fetch failed:", error);
|
|
45
|
+
return { config: null, error: "Failed to fetch configuration" };
|
|
45
46
|
}
|
|
46
47
|
});
|
|
@@ -6,7 +6,7 @@ const deleteSessionSchema = z.object({
|
|
|
6
6
|
export default defineEventHandler(async (event) => {
|
|
7
7
|
try {
|
|
8
8
|
const body = deleteSessionSchema.parse(await readBody(event));
|
|
9
|
-
const { db, schema } = await import("
|
|
9
|
+
const { db, schema } = await import("@nuxthub/db");
|
|
10
10
|
if (!schema.session)
|
|
11
11
|
throw createError({ statusCode: 500, message: "Session table not found" });
|
|
12
12
|
const { eq } = await import("drizzle-orm");
|
|
@@ -2,7 +2,7 @@ import { defineEventHandler, getQuery } from "h3";
|
|
|
2
2
|
import { paginationQuerySchema, sanitizeSearchPattern } from "./_schema.js";
|
|
3
3
|
export default defineEventHandler(async (event) => {
|
|
4
4
|
try {
|
|
5
|
-
const { db, schema } = await import("
|
|
5
|
+
const { db, schema } = await import("@nuxthub/db");
|
|
6
6
|
if (!schema.session)
|
|
7
7
|
return { sessions: [], total: 0, error: "Session table not found" };
|
|
8
8
|
const query = paginationQuerySchema.parse(getQuery(event));
|
|
@@ -26,7 +26,16 @@ export default defineEventHandler(async (event) => {
|
|
|
26
26
|
dbQuery.orderBy(desc(schema.session.createdAt)).limit(limit).offset(offset),
|
|
27
27
|
countQuery
|
|
28
28
|
]);
|
|
29
|
-
|
|
29
|
+
const safeSessions = sessions.map((s) => ({
|
|
30
|
+
id: s.id,
|
|
31
|
+
userId: s.userId,
|
|
32
|
+
createdAt: s.createdAt,
|
|
33
|
+
updatedAt: s.updatedAt,
|
|
34
|
+
expiresAt: s.expiresAt,
|
|
35
|
+
ipAddress: s.ipAddress,
|
|
36
|
+
userAgent: s.userAgent
|
|
37
|
+
}));
|
|
38
|
+
return { sessions: safeSessions, total: totalResult[0]?.count ?? 0, page, limit };
|
|
30
39
|
} catch (error) {
|
|
31
40
|
console.error("[DevTools] Fetch sessions failed:", error);
|
|
32
41
|
return { sessions: [], total: 0, error: "Failed to fetch sessions" };
|
|
@@ -2,7 +2,7 @@ import { defineEventHandler, getQuery } from "h3";
|
|
|
2
2
|
import { paginationQuerySchema, sanitizeSearchPattern } from "./_schema.js";
|
|
3
3
|
export default defineEventHandler(async (event) => {
|
|
4
4
|
try {
|
|
5
|
-
const { db, schema } = await import("
|
|
5
|
+
const { db, schema } = await import("@nuxthub/db");
|
|
6
6
|
if (!schema.user)
|
|
7
7
|
return { users: [], total: 0, error: "User table not found" };
|
|
8
8
|
const query = paginationQuerySchema.parse(getQuery(event));
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { defineEventHandler, toWebRequest } from "h3";
|
|
2
2
|
import { serverAuth } from "../../utils/auth.js";
|
|
3
3
|
export default defineEventHandler(async (event) => {
|
|
4
|
-
const auth =
|
|
4
|
+
const auth = serverAuth(event);
|
|
5
5
|
return auth.handler(toWebRequest(event));
|
|
6
6
|
});
|