mirror of
https://github.com/ZTatman/myst.git
synced 2026-11-21 04:17:59 +00:00
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
This commit is contained in:
parent
a3c202a662
commit
6884dffda6
6 changed files with 140 additions and 242 deletions
|
|
@ -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<void> {
|
||||
const envPath = path.join(process.cwd(), ".env");
|
||||
|
||||
let config: MystConfig;
|
||||
let config: Partial<MystEnvironmentVariables>;
|
||||
|
||||
try {
|
||||
config = parseEnvFile(envPath);
|
||||
|
|
@ -84,13 +31,14 @@ export async function configCommand(): Promise<void> {
|
|||
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;
|
||||
}
|
||||
}
|
||||
|
|
@ -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<void> {
|
|||
const envPath = path.join(process.cwd(), ".env");
|
||||
const results: CheckResult[] = [];
|
||||
|
||||
let config: MystConfig;
|
||||
let config: Partial<MystEnvironmentVariables>;
|
||||
|
||||
try {
|
||||
config = parseEnvFile(envPath);
|
||||
|
|
@ -154,30 +101,14 @@ export async function doctorCommand(): Promise<void> {
|
|||
|
||||
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<void> {
|
|||
p.cancel(`${c.red("Error:")} ${message}`);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -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<void> {
|
|||
|
||||
const envPath = path.join(process.cwd(), ".env");
|
||||
|
||||
let config: MystConfig;
|
||||
let config: Partial<MystEnvironmentVariables>;
|
||||
|
||||
try {
|
||||
config = parseEnvFile(envPath);
|
||||
|
|
@ -184,14 +146,15 @@ export async function verifyCommand(): Promise<void> {
|
|||
|
||||
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<void> {
|
|||
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<void> {
|
|||
return;
|
||||
}
|
||||
|
||||
const apiToken = await checkForgejoApi(
|
||||
const apiToken: CheckResult = await checkForgejoApi(
|
||||
config.forgejoBaseUrl!,
|
||||
config.forgejoPat!,
|
||||
);
|
||||
|
|
@ -257,4 +222,4 @@ export async function verifyCommand(): Promise<void> {
|
|||
p.cancel(`${c.red("Error:")} ${message}`);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
96
packages/cli/src/config.ts
Normal file
96
packages/cli/src/config.ts
Normal file
|
|
@ -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<MystEnvironmentVariables> {
|
||||
const config: Partial<MystEnvironmentVariables> = {};
|
||||
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");
|
||||
}
|
||||
|
|
@ -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)}
|
||||
`;
|
||||
}
|
||||
Loading…
Add table
Reference in a new issue