Skip to content

Commit

Permalink
feat: generate NUXT_SESSION_PASSWORD and throw if not set in production
Browse files Browse the repository at this point in the history
  • Loading branch information
atinux committed Feb 23, 2024
1 parent ea09e00 commit de890ed
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 24 deletions.
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@
"defu": "^6.1.4",
"hookable": "^5.5.3",
"ofetch": "^1.3.3",
"ohash": "^1.1.3"
"ohash": "^1.1.3",
"pathe": "^1.1.2",
"uncrypto": "^0.1.3"
},
"devDependencies": {
"@iconify-json/simple-icons": "^1.1.91",
Expand Down
35 changes: 19 additions & 16 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

22 changes: 15 additions & 7 deletions src/module.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { defineNuxtModule, addPlugin, createResolver, addImportsDir, addServerHandler } from '@nuxt/kit'
import { sha256 } from 'ohash'
import { join } from 'pathe'
import { defu } from 'defu'
import { randomUUID } from 'uncrypto'
import { writeFile, readFile } from 'node:fs/promises'

// Module options TypeScript interface definition
export interface ModuleOptions {}
Expand All @@ -12,14 +14,20 @@ export default defineNuxtModule<ModuleOptions>({
},
// Default configuration options of the Nuxt module
defaults: {},
setup (options, nuxt) {
async setup (options, nuxt) {
const resolver = createResolver(import.meta.url)

if (!process.env.NUXT_SESSION_PASSWORD && !nuxt.options._prepare) {
const randomPassword = sha256(`${Date.now()}${Math.random()}`).slice(0, 32)
process.env.NUXT_SESSION_PASSWORD = randomPassword
console.warn('No session password set, using a random password, please set NUXT_SESSION_PASSWORD in your .env file with at least 32 chars')
console.log(`NUXT_SESSION_PASSWORD=${randomPassword}`)
// Generate the session password
if (nuxt.options.dev && !process.env.NUXT_SESSION_PASSWORD) {
process.env.NUXT_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('NUXT_SESSION_PASSWORD')) {
await writeFile(envPath, `${envContent ? envContent + '\n' : envContent}NUXT_SESSION_PASSWORD=${process.env.NUXT_SESSION_PASSWORD}`, 'utf-8')
}
} else if (!nuxt.options._prepare && !process.env.NUXT_SESSION_PASSWORD) {
throw new Error('NUXT_SESSION_PASSWORD environment variable is not set')
}

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

0 comments on commit de890ed

Please sign in to comment.