Compare commits
No commits in common. "140841783b8310fe82e4b624b25b121ef6bc5395" and "6588fad4614c6e6b7ffdf7c9105e099e5500469d" have entirely different histories.
140841783b
...
6588fad461
13 changed files with 198 additions and 362 deletions
|
|
@ -2,7 +2,7 @@ FROM node:22-alpine
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
COPY package*.json pnpm-lock.yaml pnpm-workspace.yaml ./
|
COPY package*.json ./
|
||||||
COPY packages/service/package*.json ./packages/service/
|
COPY packages/service/package*.json ./packages/service/
|
||||||
COPY packages/shared/package*.json ./packages/shared/
|
COPY packages/shared/package*.json ./packages/shared/
|
||||||
COPY tsconfig.base.json ./
|
COPY tsconfig.base.json ./
|
||||||
|
|
@ -19,6 +19,4 @@ ENV PORT=3000
|
||||||
|
|
||||||
EXPOSE 3000
|
EXPOSE 3000
|
||||||
|
|
||||||
USER node
|
|
||||||
|
|
||||||
CMD ["pnpm", "--filter", "@myst/service", "start"]
|
CMD ["pnpm", "--filter", "@myst/service", "start"]
|
||||||
|
|
|
||||||
|
|
@ -95,9 +95,9 @@ GRANT_TOKEN_SECRET="your-secret-here"
|
||||||
- [x] CLI scaffold (`myst config init`)
|
- [x] CLI scaffold (`myst config init`)
|
||||||
- [x] Config generation (`.env`)
|
- [x] Config generation (`.env`)
|
||||||
- [ ] Service foundation (FastAPI + PostgreSQL)
|
- [ ] Service foundation (FastAPI + PostgreSQL)
|
||||||
- [x] `myst config verify` — verify Forgejo connectivity
|
- [ ] `myst verify` — verify Forgejo connectivity
|
||||||
- [x] `myst config verify --diagnostic` — comprehensive diagnostics
|
- [ ] `myst verify --diagnostic` — validate configuration
|
||||||
- [x] `myst config view` — show current config
|
- [ ] `myst config view` — show current config
|
||||||
- [ ] Forgejo session authentication
|
- [ ] Forgejo session authentication
|
||||||
- [ ] Repo ownership verification
|
- [ ] Repo ownership verification
|
||||||
- [ ] Private link creation (email-verified)
|
- [ ] Private link creation (email-verified)
|
||||||
|
|
|
||||||
69
agents.md
69
agents.md
|
|
@ -1,69 +0,0 @@
|
||||||
# agents.md
|
|
||||||
|
|
||||||
This file is the single source of truth for codebase obstacles, oddities, and their resolutions. Do not scatter this knowledge in comments, commit messages, or memory.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Rules for agents
|
|
||||||
|
|
||||||
1. **Before solving a problem**, check this file. If the problem is documented, use the recorded solution or workaround. Do not re-derive it.
|
|
||||||
2. **After solving a new problem**, document it here before moving on. Keep entries concise.
|
|
||||||
3. **Do not deviate** from a recorded solution without first confirming with the user. Once confirmed, update this file with the new approach and reason before proceeding.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Entry format
|
|
||||||
|
|
||||||
```text
|
|
||||||
### [Short problem title]
|
|
||||||
**Area:** [file, module, or system this affects]
|
|
||||||
**Obstacle:** What the problem is and where it appears.
|
|
||||||
**Solution/Workaround:** What was done to fix or work around it.
|
|
||||||
**Preference:** If multiple approaches exist, which was chosen and why.
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Documented obstacles
|
|
||||||
|
|
||||||
### TypeScript composite builds fail with no output
|
|
||||||
**Area:** packages/cli/tsconfig.json, tsconfig.base.json
|
|
||||||
**Obstacle:** When `composite: true` is set in tsconfig, TypeScript requires proper project references to build. The CLI package was building but producing no output files, causing "cannot find module" errors.
|
|
||||||
**Solution:** Remove `composite: true` from packages/cli/tsconfig.json. Also removed `noUncheckedIndexedAccess` and `exactOptionalPropertyTypes` from tsconfig.base.json as they caused strict type issues with dynamic config objects.
|
|
||||||
**Preference:** Use simple tsconfig without composite mode for CLI package.
|
|
||||||
|
|
||||||
### verify.ts overly complex abstraction
|
|
||||||
**Area:** packages/cli/src/commands/verify.ts
|
|
||||||
**Obstacle:** Code had too many layers: collectResults → addResult (inner function) → displayDiagnosticResults/verifyResults. Made it hard to trace and debug.
|
|
||||||
**Solution:** Rewrote to be flatter: verifyCommand → runDiagnosticMode/runVerifyMode. Used simple inline logic instead of adding functions for everything.
|
|
||||||
**Preference:** KISS - keep functions small but avoid over-abstraction.
|
|
||||||
|
|
||||||
### Error messages in forgejo-checks too generic
|
|
||||||
**Area:** packages/cli/src/utils/forgejo-checks.ts
|
|
||||||
**Obstacle:** Network errors showed "fetch failed" with no context. HTTP errors showed just status codes. Not actionable for users.
|
|
||||||
**Solution:** Added getErrorMessage() helper to detect: timeouts, connection refused, host not found. Improved HTTP error messages to include status text. Added context prefixes like "cannot reach server", "cannot connect to API".
|
|
||||||
**Preference:** Actionable messages that tell users what to fix.
|
|
||||||
|
|
||||||
### ENV_MAPPING duplicated inline in verify.ts
|
|
||||||
**Area:** packages/cli/src/commands/verify.ts
|
|
||||||
**Obstacle:** Had duplicate object with same keys as ENV_MAPPING from config.ts. Two sources of truth.
|
|
||||||
**Solution:** Import ENV_MAPPING and use it. Change display to show env var names (SNAKE_CASE) instead of internal keys.
|
|
||||||
**Preference:** Single source of truth in config.ts.
|
|
||||||
|
|
||||||
### Display verbiage redundancy
|
|
||||||
**Area:** packages/cli/src/commands/verify.ts
|
|
||||||
**Obstacle:** Displayed "MYST_PUBLIC_URL set" - "set" is redundant, icon already shows status.
|
|
||||||
**Solution:** Just show env var name, remove "set". Shows "MYST_PUBLIC_URL configured" or "MYST_PUBLIC_URL missing".
|
|
||||||
**Preference:** Cleaner, let icon indicate status.
|
|
||||||
|
|
||||||
### loadConfig returning wrong type for error case
|
|
||||||
**Area:** packages/cli/src/commands/verify.ts
|
|
||||||
**Obstacle:** loadConfig() threw error when .env not found, but caught and re-threw in verifyCommand. This caused process to exit with stack trace instead of clean message.
|
|
||||||
**Solution:** Return null on ENOENT, handle null in verifyCommand. Return type: `Record<string, string> | null`.
|
|
||||||
**Preference:** Explicit null handling over exceptions for user-facing errors.
|
|
||||||
|
|
||||||
### process.exit(0) prevents finally blocks
|
|
||||||
**Area:** CLI commands using process.exit()
|
|
||||||
**Obstacle:** process.exit(0) stops execution immediately, never runs cleanup code.
|
|
||||||
**Solution:** Use process.exitCode = 1 and return instead of process.exit().
|
|
||||||
**Preference:** Set exitCode and return to allow cleanup.
|
|
||||||
|
|
@ -45,7 +45,7 @@ Myst is a companion service deployed beside an existing Forgejo instance. It own
|
||||||
v v
|
v v
|
||||||
Myst Database Forgejo API
|
Myst Database Forgejo API
|
||||||
(Postgres) (existing instance)
|
(Postgres) (existing instance)
|
||||||
```ascii
|
```
|
||||||
|
|
||||||
Deployment boundaries:
|
Deployment boundaries:
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -8,7 +8,6 @@ interface OptionSpec {
|
||||||
type: "string" | "boolean";
|
type: "string" | "boolean";
|
||||||
short?: string;
|
short?: string;
|
||||||
default?: string | boolean | string[] | boolean[];
|
default?: string | boolean | string[] | boolean[];
|
||||||
description?: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type OptionsSpec = Record<string, OptionSpec>;
|
type OptionsSpec = Record<string, OptionSpec>;
|
||||||
|
|
@ -107,44 +106,20 @@ function showCommandHelp(
|
||||||
lines.push("");
|
lines.push("");
|
||||||
}
|
}
|
||||||
|
|
||||||
const hasSubcommands = cmdConf.subcommands && Object.keys(cmdConf.subcommands).length > 0;
|
|
||||||
const usageCmd = subcommand ? `${command} ${subcommand}` : command;
|
const usageCmd = subcommand ? `${command} ${subcommand}` : command;
|
||||||
const usageLine = hasSubcommands && !subcommand
|
|
||||||
? `myst ${command} <subcommand> [options]`
|
|
||||||
: `myst ${usageCmd} [options]`;
|
|
||||||
lines.push(c.bold("Usage:"));
|
lines.push(c.bold("Usage:"));
|
||||||
lines.push(`${INDENT}${usageLine}`);
|
lines.push(`${INDENT}myst ${usageCmd} [options]`);
|
||||||
lines.push("");
|
lines.push("");
|
||||||
|
|
||||||
if (hasSubcommands && !subcommand) {
|
|
||||||
const subcommandRows: HelpRow[] = [];
|
|
||||||
for (const [name, conf] of Object.entries(cmdConf.subcommands!)) {
|
|
||||||
subcommandRows.push({ name, desc: conf.description ?? "" });
|
|
||||||
}
|
|
||||||
const colWidth =
|
|
||||||
Math.max(...subcommandRows.map((r) => r.name.length)) + PADDING;
|
|
||||||
|
|
||||||
lines.push(c.bold("Subcommands:"));
|
|
||||||
for (const row of subcommandRows) {
|
|
||||||
if (row.desc) {
|
|
||||||
lines.push(`${INDENT}${row.name.padEnd(colWidth)}${c.dim(row.desc)}`);
|
|
||||||
} else {
|
|
||||||
lines.push(`${INDENT}${row.name}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
lines.push("");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (targetConf.options && Object.keys(targetConf.options).length > 0) {
|
if (targetConf.options && Object.keys(targetConf.options).length > 0) {
|
||||||
const optionRows: HelpRow[] = [];
|
const optionRows: HelpRow[] = [];
|
||||||
|
|
||||||
for (const [optName, optSpec] of Object.entries(targetConf.options)) {
|
for (const [optName, optSpec] of Object.entries(targetConf.options)) {
|
||||||
const short = optSpec.short ? `, -${optSpec.short}` : "";
|
const short = optSpec.short ? `, -${optSpec.short}` : "";
|
||||||
const typeHint = optSpec.type === "string" ? " <value>" : "";
|
const typeHint = optSpec.type === "string" ? " <value>" : "";
|
||||||
const desc = optSpec.description ?? "";
|
|
||||||
optionRows.push({
|
optionRows.push({
|
||||||
name: `--${optName}${short}${typeHint}`,
|
name: `--${optName}${short}${typeHint}`,
|
||||||
desc,
|
desc: "",
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -153,11 +128,7 @@ function showCommandHelp(
|
||||||
|
|
||||||
lines.push(c.bold("Options:"));
|
lines.push(c.bold("Options:"));
|
||||||
for (const row of optionRows) {
|
for (const row of optionRows) {
|
||||||
if (row.desc) {
|
lines.push(`${INDENT}${row.name.padEnd(colWidth)}`);
|
||||||
lines.push(`${INDENT}${row.name.padEnd(colWidth)}${c.dim(row.desc)}`);
|
|
||||||
} else {
|
|
||||||
lines.push(`${INDENT}${row.name}`);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
lines.push("");
|
lines.push("");
|
||||||
}
|
}
|
||||||
|
|
@ -183,7 +154,7 @@ export async function runCli(
|
||||||
const isVersionFlag = (arg: string) => arg === "--version" || arg === "-v";
|
const isVersionFlag = (arg: string) => arg === "--version" || arg === "-v";
|
||||||
|
|
||||||
// Check for version flag (early exit)
|
// Check for version flag (early exit)
|
||||||
if (argv.some(isVersionFlag)) {
|
if (argv.length > 0 && argv.every(isVersionFlag)) {
|
||||||
process.stdout.write(version + "\n");
|
process.stdout.write(version + "\n");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
@ -214,11 +185,8 @@ export async function runCli(
|
||||||
|
|
||||||
// If help is requested for a specific command, show command-specific help
|
// If help is requested for a specific command, show command-specific help
|
||||||
if (wantsCommandHelp) {
|
if (wantsCommandHelp) {
|
||||||
const subcommands = cmdConf.subcommands;
|
const isHelpFlag = (arg: string) => arg === "--help" || arg === "-h";
|
||||||
const actualSubcommand =
|
const actualSubcommand = isHelpFlag(subcommand) ? undefined : subcommand;
|
||||||
subcommand && subcommands && subcommand in subcommands
|
|
||||||
? subcommand
|
|
||||||
: undefined;
|
|
||||||
showCommandHelp(command, cmdConf, actualSubcommand);
|
showCommandHelp(command, cmdConf, actualSubcommand);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
@ -260,22 +228,14 @@ export async function runCli(
|
||||||
? [subcommand, ...remainingArgs]
|
? [subcommand, ...remainingArgs]
|
||||||
: remainingArgs;
|
: remainingArgs;
|
||||||
|
|
||||||
|
// Parse target command options
|
||||||
|
const { values: cmdOpts } = parseArgs({
|
||||||
|
args: argsForOptions,
|
||||||
|
options: targetCmdConf.options || {},
|
||||||
|
allowPositionals: true,
|
||||||
|
});
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Parse target command options
|
|
||||||
const { values: cmdOpts, positionals } = parseArgs({
|
|
||||||
args: argsForOptions,
|
|
||||||
options: targetCmdConf.options || {},
|
|
||||||
allowPositionals: true,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (positionals.length > 0) {
|
|
||||||
process.stderr.write(
|
|
||||||
`${c.red("Error:")} Unexpected argument: ${positionals[0]}\n`,
|
|
||||||
);
|
|
||||||
process.exitCode = 1;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Execute the target command handler
|
// Execute the target command handler
|
||||||
await targetCmdConf.handler(cmdOpts);
|
await targetCmdConf.handler(cmdOpts);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|
|
||||||
|
|
@ -8,7 +8,7 @@ export const commandRegistry = {
|
||||||
subcommands: {
|
subcommands: {
|
||||||
init: configInit.commandConfig,
|
init: configInit.commandConfig,
|
||||||
view: configView.commandConfig,
|
view: configView.commandConfig,
|
||||||
verify: verify.commandConfig,
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
verify: verify.commandConfig,
|
||||||
};
|
};
|
||||||
|
|
@ -5,10 +5,7 @@ import * as c from "yoctocolors";
|
||||||
import * as p from "@clack/prompts";
|
import * as p from "@clack/prompts";
|
||||||
|
|
||||||
import { generateSecret } from "../../utils/crypto.js";
|
import { generateSecret } from "../../utils/crypto.js";
|
||||||
import {
|
import { generateEnvFile } from "../../utils/config.js";
|
||||||
generateEnvFile,
|
|
||||||
SECRET_ENV_KEYS,
|
|
||||||
} from "../../utils/config.js";
|
|
||||||
import { CommandConfig } from "../../cli-router.js";
|
import { CommandConfig } from "../../cli-router.js";
|
||||||
|
|
||||||
function normalizeHttpUrl(value: string): string {
|
function normalizeHttpUrl(value: string): string {
|
||||||
|
|
@ -113,21 +110,12 @@ async function init(opts: { output?: string }) {
|
||||||
|
|
||||||
if (choice === "view") {
|
if (choice === "view") {
|
||||||
const envContent = await fs.readFile(envPath, { encoding: "utf-8" });
|
const envContent = await fs.readFile(envPath, { encoding: "utf-8" });
|
||||||
const maskedEnvContent = envContent
|
p.note(c.dim(envContent), c.yellow("Current .env"));
|
||||||
.split("\n")
|
|
||||||
.map((line) => {
|
|
||||||
if (!line.includes("=")) return line;
|
|
||||||
const [key] = line.split("=");
|
|
||||||
return SECRET_ENV_KEYS.includes(key as typeof SECRET_ENV_KEYS[number])
|
|
||||||
? `${key}=****`
|
|
||||||
: line;
|
|
||||||
})
|
|
||||||
.join("\n");
|
|
||||||
p.note(c.dim(maskedEnvContent), c.yellow("Current .env"));
|
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (choice === "overwrite") {
|
if (choice === "overwrite") {
|
||||||
|
await fs.unlink(envPath);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -186,6 +174,7 @@ async function init(opts: { output?: string }) {
|
||||||
onCancel: () => {
|
onCancel: () => {
|
||||||
p.cancel("\nOperation cancelled.");
|
p.cancel("\nOperation cancelled.");
|
||||||
process.exitCode = 0;
|
process.exitCode = 0;
|
||||||
|
throw new Error("Operation cancelled");
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
@ -211,23 +200,11 @@ async function init(opts: { output?: string }) {
|
||||||
publicUrl,
|
publicUrl,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (envExists) {
|
await fs.writeFile(envPath, envContent, {
|
||||||
const tempPath = envPath + ".tmp";
|
encoding: "utf8",
|
||||||
await fs.writeFile(tempPath, envContent, {
|
flag: "wx",
|
||||||
encoding: "utf8",
|
mode: 0o600,
|
||||||
flag: "wx",
|
});
|
||||||
mode: 0o600,
|
|
||||||
});
|
|
||||||
|
|
||||||
await fs.unlink(envPath).catch(() => {});
|
|
||||||
await fs.rename(tempPath, envPath);
|
|
||||||
} else {
|
|
||||||
await fs.writeFile(envPath, envContent, {
|
|
||||||
encoding: "utf8",
|
|
||||||
flag: "wx",
|
|
||||||
mode: 0o600,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
s.stop(c.yellow(`.env created at ${envPath}`));
|
s.stop(c.yellow(`.env created at ${envPath}`));
|
||||||
p.note(
|
p.note(
|
||||||
|
|
|
||||||
|
|
@ -6,10 +6,15 @@ import {
|
||||||
ENV_MAPPING,
|
ENV_MAPPING,
|
||||||
MystEnvironmentVariables,
|
MystEnvironmentVariables,
|
||||||
parseEnvFile,
|
parseEnvFile,
|
||||||
SECRET_KEYS,
|
|
||||||
} from "../../utils/config.js";
|
} from "../../utils/config.js";
|
||||||
import { CommandConfig } from "../../cli-router.js";
|
import { CommandConfig } from "../../cli-router.js";
|
||||||
|
|
||||||
|
function redactSecret(value: string | undefined): string {
|
||||||
|
if (!value) return c.dim("not set");
|
||||||
|
if (value.length <= 4) return c.dim("****");
|
||||||
|
return value.slice(0, 4) + c.dim("****");
|
||||||
|
}
|
||||||
|
|
||||||
export const commandConfig: CommandConfig = {
|
export const commandConfig: CommandConfig = {
|
||||||
description: "Display current configuration",
|
description: "Display current configuration",
|
||||||
handler: async () => {
|
handler: async () => {
|
||||||
|
|
@ -36,11 +41,10 @@ export const commandConfig: CommandConfig = {
|
||||||
|
|
||||||
for (const [envKey, configKey] of Object.entries(ENV_MAPPING)) {
|
for (const [envKey, configKey] of Object.entries(ENV_MAPPING)) {
|
||||||
const value = config[configKey];
|
const value = config[configKey];
|
||||||
const displayValue = SECRET_KEYS.includes(
|
const displayValue =
|
||||||
configKey as (typeof SECRET_KEYS)[number],
|
configKey === "forgejoPat" || configKey === "grantTokenSecret"
|
||||||
)
|
? redactSecret(value)
|
||||||
? c.dim("****")
|
: value || c.dim("not set");
|
||||||
: value || c.dim("not set");
|
|
||||||
process.stdout.write(`${c.bold(envKey + ":")} ${displayValue}\n`);
|
process.stdout.write(`${c.bold(envKey + ":")} ${displayValue}\n`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,13 @@ import path from "node:path";
|
||||||
import * as c from "yoctocolors";
|
import * as c from "yoctocolors";
|
||||||
import * as p from "@clack/prompts";
|
import * as p from "@clack/prompts";
|
||||||
|
|
||||||
import { ENV_MAPPING, parseEnvFile, REQUIRED_KEYS } from "../utils/config.js";
|
import {
|
||||||
|
ENV_MAPPING,
|
||||||
|
MystEnvironmentVariables,
|
||||||
|
parseEnvFile,
|
||||||
|
validateDatabaseUrl,
|
||||||
|
REQUIRED_KEYS,
|
||||||
|
} from "../utils/config.js";
|
||||||
import {
|
import {
|
||||||
checkForgejoReachability,
|
checkForgejoReachability,
|
||||||
checkForgejoApiAuthentication,
|
checkForgejoApiAuthentication,
|
||||||
|
|
@ -21,7 +27,21 @@ interface CheckResult {
|
||||||
message?: string;
|
message?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
function loadConfig(): Record<string, string> | null {
|
async function verifyCommand(opts: VerifyOptions): Promise<void> {
|
||||||
|
const isDiagnostic = opts.diagnostic ?? false;
|
||||||
|
p.intro(c.bold("myst config verify"));
|
||||||
|
|
||||||
|
const config = loadConfig();
|
||||||
|
const results: CheckResult[] = collectResults(config);
|
||||||
|
|
||||||
|
if (isDiagnostic) {
|
||||||
|
await displayDiagnosticResults(results, config);
|
||||||
|
} else {
|
||||||
|
await verifyResults(results, config);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function loadConfig(): Partial<MystEnvironmentVariables> {
|
||||||
const envPath = path.join(process.cwd(), ".env");
|
const envPath = path.join(process.cwd(), ".env");
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
|
@ -31,125 +51,64 @@ function loadConfig(): Record<string, string> | null {
|
||||||
if (err.code === "ENOENT") {
|
if (err.code === "ENOENT") {
|
||||||
p.cancel(`${c.red("Error:")} .env file not found in ${process.cwd()}`);
|
p.cancel(`${c.red("Error:")} .env file not found in ${process.cwd()}`);
|
||||||
process.exitCode = 1;
|
process.exitCode = 1;
|
||||||
return null;
|
|
||||||
}
|
}
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function getMissingKeys(config: Record<string, string>): string[] {
|
function collectResults(
|
||||||
|
config: Partial<MystEnvironmentVariables>,
|
||||||
|
): CheckResult[] {
|
||||||
|
const results: CheckResult[] = [];
|
||||||
|
|
||||||
|
function addResult(name: string, success: boolean, message?: string) {
|
||||||
|
results.push({ name, success, ...(message !== undefined && { message }) });
|
||||||
|
}
|
||||||
|
|
||||||
const missing: string[] = [];
|
const missing: string[] = [];
|
||||||
for (const key of REQUIRED_KEYS) {
|
for (const key of REQUIRED_KEYS) {
|
||||||
if (!config[key]) {
|
if (!config[key]) {
|
||||||
missing.push(key.replace(/(?<=[a-z])(?=[A-Z])/g, "_").toUpperCase());
|
missing.push(key.replace(/(?<=[a-z])(?=[A-Z])/g, "_").toUpperCase());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return missing;
|
|
||||||
|
if (missing.length > 0) {
|
||||||
|
addResult("Required config", false, `Missing: ${missing.join(", ")}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const [, configKey] of Object.entries(ENV_MAPPING)) {
|
||||||
|
const value = config[configKey];
|
||||||
|
addResult(`${configKey} set`, !!value, value ? "configured" : "missing");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (config.databaseUrl) {
|
||||||
|
const isDbValid = validateDatabaseUrl(config.databaseUrl);
|
||||||
|
addResult("Database URL format", isDbValid, isDbValid ? "valid" : "invalid");
|
||||||
|
}
|
||||||
|
|
||||||
|
const isConfigured =
|
||||||
|
config.forgejoBaseUrl && config.forgejoPat && config.forgejoBotUsername;
|
||||||
|
|
||||||
|
if (!isConfigured) {
|
||||||
|
return results;
|
||||||
|
}
|
||||||
|
|
||||||
|
const { forgejoBaseUrl, forgejoPat, forgejoBotUsername } = config;
|
||||||
|
|
||||||
|
addResult("Forgejo configured", true);
|
||||||
|
|
||||||
|
return results;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function runDiagnosticMode(
|
async function runForgejoChecks(config: Partial<MystEnvironmentVariables>): Promise<CheckResult[]> {
|
||||||
config: Record<string, string>,
|
|
||||||
missing: string[],
|
|
||||||
): Promise<void> {
|
|
||||||
const results: CheckResult[] = [];
|
const results: CheckResult[] = [];
|
||||||
|
|
||||||
if (missing.length > 0) {
|
|
||||||
results.push({
|
|
||||||
name: "Required config",
|
|
||||||
success: false,
|
|
||||||
message: `Missing: ${missing.join(", ")}`,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const [envKey, configKey] of Object.entries(ENV_MAPPING)) {
|
|
||||||
const value = config[configKey];
|
|
||||||
results.push({
|
|
||||||
name: envKey,
|
|
||||||
success: !!value,
|
|
||||||
message: value ? "configured" : "missing",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const forgejoResults = await runForgejoChecks(config);
|
|
||||||
const allResults = [...results, ...forgejoResults];
|
|
||||||
|
|
||||||
const lines = allResults.map((r) => {
|
|
||||||
const icon = r.success ? c.green("✓") : c.red("✗");
|
|
||||||
const msg = r.message ? ` ${r.message}` : "";
|
|
||||||
return `${icon} ${r.name}${msg}`;
|
|
||||||
});
|
|
||||||
|
|
||||||
p.note(lines.join("\n"), c.yellow("Results"));
|
|
||||||
|
|
||||||
const failures = allResults.filter((r) => !r.success);
|
|
||||||
if (failures.length > 0) {
|
|
||||||
p.outro(c.red(`${failures.length} issue(s) found`));
|
|
||||||
process.exitCode = 1;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
p.outro(c.green("All checks passed"));
|
|
||||||
}
|
|
||||||
|
|
||||||
async function runVerifyMode(
|
|
||||||
config: Record<string, string>,
|
|
||||||
missing: string[],
|
|
||||||
): Promise<void> {
|
|
||||||
if (missing.length > 0) {
|
|
||||||
p.cancel(
|
|
||||||
`${c.red("Error:")} Missing required env variables: ${missing.join(", ")}`,
|
|
||||||
);
|
|
||||||
process.exitCode = 1;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const s = p.spinner();
|
|
||||||
s.start("Verifying Forgejo configuration");
|
|
||||||
|
|
||||||
const forgejoResults = await runForgejoChecks(config);
|
|
||||||
|
|
||||||
const firstFailure = forgejoResults.find((r) => !r.success);
|
|
||||||
if (firstFailure) {
|
|
||||||
s.stop(firstFailure.message);
|
|
||||||
p.cancel(`${c.red("✗")} ${firstFailure.name}: ${firstFailure.message}`);
|
|
||||||
process.exitCode = 1;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (forgejoResults.length === 0) {
|
|
||||||
s.stop("No Forgejo configuration");
|
|
||||||
p.cancel(`${c.red("Error:")} Forgejo not configured`);
|
|
||||||
process.exitCode = 1;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
s.stop("Verification complete");
|
|
||||||
|
|
||||||
const [reachability, auth, repoAccess] = forgejoResults;
|
|
||||||
|
|
||||||
p.note(
|
|
||||||
[
|
|
||||||
`${c.green("✓")} ${reachability.name}`,
|
|
||||||
`${c.green("✓")} ${auth.name}: ${auth.message}`,
|
|
||||||
`${c.green(repoAccess.success ? "✓" : "✗")} ${repoAccess.name}: ${repoAccess.message}`,
|
|
||||||
].join("\n"),
|
|
||||||
c.yellow("Results"),
|
|
||||||
);
|
|
||||||
|
|
||||||
p.outro(c.green("Verification passed"));
|
|
||||||
}
|
|
||||||
|
|
||||||
async function runForgejoChecks(
|
|
||||||
config: Record<string, string>,
|
|
||||||
): Promise<CheckResult[]> {
|
|
||||||
const { forgejoBaseUrl, forgejoPat, forgejoBotUsername } = config;
|
const { forgejoBaseUrl, forgejoPat, forgejoBotUsername } = config;
|
||||||
|
|
||||||
if (!forgejoBaseUrl || !forgejoPat || !forgejoBotUsername) {
|
if (!forgejoBaseUrl || !forgejoPat || !forgejoBotUsername) {
|
||||||
return [];
|
return results;
|
||||||
}
|
}
|
||||||
|
|
||||||
const results: CheckResult[] = [];
|
|
||||||
|
|
||||||
const reachability = await checkForgejoReachability(forgejoBaseUrl);
|
const reachability = await checkForgejoReachability(forgejoBaseUrl);
|
||||||
results.push(reachability);
|
results.push(reachability);
|
||||||
|
|
||||||
|
|
@ -174,31 +133,88 @@ async function runForgejoChecks(
|
||||||
return results;
|
return results;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function verifyCommand(opts: VerifyOptions): Promise<void> {
|
async function displayDiagnosticResults(
|
||||||
const isDiagnostic = opts.diagnostic ?? false;
|
results: CheckResult[],
|
||||||
p.intro(c.bold("myst verify"));
|
config: Partial<MystEnvironmentVariables>,
|
||||||
|
): Promise<void> {
|
||||||
|
const forgejoResults = await runForgejoChecks(config);
|
||||||
|
const allResults = [...results, ...forgejoResults];
|
||||||
|
|
||||||
const config = loadConfig();
|
const lines = allResults.map((r) => {
|
||||||
if (!config) {
|
const icon = r.success ? c.green("✓") : c.red("✗");
|
||||||
|
const msg = r.message ? ` ${r.message}` : "";
|
||||||
|
return `${icon} ${r.name}${msg}`;
|
||||||
|
});
|
||||||
|
|
||||||
|
p.note(lines.join("\n"), c.yellow("Results"));
|
||||||
|
|
||||||
|
const failures = allResults.filter((r) => !r.success);
|
||||||
|
|
||||||
|
if (failures.length > 0) {
|
||||||
|
p.outro(c.red(`${failures.length} issue(s) found`));
|
||||||
|
process.exitCode = 1;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const missing = getMissingKeys(config);
|
p.outro(c.green("All checks passed"));
|
||||||
|
}
|
||||||
|
|
||||||
if (isDiagnostic) {
|
async function verifyResults(
|
||||||
await runDiagnosticMode(config, missing);
|
results: CheckResult[],
|
||||||
} else {
|
config: Partial<MystEnvironmentVariables>,
|
||||||
await runVerifyMode(config, missing);
|
): Promise<void> {
|
||||||
|
const failures = results.filter((r) => !r.success);
|
||||||
|
|
||||||
|
if (failures.length > 0) {
|
||||||
|
const msg = failures[0]?.message ?? "Unknown error";
|
||||||
|
p.cancel(`${c.red("Error:")} ${msg}`);
|
||||||
|
process.exitCode = 1;
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const s = p.spinner();
|
||||||
|
s.start("Verifying Forgejo configuration");
|
||||||
|
|
||||||
|
const forgejoResults = await runForgejoChecks(config);
|
||||||
|
|
||||||
|
const firstFailure = forgejoResults.find((r) => !r.success);
|
||||||
|
|
||||||
|
if (firstFailure) {
|
||||||
|
s.stop(firstFailure.message);
|
||||||
|
p.cancel(`${c.red("✗")} ${firstFailure.name}: ${firstFailure.message}`);
|
||||||
|
process.exitCode = 1;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (forgejoResults.length < 3) {
|
||||||
|
s.stop("No Forgejo configuration");
|
||||||
|
p.cancel(`${c.red("Error:")} Forgejo not configured`);
|
||||||
|
process.exitCode = 1;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
s.stop("Verification complete");
|
||||||
|
|
||||||
|
const reachability = forgejoResults[0]!;
|
||||||
|
const auth = forgejoResults[1]!;
|
||||||
|
const repoAccess = forgejoResults[2]!;
|
||||||
|
|
||||||
|
p.note(
|
||||||
|
[
|
||||||
|
`${c.green("✓")} ${reachability.name}`,
|
||||||
|
`${c.green("✓")} ${auth.name}: ${auth.message}`,
|
||||||
|
`${c.green(repoAccess.success ? "✓" : "✗")} ${repoAccess.name}: ${repoAccess.message}`,
|
||||||
|
].join("\n"),
|
||||||
|
c.yellow("Results"),
|
||||||
|
);
|
||||||
|
|
||||||
|
p.outro(c.green("Verification passed"));
|
||||||
}
|
}
|
||||||
|
|
||||||
export const commandConfig: CommandConfig = {
|
export const commandConfig: CommandConfig = {
|
||||||
description: "Verify Myst configuration and connection to Forgejo",
|
description: "Verify Myst configuration and connection to Forgejo",
|
||||||
options: {
|
options: {
|
||||||
diagnostic: {
|
diagnostic: { type: "boolean" },
|
||||||
type: "boolean",
|
|
||||||
description: "Show diagnostic information for all checks",
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
handler: verifyCommand,
|
handler: verifyCommand,
|
||||||
};
|
};
|
||||||
|
|
@ -28,20 +28,6 @@ export const REQUIRED_KEYS = [
|
||||||
|
|
||||||
export const DATABASE_PROTOCOLS = ["postgres:", "postgresql:"] as const;
|
export const DATABASE_PROTOCOLS = ["postgres:", "postgresql:"] as const;
|
||||||
|
|
||||||
export const SECRET_KEYS = [
|
|
||||||
"forgejoPat",
|
|
||||||
"grantTokenSecret",
|
|
||||||
"databaseUrl",
|
|
||||||
"adminUrl",
|
|
||||||
] as const;
|
|
||||||
|
|
||||||
export const SECRET_ENV_KEYS = [
|
|
||||||
"DATABASE_URL",
|
|
||||||
"FORGEJO_PAT",
|
|
||||||
"GRANT_TOKEN_SECRET",
|
|
||||||
"MYST_ADMIN_URL",
|
|
||||||
] as const;
|
|
||||||
|
|
||||||
export function parseEnvFile(
|
export function parseEnvFile(
|
||||||
envPath: string,
|
envPath: string,
|
||||||
): Partial<MystEnvironmentVariables> {
|
): Partial<MystEnvironmentVariables> {
|
||||||
|
|
|
||||||
|
|
@ -25,47 +25,29 @@ async function fetchWithTimeout(
|
||||||
return fetch(url, { ...init, signal: AbortSignal.timeout(TIMEOUT) });
|
return fetch(url, { ...init, signal: AbortSignal.timeout(TIMEOUT) });
|
||||||
}
|
}
|
||||||
|
|
||||||
function getErrorMessage(error: unknown, context: string): string {
|
|
||||||
if (error instanceof Error) {
|
|
||||||
if (error.name === "TimeoutError") {
|
|
||||||
return `${context}: connection timed out`;
|
|
||||||
}
|
|
||||||
if (error.message.includes("ECONNREFUSED")) {
|
|
||||||
return `${context}: connection refused`;
|
|
||||||
}
|
|
||||||
if (error.message.includes("ENOTFOUND") || error.message.includes("getaddrinfo")) {
|
|
||||||
return `${context}: host not found`;
|
|
||||||
}
|
|
||||||
return `${context}: ${error.message}`;
|
|
||||||
}
|
|
||||||
return `${context}: unknown error`;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function checkForgejoReachability(
|
export async function checkForgejoReachability(
|
||||||
baseUrl: string,
|
baseUrl: string,
|
||||||
): Promise<CheckResult> {
|
): Promise<CheckResult> {
|
||||||
try {
|
try {
|
||||||
const response = await fetchWithTimeout(baseUrl, { method: "GET" });
|
const response = await fetchWithTimeout(baseUrl, { method: "GET" });
|
||||||
if (response.ok) {
|
if (response.ok || response.status === 200) {
|
||||||
return createCheckResult("Forgejo reachability", true, "connected");
|
return createCheckResult("Forgejo reachability", true);
|
||||||
}
|
}
|
||||||
return createCheckResult(
|
return createCheckResult(
|
||||||
"Forgejo reachability",
|
"Forgejo reachability",
|
||||||
false,
|
false,
|
||||||
`server returned ${response.status} ${response.statusText}`,
|
`HTTP ${response.status}`,
|
||||||
);
|
);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return createCheckResult(
|
const message = error instanceof Error ? error.message : "Unknown error";
|
||||||
"Forgejo reachability",
|
return createCheckResult("Forgejo reachability", false, message);
|
||||||
false,
|
|
||||||
getErrorMessage(error, "cannot reach server"),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function checkForgejoApiAuthentication(
|
export async function checkForgejoApi(
|
||||||
baseUrl: string,
|
baseUrl: string,
|
||||||
pat: string,
|
pat: string,
|
||||||
|
colorize = false,
|
||||||
): Promise<CheckResult> {
|
): Promise<CheckResult> {
|
||||||
try {
|
try {
|
||||||
const response = await fetchWithTimeout(`${baseUrl}/api/v1/user`, {
|
const response = await fetchWithTimeout(`${baseUrl}/api/v1/user`, {
|
||||||
|
|
@ -79,15 +61,7 @@ export async function checkForgejoApiAuthentication(
|
||||||
return createCheckResult(
|
return createCheckResult(
|
||||||
"Forgejo API token",
|
"Forgejo API token",
|
||||||
false,
|
false,
|
||||||
"token is invalid or expired",
|
"Invalid or expired token",
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (response.status === 403) {
|
|
||||||
return createCheckResult(
|
|
||||||
"Forgejo API token",
|
|
||||||
false,
|
|
||||||
"token lacks sufficient permissions",
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -95,22 +69,24 @@ export async function checkForgejoApiAuthentication(
|
||||||
return createCheckResult(
|
return createCheckResult(
|
||||||
"Forgejo API token",
|
"Forgejo API token",
|
||||||
false,
|
false,
|
||||||
`server returned ${response.status}`,
|
`HTTP ${response.status}`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const user = (await response.json()) as { login: string };
|
const user = (await response.json()) as { login: string };
|
||||||
|
let login = user.login;
|
||||||
|
if (colorize) {
|
||||||
|
const { default: c } = await import("yoctocolors");
|
||||||
|
login = c.green(user.login);
|
||||||
|
}
|
||||||
return createCheckResult(
|
return createCheckResult(
|
||||||
"Forgejo API token",
|
"Forgejo API token",
|
||||||
true,
|
true,
|
||||||
`authenticated as ${user.login}`,
|
`Authenticated as ${login}`,
|
||||||
);
|
);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return createCheckResult(
|
const message = error instanceof Error ? error.message : "Unknown error";
|
||||||
"Forgejo API token",
|
return createCheckResult("Forgejo API token", false, message);
|
||||||
false,
|
|
||||||
getErrorMessage(error, "cannot connect to API"),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -130,20 +106,8 @@ export async function checkRepoAccess(
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
if (response.status === 401 || response.status === 403) {
|
|
||||||
return createCheckResult(
|
|
||||||
"Repo access",
|
|
||||||
false,
|
|
||||||
"token lacks permission to list repositories",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
return createCheckResult(
|
return createCheckResult("Repo access", false, `HTTP ${response.status}`);
|
||||||
"Repo access",
|
|
||||||
false,
|
|
||||||
`server returned ${response.status}`,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const repos = (await response.json()) as { name: string }[];
|
const repos = (await response.json()) as { name: string }[];
|
||||||
|
|
@ -151,20 +115,17 @@ export async function checkRepoAccess(
|
||||||
return createCheckResult(
|
return createCheckResult(
|
||||||
"Repo access",
|
"Repo access",
|
||||||
true,
|
true,
|
||||||
`found ${repos.length} repository`,
|
`Found ${repos.length} repo(s)`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return createCheckResult(
|
return createCheckResult(
|
||||||
"Repo access",
|
"Repo access",
|
||||||
false,
|
false,
|
||||||
"no repositories found for user",
|
"No repos found (service account may not have repo access)",
|
||||||
);
|
);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return createCheckResult(
|
const message = error instanceof Error ? error.message : "Unknown error";
|
||||||
"Repo access",
|
return createCheckResult("Repo access", false, message);
|
||||||
false,
|
|
||||||
getErrorMessage(error, "cannot list repositories"),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,9 +1,10 @@
|
||||||
{
|
{
|
||||||
"extends": "../../tsconfig.base.json",
|
"extends": "../../tsconfig.base.json",
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
|
"composite": true,
|
||||||
"rootDir": "src",
|
"rootDir": "src",
|
||||||
"outDir": "dist"
|
"outDir": "dist",
|
||||||
},
|
},
|
||||||
"references": [{ "path": "../shared" }],
|
"references": [{ "path": "../shared" }],
|
||||||
"include": ["src/**/*.ts"]
|
"include": ["src/**/*.ts"],
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -9,6 +9,8 @@
|
||||||
"@myst/shared": ["packages/shared/src/index.ts"]
|
"@myst/shared": ["packages/shared/src/index.ts"]
|
||||||
},
|
},
|
||||||
"strict": true,
|
"strict": true,
|
||||||
|
"noUncheckedIndexedAccess": true,
|
||||||
|
"exactOptionalPropertyTypes": true,
|
||||||
"skipLibCheck": true,
|
"skipLibCheck": true,
|
||||||
"declaration": true,
|
"declaration": true,
|
||||||
"sourceMap": true,
|
"sourceMap": true,
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue