-
-
Notifications
You must be signed in to change notification settings - Fork 129
/
module.ts
270 lines (244 loc) 路 7.53 KB
/
module.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
import {
defineNuxtModule,
useLogger,
createResolver,
addTypeTemplate,
addPlugin,
addServerPlugin,
addImports,
addRouteMiddleware
} from '@nuxt/kit'
import { defu } from 'defu'
import { joinURL } from 'ufo'
import { genInterface } from 'knitwork'
import type { DeepRequired } from 'ts-essentials'
import type { NuxtModule } from 'nuxt/schema'
import { getOriginAndPathnameFromURL, isProduction } from './runtime/helpers'
import type {
ModuleOptions,
ModuleOptionsNormalized,
SupportedAuthProviders,
AuthProviders
} from './runtime/types'
const topLevelDefaults = {
isEnabled: true,
disableServerSideAuth: false,
session: {
enableRefreshPeriodically: false,
enableRefreshOnWindowFocus: true
},
globalAppMiddleware: {
isEnabled: false,
allow404WithoutAuth: true,
addDefaultCallbackUrl: true
}
} satisfies ModuleOptions
const defaultsByBackend: {
[key in SupportedAuthProviders]: DeepRequired<
Extract<AuthProviders, { type: key }>
>;
} = {
local: {
type: 'local',
pages: {
login: '/login'
},
endpoints: {
signIn: { path: '/login', method: 'post' },
signOut: { path: '/logout', method: 'post' },
signUp: { path: '/register', method: 'post' },
getSession: { path: '/session', method: 'get' }
},
token: {
signInResponseTokenPointer: '/token',
type: 'Bearer',
cookieName: 'auth.token',
headerName: 'Authorization',
maxAgeInSeconds: 30 * 60, // 30 minutes
sameSiteAttribute: 'lax',
secureCookieAttribute: false,
cookieDomain: ''
},
session: {
dataType: { id: 'string | number' },
dataResponsePointer: '/'
}
},
refresh: {
type: 'refresh',
pages: {
login: '/login'
},
refreshOnlyToken: true,
endpoints: {
signIn: { path: '/login', method: 'post' },
signOut: { path: '/logout', method: 'post' },
signUp: { path: '/register', method: 'post' },
getSession: { path: '/session', method: 'get' },
refresh: { path: '/refresh', method: 'post' }
},
token: {
signInResponseTokenPointer: '/token',
type: 'Bearer',
cookieName: 'auth.token',
headerName: 'Authorization',
maxAgeInSeconds: 5 * 60, // 5 minutes
sameSiteAttribute: 'none',
secureCookieAttribute: false,
cookieDomain: ''
},
refreshToken: {
signInResponseRefreshTokenPointer: '/refreshToken',
refreshRequestTokenPointer: '/refreshToken',
cookieName: 'auth.refresh-token',
maxAgeInSeconds: 60 * 60 * 24 * 7, // 7 days
secureCookieAttribute: false,
cookieDomain: ''
},
session: {
dataType: { id: 'string | number' },
dataResponsePointer: '/'
}
},
authjs: {
type: 'authjs',
trustHost: false,
defaultProvider: '', // this satisfies Required and also gets caught at `!provider` check
addDefaultCallbackUrl: true
}
}
const PACKAGE_NAME = 'sidebase-auth'
export default defineNuxtModule<ModuleOptions>({
meta: {
name: PACKAGE_NAME,
configKey: 'auth'
},
setup (userOptions, nuxt) {
const logger = useLogger(PACKAGE_NAME)
// 0. Assemble all options
const { origin, pathname = '/api/auth' } = getOriginAndPathnameFromURL(
userOptions.baseURL ?? ''
)
const selectedProvider = userOptions.provider?.type ?? 'authjs'
const options = {
...defu(userOptions, topLevelDefaults, {
computed: {
origin,
pathname,
fullBaseUrl: joinURL(origin ?? '', pathname)
}
}),
// We use `as` to infer backend types correctly for runtime-usage (everything is set, although for user everything was optional)
provider: defu(
userOptions.provider,
defaultsByBackend[selectedProvider]
) as DeepRequired<AuthProviders>
}
// 1. Check if module should be enabled at all
if (!options.isEnabled) {
logger.info(`Skipping ${PACKAGE_NAME} setup, as module is disabled`)
return
}
logger.info('`nuxt-auth` setup starting')
// 2. Set up runtime configuration
if (!isProduction) {
const authjsAddition =
selectedProvider === 'authjs'
? ', ensure that `NuxtAuthHandler({ ... })` is there, see https://sidebase.io/nuxt-auth/configuration/nuxt-auth-handler'
: ''
logger.info(
`Selected provider: ${selectedProvider}. Auth API location is \`${options.computed.fullBaseUrl}\`${authjsAddition}`
)
}
nuxt.options.runtimeConfig = nuxt.options.runtimeConfig || { public: {} }
nuxt.options.runtimeConfig.public.auth = options
// 3. Locate runtime directory
const { resolve } = createResolver(import.meta.url)
// 4. Add the correct nuxt-auth app composable, for the desired backend
addImports([
{
name: 'useAuth',
from: resolve(`./runtime/composables/${options.provider.type}/useAuth`)
},
{
name: 'useAuthState',
from: resolve(
`./runtime/composables/${options.provider.type}/useAuthState`
)
}
])
// 5. Create virtual imports for server-side
nuxt.hook('nitro:config', (nitroConfig) => {
nitroConfig.alias = nitroConfig.alias || {}
// Inline module runtime in Nitro bundle
nitroConfig.externals = defu(
typeof nitroConfig.externals === 'object' ? nitroConfig.externals : {},
{
inline: [resolve('./runtime')]
}
)
nitroConfig.alias['#auth'] = resolve('./runtime/server/services')
})
addTypeTemplate({
filename: 'types/auth.d.ts',
getContents: () =>
[
'// AUTO-GENERATED BY @sidebase/nuxt-auth',
"declare module '#auth' {",
` const { getServerSession, getToken, NuxtAuthHandler }: typeof import('${resolve('./runtime/server/services')}')`,
...(options.provider.type === 'local'
? [genInterface(
'SessionData',
(options.provider as any).session.dataType
)]
: []
),
'}',
''
].join('\n')
})
addTypeTemplate({
filename: 'types/auth-misc.d.ts',
getContents: () => [
'// AUTO-GENERATED BY @sidebase/nuxt-auth',
`import { RouteOptions } from '${resolve('./runtime/types.ts')}'`,
"declare module 'nitropack' {",
' interface NitroRouteRules {',
' auth?: RouteOptions',
' }',
' interface NitroRouteConfig {',
' auth?: RouteOptions',
' }',
'}',
''
].join('\n')
})
// 6. Register middleware for autocomplete in definePageMeta
addRouteMiddleware({
name: 'auth',
path: resolve('./runtime/middleware/auth')
})
// 7. Add plugin for initial load
addPlugin(resolve('./runtime/plugin'))
// 8. Add a server-plugin to check the `origin` on production-startup
if (selectedProvider === 'authjs') {
addServerPlugin(resolve('./runtime/server/plugins/assertOrigin'))
}
// 7.2 Add a server-plugin to refresh the token on production-startup
if (selectedProvider === 'refresh') {
addPlugin(resolve('./runtime/plugins/refresh-token.server'))
}
logger.success('`nuxt-auth` setup done')
}
}) satisfies NuxtModule<ModuleOptions>
// Used by nuxt/module-builder for `types.d.ts` generation
export type { ModuleOptions }
export interface ModulePublicRuntimeConfig {
auth: ModuleOptionsNormalized
}
// Augment types for type inference in source code
declare module '@nuxt/schema' {
interface PublicRuntimeConfig {
auth: ModuleOptionsNormalized
}
}