-
Notifications
You must be signed in to change notification settings - Fork 187
Expand file tree
/
Copy pathmodule.ts
More file actions
337 lines (325 loc) · 9.55 KB
/
module.ts
File metadata and controls
337 lines (325 loc) · 9.55 KB
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
import { writeFile, readFile } from 'node:fs/promises'
import {
defineNuxtModule,
addPlugin,
createResolver,
addImportsDir,
addServerHandler,
addServerPlugin,
addServerImportsDir,
addComponentsDir,
logger,
} from '@nuxt/kit'
import { join } from 'pathe'
import { defu } from 'defu'
import { randomUUID } from 'uncrypto'
import type { ScryptConfig } from '@adonisjs/hash/types'
// Module options TypeScript interface definition
export interface ModuleOptions {
/**
* Enable WebAuthn (Passkeys)
* @default false
*/
webAuthn?: boolean
/**
* Use session storage
* Use 'cache' for standard cache storage,
* 'cookie' for cookies,
* 'memory' for in-memory storage,
* 'nuxt-session' for a custom storage mount named 'nuxt-session'
* @default 'cache'
*/
storageType?: 'cache' | 'cookie' | 'memory' | 'nuxt-session'
/**
* Session inactivity max age in milliseconds
* @default 2592000000 (30 days)
*/
sessionInactivityMaxAge?: number
/**
* Auto extend session
* @default true
*/
autoExtendSession?: boolean
/**
* Hash options used for password hashing
*/
hash?: {
/**
* scrypt options used for password hashing
*/
scrypt?: ScryptConfig
}
}
declare module 'nuxt/schema' {
interface RuntimeConfig {
hash: {
scrypt: ScryptConfig
}
}
}
export default defineNuxtModule<ModuleOptions>({
meta: {
name: 'auth-utils',
configKey: 'auth',
},
// Default configuration options of the Nuxt module
defaults: {
webAuthn: false,
storageType: 'cookie',
sessionInactivityMaxAge: 2592000, // 30 days
autoExtendSession: true,
hash: {
scrypt: {},
},
},
async setup(options, nuxt) {
const resolver = createResolver(import.meta.url)
nuxt.options.alias['#auth-utils'] = resolver.resolve(
'./runtime/types/index',
)
// App
addComponentsDir({ path: resolver.resolve('./runtime/app/components') })
addImportsDir(resolver.resolve('./runtime/app/composables'))
addPlugin(resolver.resolve('./runtime/app/plugins/session.server'))
addPlugin(resolver.resolve('./runtime/app/plugins/session.client'))
// Server
addServerPlugin(resolver.resolve('./runtime/server/plugins/oauth'))
addServerImportsDir(resolver.resolve('./runtime/server/lib/oauth'))
// WebAuthn enabled
if (options.webAuthn) {
// Check if dependencies are installed
const missingDeps: string[] = []
const peerDeps = ['@simplewebauthn/server', '@simplewebauthn/browser']
for (const pkg of peerDeps) {
await import(pkg).catch(() => {
missingDeps.push(pkg)
})
}
if (missingDeps.length > 0) {
logger.withTag('nuxt-auth-utils').error(`Missing dependencies for \`WebAuthn\`, please install with:\n\n\`npx nypm i ${missingDeps.join(' ')}\``)
process.exit(1)
}
addServerImportsDir(resolver.resolve('./runtime/server/lib/webauthn'))
}
addServerImportsDir(resolver.resolve('./runtime/server/utils'))
addServerHandler({
handler: resolver.resolve('./runtime/server/api/session.delete'),
route: '/api/_auth/session',
method: 'delete',
})
addServerHandler({
handler: resolver.resolve('./runtime/server/api/session.get'),
route: '/api/_auth/session',
method: 'get',
})
// Set node:crypto as unenv external
nuxt.options.nitro.unenv ||= {}
nuxt.options.nitro.unenv.external ||= []
if (!nuxt.options.nitro.unenv.external.includes('node:crypto')) {
nuxt.options.nitro.unenv.external.push('node:crypto')
}
// Runtime Config
const runtimeConfig = nuxt.options.runtimeConfig
const envSessionPassword = `${
runtimeConfig.nitro?.envPrefix || 'NUXT_'
}SESSION_PASSWORD`
runtimeConfig.session = defu(runtimeConfig.session, {
name: 'nuxt-session',
password: process.env[envSessionPassword] || '',
cookie: {
sameSite: 'lax',
},
})
runtimeConfig.hash = defu(runtimeConfig.hash, {
scrypt: options.hash?.scrypt,
})
// Generate the session password
if (nuxt.options.dev && !runtimeConfig.session.password) {
runtimeConfig.session.password = randomUUID().replace(/-/g, '')
// Add it to .env
const envPath = join(nuxt.options.rootDir, '.env')
const envContent = await readFile(envPath, 'utf-8').catch(() => '')
if (!envContent.includes(envSessionPassword)) {
await writeFile(
envPath,
`${
envContent ? envContent + '\n' : envContent
}${envSessionPassword}=${runtimeConfig.session.password}`,
'utf-8',
)
}
}
// WebAuthn settings
runtimeConfig.webauthn = defu(runtimeConfig.webauthn, {
register: {},
authenticate: {},
})
runtimeConfig.useSessionStorageType = runtimeConfig.useSessionStorageType || options.storageType
runtimeConfig.sessionInactivityMaxAge = runtimeConfig.sessionInactivityMaxAge || options.sessionInactivityMaxAge
runtimeConfig.autoExtendSession = runtimeConfig.autoExtendSession || options.autoExtendSession
logger.withTag('nuxt-auth-utils').info(`Using session storage type: ${runtimeConfig.useSessionStorageType}`)
if (runtimeConfig.useSessionStorageType === 'memory') {
logger.warn('Using in-memory session storage, this is not recommended for production')
if (!nuxt.options.dev) {
logger.error('You are not running in dev mode, please make sure this is intentional')
}
}
// OAuth settings
runtimeConfig.oauth = defu(runtimeConfig.oauth, {})
// GitHub OAuth
runtimeConfig.oauth.github = defu(runtimeConfig.oauth.github, {
clientId: '',
clientSecret: '',
redirectURL: '',
})
// GitHub OAuth
runtimeConfig.oauth.gitlab = defu(runtimeConfig.oauth.gitlab, {
clientId: '',
clientSecret: '',
redirectURL: '',
})
// Spotify OAuth
runtimeConfig.oauth.spotify = defu(runtimeConfig.oauth.spotify, {
clientId: '',
clientSecret: '',
redirectURL: '',
})
// Google OAuth
runtimeConfig.oauth.google = defu(runtimeConfig.oauth.google, {
clientId: '',
clientSecret: '',
redirectURL: '',
})
// Twitch OAuth
runtimeConfig.oauth.twitch = defu(runtimeConfig.oauth.twitch, {
clientId: '',
clientSecret: '',
redirectURL: '',
})
// Auth0 OAuth
runtimeConfig.oauth.auth0 = defu(runtimeConfig.oauth.auth0, {
clientId: '',
clientSecret: '',
domain: '',
audience: '',
redirectURL: '',
})
// Microsoft OAuth
runtimeConfig.oauth.microsoft = defu(runtimeConfig.oauth.microsoft, {
clientId: '',
clientSecret: '',
tenant: '',
scope: [],
authorizationURL: '',
tokenURL: '',
userURL: '',
redirectURL: '',
})
// Discord OAuth
runtimeConfig.oauth.discord = defu(runtimeConfig.oauth.discord, {
clientId: '',
clientSecret: '',
redirectURL: '',
})
// Battle.net OAuth
runtimeConfig.oauth.battledotnet = defu(runtimeConfig.oauth.battledotnet, {
clientId: '',
clientSecret: '',
redirectURL: '',
})
// Keycloak OAuth
runtimeConfig.oauth.keycloak = defu(runtimeConfig.oauth.keycloak, {
clientId: '',
clientSecret: '',
serverUrl: '',
realm: '',
redirectURL: '',
})
// Linear OAuth
runtimeConfig.oauth.linear = defu(runtimeConfig.oauth.linear, {
clientId: '',
clientSecret: '',
redirectURL: '',
})
// LinkedIn OAuth
runtimeConfig.oauth.linkedin = defu(runtimeConfig.oauth.linkedin, {
clientId: '',
clientSecret: '',
redirectURL: '',
})
// Cognito OAuth
runtimeConfig.oauth.cognito = defu(runtimeConfig.oauth.cognito, {
clientId: '',
clientSecret: '',
region: '',
userPoolId: '',
redirectURL: '',
})
// Facebook OAuth
runtimeConfig.oauth.facebook = defu(runtimeConfig.oauth.facebook, {
clientId: '',
clientSecret: '',
redirectURL: '',
})
// Instagram OAuth
runtimeConfig.oauth.instagram = defu(runtimeConfig.oauth.instagram, {
clientId: '',
clientSecret: '',
redirectURL: '',
})
// PayPal OAuth
runtimeConfig.oauth.paypal = defu(runtimeConfig.oauth.paypal, {
clientId: '',
clientSecret: '',
redirectURL: '',
})
// Steam OAuth
runtimeConfig.oauth.steam = defu(runtimeConfig.oauth.steam, {
apiKey: '',
redirectURL: '',
})
// X OAuth
runtimeConfig.oauth.x = defu(runtimeConfig.oauth.x, {
clientId: '',
clientSecret: '',
redirectURL: '',
})
// XSUAA OAuth
runtimeConfig.oauth.xsuaa = defu(runtimeConfig.oauth.xsuaa, {
clientId: '',
clientSecret: '',
domain: '',
redirectURL: '',
})
// VK OAuth
runtimeConfig.oauth.vk = defu(runtimeConfig.oauth.vk, {
clientId: '',
clientSecret: '',
redirectURL: '',
})
// Yandex OAuth
runtimeConfig.oauth.yandex = defu(runtimeConfig.oauth.yandex, {
clientId: '',
clientSecret: '',
redirectURL: '',
})
// TikTok OAuth
runtimeConfig.oauth.tiktok = defu(runtimeConfig.oauth.tiktok, {
clientKey: '',
clientSecret: '',
redirectURL: '',
})
// Dropbox OAuth
runtimeConfig.oauth.dropbox = defu(runtimeConfig.oauth.dropbox, {
clientId: '',
clientSecret: '',
redirectURL: '',
})
// Polar OAuth
runtimeConfig.oauth.polar = defu(runtimeConfig.oauth.polar, {
clientId: '',
clientSecret: '',
redirectURL: '',
})
},
})