feat(docker): one-line installer and release Compose file

Add scripts/install.sh, a one-line installer that checks Docker and
Compose v2, installs into ~/opencode-manager (override with OCM_DIR),
prompts for an optional OpenCode config import, a repos folder mount and
LAN sign-in, then pulls and starts the published image.

- Add docker-compose.release.yml, which runs the published image under
  the Compose project name ocm; a checkout's docker-compose.yml keeps
  building from source
- Generate AUTH_SECRET on first container start and persist it to the
  data volume when unset, so Compose installs need no .env
- Refuse to install over a source checkout or beside an existing
  install, so volumes and the auth secret are not silently replaced
- Test the installer, entrypoint secret handling, and the two Compose
  files staying in step
This commit is contained in:
Chris Scott committed 2026-10-05 15:07:23 -04:00
1 parent 87636bf1ff
commit 27996ed12d
10 files changed
+734 -31

No files matched your search

@@ -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'))
+53 -7
View File
@@ -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<string, string> = {}) => {
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..."'
+245
View File
@@ -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<string, string> = {}) =>
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')
})
})