Skip to content

Commit de890ed

Browse files
committed
feat: generate NUXT_SESSION_PASSWORD and throw if not set in production
1 parent ea09e00 commit de890ed

File tree

3 files changed

+37
-24
lines changed

3 files changed

+37
-24
lines changed

package.json

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,9 @@
3434
"defu": "^6.1.4",
3535
"hookable": "^5.5.3",
3636
"ofetch": "^1.3.3",
37-
"ohash": "^1.1.3"
37+
"ohash": "^1.1.3",
38+
"pathe": "^1.1.2",
39+
"uncrypto": "^0.1.3"
3840
},
3941
"devDependencies": {
4042
"@iconify-json/simple-icons": "^1.1.91",

pnpm-lock.yaml

Lines changed: 19 additions & 16 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/module.ts

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import { defineNuxtModule, addPlugin, createResolver, addImportsDir, addServerHandler } from '@nuxt/kit'
2-
import { sha256 } from 'ohash'
2+
import { join } from 'pathe'
33
import { defu } from 'defu'
4+
import { randomUUID } from 'uncrypto'
5+
import { writeFile, readFile } from 'node:fs/promises'
46

57
// Module options TypeScript interface definition
68
export interface ModuleOptions {}
@@ -12,14 +14,20 @@ export default defineNuxtModule<ModuleOptions>({
1214
},
1315
// Default configuration options of the Nuxt module
1416
defaults: {},
15-
setup (options, nuxt) {
17+
async setup (options, nuxt) {
1618
const resolver = createResolver(import.meta.url)
1719

18-
if (!process.env.NUXT_SESSION_PASSWORD && !nuxt.options._prepare) {
19-
const randomPassword = sha256(`${Date.now()}${Math.random()}`).slice(0, 32)
20-
process.env.NUXT_SESSION_PASSWORD = randomPassword
21-
console.warn('No session password set, using a random password, please set NUXT_SESSION_PASSWORD in your .env file with at least 32 chars')
22-
console.log(`NUXT_SESSION_PASSWORD=${randomPassword}`)
20+
// Generate the session password
21+
if (nuxt.options.dev && !process.env.NUXT_SESSION_PASSWORD) {
22+
process.env.NUXT_SESSION_PASSWORD = randomUUID().replace(/-/g, '')
23+
// Add it to .env
24+
const envPath = join(nuxt.options.rootDir, '.env')
25+
const envContent = await readFile(envPath, 'utf-8').catch(() => '')
26+
if (!envContent.includes('NUXT_SESSION_PASSWORD')) {
27+
await writeFile(envPath, `${envContent ? envContent + '\n' : envContent}NUXT_SESSION_PASSWORD=${process.env.NUXT_SESSION_PASSWORD}`, 'utf-8')
28+
}
29+
} else if (!nuxt.options._prepare && !process.env.NUXT_SESSION_PASSWORD) {
30+
throw new Error('NUXT_SESSION_PASSWORD environment variable is not set')
2331
}
2432

2533
nuxt.options.alias['#auth-utils'] = resolver.resolve('./runtime/types/index')

0 commit comments

Comments
 (0)