From 6884dffda6052b0a87a5c9c564b1139ada1bbb30 Mon Sep 17 00:00:00 2001 From: ZTatman Date: Sat, 11 Apr 2026 18:34:49 -0400 Subject: [PATCH] refactor: consolidate env config into single config.ts - Create single packages/cli/src/config.ts with: - MystEnvironmentVariables interface - ENV_MAPPING constant - REQUIRED_KEYS constant - parseEnvFile() - validateDatabaseUrl() - generateEnvFile() - Remove duplicates: - constants.ts (absorbed) - utils/config.ts (absorbed) - utils/env.ts (absorbed) - Update command files to import from config.ts --- packages/cli/src/commands/config.ts | 74 ++++------------------ packages/cli/src/commands/doctor.ts | 85 +++---------------------- packages/cli/src/commands/init.ts | 2 +- packages/cli/src/commands/verify.ts | 83 ++++++++----------------- packages/cli/src/config.ts | 96 +++++++++++++++++++++++++++++ packages/cli/src/utils/env.ts | 42 ------------- 6 files changed, 140 insertions(+), 242 deletions(-) create mode 100644 packages/cli/src/config.ts delete mode 100644 packages/cli/src/utils/env.ts diff --git a/packages/cli/src/commands/config.ts b/packages/cli/src/commands/config.ts index 30baa73..039e654 100644 --- a/packages/cli/src/commands/config.ts +++ b/packages/cli/src/commands/config.ts @@ -1,17 +1,7 @@ -import fs from "node:fs"; import path from "node:path"; import * as c from "yoctocolors"; - -interface MystConfig { - publicUrl?: string; - adminUrl?: string; - databaseUrl?: string; - forgejoBaseUrl?: string; - forgejoBotUsername?: string; - forgejoPat?: string; - grantTokenSecret?: string; -} +import { ENV_MAPPING, MystEnvironmentVariables, parseEnvFile } from "../config.js"; function redactSecret(value: string | undefined): string { if (!value) return c.dim("not set"); @@ -19,53 +9,10 @@ function redactSecret(value: string | undefined): string { return value.slice(0, 4) + c.dim("****"); } -function parseEnvFile(envPath: string): MystConfig { - const config: MystConfig = {}; - - const content = fs.readFileSync(envPath, "utf-8"); - const lines = content.split("\n"); - - for (const line of lines) { - const trimmed = line.trim(); - if (!trimmed || trimmed.startsWith("#")) continue; - - const [key, ...valueParts] = trimmed.split("="); - if (!key) continue; - - const value = valueParts.join("=").trim(); - - switch (key) { - case "MYST_PUBLIC_URL": - config.publicUrl = value; - break; - case "MYST_ADMIN_URL": - config.adminUrl = value; - break; - case "DATABASE_URL": - config.databaseUrl = value; - break; - case "FORGEJO_BASE_URL": - config.forgejoBaseUrl = value; - break; - case "FORGEJO_BOT_USERNAME": - config.forgejoBotUsername = value; - break; - case "FORGEJO_PAT": - config.forgejoPat = value; - break; - case "GRANT_TOKEN_SECRET": - config.grantTokenSecret = value; - break; - } - } - - return config; -} - export async function configCommand(): Promise { const envPath = path.join(process.cwd(), ".env"); - let config: MystConfig; + let config: Partial; try { config = parseEnvFile(envPath); @@ -84,13 +31,14 @@ export async function configCommand(): Promise { process.stdout.write(c.bold("Myst Configuration\n")); process.stdout.write(`${c.dim("─".repeat(40))}\n`); - process.stdout.write(`${c.bold("MYST_PUBLIC_URL:")} ${config.publicUrl || c.dim("not set")}\n`); - process.stdout.write(`${c.bold("MYST_ADMIN_URL:")} ${config.adminUrl || c.dim("not set")}\n`); - process.stdout.write(`${c.bold("DATABASE_URL:")} ${config.databaseUrl || c.dim("not set")}\n`); - process.stdout.write(`${c.bold("FORGEJO_BASE_URL:")} ${config.forgejoBaseUrl || c.dim("not set")}\n`); - process.stdout.write(`${c.bold("FORGEJO_BOT_USERNAME:")} ${config.forgejoBotUsername || c.dim("not set")}\n`); - process.stdout.write(`${c.bold("FORGEJO_PAT:")} ${redactSecret(config.forgejoPat)}\n`); - process.stdout.write(`${c.bold("GRANT_TOKEN_SECRET:")} ${redactSecret(config.grantTokenSecret)}\n`); + for (const [envKey, configKey] of Object.entries(ENV_MAPPING)) { + const value = config[configKey]; + const displayValue = + configKey === "forgejoPat" || configKey === "grantTokenSecret" + ? redactSecret(value) + : value || c.dim("not set"); + process.stdout.write(`${c.bold(envKey + ":")} ${displayValue}\n`); + } process.exitCode = 0; -} +} \ No newline at end of file diff --git a/packages/cli/src/commands/doctor.ts b/packages/cli/src/commands/doctor.ts index 78d4821..df7a341 100644 --- a/packages/cli/src/commands/doctor.ts +++ b/packages/cli/src/commands/doctor.ts @@ -1,61 +1,8 @@ -import fs from "node:fs"; import path from "node:path"; import * as c from "yoctocolors"; import * as p from "@clack/prompts"; - -interface MystConfig { - publicUrl?: string; - adminUrl?: string; - databaseUrl?: string; - forgejoBaseUrl?: string; - forgejoBotUsername?: string; - forgejoPat?: string; - grantTokenSecret?: string; -} - -function parseEnvFile(envPath: string): MystConfig { - const config: MystConfig = {}; - - const content = fs.readFileSync(envPath, "utf-8"); - const lines = content.split("\n"); - - for (const line of lines) { - const trimmed = line.trim(); - if (!trimmed || trimmed.startsWith("#")) continue; - - const [key, ...valueParts] = trimmed.split("="); - if (!key) continue; - - const value = valueParts.join("=").trim(); - - switch (key) { - case "MYST_PUBLIC_URL": - config.publicUrl = value; - break; - case "MYST_ADMIN_URL": - config.adminUrl = value; - break; - case "DATABASE_URL": - config.databaseUrl = value; - break; - case "FORGEJO_BASE_URL": - config.forgejoBaseUrl = value; - break; - case "FORGEJO_BOT_USERNAME": - config.forgejoBotUsername = value; - break; - case "FORGEJO_PAT": - config.forgejoPat = value; - break; - case "GRANT_TOKEN_SECRET": - config.grantTokenSecret = value; - break; - } - } - - return config; -} +import { ENV_MAPPING, MystEnvironmentVariables, parseEnvFile, validateDatabaseUrl, REQUIRED_KEYS } from "../config.js"; type CheckResult = { name: string; @@ -134,7 +81,7 @@ export async function doctorCommand(): Promise { const envPath = path.join(process.cwd(), ".env"); const results: CheckResult[] = []; - let config: MystConfig; + let config: Partial; try { config = parseEnvFile(envPath); @@ -154,30 +101,14 @@ export async function doctorCommand(): Promise { addResult("Config file exists", true, envPath); - const requiredFields = [ - { key: "publicUrl", name: "MYST_PUBLIC_URL" }, - { key: "adminUrl", name: "MYST_ADMIN_URL" }, - { key: "databaseUrl", name: "DATABASE_URL" }, - { key: "forgejoBaseUrl", name: "FORGEJO_BASE_URL" }, - { key: "forgejoBotUsername", name: "FORGEJO_BOT_USERNAME" }, - { key: "forgejoPat", name: "FORGEJO_PAT" }, - { key: "grantTokenSecret", name: "GRANT_TOKEN_SECRET" }, - ]; - - for (const field of requiredFields) { - const value = config[field.key as keyof MystConfig]; - addResult(`${field.name} set`, !!value, value ? "configured" : "missing"); + for (const [envKey, configKey] of Object.entries(ENV_MAPPING)) { + const value = config[configKey]; + addResult(`${envKey} set`, !!value, value ? "configured" : "missing"); } if (config.databaseUrl) { - try { - const url = new URL(config.databaseUrl); - const valid = url.protocol === "postgres:" || - url.protocol === "postgresql:"; - addResult("Database URL format", valid, valid ? "valid" : "invalid"); - } catch { - addResult("Database URL format", false, "invalid format"); - } + const valid = validateDatabaseUrl(config.databaseUrl); + addResult("Database URL format", valid, valid ? "valid" : "invalid"); } if (config.forgejoBaseUrl && config.forgejoPat) { @@ -223,4 +154,4 @@ export async function doctorCommand(): Promise { p.cancel(`${c.red("Error:")} ${message}`); process.exitCode = 1; } -} +} \ No newline at end of file diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.ts index 04451ec..dfc7b0a 100644 --- a/packages/cli/src/commands/init.ts +++ b/packages/cli/src/commands/init.ts @@ -5,7 +5,7 @@ import * as c from "yoctocolors"; import * as p from "@clack/prompts"; import { generateSecret } from "../utils/crypto.js"; -import { generateEnvFile } from "../utils/env.js"; +import { generateEnvFile } from "../config.js"; /** * Normalizes a URL to use https:// if no protocol is specified. diff --git a/packages/cli/src/commands/verify.ts b/packages/cli/src/commands/verify.ts index 1362b98..e38e231 100644 --- a/packages/cli/src/commands/verify.ts +++ b/packages/cli/src/commands/verify.ts @@ -1,45 +1,8 @@ -import fs from "node:fs"; import path from "node:path"; import * as c from "yoctocolors"; import * as p from "@clack/prompts"; - -interface MystConfig { - forgejoBaseUrl?: string; - forgejoBotUsername?: string; - forgejoPat?: string; -} - -function parseEnvFile(envPath: string): MystConfig { - const config: MystConfig = {}; - - const content = fs.readFileSync(envPath, "utf-8"); - const lines = content.split("\n"); - - for (const line of lines) { - const trimmed = line.trim(); - if (!trimmed || trimmed.startsWith("#")) continue; - - const [key, ...valueParts] = trimmed.split("="); - if (!key) continue; - - const value = valueParts.join("=").trim(); - - switch (key) { - case "FORGEJO_BASE_URL": - config.forgejoBaseUrl = value; - break; - case "FORGEJO_BOT_USERNAME": - config.forgejoBotUsername = value; - break; - case "FORGEJO_PAT": - config.forgejoPat = value; - break; - } - } - - return config; -} +import { MystEnvironmentVariables, parseEnvFile, REQUIRED_KEYS } from "../config.js"; type CheckResult = { name: string; @@ -100,7 +63,7 @@ async function checkForgejoApi( return { name: "Forgejo API token", success: true, - message: `Authenticated as ${c.green(user.login)}`, + message: `Authenticated as ${user.login}`, }; } catch (error) { const message = error instanceof Error ? error.message : "Unknown error"; @@ -130,31 +93,30 @@ async function checkRepoAccess( if (!response.ok) { return { - name: "Repository access", + name: "Repo access", success: false, message: `HTTP ${response.status}`, }; } - const repos = (await response.json()) as Array<{ name: string }>; + const repos = (await response.json()) as { name: string }[]; if (repos.length > 0) { - const firstRepo = repos[0]!; return { - name: "Repository access", + name: "Repo access", success: true, - message: `Can access repos (sample: ${c.green(firstRepo.name)})`, + message: `Found ${repos.length} repo(s)`, }; } return { - name: "Repository access", + name: "Repo access", success: true, - message: "Token valid but no repos found", + message: "No repos found (service account may not have repo access)", }; } catch (error) { const message = error instanceof Error ? error.message : "Unknown error"; return { - name: "Repository access", + name: "Repo access", success: false, message, }; @@ -166,7 +128,7 @@ export async function verifyCommand(): Promise { const envPath = path.join(process.cwd(), ".env"); - let config: MystConfig; + let config: Partial; try { config = parseEnvFile(envPath); @@ -184,14 +146,15 @@ export async function verifyCommand(): Promise { const missing: string[] = []; - if (!config.forgejoBaseUrl) { - missing.push("FORGEJO_BASE_URL"); - } - if (!config.forgejoPat) { - missing.push("FORGEJO_PAT"); - } - if (!config.forgejoBotUsername) { - missing.push("FORGEJO_BOT_USERNAME"); + for (const key of REQUIRED_KEYS) { + if (!config[key]) { + const envKey = Object.entries({ + forgejoBaseUrl: "FORGEJO_BASE_URL", + forgejoBotUsername: "FORGEJO_BOT_USERNAME", + forgejoPat: "FORGEJO_PAT", + }).find(([, v]) => v === key)?.[0]; + if (envKey) missing.push(envKey); + } } if (missing.length > 0) { @@ -207,7 +170,9 @@ export async function verifyCommand(): Promise { try { s.start("Verifying Forgejo configuration"); - const reachability = await checkForgejoReachability(config.forgejoBaseUrl!); + const reachability: CheckResult = await checkForgejoReachability( + config.forgejoBaseUrl!, + ); if (!reachability.success) { s.stop(reachability.message); @@ -216,7 +181,7 @@ export async function verifyCommand(): Promise { return; } - const apiToken = await checkForgejoApi( + const apiToken: CheckResult = await checkForgejoApi( config.forgejoBaseUrl!, config.forgejoPat!, ); @@ -257,4 +222,4 @@ export async function verifyCommand(): Promise { p.cancel(`${c.red("Error:")} ${message}`); process.exitCode = 1; } -} +} \ No newline at end of file diff --git a/packages/cli/src/config.ts b/packages/cli/src/config.ts new file mode 100644 index 0000000..79bb907 --- /dev/null +++ b/packages/cli/src/config.ts @@ -0,0 +1,96 @@ +import fs from "node:fs"; + +export interface MystEnvironmentVariables { + publicUrl: string; + adminUrl: string; + databaseUrl: string; + forgejoBaseUrl: string; + forgejoBotUsername: string; + forgejoPat: string; + grantTokenSecret: string; +} + +export const ENV_MAPPING = { + MYST_PUBLIC_URL: "publicUrl", + MYST_ADMIN_URL: "adminUrl", + DATABASE_URL: "databaseUrl", + FORGEJO_BASE_URL: "forgejoBaseUrl", + FORGEJO_BOT_USERNAME: "forgejoBotUsername", + FORGEJO_PAT: "forgejoPat", + GRANT_TOKEN_SECRET: "grantTokenSecret", +} as const; + +export const REQUIRED_KEYS = [ + "forgejoBaseUrl", + "forgejoBotUsername", + "forgejoPat", +] as const; + +export const DATABASE_PROTOCOLS = ["postgres:", "postgresql:"] as const; + +export type EnvKey = keyof typeof ENV_MAPPING; +export type ConfigKey = (typeof ENV_MAPPING)[EnvKey]; + +export function parseEnvFile(envPath: string): Partial { + const config: Partial = {}; + const content = fs.readFileSync(envPath, "utf-8"); + const lines = content.split("\n"); + + for (const line of lines) { + const trimmed = line.trim(); + if (!trimmed || trimmed.startsWith("#")) continue; + + const [key, ...valueParts] = trimmed.split("="); + if (!key) continue; + + const value = valueParts.join("=").trim(); + const configKey = ENV_MAPPING[key as EnvKey]; + + if (configKey) { + config[configKey] = value; + } + } + + return config; +} + +export function validateDatabaseUrl(url: string | undefined): boolean { + if (!url) return false; + try { + const parsed = new URL(url); + return parsed.protocol === "postgres:" || parsed.protocol === "postgresql:"; + } catch { + return false; + } +} + +function escapeEnvValue(value: string): string { + return `"${value + .replace(/\\/g, "\\\\") + .replace(/"/g, '\\"') + .replace(/\r?\n/g, "\\n") + .replace(/\$/g, "\\$")}"`; +} + +export function generateEnvFile(options: MystEnvironmentVariables): string { + const lines = [ + `# Public URL used for share links.`, + `${ENV_MAPPING.MYST_PUBLIC_URL}=${escapeEnvValue(options.publicUrl)}`, + ``, + `# Private operator URL for the admin UI. Protect this upstream.`, + `${ENV_MAPPING.MYST_ADMIN_URL}=${escapeEnvValue(options.adminUrl)}`, + ``, + `# Myst's own Postgres database.`, + `${ENV_MAPPING.DATABASE_URL}=${escapeEnvValue(options.databaseUrl)}`, + ``, + `# Existing Forgejo instance and operator-created PAT for the dedicated Forgejo user.`, + `${ENV_MAPPING.FORGEJO_BASE_URL}=${escapeEnvValue(options.forgejoBaseUrl)}`, + `${ENV_MAPPING.FORGEJO_BOT_USERNAME}=${escapeEnvValue(options.forgejoBotUsername)}`, + `${ENV_MAPPING.FORGEJO_PAT}=${escapeEnvValue(options.forgejoPat)}`, + ``, + `# Secret used to sign or derive grant tokens.`, + `${ENV_MAPPING.GRANT_TOKEN_SECRET}=${escapeEnvValue(options.grantTokenSecret)}`, + ]; + + return lines.join("\n"); +} \ No newline at end of file diff --git a/packages/cli/src/utils/env.ts b/packages/cli/src/utils/env.ts deleted file mode 100644 index 4fd6aff..0000000 --- a/packages/cli/src/utils/env.ts +++ /dev/null @@ -1,42 +0,0 @@ -interface EnvOptions { - adminUrl: string; - databaseUrl: string; - forgejoBaseUrl: string; - forgejoBotUsername: string; - forgejoPat: string; - grantTokenSecret: string; - publicUrl: string; -} - -function escapeEnvValue(value: string): string { - return `"${value - .replace(/\\/g, "\\\\") // Escape backslashes - .replace(/"/g, '\\"') // Escape double quotes - .replace(/\r?\n/g, "\\n") // Escape newlines - .replace(/\$/g, "\\$")}"`; // Escape dollar signs -} - -/** - * Generates an .env file for Myst with the given options. - * @param options - The options for generating the .env file. - * @returns {string} The .env file formatted as a string. - */ -export function generateEnvFile(options: EnvOptions): string { - return `# Public URL used for share links. -MYST_PUBLIC_URL=${escapeEnvValue(options.publicUrl)} - -# Private operator URL for the admin UI. Protect this upstream. -MYST_ADMIN_URL=${escapeEnvValue(options.adminUrl)} - -# Myst's own Postgres database. -DATABASE_URL=${escapeEnvValue(options.databaseUrl)} - -# Existing Forgejo instance and operator-created PAT for the dedicated Forgejo user. -FORGEJO_BASE_URL=${escapeEnvValue(options.forgejoBaseUrl)} -FORGEJO_BOT_USERNAME=${escapeEnvValue(options.forgejoBotUsername)} -FORGEJO_PAT=${escapeEnvValue(options.forgejoPat)} - -# Secret used to sign or derive grant tokens. -GRANT_TOKEN_SECRET=${escapeEnvValue(options.grantTokenSecret)} -`; -}