Complete CLI init skeleton with CodeRabbit review fixes

CLI changes:
- Narrow init to Myst-only config generation (no Forgejo provisioning)
- Add yoctocolors styling to CLI output
- Simplify URL validation logic (remove dead code)
- Fix typo in env.ts comment
- Remove docker-compose generator (out of scope)
- Move example config from src/ to packages/cli/examples/
- Fix CommandName type to match implemented commands only

Config changes:
- Remove databaseUrl from myst.config.json (DB is .env-only)
- Update example config with current fields
- Reject non-HTTP schemes before auto-prepending https://
- Use localhost -> 127.0.0.1 in Caddy/Nginx examples
- Add file existence checks and 0o600 permissions

Build passes after all changes.
This commit is contained in:
ZTatman 2026-04-02 16:37:53 -04:00
parent 9838e73403
commit 577d91fc47
9 changed files with 100 additions and 176 deletions

View file

@ -0,0 +1,6 @@
{
"adminUrl": "https://admin.example.com",
"forgejoBaseUrl": "https://git.example.com",
"forgejoServiceAccountUsername": "myst-bot",
"publicUrl": "https://share.example.com"
}

View file

@ -5,36 +5,32 @@ import * as c from "yoctocolors";
import { generateEnvFile } from "../generators/env.js"; import { generateEnvFile } from "../generators/env.js";
import { generateSecret } from "../utils/crypto.js"; import { generateSecret } from "../utils/crypto.js";
interface MystConfig { /**
adminUrl: string; * Normalizes a URL to use https:// if no protocol is specified.
databaseUrl: string; * @param value - The URL to normalize.
forgejoBaseUrl: string; * @returns The normalized URL.
forgejoServiceAccountUsername: string; */
publicUrl: string;
}
function normalizeHttpUrl(value: string): string { function normalizeHttpUrl(value: string): string {
const trimmed = value.trim(); const trimmed = value.trim();
if (/^https?:\/\//i.test(trimmed)) { const hasProtocol = /^[a-z]+:\/\//i.test(trimmed);
return trimmed; const isNotHttp = !/^https?:\/\//i.test(trimmed);
if (hasProtocol && isNotHttp) {
throw new Error("URLs must use http:// or https://");
} }
return `https://${trimmed}`; return hasProtocol ? trimmed : `https://${trimmed}`;
} }
function validateHttpUrlOrHost( function validateHttpUrlOrHost(
value: string | undefined, value: string | undefined,
label: string, label: string,
): string | undefined { ): string | undefined {
if (!value?.trim()) { if (!value?.trim()) return `${label} is required`;
return `${label} is required`;
}
try { try {
const url = new URL(normalizeHttpUrl(value)); const normalized = normalizeHttpUrl(value);
if (url.protocol !== "http:" && url.protocol !== "https:") { const url = new URL(normalized);
return `${label} must start with http:// or https://`;
}
if (!url.hostname) { if (!url.hostname) {
return `${label} must include a domain or hostname`; return `${label} must include a domain or hostname`;
@ -63,13 +59,29 @@ function validatePostgresUrl(value: string | undefined): string | undefined {
return undefined; return undefined;
} }
function generateConfigFile(config: MystConfig): string { async function writePrivateFile(
return `${JSON.stringify(config, null, 2)}\n`; filePath: string,
content: string,
): Promise<void> {
try {
await fs.writeFile(filePath, content, {
encoding: "utf8",
flag: "wx",
mode: 0o600,
});
} catch (e) {
const error = e as NodeJS.ErrnoException;
if (error.code === "EEXIST") {
throw new Error(
`Error: the file '${c.underline(path.basename(filePath))}' already exists in directory ${c.underline(path.dirname(filePath))}`,
);
}
throw error; // throw any other errors back if not EEXIST code
}
} }
export async function initCommand(_args: string[]): Promise<void> { export async function initCommand(_args: string[]): Promise<void> {
p.intro(c.bold("myst init")); p.intro(c.bold("myst init"));
p.note( p.note(
[ [
`${c.bold("Run this in the directory where you plan to deploy Myst.")}`, `${c.bold("Run this in the directory where you plan to deploy Myst.")}`,
@ -140,7 +152,7 @@ export async function initCommand(_args: string[]): Promise<void> {
}, },
{ {
onCancel: () => { onCancel: () => {
process.stderr.write("\nOperation cancelled."); p.cancel("\nOperation cancelled.");
process.exit(0); process.exit(0);
}, },
}, },
@ -148,7 +160,6 @@ export async function initCommand(_args: string[]): Promise<void> {
const s = p.spinner(); const s = p.spinner();
s.start("Generating config files"); s.start("Generating config files");
const publicUrl = normalizeHttpUrl(answers.publicUrl); const publicUrl = normalizeHttpUrl(answers.publicUrl);
const adminUrl = normalizeHttpUrl(answers.adminUrl); const adminUrl = normalizeHttpUrl(answers.adminUrl);
const forgejoBaseUrl = normalizeHttpUrl(answers.forgejoBaseUrl); const forgejoBaseUrl = normalizeHttpUrl(answers.forgejoBaseUrl);
@ -162,23 +173,35 @@ export async function initCommand(_args: string[]): Promise<void> {
grantTokenSecret, grantTokenSecret,
publicUrl, publicUrl,
}); });
const configContent = generateConfigFile({ const configContent = JSON.stringify(
adminUrl, {
databaseUrl: answers.databaseUrl, adminUrl,
forgejoBaseUrl, forgejoBaseUrl,
forgejoServiceAccountUsername: answers.forgejoServiceAccountUsername, forgejoServiceAccountUsername: answers.forgejoServiceAccountUsername,
publicUrl, publicUrl,
}); },
null,
2,
);
const outDir = process.cwd(); const outDir = process.cwd();
await Promise.all([ const envPath = path.join(outDir, ".env");
fs.writeFile(path.join(outDir, ".env"), envContent, "utf8"), const configPath = path.join(outDir, "myst.config.json");
fs.writeFile(
path.join(outDir, "myst.config.json"), try {
configContent, await Promise.all([
"utf8", writePrivateFile(envPath, envContent),
), writePrivateFile(configPath, configContent),
]); ]);
} catch (e) {
s.stop();
p.cancel(
e instanceof Error
? e.message
: `Failed to write config files to ${outDir}`,
);
return;
}
s.stop("Config files generated"); s.stop("Config files generated");
@ -193,19 +216,14 @@ export async function initCommand(_args: string[]): Promise<void> {
`${c.bold("Private admin URL:")} ${c.cyan(adminUrl)}`, `${c.bold("Private admin URL:")} ${c.cyan(adminUrl)}`,
`${c.bold("Forgejo base URL:")} ${c.cyan(forgejoBaseUrl)}`, `${c.bold("Forgejo base URL:")} ${c.cyan(forgejoBaseUrl)}`,
`${c.bold("Forgejo service account:")} ${c.green(answers.forgejoServiceAccountUsername)}`, `${c.bold("Forgejo service account:")} ${c.green(answers.forgejoServiceAccountUsername)}`,
`${c.bold("Tip:")} entering a bare hostname defaults to ${c.bold("https://")}.`, "",
`${c.bold("Admin URL reminder:")} protect this upstream with Tailscale, VPN, Cloudflare Access, or reverse-proxy auth.`, `${c.bold("Admin URL reminder:")} protect this upstream with Tailscale, VPN, Cloudflare Access, or reverse-proxy auth.`,
`${c.bold("PAT setup docs:")} ${c.cyan("https://forgejo.org/docs/latest/user/api-usage/")}`,
`${c.bold("PAT scope docs:")} ${c.cyan("https://forgejo.org/docs/latest/user/token-scope/")}`,
`${c.bold("Next commands:")} ${c.green("myst forgejo bootstrap")} then ${c.green("myst doctor")}`,
].join("\n"), ].join("\n"),
c.yellow("Next steps"), c.yellow("Next steps"),
); );
p.outro( p.outro(
c.green("Done. Deploy Myst, then run forgejo bootstrap and doctor."), c.green(
"Done. Deploy Myst, then run forgejo bootstrap and doctor commands to verify setup.",
),
); );
} }
export async function startCommand(...args: any[]): Promise<void> {}
export async function stopCommand(...args: any[]): Promise<void> {}
export async function statusCommand(...args: any[]): Promise<void> {}

View file

@ -1,49 +0,0 @@
services:
postgres:
image: postgres:16
restart: unless-stopped
env_file:
- .env
volumes:
- postgres-data:/var/lib/postgresql/data
networks:
- private
forgejo:
image: codeberg.org/forgejo/forgejo:11.0.11
restart: unless-stopped
env_file:
- .env
depends_on:
- postgres
ports:
- "3000:3000"
- "2222:22"
volumes:
- forgejo-data:/data
networks:
- private
myst:
image: node:22-alpine
restart: unless-stopped
env_file:
- .env
depends_on:
- forgejo
ports:
- "4000:4000"
environment:
MYST_DOMAIN: myst.example.com
networks:
- private
- public
networks:
private:
internal: true
public:
volumes:
postgres-data:
forgejo-data:

View file

@ -1,55 +0,0 @@
export function generateDockerCompose({ domain }: { domain: string }): string {
return `services:
postgres:
container_name: postgres
image: postgres:16
restart: always
env_file:
- .env
volumes:
- postgres:/var/lib/postgresql/data
networks:
- private
forgejo:
container_name: forgejo
image: codeberg.org/forgejo/forgejo:14
restart: always
env_file:
- .env
depends_on:
- postgres
ports:
- "3000:3000"
- "2222:22"
volumes:
- forgejo:/data
networks:
- private
myst:
container_name: myst
image: node:22-alpine
restart: always
env_file:
- .env
depends_on:
- forgejo
ports:
- "4000:4000"
environment:
MYST_DOMAIN: ${domain}
networks:
- private
- public
networks:
private:
internal: true
public:
volumes:
postgres:
forgejo:
`;
}

View file

@ -8,22 +8,29 @@ interface EnvOptions {
publicUrl: 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
}
export function generateEnvFile(options: EnvOptions): string { export function generateEnvFile(options: EnvOptions): string {
return `# Public URL used for share links. return `# Public URL used for share links.
MYST_PUBLIC_URL=${options.publicUrl} MYST_PUBLIC_URL=${escapeEnvValue(options.publicUrl)}
# Private operator URL for the admin UI. Protect this upstream. # Private operator URL for the admin UI. Protect this upstream.
MYST_ADMIN_URL=${options.adminUrl} MYST_ADMIN_URL=${escapeEnvValue(options.adminUrl)}
# Myst's own Postgres database. # Myst's own Postgres database.
DATABASE_URL=${options.databaseUrl} DATABASE_URL=${escapeEnvValue(options.databaseUrl)}
# Existing Forgejo instance and operator-created service account token. # Existing Forgejo instance and operator-created service account token.
FORGEJO_BASE_URL=${options.forgejoBaseUrl} FORGEJO_BASE_URL=${escapeEnvValue(options.forgejoBaseUrl)}
FORGEJO_SERVICE_ACCOUNT_USERNAME=${options.forgejoServiceAccountUsername} FORGEJO_SERVICE_ACCOUNT_USERNAME=${escapeEnvValue(options.forgejoServiceAccountUsername)}
FORGEJO_PAT=${options.forgejoPat} FORGEJO_PAT=${escapeEnvValue(options.forgejoPat)}
# Secret used to sign or derive grant tokens. # Secret used to sign or derive grant tokens.
GRANT_TOKEN_SECRET=${options.grantTokenSecret} GRANT_TOKEN_SECRET=${escapeEnvValue(options.grantTokenSecret)}
`; `;
} }

View file

@ -1,7 +1,7 @@
export function generateExampleCaddyfile(domain: string): string { export function generateExampleCaddyfile(domain: string): string {
return `${domain} { return `${domain} {
reverse_proxy /_myst/* localhost:4000 reverse_proxy /_myst/* 127.0.0.1:4000
reverse_proxy localhost:3000 reverse_proxy 127.0.0.1:3000
} }
`; `;
} }

View file

@ -1,5 +1,3 @@
export * from "./app-ini.js"; export * from "./app-ini.js";
export * from "./docker-compose.js";
export * from "./env.js"; export * from "./env.js";
export * from "./examples.js"; export * from "./examples.js";

View file

@ -4,16 +4,13 @@ import pkg from "../package.json" with { type: "json" };
import { import {
initCommand, initCommand,
startCommand,
statusCommand,
stopCommand,
} from "./commands/index.js"; } from "./commands/index.js";
const PADDING = 4; const PADDING = 4;
const INDENT = " "; const INDENT = " ";
const USAGE = "myst <command> [options/flags] [arguments]"; const USAGE = "myst <command> [options/flags] [arguments]";
type CommandName = "init" | "start" | "status" | "stop"; type CommandName = "init";
interface Option { interface Option {
name: CommandName | string | string[]; name: CommandName | string | string[];
@ -92,9 +89,6 @@ async function main(): Promise<void> {
const knownCommands: Record<CommandName, (args: string[]) => Promise<void>> = const knownCommands: Record<CommandName, (args: string[]) => Promise<void>> =
{ {
init: initCommand, init: initCommand,
start: startCommand,
status: statusCommand,
stop: stopCommand,
}; };
const isKnownCommand = (cmd: string): cmd is CommandName => const isKnownCommand = (cmd: string): cmd is CommandName =>
@ -106,7 +100,13 @@ async function main(): Promise<void> {
return; return;
} }
await knownCommands[command](options); try {
await knownCommands[command](options);
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error";
process.stderr.write(`${c.red("Error:")} ${message}\n`);
process.exitCode = 1;
}
} }
await main(); await main();

View file

@ -1,7 +1,6 @@
{ {
"adminUrl": "https://admin.myshit.com", "adminUrl": "https://sdfsdf",
"databaseUrl": "postgresql://myst:password@postgres.myshit.com:5432/myst", "forgejoBaseUrl": "https://sdfsdf",
"forgejoBaseUrl": "https://git.myshit.com", "forgejoServiceAccountUsername": "sdfsdf",
"forgejoServiceAccountUsername": "myshit-bot", "publicUrl": "https://asfsf"
"publicUrl": "https://werwr.werwer.werwre"
} }