diff --git a/.dockerignore b/.dockerignore index 98b322b..5f1c4d2 100644 --- a/.dockerignore +++ b/.dockerignore @@ -9,4 +9,5 @@ docker/secrets/ *.tsbuildinfo coverage/ tests/ +scripts/ .DS_Store diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..6dc33fe --- /dev/null +++ b/.env.example @@ -0,0 +1,94 @@ +# GCoordinator v1.1.0 — Example Environment Configuration +# Copy this file to `.env` or run `./scripts/setup.sh` to generate `.env` and +# `docker/secrets/gcoord_master_key.txt` automatically. +# IMPORTANT: Keep `.env` private (`chmod 600 .env`) and never commit it. + +# --------------------------------------------------------------------------- +# Deployment Mode (used by ./scripts/setup.sh, build.sh, up.sh, down.sh, etc.) +# --------------------------------------------------------------------------- +# `lan`: binds ports on GCOORD_LAN_BIND via docker/docker-compose.lan.yml and +# disables the cloudflared sidecar and TRUST_CLOUDFLARE. +# `cloudflare`: exposes no host ports and routes ingress through cloudflared. +GCOORD_DEPLOY_MODE=lan + +# --------------------------------------------------------------------------- +# Resource & Throttling Profile (tuned for 1 vCPU / 1 GB RAM + 2 GB Swap) +# --------------------------------------------------------------------------- +# Runtime throttle profile: `low-resource` | `balanced` | `unthrottled` +# Switch to `balanced` or `unthrottled` on multi-core / higher-RAM hosts. +GCOORD_THROTTLE_MODE=low-resource + +# Docker container RAM ceiling and Node.js V8 heap limit (MB) +GCOORD_MEM_LIMIT=512m +GCOORD_NODE_MAX_OLD_SPACE=384 +GCOORD_PIDS_LIMIT=128 + +# --------------------------------------------------------------------------- +# Network, Ports & LAN Mode +# --------------------------------------------------------------------------- +# Host bind address in LAN mode (`127.0.0.1` recommended behind local Caddy/Nginx, +# or `0.0.0.0` / your WireGuard/LAN IP for direct LAN reachability). +GCOORD_LAN_BIND=127.0.0.1 +GCOORD_HTTP_PORT=3000 +GCOORD_TUNNEL_PORT_RANGE=20000-20020 + +# Set `true` only if you want SSH local/remote TCP tunnels to bind non-loopback +GCOORD_ALLOW_LAN_TUNNELS=false + +# Container internal listen address/port (rarely needs changing) +# PORT=3000 +# HOST=0.0.0.0 + +# --------------------------------------------------------------------------- +# Cloudflare Tunnel & Reverse Proxy Trust +# --------------------------------------------------------------------------- +# Required when GCOORD_DEPLOY_MODE=cloudflare +CLOUDFLARED_TUNNEL_TOKEN= + +# Override proxy header trust (defaults: `true` in Cloudflare mode, `false` in LAN mode) +# TRUST_CLOUDFLARE=true + +# Comma-separated CIDR allowlist of trusted upstream reverse proxies +# TRUSTED_PROXY_CIDRS=172.16.0.0/12,10.0.0.0/8 + +# --------------------------------------------------------------------------- +# Origin-Isolated Reverse Proxy Tunnels (v1.1) +# --------------------------------------------------------------------------- +# Dedicated local port for origin-isolated HTTP/WS reverse-proxy tunnels +# (isolated cookies/storage via /proxy-ticket). Also published by LAN compose. +# GCOORD_PROXY_PORT=3001 + +# Alternative wildcard subdomain base host for origin-isolated proxy tunnels +# GCOORD_PROXY_BASE_DOMAIN=proxy.example.com + +# --------------------------------------------------------------------------- +# Vault, Database & Backup Secrets +# --------------------------------------------------------------------------- +# Primary Docker method mounts `docker/secrets/gcoord_master_key.txt` at +# `/run/secrets/gcoord_master_key` (created with 0600 perms by `./scripts/setup.sh`). +# Non-Docker / local fallback variables: +# GCOORD_MASTER_KEY= +# GCOORD_MASTER_KEY_FILE=/run/secrets/gcoord_master_key + +# Optional 64-hex-char (32-byte) key encrypting TOTP secrets at rest in SQLite +# (auto-generated at `data/db.key` if omitted). +# GCOORD_DB_KEY= + +# Mirror env/secret Vault master key to `data/vault.key` (`0600`) when set `true` +# GCOORD_AUTO_KEYFILE=false + +# Optional passphrase for `gcoord` CLI backup/verify-backup/restore commands +# GCOORD_BACKUP_PASSPHRASE= + +# --------------------------------------------------------------------------- +# Optional WebAuthn, Prometheus & Local Path Overrides +# --------------------------------------------------------------------------- +# Explicit WebAuthn Relying Party ID and allowed origins (for custom proxy domains) +# GCOORD_WEBAUTHN_RP_ID=hub.example.com +# GCOORD_WEBAUTHN_ORIGINS=https://hub.example.com + +# Optional Bearer token override for opt-in Prometheus `GET /metrics` +# GCOORD_METRICS_TOKEN= + +# Persistent state path (set to `/data` inside Docker; defaults to `./data` locally) +# GCOORD_DATA_DIR=./data diff --git a/How/AGENTS.md b/How/AGENTS.md index d6e7f91..e824fae 100644 --- a/How/AGENTS.md +++ b/How/AGENTS.md @@ -25,7 +25,7 @@ All 5 phases of [Plan.md](file:///home/devuser/workspace/GCoordinator/How/Plan.m ```bash export PATH="$HOME/.local/bin:$PATH" ``` -- **Containers**: `docker` CLI is not installed in this dev container; `docker/Dockerfile`, `docker/docker-compose.yml`, and `docker/docker-compose.lan.yml` are deployment definitions. +- **Containers & Docker Helper Scripts**: `docker` CLI is not installed in this dev container; `docker/Dockerfile`, `docker/docker-compose.yml`, and `docker/docker-compose.lan.yml` are deployment definitions configured via `.env` (see `.env.example`) and helper scripts under `scripts/` (`setup.sh`, `build.sh`, `up.sh`, `down.sh`, `logs.sh`, `cli.sh`). ### NPM Scripts (`package.json`) - `npm run typecheck` — `tsc --noEmit` (strict TypeScript with `noUncheckedIndexedAccess: true` and `noImplicitOverride: true`). @@ -74,6 +74,7 @@ node dist/cli/gcoord.js restore [--bundle ] [--data-dir ```text GCoordinator/ +├── .env.example # Environment template for Docker Compose & runtime options ├── How/ │ ├── AGENTS.md # This guide (authoritative for live codebase conventions) │ └── Plan.md # Original Phase 1–5 architecture blueprint @@ -81,6 +82,14 @@ GCoordinator/ │ ├── Dockerfile │ ├── docker-compose.yml │ └── docker-compose.lan.yml +├── scripts/ # Docker Compose setup, build, run, logs & container CLI helpers +│ ├── _compose.sh +│ ├── setup.sh +│ ├── build.sh +│ ├── up.sh +│ ├── down.sh +│ ├── logs.sh +│ └── cli.sh ├── src/ │ ├── cli/ │ │ └── gcoord.ts # status, panic-lock, reset-2fa, reset-password, rotate-key, backup, verify-backup, restore diff --git a/docker/docker-compose.lan.yml b/docker/docker-compose.lan.yml index 2ccd7dc..767ff94 100644 --- a/docker/docker-compose.lan.yml +++ b/docker/docker-compose.lan.yml @@ -1,8 +1,12 @@ services: gcoordinator: environment: - - TRUST_CLOUDFLARE=false + - TRUST_CLOUDFLARE=${TRUST_CLOUDFLARE:-false} - GCOORD_ALLOW_LAN_TUNNELS=${GCOORD_ALLOW_LAN_TUNNELS:-false} ports: - - "${GCOORD_LAN_BIND:-127.0.0.1}:3000:3000" - - "${GCOORD_LAN_BIND:-127.0.0.1}:20000-20020:20000-20020" + - "${GCOORD_LAN_BIND:-127.0.0.1}:${GCOORD_HTTP_PORT:-3000}:3000" + - "${GCOORD_LAN_BIND:-127.0.0.1}:${GCOORD_PROXY_PORT:-3001}:${GCOORD_PROXY_PORT:-3001}" + - "${GCOORD_LAN_BIND:-127.0.0.1}:${GCOORD_TUNNEL_PORT_RANGE:-20000-20020}:${GCOORD_TUNNEL_PORT_RANGE:-20000-20020}" + + cloudflared: + profiles: ["cloudflare"] diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml index 15a1e1f..947a8f7 100644 --- a/docker/docker-compose.yml +++ b/docker/docker-compose.yml @@ -12,7 +12,7 @@ services: security_opt: - no-new-privileges:true mem_limit: ${GCOORD_MEM_LIMIT:-512m} - pids_limit: 128 + pids_limit: ${GCOORD_PIDS_LIMIT:-128} tmpfs: - /tmp:rw,noexec,nosuid,nodev,size=64m environment: @@ -20,8 +20,17 @@ services: - PORT=3000 - HOST=0.0.0.0 - GCOORD_DATA_DIR=/data - - TRUST_CLOUDFLARE=true + - TRUST_CLOUDFLARE=${TRUST_CLOUDFLARE:-true} + - TRUSTED_PROXY_CIDRS=${TRUSTED_PROXY_CIDRS:-} - GCOORD_THROTTLE_MODE=${GCOORD_THROTTLE_MODE:-low-resource} + - GCOORD_ALLOW_LAN_TUNNELS=${GCOORD_ALLOW_LAN_TUNNELS:-false} + - GCOORD_PROXY_PORT=${GCOORD_PROXY_PORT:-} + - GCOORD_PROXY_BASE_DOMAIN=${GCOORD_PROXY_BASE_DOMAIN:-} + - GCOORD_WEBAUTHN_RP_ID=${GCOORD_WEBAUTHN_RP_ID:-} + - GCOORD_WEBAUTHN_ORIGINS=${GCOORD_WEBAUTHN_ORIGINS:-} + - GCOORD_METRICS_TOKEN=${GCOORD_METRICS_TOKEN:-} + - GCOORD_DB_KEY=${GCOORD_DB_KEY:-} + - GCOORD_AUTO_KEYFILE=${GCOORD_AUTO_KEYFILE:-false} - NODE_OPTIONS=--max-old-space-size=${GCOORD_NODE_MAX_OLD_SPACE:-384} secrets: - gcoord_master_key @@ -44,7 +53,7 @@ services: pids_limit: 64 command: tunnel --no-autoupdate run environment: - - TUNNEL_TOKEN=${CLOUDFLARED_TUNNEL_TOKEN} + - TUNNEL_TOKEN=${CLOUDFLARED_TUNNEL_TOKEN:-} depends_on: - gcoordinator networks: diff --git a/scripts/_compose.sh b/scripts/_compose.sh new file mode 100755 index 0000000..c4057f0 --- /dev/null +++ b/scripts/_compose.sh @@ -0,0 +1,175 @@ +#!/usr/bin/env bash +# Shared helpers for GCoordinator Docker Compose wrapper scripts. +# Intended to be sourced, not executed directly. + +if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then + echo "Error: scripts/_compose.sh is a shared helper and should be sourced, not executed directly." >&2 + exit 1 +fi + +SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)" +REPO_ROOT="$(cd -- "$SCRIPT_DIR/.." && pwd -P)" +DOCKER_DIR="$REPO_ROOT/docker" +ENV_FILE="$REPO_ROOT/.env" +ENV_EXAMPLE="$REPO_ROOT/.env.example" +SECRET_DIR="$DOCKER_DIR/secrets" +SECRET_FILE="$SECRET_DIR/gcoord_master_key.txt" +DATA_DIR="$REPO_ROOT/data" + +DRY_RUN="${DRY_RUN:-0}" +COMPOSE_CMD=() +COMPOSE_ARGS=() + +log_info() { + printf '[gcoord] %s\n' "$*" +} + +log_warn() { + printf '[gcoord] WARNING: %s\n' "$*" >&2 +} + +die() { + printf '[gcoord] ERROR: %s\n' "$*" >&2 + exit 1 +} + +# Safely read KEY from .env without executing arbitrary shell code. +env_get() { + local key="$1" + local file="${2:-$ENV_FILE}" + [[ -f "$file" && ! -L "$file" ]] || return 1 + + local line val="" found=0 + while IFS= read -r line || [[ -n "$line" ]]; do + line="${line%$'\r'}" + [[ "$line" =~ ^[[:space:]]*# ]] && continue + [[ "$line" =~ ^[[:space:]]*$ ]] && continue + if [[ "$line" =~ ^[[:space:]]*(export[[:space:]]+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$ ]]; then + if [[ "${BASH_REMATCH[2]}" == "$key" ]]; then + val="${BASH_REMATCH[3]}" + found=1 + fi + fi + done <"$file" + + [[ "$found" -eq 1 ]] || return 1 + + # Strip leading/trailing whitespace, then matching outer quotes if present. + val="${val#"${val%%[![:space:]]*}"}" + val="${val%"${val##*[![:space:]]}"}" + if [[ "${#val}" -ge 2 ]]; then + if [[ "$val" == \"*\" && "$val" == *\" ]]; then + val="${val:1:${#val}-2}" + elif [[ "$val" == \'*\' && "$val" == *\' ]]; then + val="${val:1:${#val}-2}" + fi + fi + printf '%s' "$val" +} + +# Resolve effective setting: process env -> .env -> fallback. +env_effective() { + local key="$1" + local fallback="${2:-}" + local val="" + + if [[ -n "${!key:-}" ]]; then + printf '%s' "${!key}" + return 0 + fi + if val="$(env_get "$key" 2>/dev/null)" && [[ -n "$val" ]]; then + printf '%s' "$val" + return 0 + fi + printf '%s' "$fallback" +} + +detect_compose() { + if command -v docker >/dev/null 2>&1 && docker compose version >/dev/null 2>&1; then + COMPOSE_CMD=(docker compose) + return 0 + fi + if command -v docker-compose >/dev/null 2>&1; then + COMPOSE_CMD=(docker-compose) + return 0 + fi + if [[ "$DRY_RUN" == "1" ]]; then + COMPOSE_CMD=(docker compose) + return 0 + fi + die "Neither 'docker compose' (v2) nor 'docker-compose' (v1) is installed on PATH." +} + +validate_mode() { + local mode="$1" + case "$mode" in + lan|cloudflare) + return 0 + ;; + *) + die "Invalid deployment mode '$mode' (expected 'lan' or 'cloudflare')." + ;; + esac +} + +resolve_mode() { + local explicit="${1:-}" + if [[ -n "$explicit" ]]; then + validate_mode "$explicit" + printf '%s' "$explicit" + return 0 + fi + + local from_env="" + if [[ -n "${GCOORD_DEPLOY_MODE:-}" ]]; then + from_env="$GCOORD_DEPLOY_MODE" + elif from_env="$(env_get GCOORD_DEPLOY_MODE 2>/dev/null)" && [[ -n "$from_env" ]]; then + : + else + from_env="" + fi + + if [[ -n "$from_env" ]]; then + validate_mode "$from_env" + printf '%s' "$from_env" + return 0 + fi + + local cf_token="" + cf_token="$(env_effective CLOUDFLARED_TUNNEL_TOKEN "")" + if [[ -n "$cf_token" ]]; then + printf 'cloudflare' + else + printf 'lan' + fi +} + +build_compose_args() { + local mode="$1" + validate_mode "$mode" + + COMPOSE_ARGS=() + if [[ -f "$ENV_FILE" && ! -L "$ENV_FILE" ]]; then + COMPOSE_ARGS+=(--env-file "$ENV_FILE") + fi + COMPOSE_ARGS+=(-f "$DOCKER_DIR/docker-compose.yml") + if [[ "$mode" == "lan" ]]; then + COMPOSE_ARGS+=(-f "$DOCKER_DIR/docker-compose.lan.yml") + fi +} + +run_compose() { + local mode="$1" + shift + detect_compose + build_compose_args "$mode" + + if [[ "$DRY_RUN" == "1" ]]; then + printf '[dry-run]' + printf ' %q' "${COMPOSE_CMD[@]}" "${COMPOSE_ARGS[@]}" "$@" + printf '\n' + return 0 + fi + + "${COMPOSE_CMD[@]}" "${COMPOSE_ARGS[@]}" "$@" +} diff --git a/scripts/build.sh b/scripts/build.sh new file mode 100755 index 0000000..854767c --- /dev/null +++ b/scripts/build.sh @@ -0,0 +1,82 @@ +#!/usr/bin/env bash +set -euo pipefail + +# shellcheck source=scripts/_compose.sh +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)/_compose.sh" + +usage() { + cat <<'EOF' +Usage: ./scripts/build.sh [options] [-- ] + +Build the GCoordinator Docker image using BuildKit and compose configuration. + +Options: + --lan Use LAN compose override (default unless GCOORD_DEPLOY_MODE=cloudflare) + --cloudflare Use Cloudflare Tunnel compose configuration + --mode Explicitly select deployment mode + --no-cache Pass --no-cache to docker compose build + --pull Pass --pull to docker compose build + --dry-run Print the compose command without executing it + -h, --help Show this help message +EOF +} + +REQ_MODE="" +BUILD_FLAGS=() + +while [[ $# -gt 0 ]]; do + case "$1" in + --lan) + REQ_MODE="lan" + shift + ;; + --cloudflare) + REQ_MODE="cloudflare" + shift + ;; + --mode) + [[ $# -ge 2 ]] || die "--mode requires an argument." + REQ_MODE="$2" + shift 2 + ;; + --mode=*) + REQ_MODE="${1#*=}" + shift + ;; + --no-cache|--pull) + BUILD_FLAGS+=("$1") + shift + ;; + --dry-run) + DRY_RUN=1 + shift + ;; + -h|--help) + usage + exit 0 + ;; + --) + shift + BUILD_FLAGS+=("$@") + break + ;; + *) + die "Unknown option: $1 (pass extra compose build flags after '--', or run --help)" + ;; + esac +done + +MODE="$(resolve_mode "$REQ_MODE")" + +if [[ -r /proc/meminfo ]]; then + mem_kb="$(awk '/^MemTotal:/ {print $2}' /proc/meminfo 2>/dev/null || echo 0)" + swap_kb="$(awk '/^SwapTotal:/ {print $2}' /proc/meminfo 2>/dev/null || echo 0)" + if [[ "$mem_kb" =~ ^[0-9]+$ && "$swap_kb" =~ ^[0-9]+$ ]] && [[ "$mem_kb" -lt 1500000 && "$swap_kb" -lt 1000000 ]]; then + log_warn "Low RAM (~$((mem_kb / 1024)) MB) and low swap (~$((swap_kb / 1024)) MB) detected; Docker image compilation may need >= 1-2 GB swap." + fi +fi + +log_info "Building GCoordinator image (mode=$MODE)..." +export DOCKER_BUILDKIT=1 +export COMPOSE_DOCKER_CLI_BUILD=1 +run_compose "$MODE" build "${BUILD_FLAGS[@]}" gcoordinator diff --git a/scripts/cli.sh b/scripts/cli.sh new file mode 100755 index 0000000..af04cff --- /dev/null +++ b/scripts/cli.sh @@ -0,0 +1,95 @@ +#!/usr/bin/env bash +set -euo pipefail + +# shellcheck source=scripts/_compose.sh +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)/_compose.sh" + +usage() { + cat <<'EOF' +Usage: ./scripts/cli.sh [wrapper options] + +Run GCoordinator's CLI (`dist/cli/gcoord.js`) inside the `gcoordinator` container. +Uses `docker compose exec` if running, otherwise `docker compose run --rm --no-deps`. + +Wrapper options (must appear before the gcoord subcommand): + --lan Use LAN compose configuration + --cloudflare Use Cloudflare compose configuration + --mode Explicitly select deployment mode + --dry-run Print the compose command without executing it + -h, --help Show this help message + +Examples: + ./scripts/cli.sh status --json + ./scripts/cli.sh panic-lock + ./scripts/cli.sh reset-2fa --disable + ./scripts/cli.sh backup --out /data/manual-backup.gcoord.enc +EOF +} + +REQ_MODE="" + +while [[ $# -gt 0 ]]; do + case "$1" in + --lan) + REQ_MODE="lan" + shift + ;; + --cloudflare) + REQ_MODE="cloudflare" + shift + ;; + --mode) + [[ $# -ge 2 ]] || die "--mode requires an argument." + REQ_MODE="$2" + shift 2 + ;; + --mode=*) + REQ_MODE="${1#*=}" + shift + ;; + --dry-run) + DRY_RUN=1 + shift + ;; + -h|--help) + usage + exit 0 + ;; + --) + shift + break + ;; + *) + break + ;; + esac +done + +if [[ $# -eq 0 ]]; then + usage + exit 1 +fi + +MODE="$(resolve_mode "$REQ_MODE")" +detect_compose +build_compose_args "$MODE" + +container_id="" +is_running="false" +if [[ "$DRY_RUN" != "1" ]] && command -v docker >/dev/null 2>&1; then + container_id="$("${COMPOSE_CMD[@]}" "${COMPOSE_ARGS[@]}" ps -q gcoordinator 2>/dev/null || true)" + if [[ -n "$container_id" ]]; then + is_running="$(docker inspect -f '{{.State.Running}}' "$container_id" 2>/dev/null || echo false)" + fi +fi + +tty_args=() +if [[ ! -t 0 ]]; then + tty_args+=(-T) +fi + +if [[ "$is_running" == "true" ]]; then + run_compose "$MODE" exec "${tty_args[@]}" gcoordinator node dist/cli/gcoord.js "$@" +else + run_compose "$MODE" run --rm --no-deps "${tty_args[@]}" gcoordinator node dist/cli/gcoord.js "$@" +fi diff --git a/scripts/down.sh b/scripts/down.sh new file mode 100755 index 0000000..79e3d48 --- /dev/null +++ b/scripts/down.sh @@ -0,0 +1,65 @@ +#!/usr/bin/env bash +set -euo pipefail + +# shellcheck source=scripts/_compose.sh +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)/_compose.sh" + +usage() { + cat <<'EOF' +Usage: ./scripts/down.sh [options] [-- ] + +Stop and remove GCoordinator Docker Compose containers (preserves ./data and secrets). + +Options: + --lan Target LAN compose stack + --cloudflare Target Cloudflare compose stack + --mode Explicitly select deployment mode + --dry-run Print the compose command without executing it + -h, --help Show this help message +EOF +} + +REQ_MODE="" +EXTRA_ARGS=() + +while [[ $# -gt 0 ]]; do + case "$1" in + --lan) + REQ_MODE="lan" + shift + ;; + --cloudflare) + REQ_MODE="cloudflare" + shift + ;; + --mode) + [[ $# -ge 2 ]] || die "--mode requires an argument." + REQ_MODE="$2" + shift 2 + ;; + --mode=*) + REQ_MODE="${1#*=}" + shift + ;; + --dry-run) + DRY_RUN=1 + shift + ;; + -h|--help) + usage + exit 0 + ;; + --) + shift + EXTRA_ARGS+=("$@") + break + ;; + *) + die "Unknown option: $1 (pass extra compose flags after '--', or run --help)" + ;; + esac +done + +MODE="$(resolve_mode "$REQ_MODE")" +log_info "Stopping GCoordinator stack (mode=$MODE)..." +run_compose "$MODE" down --remove-orphans "${EXTRA_ARGS[@]}" diff --git a/scripts/logs.sh b/scripts/logs.sh new file mode 100755 index 0000000..f83f3aa --- /dev/null +++ b/scripts/logs.sh @@ -0,0 +1,95 @@ +#!/usr/bin/env bash +set -euo pipefail + +# shellcheck source=scripts/_compose.sh +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)/_compose.sh" + +usage() { + cat <<'EOF' +Usage: ./scripts/logs.sh [options] [service...] + +Stream or view logs from GCoordinator Docker Compose services. + +Options: + --lan Use LAN compose configuration + --cloudflare Use Cloudflare compose configuration + --mode Explicitly select deployment mode + -n, --tail Number of historical log lines to show (default: 100) + --no-follow Print recent logs and exit without following + --dry-run Print the compose command without executing it + -h, --help Show this help message +EOF +} + +REQ_MODE="" +TAIL_LINES="100" +FOLLOW=1 +SERVICES=() + +while [[ $# -gt 0 ]]; do + case "$1" in + --lan) + REQ_MODE="lan" + shift + ;; + --cloudflare) + REQ_MODE="cloudflare" + shift + ;; + --mode) + [[ $# -ge 2 ]] || die "--mode requires an argument." + REQ_MODE="$2" + shift 2 + ;; + --mode=*) + REQ_MODE="${1#*=}" + shift + ;; + -n|--tail) + [[ $# -ge 2 ]] || die "$1 requires a number." + TAIL_LINES="$2" + shift 2 + ;; + --tail=*) + TAIL_LINES="${1#*=}" + shift + ;; + --no-follow) + FOLLOW=0 + shift + ;; + --dry-run) + DRY_RUN=1 + shift + ;; + -h|--help) + usage + exit 0 + ;; + --) + shift + SERVICES+=("$@") + break + ;; + -*) + die "Unknown option: $1 (run with --help)" + ;; + *) + SERVICES+=("$1") + shift + ;; + esac +done + +[[ "$TAIL_LINES" =~ ^[0-9]+$ || "$TAIL_LINES" == "all" ]] || die "Invalid --tail value '$TAIL_LINES'." + +MODE="$(resolve_mode "$REQ_MODE")" +LOG_ARGS=(logs --tail "$TAIL_LINES") +if [[ "$FOLLOW" -eq 1 ]]; then + LOG_ARGS+=(-f) +fi +if [[ ${#SERVICES[@]} -gt 0 ]]; then + LOG_ARGS+=("${SERVICES[@]}") +fi + +run_compose "$MODE" "${LOG_ARGS[@]}" diff --git a/scripts/setup.sh b/scripts/setup.sh new file mode 100755 index 0000000..929d29c --- /dev/null +++ b/scripts/setup.sh @@ -0,0 +1,196 @@ +#!/usr/bin/env bash +set -euo pipefail + +# shellcheck source=scripts/_compose.sh +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)/_compose.sh" + +usage() { + cat <<'EOF' +Usage: ./scripts/setup.sh [options] + +Initialize `.env`, generate `docker/secrets/gcoord_master_key.txt` (if absent), +and prepare the persistent `data/` directory with secure permissions. + +Options: + --mode Set GCOORD_DEPLOY_MODE in `.env` + --throttle + Set GCOORD_THROTTLE_MODE in `.env` + --force-env Overwrite `.env` from `.env.example` + -h, --help Show this help message +EOF +} + +REQ_MODE="" +REQ_THROTTLE="" +FORCE_ENV=0 + +while [[ $# -gt 0 ]]; do + case "$1" in + --mode) + [[ $# -ge 2 ]] || die "--mode requires an argument ('lan' or 'cloudflare')." + REQ_MODE="$2" + validate_mode "$REQ_MODE" + shift 2 + ;; + --mode=*) + REQ_MODE="${1#*=}" + validate_mode "$REQ_MODE" + shift + ;; + --lan) + REQ_MODE="lan" + shift + ;; + --cloudflare) + REQ_MODE="cloudflare" + shift + ;; + --throttle) + [[ $# -ge 2 ]] || die "--throttle requires 'low-resource', 'balanced', or 'unthrottled'." + REQ_THROTTLE="$2" + shift 2 + ;; + --throttle=*) + REQ_THROTTLE="${1#*=}" + shift + ;; + --force-env) + FORCE_ENV=1 + shift + ;; + -h|--help) + usage + exit 0 + ;; + *) + die "Unknown option: $1 (run with --help)" + ;; + esac +done + +if [[ -n "$REQ_THROTTLE" ]]; then + case "$REQ_THROTTLE" in + low-resource|balanced|unthrottled) ;; + *) die "Invalid --throttle value '$REQ_THROTTLE' (expected low-resource, balanced, or unthrottled)." ;; + esac +fi + +[[ -f "$ENV_EXAMPLE" && ! -L "$ENV_EXAMPLE" ]] || die "Missing template file: $ENV_EXAMPLE" +[[ ! -L "$ENV_FILE" ]] || die "Refusing to operate on symlinked .env: $ENV_FILE" +[[ ! -L "$SECRET_FILE" ]] || die "Refusing to operate on symlinked secret file: $SECRET_FILE" +[[ ! -L "$DATA_DIR" ]] || die "Refusing to operate on symlinked data dir: $DATA_DIR" + +set_env_var() { + local file="$1" + local key="$2" + local val="$3" + local tmp_file + tmp_file="$(mktemp "${file}.tmp.XXXXXX")" + chmod 0600 "$tmp_file" + TARGET_KEY="$key" TARGET_VAL="$val" awk ' + BEGIN { updated = 0 } + { + if ($0 ~ "^[[:space:]]*" ENVIRON["TARGET_KEY"] "=") { + print ENVIRON["TARGET_KEY"] "=" ENVIRON["TARGET_VAL"] + updated = 1 + } else { + print $0 + } + } + END { + if (!updated) { + print ENVIRON["TARGET_KEY"] "=" ENVIRON["TARGET_VAL"] + } + } + ' "$file" >"$tmp_file" + mv -f "$tmp_file" "$file" + chmod 0600 "$file" +} + +generate_hex_key() { + if command -v openssl >/dev/null 2>&1; then + openssl rand -hex 32 + return 0 + fi + if command -v node >/dev/null 2>&1; then + node -e "process.stdout.write(require('crypto').randomBytes(32).toString('hex') + '\n')" + return 0 + fi + if command -v python3 >/dev/null 2>&1; then + python3 -c "import secrets; print(secrets.token_hex(32))" + return 0 + fi + if [[ -r /dev/urandom ]]; then + od -An -tx1 -N32 /dev/urandom | tr -d ' \n' + printf '\n' + return 0 + fi + die "Unable to generate random master key (need openssl, node, python3, or /dev/urandom)." +} + +if [[ ! -f "$ENV_FILE" || "$FORCE_ENV" -eq 1 ]]; then + tmp_env="$(mktemp "${ENV_FILE}.tmp.XXXXXX")" + chmod 0600 "$tmp_env" + cp "$ENV_EXAMPLE" "$tmp_env" + chmod 0600 "$tmp_env" + mv -f "$tmp_env" "$ENV_FILE" + chmod 0600 "$ENV_FILE" + log_info "Created $ENV_FILE (0600) from .env.example." +else + chmod 0600 "$ENV_FILE" || true + log_info "Keeping existing $ENV_FILE (use --force-env to reset from .env.example)." +fi + +if [[ -n "$REQ_MODE" ]]; then + set_env_var "$ENV_FILE" "GCOORD_DEPLOY_MODE" "$REQ_MODE" + log_info "Set GCOORD_DEPLOY_MODE=$REQ_MODE in .env." +fi + +if [[ -n "$REQ_THROTTLE" ]]; then + set_env_var "$ENV_FILE" "GCOORD_THROTTLE_MODE" "$REQ_THROTTLE" + log_info "Set GCOORD_THROTTLE_MODE=$REQ_THROTTLE in .env." +fi + +mkdir -p -m 0700 "$SECRET_DIR" +chmod 0700 "$SECRET_DIR" + +if [[ -s "$SECRET_FILE" ]]; then + chmod 0600 "$SECRET_FILE" || true + log_info "Keeping existing Vault master key at $SECRET_FILE (0600)." +else + key_hex="$(generate_hex_key | tr -d '[:space:]')" + [[ "$key_hex" =~ ^[0-9a-fA-F]{64}$ ]] || die "Generated master key has unexpected format." + tmp_key="$(mktemp "${SECRET_FILE}.tmp.XXXXXX")" + chmod 0600 "$tmp_key" + printf '%s\n' "$key_hex" >"$tmp_key" + mv -f "$tmp_key" "$SECRET_FILE" + chmod 0600 "$SECRET_FILE" + log_info "Generated new 256-bit Vault master key at $SECRET_FILE (0600)." + log_warn "Back up $SECRET_FILE securely offline; losing both the master key and backups makes vault.enc unrecoverable." +fi + +mkdir -p -m 0700 "$DATA_DIR" +chmod 0700 "$DATA_DIR" +cur_uid="$(id -u)" +if [[ "$cur_uid" -eq 0 ]]; then + chown 1000:1000 "$DATA_DIR" + log_info "Prepared $DATA_DIR owned by 1000:1000 (0700)." +elif [[ "$cur_uid" -ne 1000 ]]; then + log_info "Prepared $DATA_DIR (0700)." + log_warn "Container runs as UID:GID 1000:1000, while your host UID is $cur_uid. If GCoordinator fails with EACCES on /data, run: sudo chown -R 1000:1000 \"$DATA_DIR\"" +else + log_info "Prepared $DATA_DIR (0700, UID 1000)." +fi + +effective_mode="$(resolve_mode "$REQ_MODE")" +effective_throttle="$(env_effective GCOORD_THROTTLE_MODE low-resource)" + +printf '\nSetup complete (mode=%s, throttle=%s).\n' "$effective_mode" "$effective_throttle" +printf 'Next steps:\n' +if [[ "$effective_mode" == "cloudflare" ]]; then + printf ' 1. Set CLOUDFLARED_TUNNEL_TOKEN in %s\n' "$ENV_FILE" + printf ' 2. ./scripts/build.sh --cloudflare && ./scripts/up.sh --cloudflare\n' +else + printf ' 1. Review %s (GCOORD_LAN_BIND, ports, GCOORD_PROXY_PORT, GCOORD_THROTTLE_MODE)\n' "$ENV_FILE" + printf ' 2. ./scripts/build.sh && ./scripts/up.sh\n' +fi diff --git a/scripts/up.sh b/scripts/up.sh new file mode 100755 index 0000000..9b6609b --- /dev/null +++ b/scripts/up.sh @@ -0,0 +1,111 @@ +#!/usr/bin/env bash +set -euo pipefail + +# shellcheck source=scripts/_compose.sh +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)/_compose.sh" + +usage() { + cat <<'EOF' +Usage: ./scripts/up.sh [options] + +Start GCoordinator in the background with pre-flight secret/config checks. + +Options: + --lan Start with LAN port bindings (default unless cloudflare) + --cloudflare Start with cloudflared ingress sidecar + --mode Explicitly select deployment mode + --build Rebuild the image before starting containers + --logs Tail service logs after starting containers + --dry-run Print compose commands without executing them + -h, --help Show this help message +EOF +} + +REQ_MODE="" +DO_BUILD=0 +FOLLOW_LOGS=0 + +while [[ $# -gt 0 ]]; do + case "$1" in + --lan) + REQ_MODE="lan" + shift + ;; + --cloudflare) + REQ_MODE="cloudflare" + shift + ;; + --mode) + [[ $# -ge 2 ]] || die "--mode requires an argument." + REQ_MODE="$2" + shift 2 + ;; + --mode=*) + REQ_MODE="${1#*=}" + shift + ;; + --build) + DO_BUILD=1 + shift + ;; + --logs) + FOLLOW_LOGS=1 + shift + ;; + --dry-run) + DRY_RUN=1 + shift + ;; + -h|--help) + usage + exit 0 + ;; + *) + die "Unknown option: $1 (run with --help)" + ;; + esac +done + +MODE="$(resolve_mode "$REQ_MODE")" + +if [[ ! -f "$SECRET_FILE" || -L "$SECRET_FILE" || ! -s "$SECRET_FILE" ]]; then + die "Missing or invalid Vault master key at $SECRET_FILE. Run ./scripts/setup.sh first." +fi + +[[ ! -L "$DATA_DIR" ]] || die "Refusing symlinked data directory: $DATA_DIR" +mkdir -p -m 0700 "$DATA_DIR" + +if [[ "$MODE" == "cloudflare" ]]; then + cf_token="$(env_effective CLOUDFLARED_TUNNEL_TOKEN "")" + if [[ -z "$cf_token" ]]; then + die "CLOUDFLARED_TUNNEL_TOKEN is required when mode=cloudflare. Set it in $ENV_FILE or switch to --lan." + fi +fi + +UP_ARGS=(up -d --remove-orphans) +if [[ "$DO_BUILD" -eq 1 ]]; then + UP_ARGS+=(--build) +fi + +log_info "Starting GCoordinator stack (mode=$MODE)..." +run_compose "$MODE" "${UP_ARGS[@]}" + +if [[ "$DRY_RUN" != "1" ]]; then + run_compose "$MODE" ps +fi + +if [[ "$MODE" == "lan" ]]; then + lan_bind="$(env_effective GCOORD_LAN_BIND 127.0.0.1)" + http_port="$(env_effective GCOORD_HTTP_PORT 3000)" + proxy_port="$(env_effective GCOORD_PROXY_PORT "")" + log_info "UI listening on http://${lan_bind}:${http_port}" + if [[ -n "$proxy_port" ]]; then + log_info "Isolated proxy origin port configured on ${lan_bind}:${proxy_port}" + fi +else + log_info "Ingress routed privately via cloudflared tunnel (no host ports exposed)." +fi + +if [[ "$FOLLOW_LOGS" -eq 1 ]]; then + exec "$SCRIPT_DIR/logs.sh" --mode "$MODE" +fi