@nuxt-atelier/auth-better-auth 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ano Rebel
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,7 @@
1
- # Temporary Holding Version
1
+ # @nuxt-atelier/auth-better-auth
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Better Auth adapter for Nuxt Atelier
4
+
5
+ Part of [Nuxt Atelier](https://nuxt-atelier.anorebel.net), a visual CMS for Nuxt. See the [documentation](https://nuxt-atelier.anorebel.net) to get started, or try the [live demo](https://nuxt-atelier-demo.anorebel.net).
6
+
7
+ MIT License
@@ -0,0 +1,34 @@
1
+ import { BetterAuthOptions } from 'better-auth';
2
+ import { TableSpec } from 'nuxt-atelier';
3
+
4
+ interface AtelierBetterAuthConfig {
5
+ /**
6
+ * Better Auth options: providers, plugins (two-factor, passkeys, generic OAuth…). Nuxt Atelier sets
7
+ * the database (the CMS's), the base path (`/api/auth`) and the table names; `secret` defaults to one
8
+ * derived from `NUXT_APP_SECRET`, and `baseURL` to the public site URL.
9
+ */
10
+ betterAuth?: Omit<BetterAuthOptions, 'database' | 'basePath'>;
11
+ /**
12
+ * The CMS role a new user gets, e.g. from their email domain. `null` (the default): none, so they can
13
+ * sign in but reach nothing in the CMS until an administrator gives them a role.
14
+ */
15
+ mapRole?: (user: {
16
+ email: string;
17
+ name: string;
18
+ emailVerified: boolean;
19
+ }) => string | null | Promise<string | null>;
20
+ }
21
+ /** Returns the config, typed. Default-export it from `server/atelier/auth.ts`. */
22
+ declare const defineAtelierBetterAuth: (config: AtelierBetterAuthConfig) => AtelierBetterAuthConfig;
23
+ /** The Better Auth options with Atelier's table names, email and password sign-in, and the CMS role field. */
24
+ declare function withAtelierModels(options?: AtelierBetterAuthConfig['betterAuth']): BetterAuthOptions;
25
+ /** The SQL table of a Better Auth model: plugin models (`twoFactor`) become `atelier_ba_two_factor`. */
26
+ declare const tableOf: (model: string) => string;
27
+ /**
28
+ * Better Auth's tables for this config, plugins included, for `server/atelier/tables.ts`:
29
+ * `export default defineTables(betterAuthTables(auth))`. They're migrated with the content tables.
30
+ */
31
+ declare function betterAuthTables(config: AtelierBetterAuthConfig): Record<string, TableSpec>;
32
+
33
+ export { betterAuthTables, defineAtelierBetterAuth, tableOf, withAtelierModels };
34
+ export type { AtelierBetterAuthConfig };
@@ -0,0 +1,41 @@
1
+ import { getSchema } from 'better-auth/db';
2
+
3
+ const defineAtelierBetterAuth = (config) => config;
4
+ const MODELS = {
5
+ user: "atelier_ba_users",
6
+ session: "atelier_ba_sessions",
7
+ account: "atelier_ba_accounts",
8
+ verification: "atelier_ba_verifications"
9
+ };
10
+ function withAtelierModels(options = {}) {
11
+ return {
12
+ ...options,
13
+ emailAndPassword: { enabled: true, ...options.emailAndPassword },
14
+ user: {
15
+ ...options.user,
16
+ modelName: MODELS.user,
17
+ additionalFields: { ...options.user?.additionalFields, role: { type: "string", required: false, input: false } }
18
+ },
19
+ session: { ...options.session, modelName: MODELS.session },
20
+ account: { ...options.account, modelName: MODELS.account },
21
+ verification: { ...options.verification, modelName: MODELS.verification }
22
+ };
23
+ }
24
+ const tableOf = (model) => model.startsWith("atelier_") ? model : `atelier_ba_${model.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`)}`;
25
+ const columnType = (type) => type === "string" || type === "number" || type === "boolean" || type === "date" ? type : Array.isArray(type) ? "string" : "json";
26
+ function betterAuthTables(config) {
27
+ const schema = getSchema(withAtelierModels(config.betterAuth));
28
+ return Object.fromEntries(Object.entries(schema).toSorted(([, a], [, b]) => a.order - b.order).map(([model, table]) => [tableOf(model), {
29
+ columns: Object.fromEntries(Object.entries(table.fields).map(([key, field]) => [field.fieldName ?? key, {
30
+ type: columnType(field.type),
31
+ required: field.required === true,
32
+ unique: field.unique === true,
33
+ index: field.index === true,
34
+ bigint: field.bigint === true,
35
+ // cascade unless the plugin says otherwise, as Better Auth's own schema generator does
36
+ ...field.references ? { references: { table: tableOf(field.references.model), onDelete: field.references.onDelete ?? "cascade" } } : {}
37
+ }]))
38
+ }]));
39
+ }
40
+
41
+ export { betterAuthTables, defineAtelierBetterAuth, tableOf, withAtelierModels };
@@ -0,0 +1,5 @@
1
+ import { NuxtModule } from '@nuxt/schema';
2
+
3
+ declare const module$1: NuxtModule;
4
+
5
+ export { module$1 as default };
@@ -0,0 +1,12 @@
1
+ {
2
+ "name": "@nuxt-atelier/auth-better-auth",
3
+ "compatibility": {
4
+ "nuxt": ">=4.6.0"
5
+ },
6
+ "configKey": "@nuxt-atelier/auth-better-auth",
7
+ "version": "0.1.0",
8
+ "builder": {
9
+ "@nuxt/module-builder": "1.0.3",
10
+ "unbuild": "unknown"
11
+ }
12
+ }
@@ -0,0 +1,35 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { defineNuxtModule, createResolver, getLayerDirectories, useLogger, addServerTemplate, addTypeTemplate, addServerPlugin, addServerHandler } from '@nuxt/kit';
4
+
5
+ const module$1 = defineNuxtModule({
6
+ meta: {
7
+ name: "@nuxt-atelier/auth-better-auth",
8
+ compatibility: {
9
+ nuxt: ">=4.6.0"
10
+ }
11
+ },
12
+ setup(_options, nuxt) {
13
+ const { resolve } = createResolver(import.meta.url);
14
+ const configFile = getLayerDirectories(nuxt).flatMap((layer) => ["ts", "mts", "js", "mjs"].map((ext) => join(layer.server, "atelier", `auth.${ext}`))).find(existsSync);
15
+ if (!configFile)
16
+ useLogger("nuxt-atelier").warn("@nuxt-atelier/auth-better-auth: no server/atelier/auth.ts; using Better Auth with its defaults (email and password)");
17
+ addServerTemplate({
18
+ filename: "#atelier-better-auth",
19
+ getContents: () => configFile ? `export { default } from ${JSON.stringify(configFile)}` : "export default {}"
20
+ });
21
+ addTypeTemplate({
22
+ filename: "types/atelier-better-auth.d.ts",
23
+ getContents: () => `declare module '#atelier-better-auth' {
24
+ const config: import(${JSON.stringify(resolve("./config"))}).AtelierBetterAuthConfig
25
+ export default config
26
+ }
27
+ `
28
+ }, { nitro: true });
29
+ addServerPlugin(resolve("./runtime/server/plugin"));
30
+ addServerHandler({ route: "/api/auth/**", handler: resolve("./runtime/server/handler") });
31
+ addServerHandler({ route: "/api/_atelier/auth/oauth/**", method: "get", handler: resolve("./runtime/server/oauth") });
32
+ }
33
+ });
34
+
35
+ export { module$1 as default };
@@ -0,0 +1,358 @@
1
+ import type { AuthAdapter } from '#atelier/server';
2
+ import type { AtelierBetterAuthConfig } from '../../config.js';
3
+ /** The Better Auth instance, created on first use. */
4
+ export declare function useBetterAuth(config: AtelierBetterAuthConfig): Promise<import("better-auth").Auth<{
5
+ secret: string;
6
+ baseURL: import("better-auth").BaseURLConfig | undefined;
7
+ basePath: string;
8
+ database: (options: import("better-auth").BetterAuthOptions) => import("better-auth").DBAdapter<import("better-auth").BetterAuthOptions>;
9
+ databaseHooks: {
10
+ user: {
11
+ create: {
12
+ before(user: {
13
+ id: string;
14
+ createdAt: Date;
15
+ updatedAt: Date;
16
+ email: string;
17
+ emailVerified: boolean;
18
+ name: string;
19
+ image?: string | null | undefined;
20
+ } & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null): Promise<false | {
21
+ data: {
22
+ role: string | null;
23
+ id: string;
24
+ createdAt: Date;
25
+ updatedAt: Date;
26
+ email: string;
27
+ emailVerified: boolean;
28
+ name: string;
29
+ image?: string | null | undefined;
30
+ };
31
+ }>;
32
+ after?: (user: import("better-auth").User & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<void>;
33
+ };
34
+ update?: {
35
+ before?: (user: Partial<import("better-auth").User> & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<boolean | void | {
36
+ data: {
37
+ [x: string]: any;
38
+ id?: string | undefined;
39
+ createdAt?: Date | undefined;
40
+ updatedAt?: Date | undefined;
41
+ email?: string | undefined;
42
+ emailVerified?: boolean | undefined;
43
+ name?: string | undefined;
44
+ image?: string | null | undefined;
45
+ };
46
+ }>;
47
+ after?: (user: import("better-auth").User & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<void>;
48
+ };
49
+ delete?: {
50
+ before?: (user: import("better-auth").User & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<boolean | void>;
51
+ after?: (user: import("better-auth").User & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<void>;
52
+ };
53
+ };
54
+ session?: {
55
+ create?: {
56
+ before?: (session: import("better-auth").Session & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<boolean | void | {
57
+ data: {
58
+ id?: string | undefined;
59
+ createdAt?: Date | undefined;
60
+ updatedAt?: Date | undefined;
61
+ userId?: string | undefined;
62
+ expiresAt?: Date | undefined;
63
+ token?: string | undefined;
64
+ ipAddress?: string | null | undefined;
65
+ userAgent?: string | null | undefined;
66
+ } & Record<string, any>;
67
+ }>;
68
+ after?: (session: import("better-auth").Session & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<void>;
69
+ };
70
+ update?: {
71
+ before?: (session: Partial<import("better-auth").Session> & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<boolean | void | {
72
+ data: {
73
+ [x: string]: any;
74
+ id?: string | undefined;
75
+ createdAt?: Date | undefined;
76
+ updatedAt?: Date | undefined;
77
+ userId?: string | undefined;
78
+ expiresAt?: Date | undefined;
79
+ token?: string | undefined;
80
+ ipAddress?: string | null | undefined;
81
+ userAgent?: string | null | undefined;
82
+ };
83
+ }>;
84
+ after?: (session: import("better-auth").Session & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<void>;
85
+ };
86
+ delete?: {
87
+ before?: (session: import("better-auth").Session & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<boolean | void>;
88
+ after?: (session: import("better-auth").Session & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<void>;
89
+ };
90
+ };
91
+ account?: {
92
+ create?: {
93
+ before?: (account: import("better-auth").Account, context: import("better-auth").GenericEndpointContext | null) => Promise<boolean | void | {
94
+ data: {
95
+ id?: string | undefined;
96
+ createdAt?: Date | undefined;
97
+ updatedAt?: Date | undefined;
98
+ providerId?: string | undefined;
99
+ accountId?: string | undefined;
100
+ userId?: string | undefined;
101
+ accessToken?: string | null | undefined;
102
+ refreshToken?: string | null | undefined;
103
+ idToken?: string | null | undefined;
104
+ accessTokenExpiresAt?: Date | null | undefined;
105
+ refreshTokenExpiresAt?: Date | null | undefined;
106
+ scope?: string | null | undefined;
107
+ password?: string | null | undefined;
108
+ } & Record<string, any>;
109
+ }>;
110
+ after?: (account: import("better-auth").Account, context: import("better-auth").GenericEndpointContext | null) => Promise<void>;
111
+ };
112
+ update?: {
113
+ before?: (account: Partial<import("better-auth").Account> & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<boolean | void | {
114
+ data: {
115
+ [x: string]: any;
116
+ id?: string | undefined;
117
+ createdAt?: Date | undefined;
118
+ updatedAt?: Date | undefined;
119
+ providerId?: string | undefined;
120
+ accountId?: string | undefined;
121
+ userId?: string | undefined;
122
+ accessToken?: string | null | undefined;
123
+ refreshToken?: string | null | undefined;
124
+ idToken?: string | null | undefined;
125
+ accessTokenExpiresAt?: Date | null | undefined;
126
+ refreshTokenExpiresAt?: Date | null | undefined;
127
+ scope?: string | null | undefined;
128
+ password?: string | null | undefined;
129
+ };
130
+ }>;
131
+ after?: (account: import("better-auth").Account & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<void>;
132
+ };
133
+ delete?: {
134
+ before?: (account: import("better-auth").Account & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<boolean | void>;
135
+ after?: (account: import("better-auth").Account & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<void>;
136
+ };
137
+ };
138
+ verification?: {
139
+ create?: {
140
+ before?: (verification: import("better-auth").Verification & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<boolean | void | {
141
+ data: {
142
+ id?: string | undefined;
143
+ createdAt?: Date | undefined;
144
+ updatedAt?: Date | undefined;
145
+ value?: string | undefined;
146
+ expiresAt?: Date | undefined;
147
+ identifier?: string | undefined;
148
+ } & Record<string, any>;
149
+ }>;
150
+ after?: (verification: import("better-auth").Verification & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<void>;
151
+ };
152
+ update?: {
153
+ before?: (verification: Partial<import("better-auth").Verification> & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<boolean | void | {
154
+ data: {
155
+ [x: string]: any;
156
+ id?: string | undefined;
157
+ createdAt?: Date | undefined;
158
+ updatedAt?: Date | undefined;
159
+ value?: string | undefined;
160
+ expiresAt?: Date | undefined;
161
+ identifier?: string | undefined;
162
+ };
163
+ }>;
164
+ after?: (verification: import("better-auth").Verification & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<void>;
165
+ };
166
+ delete?: {
167
+ before?: (verification: import("better-auth").Verification & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<boolean | void>;
168
+ after?: (verification: import("better-auth").Verification & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<void>;
169
+ };
170
+ };
171
+ };
172
+ appName?: string | undefined;
173
+ secrets?: Array<{
174
+ version: number;
175
+ value: string;
176
+ }> | undefined;
177
+ secondaryStorage?: import("better-auth").SecondaryStorage | undefined;
178
+ emailVerification?: {
179
+ sendVerificationEmail?: (data: {
180
+ user: import("better-auth").User;
181
+ url: string;
182
+ token: string;
183
+ }, request?: Request) => Promise<void>;
184
+ sendOnSignUp?: boolean;
185
+ sendOnSignIn?: boolean;
186
+ autoSignInAfterVerification?: boolean;
187
+ expiresIn?: number;
188
+ beforeEmailVerification?: (user: import("better-auth").User, request?: Request) => Promise<void>;
189
+ afterEmailVerification?: (user: import("better-auth").User, request?: Request) => Promise<void>;
190
+ } | undefined;
191
+ emailAndPassword?: {
192
+ enabled: boolean;
193
+ disableSignUp?: boolean;
194
+ requireEmailVerification?: boolean;
195
+ maxPasswordLength?: number;
196
+ minPasswordLength?: number;
197
+ sendResetPassword?: (data: {
198
+ user: import("better-auth").User;
199
+ url: string;
200
+ token: string;
201
+ }, request?: Request) => Promise<void>;
202
+ resetPasswordTokenExpiresIn?: number;
203
+ onPasswordReset?: (data: {
204
+ user: import("better-auth").User;
205
+ }, request?: Request) => Promise<void>;
206
+ password?: {
207
+ hash?: (password: string) => Promise<string>;
208
+ verify?: (data: {
209
+ hash: string;
210
+ password: string;
211
+ }) => Promise<boolean>;
212
+ };
213
+ autoSignIn?: boolean;
214
+ revokeSessionsOnPasswordReset?: boolean;
215
+ onExistingUserSignUp?: (data: {
216
+ user: import("better-auth").User;
217
+ }, request?: Request) => Promise<void>;
218
+ customSyntheticUser?: (params: {
219
+ coreFields: {
220
+ name: string;
221
+ email: string;
222
+ emailVerified: boolean;
223
+ image: string | null;
224
+ createdAt: Date;
225
+ updatedAt: Date;
226
+ };
227
+ additionalFields: Record<string, unknown>;
228
+ id: string;
229
+ }) => Record<string, unknown>;
230
+ } | undefined;
231
+ socialProviders?: import("better-auth").SocialProviders | undefined;
232
+ plugins?: ([] | import("better-auth").BetterAuthPlugin[]) | undefined;
233
+ user?: (import("better-auth").BetterAuthDBOptions<"user", keyof import("better-auth").BaseUser> & {
234
+ validateUserInfo?: (data: {
235
+ user: Partial<import("better-auth").User> & Record<string, unknown>;
236
+ source: import("better-auth").ValidateUserInfoSource;
237
+ }, context: import("better-auth").GenericEndpointContext) => import("better-auth").Awaitable<void | import("better-auth").ValidateUserInfoResult>;
238
+ changeEmail?: {
239
+ enabled: boolean;
240
+ sendChangeEmailConfirmation?: (data: {
241
+ user: import("better-auth").User;
242
+ newEmail: string;
243
+ url: string;
244
+ token: string;
245
+ }, request?: Request) => Promise<void>;
246
+ updateEmailWithoutVerification?: boolean;
247
+ };
248
+ deleteUser?: {
249
+ enabled?: boolean;
250
+ sendDeleteAccountVerification?: (data: {
251
+ user: import("better-auth").User;
252
+ url: string;
253
+ token: string;
254
+ }, request?: Request) => Promise<void>;
255
+ beforeDelete?: (user: import("better-auth").User, request?: Request) => Promise<void>;
256
+ afterDelete?: (user: import("better-auth").User, request?: Request) => Promise<void>;
257
+ deleteTokenExpiresIn?: number;
258
+ };
259
+ }) | undefined;
260
+ session?: (import("better-auth").BetterAuthDBOptions<"session", keyof import("better-auth").BaseSession> & {
261
+ expiresIn?: number;
262
+ updateAge?: number;
263
+ disableSessionRefresh?: boolean;
264
+ deferSessionRefresh?: boolean;
265
+ storeSessionInDatabase?: boolean;
266
+ preserveSessionInDatabase?: boolean;
267
+ cookieCache?: {
268
+ maxAge?: number;
269
+ enabled?: boolean;
270
+ strategy?: "compact" | "jwt" | "jwe";
271
+ refreshCache?: boolean | {
272
+ updateAge?: number;
273
+ };
274
+ version?: string | ((session: import("better-auth").Session & Record<string, any>, user: import("better-auth").User & Record<string, any>) => string) | ((session: import("better-auth").Session & Record<string, any>, user: import("better-auth").User & Record<string, any>) => Promise<string>);
275
+ };
276
+ freshAge?: number;
277
+ }) | undefined;
278
+ account?: (import("better-auth").BetterAuthDBOptions<"account", keyof import("better-auth").BaseAccount> & {
279
+ updateAccountOnSignIn?: boolean;
280
+ accountLinking?: {
281
+ enabled?: boolean;
282
+ disableImplicitLinking?: boolean;
283
+ requireLocalEmailVerified?: boolean;
284
+ trustedProviders?: Array<import("better-auth").LiteralUnion<import("better-auth").SocialProviderList[number] | "email-password", string>> | ((request?: Request | undefined) => import("better-auth").Awaitable<Array<import("better-auth").LiteralUnion<import("better-auth").SocialProviderList[number] | "email-password", string>>>);
285
+ allowDifferentEmails?: boolean;
286
+ allowUnlinkingAll?: boolean;
287
+ updateUserInfoOnLink?: boolean;
288
+ };
289
+ encryptOAuthTokens?: boolean;
290
+ skipStateCookieCheck?: boolean;
291
+ storeStateStrategy?: "database" | "cookie";
292
+ storeAccountCookie?: boolean;
293
+ }) | undefined;
294
+ verification?: (import("better-auth").BetterAuthDBOptions<"verification", keyof import("better-auth").BaseVerification> & {
295
+ disableCleanup?: boolean;
296
+ storeIdentifier?: import("better-auth").StoreIdentifierOption | {
297
+ default: import("better-auth").StoreIdentifierOption;
298
+ overrides?: Record<string, import("better-auth").StoreIdentifierOption>;
299
+ };
300
+ storeInDatabase?: boolean;
301
+ }) | undefined;
302
+ trustedOrigins?: (string[] | ((request?: Request | undefined) => import("better-auth").Awaitable<(string | undefined | null)[]>)) | undefined;
303
+ rateLimit?: import("better-auth").BetterAuthRateLimitOptions | undefined;
304
+ advanced?: import("better-auth").BetterAuthAdvancedOptions | undefined;
305
+ logger?: import("better-auth").Logger | undefined;
306
+ onAPIError?: {
307
+ throw?: boolean;
308
+ onError?: (error: unknown, ctx: import("better-auth").AuthContext) => void | Promise<void>;
309
+ errorURL?: string;
310
+ customizeDefaultErrorPage?: {
311
+ colors?: {
312
+ background?: string;
313
+ foreground?: string;
314
+ primary?: string;
315
+ primaryForeground?: string;
316
+ mutedForeground?: string;
317
+ border?: string;
318
+ destructive?: string;
319
+ titleBorder?: string;
320
+ titleColor?: string;
321
+ gridColor?: string;
322
+ cardBackground?: string;
323
+ cornerBorder?: string;
324
+ };
325
+ size?: {
326
+ radiusSm?: string;
327
+ radiusMd?: string;
328
+ radiusLg?: string;
329
+ textSm?: string;
330
+ text2xl?: string;
331
+ text4xl?: string;
332
+ text6xl?: string;
333
+ };
334
+ font?: {
335
+ defaultFamily?: string;
336
+ monoFamily?: string;
337
+ };
338
+ disableTitleBorder?: boolean;
339
+ disableCornerDecorations?: boolean;
340
+ disableBackgroundGrid?: boolean;
341
+ };
342
+ } | undefined;
343
+ hooks?: {
344
+ before?: import("better-auth/api").AuthMiddleware;
345
+ after?: import("better-auth/api").AuthMiddleware;
346
+ } | undefined;
347
+ disabledPaths?: string[] | undefined;
348
+ telemetry?: {
349
+ enabled?: boolean;
350
+ debug?: boolean;
351
+ } | undefined;
352
+ experimental?: {
353
+ instrumentation?: {
354
+ enabled?: boolean | undefined;
355
+ } | undefined;
356
+ } | undefined;
357
+ }>>;
358
+ export declare function createBetterAuthAdapter(config: AtelierBetterAuthConfig): Promise<AuthAdapter>;
@@ -0,0 +1,123 @@
1
+ import { betterAuth } from "better-auth";
2
+ import { drizzleAdapter } from "better-auth/adapters/drizzle";
3
+ import { getSchema } from "better-auth/db";
4
+ import { createError, deriveSecret, useRuntimeConfig } from "nuxt/server";
5
+ import { useAtelierDatabase, useAtelierTables } from "#atelier/server";
6
+ import { tableOf, withAtelierModels } from "../../config";
7
+ const PROVIDERS = { sqlite: "sqlite", postgres: "pg", mysql: "mysql" };
8
+ async function create(config) {
9
+ const driver = await useAtelierDatabase();
10
+ const tables = await useAtelierTables();
11
+ const options = withAtelierModels(config.betterAuth);
12
+ const schema = Object.fromEntries(Object.keys(getSchema(options)).map((model) => [model, tables[tableOf(model)]]));
13
+ const missing = Object.entries(schema).filter(([, table]) => !table).map(([model]) => tableOf(model));
14
+ if (missing.length)
15
+ throw new Error(`[nuxt-atelier] Better Auth's tables aren't in the schema: ${missing.join(", ")}. Export them from server/atelier/tables.ts: \`export default defineTables(betterAuthTables(auth))\`.`);
16
+ const siteUrl = useRuntimeConfig().public.atelier?.siteUrl;
17
+ const userHook = options.databaseHooks?.user?.create?.before;
18
+ return betterAuth({
19
+ ...options,
20
+ secret: options.secret ?? await deriveSecret("nuxt-atelier:better-auth"),
21
+ baseURL: options.baseURL ?? (siteUrl || void 0),
22
+ basePath: "/api/auth",
23
+ database: drizzleAdapter(driver.db, { provider: PROVIDERS[driver.dialect], schema, transaction: driver.capabilities.transactions }),
24
+ databaseHooks: {
25
+ ...options.databaseHooks,
26
+ user: {
27
+ ...options.databaseHooks?.user,
28
+ create: {
29
+ ...options.databaseHooks?.user?.create,
30
+ async before(user, context) {
31
+ const own = userHook ? await userHook(user, context) : void 0;
32
+ if (own === false)
33
+ return false;
34
+ const data = { ...user, ...own?.data };
35
+ return { data: { ...data, role: data.role ?? await config.mapRole?.(data) ?? null } };
36
+ }
37
+ }
38
+ }
39
+ }
40
+ });
41
+ }
42
+ let instance;
43
+ export function useBetterAuth(config) {
44
+ instance ??= create(config).catch((error) => {
45
+ instance = void 0;
46
+ throw error;
47
+ });
48
+ return instance;
49
+ }
50
+ const toUser = (user) => ({ id: user.id, email: user.email, name: user.name || null, role: user.role ?? "" });
51
+ export async function createBetterAuthAdapter(config) {
52
+ const auth = await useBetterAuth(config);
53
+ const context = await auth.$context;
54
+ const internal = context.internalAdapter;
55
+ const copyCookies = (event, response) => {
56
+ for (const cookie of response.headers.getSetCookie())
57
+ event.res.headers.append("set-cookie", cookie);
58
+ };
59
+ const setPassword = async (userId, password) => {
60
+ const hash = await context.password.hash(password);
61
+ const credential = (await internal.findAccounts(userId)).find((a) => a.providerId === "credential");
62
+ if (credential)
63
+ await internal.updatePassword(userId, hash);
64
+ else
65
+ await internal.linkAccount({ userId, providerId: "credential", accountId: userId, password: hash });
66
+ };
67
+ const found = async (id) => {
68
+ const user = await internal.findUserById(id);
69
+ if (!user)
70
+ throw createError({ status: 404, message: `No user "${id}"` });
71
+ return user;
72
+ };
73
+ return {
74
+ name: "better-auth",
75
+ // social and generic OAuth providers alike (the generic-oauth plugin adds its own to the same list);
76
+ // each link starts the sign-in through the CMS (runtime/server/oauth.ts), then comes back
77
+ oauthProviders: () => context.socialProviders.map((p) => ({ id: p.id, name: p.name || p.id, url: `/api/_atelier/auth/oauth/${encodeURIComponent(p.id)}` })),
78
+ async getUser(event) {
79
+ const session = await auth.api.getSession({ headers: event.req.headers });
80
+ const user = session?.user;
81
+ return user?.role ? toUser(user) : null;
82
+ },
83
+ async signIn(event, { email, password }) {
84
+ const response = await auth.api.signInEmail({ body: { email, password }, headers: event.req.headers, asResponse: true });
85
+ if (!response.ok)
86
+ throw createError({ status: 401, message: "Wrong email or password" });
87
+ copyCookies(event, response);
88
+ const { user } = await response.json();
89
+ if (!user.role)
90
+ throw createError({ status: 403, message: "You're signed in, but have no role in the CMS yet: ask an administrator" });
91
+ return toUser(user);
92
+ },
93
+ async signOut(event) {
94
+ copyCookies(event, await auth.api.signOut({ headers: event.req.headers, asResponse: true }));
95
+ },
96
+ users: {
97
+ list: async () => (await internal.listUsers()).map(toUser),
98
+ get: async (id) => await internal.findUserById(id).then((u) => u && toUser(u)) ?? null,
99
+ async create(user) {
100
+ if (await internal.findUserByEmail(user.email.trim().toLowerCase()))
101
+ throw createError({ status: 409, message: `A user with the email ${user.email} already exists` });
102
+ const created = await internal.createUser({ email: user.email.trim().toLowerCase(), name: user.name ?? "", role: user.role, emailVerified: false });
103
+ if (user.password !== void 0)
104
+ await setPassword(created.id, user.password);
105
+ return toUser(created);
106
+ },
107
+ async update(id, changes) {
108
+ await found(id);
109
+ const fields = Object.fromEntries(Object.entries({ email: changes.email?.trim().toLowerCase(), name: changes.name, role: changes.role }).filter(([, v]) => v !== void 0));
110
+ const updated = Object.keys(fields).length ? await internal.updateUser(id, fields) : await found(id);
111
+ if (changes.password !== void 0) {
112
+ await setPassword(id, changes.password);
113
+ await internal.deleteUserSessions(id);
114
+ }
115
+ return toUser(updated);
116
+ },
117
+ async delete(id) {
118
+ await internal.deleteUserSessions(id);
119
+ await internal.deleteUser(id);
120
+ }
121
+ }
122
+ };
123
+ }
@@ -0,0 +1,5 @@
1
+ // Generated by the module (addServerTemplate); declared here for the package's own build.
2
+ declare module '#atelier-better-auth' {
3
+ const config: import('../../config').AtelierBetterAuthConfig
4
+ export default config
5
+ }
@@ -0,0 +1,2 @@
1
+ declare const _default: import("nuxt/server").EventHandler<Promise<Response>>;
2
+ export default _default;
@@ -0,0 +1,4 @@
1
+ import config from "#atelier-better-auth";
2
+ import { defineEventHandler } from "nuxt/server";
3
+ import { useBetterAuth } from "./adapter.js";
4
+ export default defineEventHandler(async (event) => (await useBetterAuth(config)).handler(event.req));
@@ -0,0 +1,2 @@
1
+ declare const _default: import("nuxt/server").EventHandler<Promise<Response>>;
2
+ export default _default;
@@ -0,0 +1,28 @@
1
+ import config from "#atelier-better-auth";
2
+ import { defineEventHandler, getQuery, getRequestURL } from "nuxt/server";
3
+ import { apiError } from "#atelier/server";
4
+ import { useBetterAuth } from "./adapter.js";
5
+ const PREFIX = "/api/_atelier/auth/oauth/";
6
+ export default defineEventHandler(async (event) => {
7
+ const provider = decodeURIComponent(getRequestURL(event).pathname.slice(PREFIX.length));
8
+ const redirect = String(getQuery(event).redirect ?? "/");
9
+ if (!redirect.startsWith("/") || redirect.startsWith("//") || redirect.includes("\\"))
10
+ throw apiError(400, "redirect: expected a path on this site, like /admin");
11
+ const auth = await useBetterAuth(config);
12
+ const headers = new Headers(event.req.headers);
13
+ headers.set("content-type", "application/json");
14
+ const started = await auth.handler(new Request(new URL("/api/auth/sign-in/social", getRequestURL(event).origin), {
15
+ method: "POST",
16
+ headers,
17
+ body: JSON.stringify({ provider, callbackURL: redirect })
18
+ }));
19
+ if (started.status === 429)
20
+ throw apiError(429, "Too many sign-in attempts: try again in a minute");
21
+ if (!started.ok)
22
+ throw apiError(started.status === 404 ? 404 : 400, `No sign-in with "${provider}"`);
23
+ const { url } = await started.json();
24
+ const response = new Response(null, { status: 302, headers: { location: url } });
25
+ for (const cookie of started.headers.getSetCookie())
26
+ response.headers.append("set-cookie", cookie);
27
+ return response;
28
+ });
@@ -0,0 +1,2 @@
1
+ declare const _default: () => void;
2
+ export default _default;
@@ -0,0 +1,6 @@
1
+ import { registerAuthAdapter } from "#atelier/server";
2
+ import config from "#atelier-better-auth";
3
+ import { createBetterAuthAdapter } from "./adapter.js";
4
+ export default () => {
5
+ registerAuthAdapter(() => createBetterAuthAdapter(config));
6
+ };
@@ -0,0 +1,7 @@
1
+ import type { NuxtModule } from '@nuxt/schema'
2
+
3
+ import type { default as Module } from './module.mjs'
4
+
5
+ export type ModuleOptions = typeof Module extends NuxtModule<infer O> ? Partial<O> : Record<string, any>
6
+
7
+ export { default } from './module.mjs'
package/package.json CHANGED
@@ -1,6 +1,54 @@
1
1
  {
2
2
  "name": "@nuxt-atelier/auth-better-auth",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "license": "MIT",
5
+ "type": "module",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/AnoRebel/nuxt-atelier.git",
9
+ "directory": "packages/auth-better-auth"
10
+ },
11
+ "homepage": "https://nuxt-atelier.anorebel.net",
12
+ "description": "Better Auth adapter for Nuxt Atelier",
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/types.d.mts",
16
+ "import": "./dist/module.mjs"
17
+ },
18
+ "./config": {
19
+ "types": "./dist/config.d.mts",
20
+ "import": "./dist/config.mjs"
21
+ }
22
+ },
23
+ "main": "./dist/module.mjs",
24
+ "typesVersions": {
25
+ "*": {
26
+ ".": [
27
+ "./dist/types.d.mts"
28
+ ],
29
+ "config": [
30
+ "./dist/config.d.mts"
31
+ ]
32
+ }
33
+ },
34
+ "files": [
35
+ "dist"
36
+ ],
37
+ "scripts": {
38
+ "build": "nuxt-module-build build",
39
+ "prepack": "nuxt-module-build build",
40
+ "check:pkg": "publint --pack bun && attw --pack . --profile esm-only"
41
+ },
42
+ "peerDependencies": {
43
+ "nuxt": ">=4.6.0",
44
+ "nuxt-atelier": "^0.1.0"
45
+ },
46
+ "dependencies": {
47
+ "@nuxt/kit": "^4.6.3",
48
+ "better-auth": "1.7.14"
49
+ },
50
+ "devDependencies": {
51
+ "@nuxt/schema": "4.6.3",
52
+ "nuxt-atelier": "^0.1.0"
53
+ }
54
+ }