Skip to content

feat(secret): add --write to auth secret #5

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
May 15, 2024
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
7 changes: 5 additions & 2 deletions commands/framework.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
// @ts-check

import { detectFramework } from "../lib/detect.js"

// TODO: Get this programmatically
export const frameworks = {
nextjs: {
Expand All @@ -16,8 +18,9 @@ export const frameworks = {
},
}

export function action(framework) {
if (!framework) {
export async function action(framework) {
framework ??= await detectFramework()
if (framework === "unknown") {
return console.log(`
Supported frameworks are: ${Object.keys(frameworks).join(", ")}`)
}
Expand Down
99 changes: 85 additions & 14 deletions commands/secret.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

import * as y from "yoctocolors"
import { write } from "../lib/clipboard/index.js"
import { detectFramework } from "../lib/detect.js"
import { readFile, writeFile } from "node:fs/promises"
import { join } from "node:path"
import prompt from "prompts"

/** Web compatible method to create a random string of a given length */
function randomString(size = 32) {
Expand All @@ -10,30 +14,97 @@ function randomString(size = 32) {
return Buffer.from(bytes, "base64").toString("base64")
}

export function action(options) {
let value = randomString()
if (options.raw) return console.log(value)
/** @type {Record<import("../lib/detect.js").SupportedFramework, string>} */
export const frameworkDotEnvFile = {
nextjs: ".env.local",
express: ".env",
sveltekit: ".env",
}

value = `AUTH_SECRET="${value}"`
if (!options.copy) return console.log(value)
export async function action(options) {
const key = "AUTH_SECRET"
const value = randomString()
if (options.raw) return console.log(value)

const line = `${key}="${value}"`
const message = {
introClipboard:
"Secret generated. It has been copied to your clipboard, paste it to your .env/.env.local file to continue.",
introCopy:
"Secret generated. Copy it to your .env/.env.local file (depending on your framework):",
value: `\n${value}`,
value: `\n${line}`,
}

if (options.copy) {
try {
write(line)
console.log(message.introClipboard)
} catch (error) {
console.error(y.red(error))
console.log(message.introCopy)
} finally {
console.log(message.value)
process.exit(0)
}
}

if (options.write) {
try {
const framework = await detectFramework()
if (framework === "unknown") {
return console.log(
`No framework detected. Currently supported frameworks are: ${y.bold(
Object.keys(frameworkDotEnvFile).join(", ")
)}`
)
}
const dotEnvFile = frameworkDotEnvFile[framework]
await updateEnvFile(
dotEnvFile,
join(process.cwd(), dotEnvFile),
key,
value
)
} catch (error) {
console.error(y.red(error))
}
}
}

// TODO: Detect framework, check for existing value, and write automatically
/**
* Update a key-value pair to a .env file
* @param {string} file
* @param {string} envPath
* @param {string} key
* @param {string} value
*/
async function updateEnvFile(file, envPath, key, value) {
let content = ""
const line = `${key}="${value}" # Added by \`npx auth\`. Read more: https://cli.authjs.dev`
try {
write(value)
console.log(message.introClipboard)
await readFile(envPath, "utf-8")
content = await readFile(envPath, "utf-8")
if (!content.includes(`${key}=`)) {
console.log(`➕ Added ${key} to ${y.italic(file)}.`)
content = `${line}\n${content}`
} else {
const { overwrite } = await prompt({
type: "confirm",
name: "overwrite",
message: `Overwrite existing ${key}?`,
initial: false,
})
if (!overwrite) return
console.log(`✨ Updated ${key} in ${y.italic(file)}.`)
content = content.replace(new RegExp(`${key}=(.*)`), `${line}`)
}
} catch (error) {
console.error(y.red(error))
console.log(message.introCopy)
} finally {
console.log(message.value)
process.exit(0)
if (error.code === "ENOENT") {
console.log(`📝 Created ${y.italic(file)} with ${key}.`)
content = line
} else {
throw error
}
}
if (content) await writeFile(envPath, content)
}
2 changes: 1 addition & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ program
program
.command("framework")
.argument("[framework]", "The framework to use.", (value) => {
if (!value) return value
if (Object.keys(framework.frameworks).includes(value)) return value
throw new InvalidArgumentError(
`Valid frameworks are: ${framework.frameworks.join(", ")}`
Expand All @@ -48,6 +47,7 @@ program
.command("secret")
.option("--raw", "Output the string without any formatting.")
.option("--copy", 'Copy AUTH_SECRET="value"')
.option("--write", 'Write AUTH_SECRET="value" to the .env file.')
.description("Generate a random string.")
.action(secret.action)

Expand Down
40 changes: 40 additions & 0 deletions lib/detect.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// @ts-check
import { readFile } from "node:fs/promises"
import { join } from "node:path"

/**
* @typedef {"nextjs" | "express" | "sveltekit"} SupportedFramework
*/

/**
* When this function runs in a framework directory we support,
* it will return the framework's name
* @returns {Promise<SupportedFramework | "unknown">}
*/
export async function detectFramework() {
const dir = process.cwd()
const packageJsonPath = join(dir, "package.json")
try {
const packageJson = JSON.parse(await readFile(packageJsonPath, "utf-8"))

/** @type {SupportedFramework[]} */
const foundFrameworks = []

if (packageJson.dependencies["next"]) foundFrameworks.push("nextjs")
if (packageJson.dependencies["express"]) foundFrameworks.push("express")
if (packageJson.devDependencies["@sveltejs/kit"])
foundFrameworks.push("sveltekit")

if (foundFrameworks.length === 1) return foundFrameworks[0]

if (foundFrameworks.length > 1) {
console.error(
`Multiple supported frameworks detected: ${foundFrameworks.join(", ")}`
)
return "unknown"
}
return "unknown"
} catch (error) {
return "unknown"
}
}
4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,13 @@
"dependencies": {
"@inquirer/prompts": "3.3.2",
"commander": "11.1.0",
"prompts": "^2.4.2",
"yoctocolors": "1.0.0"
},
"prettier": {
"semi": false
},
"devDependencies": {
"@types/node": "^20.12.12"
}
}
35 changes: 29 additions & 6 deletions pnpm-lock.yaml

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