diff --git a/.env.example b/.env.example index c8e6569a..5bc3d226 100644 --- a/.env.example +++ b/.env.example @@ -74,8 +74,11 @@ DEBUG=false # ============================================ # Authentication (Better Auth) # ============================================ -# AUTH_SECRET is required - generate with: openssl rand -base64 32 -AUTH_SECRET=CHANGE_ME_GENERATE_WITH_openssl_rand_base64_32 +# Docker: optional. When unset, the container generates one on first start and +# persists it in the data volume (/app/data/.auth-secret). +# Outside Docker: required in production - generate with: openssl rand -base64 32 +# Changing it later invalidates sessions and stored encrypted credentials. +# AUTH_SECRET= # Trusted origins for authentication (comma-separated) # Add your server's external URL when accessing remotely diff --git a/README.md b/README.md index 18df6d99..7b6a6e03 100644 --- a/README.md +++ b/README.md @@ -44,16 +44,25 @@ OpenCode Manager requires **OpenCode 2.x at 2.0.15 or newer** (bundled 2.0.15); ## Quick Start +Requires Docker with Compose v2. + ```bash -git clone https://github.com/chriswritescode-dev/opencode-manager.git -cd opencode-manager -cp .env.example .env -echo "AUTH_SECRET=$(openssl rand -base64 32)" >> .env -docker-compose up -d -# Open http://localhost:5003 +curl -fsSL https://opencodemanager.app/install | sh ``` -On first launch, you'll be prompted to create an admin account. That's it! +The installer pulls the published image into `~/opencode-manager`, starts it, and opens on http://localhost:5003. It asks before sharing anything from your machine: importing an existing OpenCode config and chat history, sharing a folder of repositories, and allowing sign-in from your phone on the same network. Re-run it to update. + +Prefer to run Compose yourself with the published image: + +```bash +mkdir opencode-manager && cd opencode-manager +curl -fsSL https://raw.githubusercontent.com/chriswritescode-dev/opencode-manager/main/docker-compose.release.yml -o docker-compose.yml +docker compose up -d +``` + +Or build from source: in a clone of this repository, `docker-compose.yml` builds the image from the checkout, so `docker compose up -d --build` and `./scripts/docker-upgrade.sh` work as before. + +On first launch, you'll be prompted to create an admin account. `AUTH_SECRET` is generated on first start and kept in the data volume when you don't set one. For local development setup, see the [Development Guide](https://opencodemanager.app/docs/development/setup). @@ -101,7 +110,7 @@ See the [Development Guide](https://opencodemanager.app/docs/development/setup) ## Configuration ```bash -# Required for production +# Generated automatically in Docker; required for production outside Docker AUTH_SECRET=your-secure-random-secret # Generate with: openssl rand -base64 32 # Pre-configured admin (optional) diff --git a/backend/test/helpers/shell-function.ts b/backend/test/helpers/shell-function.ts new file mode 100644 index 00000000..35f3b21b --- /dev/null +++ b/backend/test/helpers/shell-function.ts @@ -0,0 +1,11 @@ +import { readFileSync } from 'fs' + +/** + * Returns the source of a top-level `name() { ... }` function from a shell script so tests can run it in isolation. + * Throws when the script does not define the function. + */ +export function extractShellFunction(scriptPath: string, name: string): string { + const match = readFileSync(scriptPath, 'utf-8').match(new RegExp(`^${name}\\(\\) \\{\\n[\\s\\S]*?\\n\\}`, 'm')) + if (!match) throw new Error(`${name}() not found in ${scriptPath}`) + return match[0] +} diff --git a/backend/test/scripts/docker-config.test.ts b/backend/test/scripts/docker-config.test.ts index 13cf317c..20cd381b 100644 --- a/backend/test/scripts/docker-config.test.ts +++ b/backend/test/scripts/docker-config.test.ts @@ -239,6 +239,32 @@ describe('workspace ownership configuration', () => { }) }) +describe('compose image source', () => { + const RELEASE_IMAGE_LINE = ' image: ghcr.io/chriswritescode-dev/opencode-manager:latest\n' + const BUILD_BLOCK_RE = /^ {4}build:\n(?: {6}.*\n)+/m + const withoutComments = (source: string) => source.replace(/^#.*\n/gm, '').replace(/^\n+/, '') + + it('builds docker-compose.yml from the checkout so git pull and rebuild keep working', () => { + const compose = read(composePath) + expect(compose).toMatch(/^ {4}build:\n {6}context: \.\n {6}dockerfile: Dockerfile\n/m) + expect(compose).not.toMatch(/^ {4}image:/m) + }) + + it('keeps docker-compose.release.yml identical to docker-compose.yml apart from its project name and pulling the published image', () => { + const compose = read(composePath) + const release = withoutComments(read(join(repoRoot, 'docker-compose.release.yml'))) + const workflow = read(join(repoRoot, '.github/workflows/docker-build.yml')) + expect(workflow).toContain('images: ghcr.io/${{ github.repository }}') + expect(release).not.toMatch(/^ {4}build:/m) + expect(release).toBe(`name: ocm\n\n${compose.replace(BUILD_BLOCK_RE, RELEASE_IMAGE_LINE)}`) + }) + + it('lets the entrypoint generate AUTH_SECRET when .env does not set one', () => { + expect(read(composePath)).toContain('- AUTH_SECRET=${AUTH_SECRET:-}') + expect(read(envExamplePath)).not.toMatch(/^AUTH_SECRET=/m) + }) +}) + describe('docker lifecycle scripts', () => { it('keeps docker:down non-destructive and docker:reset destructive', () => { const pkg = read(join(repoRoot, 'package.json')) diff --git a/backend/test/scripts/docker-entrypoint.test.ts b/backend/test/scripts/docker-entrypoint.test.ts index 089e3740..ec7dcb18 100644 --- a/backend/test/scripts/docker-entrypoint.test.ts +++ b/backend/test/scripts/docker-entrypoint.test.ts @@ -1,9 +1,10 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest' import { spawnSync } from 'child_process' -import { mkdirSync, writeFileSync, rmSync, chmodSync, existsSync, readFileSync } from 'fs' +import { mkdirSync, writeFileSync, rmSync, chmodSync, existsSync, readFileSync, statSync } from 'fs' import { join } from 'path' import { tmpdir } from 'os' import { repoRoot } from '../helpers/repo-root' +import { extractShellFunction as extractEntrypointFunction } from '../helpers/shell-function' const entrypointPath = join(repoRoot, 'scripts/docker-entrypoint.sh') @@ -16,12 +17,7 @@ const writeStub = (name: string, body: string) => { chmodSync(file, 0o755) } -const extractShellFunction = (name: string) => { - const entrypoint = readFileSync(entrypointPath, 'utf-8') - const match = entrypoint.match(new RegExp(`^${name}\\(\\) \\{\\n[\\s\\S]*?\\n\\}`, 'm')) - if (!match) throw new Error(`${name}() not found in docker-entrypoint.sh`) - return match[0] -} +const extractShellFunction = (name: string) => extractEntrypointFunction(entrypointPath, name) const extractSupportedFloor = () => { const match = readFileSync(entrypointPath, 'utf-8').match(/^OPENCODE_SUPPORTED_FLOOR="[^"]+"$/m) @@ -169,6 +165,56 @@ describe('grant_kvm_access', () => { }) }) +describe('ensure_auth_secret', () => { + const runEnsureAuthSecret = (secretFile: string, env: Record = {}) => { + const scriptPath = join(stubDir, 'test.sh') + writeFileSync( + scriptPath, + `set -e\n${extractShellFunction('ensure_auth_secret')}\nensure_auth_secret ${JSON.stringify(secretFile)}\nprintf 'SECRET=%s\\n' "$AUTH_SECRET"\n`, + ) + const baseEnv = { ...process.env } + delete baseEnv.AUTH_SECRET + return spawnSync('bash', [scriptPath], { encoding: 'utf-8', env: { ...baseEnv, ...env } }) + } + const exportedSecret = (stdout: string) => stdout.match(/^SECRET=(.*)$/m)?.[1] ?? '' + + it('generates, persists, and exports a private secret when AUTH_SECRET is unset', () => { + const secretFile = join(stubDir, 'data', '.auth-secret') + const res = runEnsureAuthSecret(secretFile) + expect(res.status).toBe(0) + expect(res.stdout).toContain(`Generated AUTH_SECRET and saved it to ${secretFile}`) + const secret = exportedSecret(res.stdout) + expect(Buffer.from(secret, 'base64')).toHaveLength(32) + expect(readFileSync(secretFile, 'utf-8').trim()).toBe(secret) + expect(statSync(secretFile).mode & 0o777).toBe(0o600) + }) + + it('reuses the persisted secret on later starts', () => { + const secretFile = join(stubDir, 'data', '.auth-secret') + const first = exportedSecret(runEnsureAuthSecret(secretFile).stdout) + const second = runEnsureAuthSecret(secretFile) + expect(second.status).toBe(0) + expect(second.stdout).not.toContain('Generated AUTH_SECRET') + expect(exportedSecret(second.stdout)).toBe(first) + }) + + it('keeps an explicit AUTH_SECRET and writes nothing', () => { + const secretFile = join(stubDir, 'data', '.auth-secret') + const res = runEnsureAuthSecret(secretFile, { AUTH_SECRET: 'explicit-secret' }) + expect(res.status).toBe(0) + expect(exportedSecret(res.stdout)).toBe('explicit-secret') + expect(existsSync(secretFile)).toBe(false) + }) + + it('fails when the secret file cannot be written', () => { + const blocker = join(stubDir, 'not-a-dir') + writeFileSync(blocker, '') + const res = runEnsureAuthSecret(join(blocker, '.auth-secret')) + expect(res.status).not.toBe(0) + expect(res.stdout).not.toContain('SECRET=') + }) +}) + const extractOpenCodeInstallSection = () => { const entrypoint = readFileSync(entrypointPath, 'utf-8') const startMarker = 'echo "Checking OpenCode installation..."' diff --git a/backend/test/scripts/install.test.ts b/backend/test/scripts/install.test.ts new file mode 100644 index 00000000..a89c0e2e --- /dev/null +++ b/backend/test/scripts/install.test.ts @@ -0,0 +1,245 @@ +import { describe, it, expect, beforeEach, afterEach } from 'vitest' +import { spawn, spawnSync } from 'child_process' +import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs' +import { join } from 'path' +import { tmpdir } from 'os' +import { repoRoot } from '../helpers/repo-root' +import { extractShellFunction } from '../helpers/shell-function' + +const installerPath = join(repoRoot, 'scripts/install.sh') +const STUB_COMPOSE = 'services:\n app:\n image: stub\n' + +let workDir: string +let stubDir: string +let installDir: string +let logPath: string + +const writeStub = (name: string, body: string) => { + const file = join(stubDir, name) + writeFileSync(file, `#!/bin/sh\n${body}\n`) + chmodSync(file, 0o755) +} + +const stubCalls = () => (existsSync(logPath) ? readFileSync(logPath, 'utf-8').split('\n').filter(Boolean) : []) + +beforeEach(() => { + workDir = mkdtempSync(join(tmpdir(), 'ocm-install-')) + stubDir = join(workDir, 'bin') + installDir = join(workDir, 'opencode-manager') + logPath = join(workDir, 'calls.log') + mkdirSync(stubDir) + + writeStub('docker', `echo "$(pwd) docker $*" >> "$OCM_STUB_LOG" +if [ "$1" = info ]; then exit "\${OCM_STUB_DOCKER_INFO_EXIT:-0}"; fi +if [ "$1" = inspect ]; then + [ -n "\${OCM_STUB_CONTAINER+x}" ] || exit 1 + case "$*" in + *project.working_dir*) echo "\${OCM_STUB_CONTAINER_DIR:-}" ;; + *com.docker.compose.project*) echo "\${OCM_STUB_CONTAINER_PROJECT:-}" ;; + esac + exit 0 +fi +exit 0`) + writeStub('curl', `echo "curl $*" >> "$OCM_STUB_LOG" +out="" +while [ "$#" -gt 0 ]; do + if [ "$1" = "-o" ]; then out="$2"; fi + shift +done +if [ -n "$out" ] && [ "$out" != /dev/null ]; then printf '%s' "$OCM_STUB_COMPOSE" > "$out"; fi +exit 0`) +}) + +afterEach(() => { + rmSync(workDir, { recursive: true, force: true }) +}) + +const runInstaller = (env: Record = {}) => + new Promise<{ status: number | null; stdout: string; stderr: string }>((resolve, reject) => { + const child = spawn('sh', [installerPath], { + detached: true, + stdio: ['ignore', 'pipe', 'pipe'], + env: { + PATH: `${stubDir}:/usr/bin:/bin`, + HOME: workDir, + OCM_DIR: installDir, + OCM_STUB_LOG: logPath, + OCM_STUB_COMPOSE: STUB_COMPOSE, + ...env, + }, + }) + let stdout = '' + let stderr = '' + child.stdout.on('data', (chunk) => { stdout += chunk }) + child.stderr.on('data', (chunk) => { stderr += chunk }) + child.on('error', reject) + child.on('close', (status) => resolve({ status, stdout, stderr })) + }) + +describe('install.sh', () => { + it('installs with defaults and shares no host folders when no terminal is available', async () => { + const res = await runInstaller({ OCM_REF: 'beta' }) + + expect(res.status, res.stderr).toBe(0) + expect(res.stdout).toContain('No terminal available') + expect(readFileSync(join(installDir, 'docker-compose.yml'), 'utf-8')).toBe(STUB_COMPOSE) + expect(existsSync(join(installDir, '.env'))).toBe(false) + expect(existsSync(join(installDir, 'docker-compose.override.yml'))).toBe(false) + + const calls = stubCalls() + expect(calls).toContain( + `curl -fsSL https://raw.githubusercontent.com/chriswritescode-dev/opencode-manager/beta/docker-compose.release.yml -o ${installDir}/docker-compose.yml.download`, + ) + const pullIndex = calls.indexOf(`${installDir} docker compose pull`) + const upIndex = calls.indexOf(`${installDir} docker compose up -d`) + expect(pullIndex).toBeGreaterThan(-1) + expect(upIndex).toBeGreaterThan(pullIndex) + expect(calls.some((call) => call.includes('http://localhost:5003/api/health'))).toBe(true) + expect(res.stdout).toContain('OpenCode Manager is running.') + }) + + it('updates an existing install without prompting or touching its settings', async () => { + mkdirSync(installDir) + writeFileSync(join(installDir, 'docker-compose.yml'), 'old') + writeFileSync(join(installDir, '.env'), "OCM_REPOS_HOST_PATH='/srv/repos'\n") + + const res = await runInstaller() + + expect(res.status, res.stderr).toBe(0) + expect(res.stdout).toContain(`Updating OpenCode Manager in ${installDir}`) + expect(res.stdout).not.toContain('No terminal available') + expect(readFileSync(join(installDir, 'docker-compose.yml'), 'utf-8')).toBe(STUB_COMPOSE) + expect(readFileSync(join(installDir, '.env'), 'utf-8')).toBe("OCM_REPOS_HOST_PATH='/srv/repos'\n") + expect(stubCalls()).toContain(`${installDir} docker compose up -d`) + }) + + it('updates the container it installed earlier', async () => { + mkdirSync(installDir) + writeFileSync(join(installDir, 'docker-compose.yml'), 'old') + + const res = await runInstaller({ OCM_STUB_CONTAINER: '1', OCM_STUB_CONTAINER_PROJECT: 'ocm' }) + + expect(res.status, res.stderr).toBe(0) + expect(stubCalls()).toContain(`${installDir} docker compose up -d`) + }) + + it('refuses to install over a source checkout', async () => { + mkdirSync(join(installDir, '.git'), { recursive: true }) + writeFileSync(join(installDir, 'docker-compose.yml'), 'tracked') + + const res = await runInstaller() + + expect(res.status).toBe(1) + expect(res.stderr).toContain('is a source checkout of OpenCode Manager') + expect(readFileSync(join(installDir, 'docker-compose.yml'), 'utf-8')).toBe('tracked') + expect(stubCalls().some((call) => call.startsWith('curl '))).toBe(false) + }) + + it('refuses to start next to an install from a source checkout and names where it runs', async () => { + const res = await runInstaller({ + OCM_STUB_CONTAINER: '1', + OCM_STUB_CONTAINER_PROJECT: 'opencode-manager', + OCM_STUB_CONTAINER_DIR: '/home/me/src/opencode-manager', + }) + + expect(res.status).toBe(1) + expect(res.stderr).toContain('already installed from /home/me/src/opencode-manager') + expect(existsSync(installDir)).toBe(false) + expect(stubCalls().some((call) => call.includes('compose pull'))).toBe(false) + }) + + it('refuses to start next to a container named opencode-manager that Compose does not manage', async () => { + const res = await runInstaller({ OCM_STUB_CONTAINER: '1', OCM_STUB_CONTAINER_PROJECT: '' }) + + expect(res.status).toBe(1) + expect(res.stderr).toContain('already exists outside Docker Compose') + expect(existsSync(installDir)).toBe(false) + }) + + it('stops before downloading anything when Docker is missing', async () => { + rmSync(join(stubDir, 'docker')) + + const res = await runInstaller() + + expect(res.status).toBe(1) + expect(res.stderr).toContain('Docker is required') + expect(stubCalls()).toEqual([]) + expect(existsSync(installDir)).toBe(false) + }) + + it('explains an unreachable Docker daemon', async () => { + const res = await runInstaller({ OCM_STUB_DOCKER_INFO_EXIT: '1' }) + + expect(res.status).toBe(1) + expect(res.stderr).toContain('Docker is installed but not reachable') + expect(stubCalls().some((call) => call.startsWith('curl '))).toBe(false) + }) +}) + +describe('install.sh helpers', () => { + const runHelper = (functions: string[], snippet: string) => + spawnSync('sh', ['-c', `set -eu\n${functions.map((name) => extractShellFunction(installerPath, name)).join('\n')}\n${snippet}`], { + encoding: 'utf-8', + cwd: workDir, + }) + + it('writes an override that imports OpenCode read-only and shares the repositories folder at its host path', () => { + const res = runHelper(['write_override', 'write_bind_mount'], 'write_override override.yml opencode.jsonc 1 1') + expect(res.status, res.stderr).toBe(0) + expect(readFileSync(join(workDir, 'override.yml'), 'utf-8')).toBe(`services: + app: + environment: + - OPENCODE_IMPORT_CONFIG_PATH=/import/opencode-config/opencode.jsonc + - OPENCODE_IMPORT_STATE_PATH=/import/opencode-state + volumes: + - type: bind + source: "\${OCM_OPENCODE_CONFIG_HOST_PATH}" + target: "/import/opencode-config" + read_only: true + - type: bind + source: "\${OCM_OPENCODE_STATE_HOST_PATH}" + target: "/import/opencode-state" + read_only: true + - type: bind + source: "\${OCM_REPOS_HOST_PATH}" + target: "\${OCM_REPOS_HOST_PATH}" + read_only: false +`) + }) + + it('writes only the repositories mount when nothing is imported', () => { + const res = runHelper(['write_override', 'write_bind_mount'], "write_override override.yml '' 0 1") + expect(res.status, res.stderr).toBe(0) + expect(readFileSync(join(workDir, 'override.yml'), 'utf-8')).toBe(`services: + app: + volumes: + - type: bind + source: "\${OCM_REPOS_HOST_PATH}" + target: "\${OCM_REPOS_HOST_PATH}" + read_only: false +`) + }) + + it('prefers opencode.jsonc over opencode.json and the legacy config.json', () => { + mkdirSync(join(workDir, 'config')) + writeFileSync(join(workDir, 'config', 'config.json'), '{}') + writeFileSync(join(workDir, 'config', 'opencode.json'), '{}') + expect(runHelper(['find_opencode_config_file'], 'find_opencode_config_file config').stdout).toBe('opencode.json') + writeFileSync(join(workDir, 'config', 'opencode.jsonc'), '{}') + expect(runHelper(['find_opencode_config_file'], 'find_opencode_config_file config').stdout).toBe('opencode.jsonc') + expect(runHelper(['find_opencode_config_file'], 'find_opencode_config_file missing').stdout).toBe('') + }) + + it('single-quotes .env values with spaces and rejects values containing a single quote', () => { + const ok = runHelper(['fail', 'env_line'], "env_line OCM_REPOS_HOST_PATH '/Users/me/My Repos'") + expect(ok.stdout).toBe("OCM_REPOS_HOST_PATH='/Users/me/My Repos'\n") + const rejected = runHelper(['fail', 'env_line'], `env_line OCM_REPOS_HOST_PATH "/Users/me/it's"`) + expect(rejected.status).toBe(1) + expect(rejected.stderr).toContain('single quote') + }) + + it('expands a leading ~ to HOME', () => { + const res = runHelper(['expand_home'], 'HOME=/home/me; expand_home "~/code"; printf "|"; expand_home "~"; printf "|"; expand_home /abs') + expect(res.stdout).toBe('/home/me/code|/home/me|/abs') + }) +}) diff --git a/docker-compose.release.yml b/docker-compose.release.yml new file mode 100644 index 00000000..2ff78011 --- /dev/null +++ b/docker-compose.release.yml @@ -0,0 +1,71 @@ +# Runs the published release image instead of building from source. +# The installer saves this file as docker-compose.yml. +# Keep it identical to docker-compose.yml apart from name and image/build. + +name: ocm + +services: + app: + image: ghcr.io/chriswritescode-dev/opencode-manager:latest + container_name: opencode-manager + ports: + - "5003:5003" + - "5004:5004" + - "5100:5100" + - "5101:5101" + - "5102:5102" + - "5103:5103" + environment: + - NODE_ENV=${NODE_ENV:-production} + - PUID=${PUID:-1000} + - PGID=${PGID:-1000} + - HOST=0.0.0.0 + - PORT=5003 + - OPENCODE_SERVER_PORT=5551 + - OPENCODE_HOST=127.0.0.1 + - DATABASE_PATH=/app/data/opencode.db + - WORKSPACE_PATH=/workspace + - PROCESS_START_WAIT_MS=2000 + - PROCESS_VERIFY_WAIT_MS=1000 + - HEALTH_CHECK_TIMEOUT_MS=30000 + - MAX_FILE_SIZE_MB=50 + - MAX_UPLOAD_SIZE_MB=50 + - DEBUG=false + - AUTH_SECRET=${AUTH_SECRET:-} + - AUTH_TRUSTED_ORIGINS=${AUTH_TRUSTED_ORIGINS:-http://localhost:5003} + - ADMIN_EMAIL=${ADMIN_EMAIL:-} + - ADMIN_PASSWORD=${ADMIN_PASSWORD:-} + - ADMIN_PASSWORD_RESET=${ADMIN_PASSWORD_RESET:-false} + - GITHUB_CLIENT_ID=${GITHUB_CLIENT_ID:-} + - GITHUB_CLIENT_SECRET=${GITHUB_CLIENT_SECRET:-} + - GOOGLE_CLIENT_ID=${GOOGLE_CLIENT_ID:-} + - GOOGLE_CLIENT_SECRET=${GOOGLE_CLIENT_SECRET:-} + - DISCORD_CLIENT_ID=${DISCORD_CLIENT_ID:-} + - DISCORD_CLIENT_SECRET=${DISCORD_CLIENT_SECRET:-} + - AUTH_SECURE_COOKIES=${AUTH_SECURE_COOKIES:-false} + - PASSKEY_RP_ID=${PASSKEY_RP_ID:-localhost} + - PASSKEY_RP_NAME=${PASSKEY_RP_NAME:-OpenCode Manager} + - PASSKEY_ORIGIN=${PASSKEY_ORIGIN:-http://localhost:5003} + - PREVIEW_PUBLIC_URL=${PREVIEW_PUBLIC_URL:-} + - VAPID_PUBLIC_KEY=${VAPID_PUBLIC_KEY:-} + - VAPID_PRIVATE_KEY=${VAPID_PRIVATE_KEY:-} + - VAPID_SUBJECT=${VAPID_SUBJECT:-} + volumes: + - ${OCM_WORKSPACE_HOST_PATH:-opencode-workspace}:/workspace + - opencode-data:/app/data + - opencode-bin:/home/node/.opencode/bin + restart: unless-stopped + healthcheck: + test: ["CMD", "curl", "-f", "http://localhost:5003/api/health"] + interval: 30s + timeout: 3s + retries: 3 + start_period: 40s + +volumes: + opencode-workspace: + driver: local + opencode-data: + driver: local + opencode-bin: + driver: local diff --git a/docker-compose.yml b/docker-compose.yml index ac250c79..31104d2e 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -29,7 +29,7 @@ services: - MAX_FILE_SIZE_MB=50 - MAX_UPLOAD_SIZE_MB=50 - DEBUG=false - - AUTH_SECRET=${AUTH_SECRET} + - AUTH_SECRET=${AUTH_SECRET:-} - AUTH_TRUSTED_ORIGINS=${AUTH_TRUSTED_ORIGINS:-http://localhost:5003} - ADMIN_EMAIL=${ADMIN_EMAIL:-} - ADMIN_PASSWORD=${ADMIN_PASSWORD:-} diff --git a/scripts/docker-entrypoint.sh b/scripts/docker-entrypoint.sh index 8a937955..ef8976f2 100644 --- a/scripts/docker-entrypoint.sh +++ b/scripts/docker-entrypoint.sh @@ -43,6 +43,23 @@ grant_kvm_access() { echo "Granted node access to $dev (group '$group_name', gid $dev_gid)" } +ensure_auth_secret() { + local secret_file="$1" + [ -n "${AUTH_SECRET:-}" ] && return 0 + + if [ ! -s "$secret_file" ]; then + mkdir -p "$(dirname "$secret_file")" || return 1 + (umask 077 && head -c 32 /dev/urandom | base64 > "$secret_file") || { + echo "ERROR: could not write a generated AUTH_SECRET to $secret_file" >&2 + return 1 + } + echo "Generated AUTH_SECRET and saved it to $secret_file" + fi + + AUTH_SECRET="$(cat "$secret_file")" || return 1 + export AUTH_SECRET +} + OPENCODE_SUPPORTED_FLOOR="${OPENCODE_BUNDLED_VERSION:-}" read_opencode_version() { @@ -135,19 +152,7 @@ fi echo "Starting OpenCode Manager Backend..." -if [ -z "$AUTH_SECRET" ]; then - echo "AUTH_SECRET is required but not set" - echo "" - echo "Please set AUTH_SECRET environment variable with a secure random string." - echo "Generate one with: openssl rand -base64 32" - echo "" - echo "Example in docker-compose.yml:" - echo " environment:" - echo " - AUTH_SECRET=your-secure-random-secret-here" - echo "" - echo "Example with Docker run:" - echo " docker run -e AUTH_SECRET=\$(openssl rand -base64 32) ..." - echo "" +if ! ensure_auth_secret /app/data/.auth-secret; then exit 1 fi diff --git a/scripts/install.sh b/scripts/install.sh new file mode 100755 index 00000000..63d0fbfe --- /dev/null +++ b/scripts/install.sh @@ -0,0 +1,287 @@ +#!/bin/sh +set -eu + +OCM_REF="${OCM_REF:-main}" +OCM_DIR="${OCM_DIR:-$HOME/opencode-manager}" +OCM_RAW_URL="https://raw.githubusercontent.com/chriswritescode-dev/opencode-manager/$OCM_REF" +OCM_PROJECT="ocm" +OCM_LOCAL_URL="http://localhost:5003" +OCM_DOCS_URL="https://opencodemanager.app/docs" +HEALTH_TIMEOUT_SECONDS=180 + +say() { + printf '%s\n' "$*" +} + +fail() { + printf 'Error: %s\n' "$*" >&2 + exit 1 +} + +require_docker() { + if ! command -v docker >/dev/null 2>&1; then + fail "Docker is required. Install Docker Desktop (macOS, Windows) or Docker Engine (Linux): https://docs.docker.com/get-docker/" + fi + if ! docker info >/dev/null 2>&1; then + fail "Docker is installed but not reachable. Start Docker Desktop or the docker service, and make sure your user can run 'docker info'." + fi + if ! docker compose version >/dev/null 2>&1; then + fail "Docker Compose v2 ('docker compose') is required: https://docs.docker.com/compose/install/" + fi +} + +require_no_conflicting_install() { + if [ -e "$OCM_DIR/.git" ] || [ -f "$OCM_DIR/Dockerfile" ]; then + fail "$OCM_DIR is a source checkout of OpenCode Manager. Keep updating it with ./scripts/docker-upgrade.sh, or set OCM_DIR to install somewhere else." + fi + running_project="$(docker inspect -f '{{ index .Config.Labels "com.docker.compose.project" }}' opencode-manager 2>/dev/null || true)" + if [ -z "$running_project" ] && docker inspect opencode-manager >/dev/null 2>&1; then + fail "A container named opencode-manager already exists outside Docker Compose. Remove it with 'docker rm -f opencode-manager' (its volumes are kept) and re-run." + fi + if [ -n "$running_project" ] && [ "$running_project" != "$OCM_PROJECT" ]; then + running_dir="$(docker inspect -f '{{ index .Config.Labels "com.docker.compose.project.working_dir" }}' opencode-manager 2>/dev/null || true)" + fail "OpenCode Manager is already installed from ${running_dir:-another Compose project}. Keep using that install, or stop it there with 'docker compose down' before installing here. The two installs keep separate data." + fi +} + +can_prompt() { + (: /dev/null +} + +ask_yes_no() { + if [ "$2" = y ]; then + ask_hint="[Y/n]" + else + ask_hint="[y/N]" + fi + printf '%s %s ' "$1" "$ask_hint" >/dev/tty + read -r ask_answer /dev/tty + read -r ask_answer /dev/null || ipconfig getifaddr en1 2>/dev/null || true ;; + *) ip -4 route get 1.1.1.1 2>/dev/null | awk '{ for (i = 1; i < NF; i++) if ($i == "src") { print $(i + 1); exit } }' ;; + esac +} + +write_override() { + { + printf 'services:\n app:\n' + if [ -n "$2" ] || [ "$3" = 1 ]; then + printf ' environment:\n' + if [ -n "$2" ]; then + printf ' - OPENCODE_IMPORT_CONFIG_PATH=/import/opencode-config/%s\n' "$2" + fi + if [ "$3" = 1 ]; then + printf ' - OPENCODE_IMPORT_STATE_PATH=/import/opencode-state\n' + fi + fi + printf ' volumes:\n' + if [ -n "$2" ]; then + write_bind_mount '${OCM_OPENCODE_CONFIG_HOST_PATH}' /import/opencode-config true + fi + if [ "$3" = 1 ]; then + write_bind_mount '${OCM_OPENCODE_STATE_HOST_PATH}' /import/opencode-state true + fi + if [ "$4" = 1 ]; then + write_bind_mount '${OCM_REPOS_HOST_PATH}' '${OCM_REPOS_HOST_PATH}' false + fi + } >"$1" +} + +write_bind_mount() { + printf ' - type: bind\n source: "%s"\n target: "%s"\n read_only: %s\n' "$1" "$2" "$3" +} + +configure_new_install() { + env_content="" + import_config_name="" + import_state=0 + mount_repos=0 + + if ! can_prompt; then + say "No terminal available, installing with defaults (no host folders shared)." + return 0 + fi + + config_dir="${XDG_CONFIG_HOME:-$HOME/.config}/opencode" + state_dir="${XDG_DATA_HOME:-$HOME/.local/share}/opencode" + found_config_name="$(find_opencode_config_file "$config_dir")" + found_state=0 + if [ -f "$state_dir/opencode.db" ]; then + found_state=1 + fi + + if [ -n "$found_config_name" ] || [ "$found_state" = 1 ]; then + say "" + say "Found OpenCode on this machine." + if [ "$found_state" = 1 ]; then + say " Chat history and provider logins: $state_dir ($(du -sh "$state_dir" 2>/dev/null | cut -f1))" + fi + if [ -n "$found_config_name" ]; then + say " Config: $config_dir/$found_config_name" + fi + if ask_yes_no "Copy them into OpenCode Manager? They are shared read-only and copied once on first start." n; then + IMPORTED_OPENCODE=1 + if [ -n "$found_config_name" ]; then + import_config_name="$found_config_name" + env_content="$env_content$(env_line OCM_OPENCODE_CONFIG_HOST_PATH "$config_dir") +" + fi + if [ "$found_state" = 1 ]; then + import_state=1 + env_content="$env_content$(env_line OCM_OPENCODE_STATE_HOST_PATH "$state_dir") +" + fi + fi + fi + + say "" + if ask_yes_no "Share a folder of existing repositories with OpenCode Manager? Agents can read and change files in it." n; then + repos_answer="$(expand_home "$(ask_value "Repositories folder (absolute path)")")" + case "$repos_answer" in + /*) + if [ -d "$repos_answer" ]; then + mount_repos=1 + REPOS_DIR="${repos_answer%/}" + env_content="$env_content$(env_line OCM_REPOS_HOST_PATH "$REPOS_DIR") +" + else + say "Skipping: $repos_answer is not a folder." + fi + ;; + "") say "Skipping: no folder entered." ;; + *) say "Skipping: $repos_answer is not an absolute path." ;; + esac + fi + + if [ "$(uname -s)" = Linux ] && [ "$(id -u)" != 0 ] && { [ -n "$import_config_name" ] || [ "$import_state" = 1 ] || [ "$mount_repos" = 1 ]; }; then + env_content="${env_content}PUID=$(id -u) +PGID=$(id -g) +" + fi + + lan_ip="$(detect_lan_ip)" + if [ -n "$lan_ip" ]; then + say "" + if ask_yes_no "Allow sign-in from other devices on your network, like your phone (http://$lan_ip:5003)?" y; then + LAN_URL="http://$lan_ip:5003" + env_content="${env_content}AUTH_TRUSTED_ORIGINS=$OCM_LOCAL_URL,$LAN_URL +" + fi + fi + + if [ -n "$env_content" ]; then + printf '%s' "$env_content" >"$OCM_DIR/.env" + fi + if [ -n "$import_config_name" ] || [ "$import_state" = 1 ] || [ "$mount_repos" = 1 ]; then + write_override "$OCM_DIR/docker-compose.override.yml" "$import_config_name" "$import_state" "$mount_repos" + fi +} + +wait_for_health() { + waited=0 + until curl -fsS -o /dev/null "$OCM_LOCAL_URL/api/health" 2>/dev/null; do + if [ "$waited" -ge "$HEALTH_TIMEOUT_SECONDS" ]; then + return 1 + fi + sleep 2 + waited=$((waited + 2)) + done +} + +print_summary() { + say "" + say "OpenCode Manager is running." + say "" + say " Open: $OCM_LOCAL_URL" + if [ -n "$LAN_URL" ]; then + say " On your network: $LAN_URL" + fi + say "" + if [ "$IMPORTED_OPENCODE" = 1 ]; then + say "Next: create your admin account. Your OpenCode providers and chats are imported on first start." + else + say "Next: create your admin account, then connect a model provider in Settings > Providers." + fi + if [ -n "$REPOS_DIR" ]; then + say "Add your repositories with Add Repository > Folder > $REPOS_DIR" + fi + say "" + say "Manage it from $OCM_DIR:" + say " docker compose logs -f View logs" + say " docker compose down Stop (your data is kept)" + say " Re-run the installer Update to the latest release" + say "" + say "Customize with .env or docker-compose.override.yml; docker-compose.yml is replaced on update." + say "Docs: $OCM_DOCS_URL" +} + +main() { + require_docker + require_no_conflicting_install + REPOS_DIR="" + LAN_URL="" + IMPORTED_OPENCODE=0 + + if [ -f "$OCM_DIR/docker-compose.yml" ]; then + say "Updating OpenCode Manager in $OCM_DIR (your settings are kept)." + else + say "Installing OpenCode Manager into $OCM_DIR" + mkdir -p "$OCM_DIR" + configure_new_install + fi + + curl -fsSL "$OCM_RAW_URL/docker-compose.release.yml" -o "$OCM_DIR/docker-compose.yml.download" || + fail "Could not download docker-compose.release.yml from $OCM_RAW_URL" + mv "$OCM_DIR/docker-compose.yml.download" "$OCM_DIR/docker-compose.yml" + + cd "$OCM_DIR" + say "" + say "Pulling the OpenCode Manager image (about 1.2 GB the first time)..." + docker compose pull + docker compose up -d || fail "Could not start the container. Check the error above, then re-run the installer." + + say "Waiting for OpenCode Manager to start..." + if ! wait_for_health; then + fail "OpenCode Manager did not become healthy within ${HEALTH_TIMEOUT_SECONDS}s. Check the logs: cd $OCM_DIR && docker compose logs" + fi + print_summary +} + +main "$@"