Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,8 @@ export default defineNuxtModule<BetterAuthModuleOptions>({
secondaryStorage: false,
},
async onInstall(nuxt) {
const generatedSecret = await promptForSecret(nuxt.options.rootDir, consola)
const configuredSecret = nuxt.options.runtimeConfig?.betterAuthSecret as string | undefined
const generatedSecret = await promptForSecret(nuxt.options.rootDir, consola, { configuredSecret, prepare: Boolean(nuxt.options._prepare) })
if (generatedSecret)
process.env.BETTER_AUTH_SECRET = generatedSecret

Expand Down
19 changes: 17 additions & 2 deletions src/module/secret.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,29 @@ function appendSecretToEnv(rootDir: string, secret: string): void {
writeFileSync(envPath, content, 'utf-8')
}

export async function promptForSecret(rootDir: string, consola: ConsolaInstance): Promise<string | undefined> {
export interface PromptForSecretOptions {
configuredSecret?: string
prepare?: boolean
}

export async function promptForSecret(rootDir: string, consola: ConsolaInstance, options: PromptForSecretOptions = {}): Promise<string | undefined> {
const configuredSecret = options.configuredSecret?.trim()
if (configuredSecret)
return undefined

if (process.env.BETTER_AUTH_SECRET || hasEnvSecret(rootDir))
return undefined

const hasTty = Boolean(process.stdin.isTTY && process.stdout.isTTY)
if (options.prepare || !hasTty) {
consola.warn('[nuxt-better-auth] Skipping BETTER_AUTH_SECRET prompt (non-interactive). Set BETTER_AUTH_SECRET or NUXT_BETTER_AUTH_SECRET.')
return undefined
}

if (isCI || isTest) {
const secret = generateSecret()
appendSecretToEnv(rootDir, secret)
consola.info('Generated BETTER_AUTH_SECRET and added to .env (CI mode)')
consola.info('Generated BETTER_AUTH_SECRET and added to .env (CI/test mode)')
return secret
}

Expand Down
72 changes: 72 additions & 0 deletions test/non-tty-secret-prompt.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { spawnSync } from 'node:child_process'
import { fileURLToPath } from 'node:url'
import { describe, expect, it } from 'vitest'

const repoDir = fileURLToPath(new URL('..', import.meta.url))

function createNonTestEnv(): NodeJS.ProcessEnv {
const env: NodeJS.ProcessEnv = { ...process.env }

// Make std-env treat this as non-test/non-ci so we exercise the non-interactive path.
delete env.CI
delete env.VITEST
delete env.VITEST_WORKER_ID
delete env.JEST_WORKER_ID
delete env.AVA_PATH
delete env.TAP
delete env.TEST
env.NODE_ENV = 'production'
delete env.npm_lifecycle_event

// Ensure no secret is configured via env.
delete env.BETTER_AUTH_SECRET
delete env.NUXT_BETTER_AUTH_SECRET

env.FORCE_COLOR = '0'

return env
}

describe('promptForSecret', () => {
it('skips prompting in non-interactive/prepare mode', () => {
const env = createNonTestEnv()

const script = `
import { createJiti } from 'jiti'
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'

const jiti = createJiti(process.cwd(), { interopDefault: true, moduleCache: false })
const { promptForSecret } = await jiti.import('./src/module/secret.ts')

let promptCalls = 0
const consola = {
warn: (...args) => console.log(String(args[0] ?? '')),
info: () => {},
success: () => {},
box: () => {},
prompt: async () => {
promptCalls++
throw new Error('prompt called')
},
}

const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nuxt-better-auth-secret-'))
await promptForSecret(rootDir, consola, { prepare: true })
console.log('PROMPT_CALLS=' + promptCalls)
`

const run = spawnSync(process.execPath, ['--input-type=module', '-e', script], {
cwd: repoDir,
env,
encoding: 'utf8',
timeout: 60_000,
})

expect(run.status, `node script failed:\n${run.stdout}\n${run.stderr}`).toBe(0)
const output = `${run.stdout}\n${run.stderr}`
expect(output).toContain('Skipping BETTER_AUTH_SECRET prompt')
expect(output).toContain('PROMPT_CALLS=0')
})
})
Loading