feat(config): config module with idempotent bootstrap and strict v1 validation (#1)
- scripts/mosaic-config.mjs: bootstrap | validate | env operations - Exclusive creation (O_EXCL 'wx'); existing config validated, never rewritten - Strict schema: unknown keys rejected, configVersion===1, backend docker only - dataRoot guards: absolute, canonical, not root/home/ancestor-of-config - MOSAIC_CONFIG override for sandboxed tests; exit codes 0/2/3 - scripts/bootstrap.sh: explicit bootstrap entry point Closes #1
This commit is contained in:
Executable
+11
@@ -0,0 +1,11 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Explicit, idempotent configuration bootstrap.
|
||||||
|
#
|
||||||
|
# Creates ~/.config/mosaic-dev/config.json (or $MOSAIC_CONFIG) only when
|
||||||
|
# absent. An existing configuration is validated, never modified.
|
||||||
|
# Normal run paths (build/hello/verify) deliberately do NOT auto-bootstrap:
|
||||||
|
# missing configuration is an error there, not something to invent.
|
||||||
|
set -euo pipefail
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
|
||||||
|
exec node scripts/mosaic-config.mjs bootstrap
|
||||||
Executable
+83
@@ -0,0 +1,83 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Minimal Gitea API client for this repository.
|
||||||
|
#
|
||||||
|
# Usage: scripts/gitea-api.sh METHOD api/path [json-body]
|
||||||
|
# e.g. scripts/gitea-api.sh GET repos/mosaicstack/stack-v2/issues
|
||||||
|
#
|
||||||
|
# Security:
|
||||||
|
# - Reads credentials from ~/secrets/mosaic.gitea.json (or
|
||||||
|
# MOSAIC_GITEA_CREDENTIAL_FILE); file must be 0600, non-symlink.
|
||||||
|
# - Token is passed to curl via a config stream (never argv, never disk,
|
||||||
|
# never stdout/stderr).
|
||||||
|
# - Prints the response body on stdout and "HTTP <code>" on stderr.
|
||||||
|
# Exits nonzero when the API reports an error.
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
METHOD="${1:?usage: gitea-api.sh METHOD api/path [json-body]}"
|
||||||
|
API_PATH="${2:?missing api/path}"
|
||||||
|
API_PATH="${API_PATH#/}"
|
||||||
|
BODY="${3:-}"
|
||||||
|
|
||||||
|
command -v curl >/dev/null || { echo "gitea-api: curl not found" >&2; exit 1; }
|
||||||
|
command -v node >/dev/null || { echo "gitea-api: node not found" >&2; exit 1; }
|
||||||
|
|
||||||
|
export MOSAIC_GITEA_CREDENTIAL_FILE="${MOSAIC_GITEA_CREDENTIAL_FILE:-$HOME/secrets/mosaic.gitea.json}"
|
||||||
|
|
||||||
|
# Validate credential file; emit only the non-secret base URL on stdout.
|
||||||
|
BASE="$(node -e '
|
||||||
|
const fs = require("fs");
|
||||||
|
const p = process.env.MOSAIC_GITEA_CREDENTIAL_FILE;
|
||||||
|
let s;
|
||||||
|
try { s = fs.lstatSync(p); } catch { process.exit(3); }
|
||||||
|
if (!s.isFile() || s.isSymbolicLink() || (s.mode & 0o077) !== 0) process.exit(3);
|
||||||
|
let e;
|
||||||
|
try { e = JSON.parse(fs.readFileSync(p, "utf8")).mosaicstack || {}; } catch { process.exit(3); }
|
||||||
|
const base = String(e.url || "").replace(/\/+$/, "");
|
||||||
|
if (!/^https:\/\/git\.mosaicstack\.dev$/.test(base)) process.exit(3);
|
||||||
|
if (typeof e.api_token !== "string" || e.api_token.length === 0) process.exit(3);
|
||||||
|
process.stdout.write(base);
|
||||||
|
')"
|
||||||
|
|
||||||
|
# Repo path from the configured origin remote (never from credentials).
|
||||||
|
REMOTE_URL="$(git remote get-url origin)"
|
||||||
|
REPO_PATH="${REMOTE_URL#https://git.mosaicstack.dev/}"
|
||||||
|
REPO_PATH="${REPO_PATH%.git}"
|
||||||
|
|
||||||
|
# curl config stream: auth header via fd, never argv.
|
||||||
|
gen_curl_cfg() {
|
||||||
|
node -e '
|
||||||
|
const fs = require("fs");
|
||||||
|
const e = JSON.parse(fs.readFileSync(process.env.MOSAIC_GITEA_CREDENTIAL_FILE, "utf8")).mosaicstack || {};
|
||||||
|
process.stdout.write("header = \"Authorization: token " + e.api_token + "\"\n");
|
||||||
|
process.stdout.write("header = \"Content-Type: application/json\"\n");
|
||||||
|
'
|
||||||
|
}
|
||||||
|
|
||||||
|
BODY_FILE=""
|
||||||
|
cleanup() { [ -n "$BODY_FILE" ] && rm -f "$BODY_FILE"; }
|
||||||
|
trap cleanup EXIT
|
||||||
|
if [ -n "$BODY" ]; then
|
||||||
|
BODY_FILE="$(mktemp)"
|
||||||
|
chmod 600 "$BODY_FILE"
|
||||||
|
printf '%s' "$BODY" > "$BODY_FILE"
|
||||||
|
fi
|
||||||
|
|
||||||
|
URL="$BASE/api/v1/$API_PATH"
|
||||||
|
if [ -n "$BODY_FILE" ]; then
|
||||||
|
HTTP_CODE="$(curl -sS -K <(gen_curl_cfg) -o /tmp/gitea-api-response.$$ \
|
||||||
|
-w '%{http_code}' -X "$METHOD" "$URL" --data-binary @"$BODY_FILE")" || {
|
||||||
|
echo "gitea-api: request failed" >&2; exit 1; }
|
||||||
|
else
|
||||||
|
HTTP_CODE="$(curl -sS -K <(gen_curl_cfg) -o /tmp/gitea-api-response.$$ \
|
||||||
|
-w '%{http_code}' -X "$METHOD" "$URL")" || {
|
||||||
|
echo "gitea-api: request failed" >&2; exit 1; }
|
||||||
|
fi
|
||||||
|
|
||||||
|
cat /tmp/gitea-api-response.$$ 2>/dev/null || true
|
||||||
|
rm -f /tmp/gitea-api-response.$$
|
||||||
|
echo "HTTP $HTTP_CODE" >&2
|
||||||
|
|
||||||
|
case "$HTTP_CODE" in
|
||||||
|
2*) exit 0 ;;
|
||||||
|
*) echo "gitea-api: $METHOD $API_PATH failed (HTTP $HTTP_CODE)" >&2; exit 1 ;;
|
||||||
|
esac
|
||||||
Executable
+233
@@ -0,0 +1,233 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
/**
|
||||||
|
* Mosaic development configuration: bootstrap, validate, resolve.
|
||||||
|
*
|
||||||
|
* Operations:
|
||||||
|
* bootstrap Create the default config ONLY if absent; otherwise validate
|
||||||
|
* the existing file without writing (idempotent).
|
||||||
|
* validate Load and strictly validate; print resolved config on stdout.
|
||||||
|
* env Print shell-safe exports for launcher scripts:
|
||||||
|
* MOSAIC_DATA_ROOT, MOSAIC_PROVIDER, MOSAIC_MODEL.
|
||||||
|
*
|
||||||
|
* Config location: $MOSAIC_CONFIG or ~/.config/mosaic-dev/config.json
|
||||||
|
*
|
||||||
|
* Exit codes:
|
||||||
|
* 0 success
|
||||||
|
* 2 configuration exists but is invalid (never modified by this tool)
|
||||||
|
* 3 configuration is missing for a read operation (validate/env)
|
||||||
|
*
|
||||||
|
* Invariants (docs/plans/2026-09-02_atomic-mosaic-foundation.md):
|
||||||
|
* - Existing configuration is never overwritten.
|
||||||
|
* - Validation failure modifies nothing.
|
||||||
|
* - Secrets are never stored in configuration.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import fs from "node:fs";
|
||||||
|
import os from "node:os";
|
||||||
|
import path from "node:path";
|
||||||
|
import process from "node:process";
|
||||||
|
|
||||||
|
const SUPPORTED_CONFIG_VERSION = 1;
|
||||||
|
const SUPPORTED_ENVIRONMENTS = new Set(["development", "production"]);
|
||||||
|
const SUPPORTED_BACKENDS = new Set(["docker"]);
|
||||||
|
const NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,199}$/;
|
||||||
|
|
||||||
|
function fail(exitCode, message) {
|
||||||
|
process.stderr.write(`mosaic-config: ${message}\n`);
|
||||||
|
process.exit(exitCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
function configPath() {
|
||||||
|
return process.env.MOSAIC_CONFIG
|
||||||
|
? path.resolve(process.env.MOSAIC_CONFIG)
|
||||||
|
: path.join(os.homedir(), ".config", "mosaic-dev", "config.json");
|
||||||
|
}
|
||||||
|
|
||||||
|
function readRaw(file) {
|
||||||
|
let stat;
|
||||||
|
try {
|
||||||
|
stat = fs.lstatSync(file);
|
||||||
|
} catch {
|
||||||
|
return null; // missing
|
||||||
|
}
|
||||||
|
if (!stat.isFile() || stat.isSymbolicLink()) {
|
||||||
|
fail(2, `configuration path must be a regular, non-symbolic-link file: ${file}`);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return fs.readFileSync(file, "utf8");
|
||||||
|
} catch {
|
||||||
|
fail(2, `configuration file is not readable: ${file}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function rejectUnknownKeys(object, allowed, where) {
|
||||||
|
for (const key of Object.keys(object)) {
|
||||||
|
if (!allowed.includes(key)) {
|
||||||
|
fail(2, `unsupported ${where} key: "${key}"`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function isPlainObject(value) {
|
||||||
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateDataRoot(value, file) {
|
||||||
|
if (typeof value !== "string" || value.length === 0) {
|
||||||
|
fail(2, 'execution "dataRoot" must be a non-empty string');
|
||||||
|
}
|
||||||
|
if (value.includes("\0")) {
|
||||||
|
fail(2, 'execution "dataRoot" contains a NUL byte');
|
||||||
|
}
|
||||||
|
if (!path.isAbsolute(value)) {
|
||||||
|
fail(2, `execution "dataRoot" must be an absolute path (got "${value}")`);
|
||||||
|
}
|
||||||
|
const resolved = path.resolve(value);
|
||||||
|
if (resolved !== value) {
|
||||||
|
fail(2, `execution "dataRoot" must be canonical without ".", "..", trailing slashes, or redundant separators (got "${value}")`);
|
||||||
|
}
|
||||||
|
if (resolved === path.parse(resolved).root) {
|
||||||
|
fail(2, 'execution "dataRoot" must not be the filesystem root');
|
||||||
|
}
|
||||||
|
const home = path.resolve(os.homedir());
|
||||||
|
if (resolved === home || isAncestorOf(resolved, home)) {
|
||||||
|
fail(2, `execution "dataRoot" must not be or contain the home directory (${home})`);
|
||||||
|
}
|
||||||
|
const configDir = path.dirname(path.resolve(file));
|
||||||
|
if (resolved === configDir || isAncestorOf(resolved, configDir)) {
|
||||||
|
fail(2, `execution "dataRoot" must not be or contain the configuration directory (${configDir})`);
|
||||||
|
}
|
||||||
|
return resolved;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isAncestorOf(ancestor, candidate) {
|
||||||
|
const rel = path.relative(ancestor, candidate);
|
||||||
|
return rel !== "" && !rel.startsWith("..") && !path.isAbsolute(rel);
|
||||||
|
}
|
||||||
|
|
||||||
|
function validate(document, file) {
|
||||||
|
if (!isPlainObject(document)) {
|
||||||
|
fail(2, "configuration must be a JSON object");
|
||||||
|
}
|
||||||
|
rejectUnknownKeys(
|
||||||
|
document,
|
||||||
|
["configVersion", "environment", "dataRoot", "execution"],
|
||||||
|
"configuration",
|
||||||
|
);
|
||||||
|
|
||||||
|
if (document.configVersion !== SUPPORTED_CONFIG_VERSION) {
|
||||||
|
fail(2, `unsupported configVersion: ${JSON.stringify(document.configVersion)} (supported: ${SUPPORTED_CONFIG_VERSION})`);
|
||||||
|
}
|
||||||
|
if (!SUPPORTED_ENVIRONMENTS.has(document.environment)) {
|
||||||
|
fail(2, `unsupported environment: ${JSON.stringify(document.environment)} (supported: ${[...SUPPORTED_ENVIRONMENTS].join(", ")})`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const dataRoot = validateDataRoot(document.dataRoot, file);
|
||||||
|
|
||||||
|
if (!isPlainObject(document.execution)) {
|
||||||
|
fail(2, '"execution" must be a JSON object');
|
||||||
|
}
|
||||||
|
rejectUnknownKeys(document.execution, ["backend", "provider", "model"], '"execution"');
|
||||||
|
if (!SUPPORTED_BACKENDS.has(document.execution.backend)) {
|
||||||
|
fail(2, `unsupported execution.backend: ${JSON.stringify(document.execution.backend)} (supported: ${[...SUPPORTED_BACKENDS].join(", ")})`);
|
||||||
|
}
|
||||||
|
for (const key of ["provider", "model"]) {
|
||||||
|
const value = document.execution[key];
|
||||||
|
if (typeof value !== "string" || !NAME_PATTERN.test(value)) {
|
||||||
|
fail(2, `execution.${key} must match ${NAME_PATTERN} (got ${JSON.stringify(value)})`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
configVersion: document.configVersion,
|
||||||
|
environment: document.environment,
|
||||||
|
dataRoot,
|
||||||
|
execution: {
|
||||||
|
backend: document.execution.backend,
|
||||||
|
provider: document.execution.provider,
|
||||||
|
model: document.execution.model,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function load(file) {
|
||||||
|
const raw = readRaw(file);
|
||||||
|
if (raw === null) {
|
||||||
|
fail(3, `configuration not found: ${file} (run scripts/bootstrap.sh to create it)`);
|
||||||
|
}
|
||||||
|
let document;
|
||||||
|
try {
|
||||||
|
document = JSON.parse(raw);
|
||||||
|
} catch (error) {
|
||||||
|
fail(2, `configuration is not valid JSON (${file}): ${error.message}`);
|
||||||
|
}
|
||||||
|
return validate(document, file);
|
||||||
|
}
|
||||||
|
|
||||||
|
function shellQuote(value) {
|
||||||
|
return `'${String(value).replaceAll("'", `'\\''`)}'`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const DEFAULT_CONFIG = {
|
||||||
|
configVersion: 1,
|
||||||
|
environment: "development",
|
||||||
|
dataRoot: path.join(os.homedir(), ".mosaic-dev"),
|
||||||
|
execution: {
|
||||||
|
backend: "docker",
|
||||||
|
provider: "zai",
|
||||||
|
model: "glm-5.3-flash",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const operation = process.argv[2];
|
||||||
|
const file = configPath();
|
||||||
|
|
||||||
|
switch (operation) {
|
||||||
|
case "bootstrap": {
|
||||||
|
if (fs.existsSync(file)) {
|
||||||
|
load(file); // validate only; never rewrite
|
||||||
|
process.stderr.write(`mosaic-config: configuration already present, validated without changes: ${file}\n`);
|
||||||
|
process.exit(0);
|
||||||
|
}
|
||||||
|
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||||||
|
let fd;
|
||||||
|
try {
|
||||||
|
// 'wx': creation is exclusive; an existing file is never overwritten.
|
||||||
|
fd = fs.openSync(file, "wx", 0o644);
|
||||||
|
fs.writeFileSync(fd, `${JSON.stringify(DEFAULT_CONFIG, null, 2)}\n`);
|
||||||
|
} catch (error) {
|
||||||
|
if (error.code === "EEXIST") {
|
||||||
|
load(file);
|
||||||
|
process.exit(0);
|
||||||
|
}
|
||||||
|
fail(1, `unable to create configuration: ${error.message}`);
|
||||||
|
} finally {
|
||||||
|
if (fd !== undefined) fs.closeSync(fd);
|
||||||
|
}
|
||||||
|
load(file);
|
||||||
|
process.stderr.write(`mosaic-config: created default configuration: ${file}\n`);
|
||||||
|
process.exit(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
case "validate": {
|
||||||
|
const resolved = load(file);
|
||||||
|
process.stdout.write(`${JSON.stringify(resolved, null, 2)}\n`);
|
||||||
|
process.exit(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
case "env": {
|
||||||
|
const resolved = load(file);
|
||||||
|
process.stdout.write(
|
||||||
|
[
|
||||||
|
`MOSAIC_DATA_ROOT=${shellQuote(resolved.dataRoot)}`,
|
||||||
|
`MOSAIC_PROVIDER=${shellQuote(resolved.execution.provider)}`,
|
||||||
|
`MOSAIC_MODEL=${shellQuote(resolved.execution.model)}`,
|
||||||
|
"",
|
||||||
|
].join("\n"),
|
||||||
|
);
|
||||||
|
process.exit(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
default:
|
||||||
|
fail(1, `unknown operation: ${JSON.stringify(operation ?? "")} (expected bootstrap | validate | env)`);
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user