@open-mercato/starter 0.10.1-develop.7994.1.c9f31972aa → 0.10.1-develop.8022.1.b6753de892

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,15 +3,18 @@
3
3
  The central, cross-platform way to stand up an Open Mercato dev environment. One command, idempotent, platform-aware:
4
4
 
5
5
  ```bash
6
- # Anywhere (clones the repo if you are not inside one):
6
+ # Outside a clone (clones the repo into ./open-mercato first):
7
7
  npx @open-mercato/starter
8
8
 
9
- # Inside a clone:
9
+ # Inside a fresh clone, before the first `yarn install`:
10
+ node packages/starter/bin/om-start.mjs
11
+
12
+ # Inside a clone once dependencies are installed:
10
13
  yarn setup # same as `yarn om up`: everything from install to a running app
11
14
  yarn om # alias for node packages/starter/bin/om-start.mjs
12
15
  ```
13
16
 
14
- `yarn setup` checks Docker (CLI, Compose v2, a running engine), refuses ports another process already holds, starts PostgreSQL, Redis, Meilisearch and OpenCode, and waits for their healthchecks before it touches the database. Each failure says what to fix. Nothing installs Docker or asks for sudo. Already running those services yourself? `yarn setup --no-infra` skips every Docker call and uses the URLs in your `.env`. Re-running is safe: containers and volumes are reused, `.env` values are never overwritten.
17
+ Without a service flag `yarn setup` picks the services itself: it reuses those configured in `apps/mercato/.env` when they answer, their credentials verify and they are not another checkout's containers; starts this checkout's Compose services on the configured ports when nothing answers; starts an isolated stack on free ports (and says why) when the configured ports are held by something unusable; and stops with the Docker problem plus the [Without Docker](https://github.com/open-mercato/open-mercato#without-docker) guide when Docker is unusable and nothing usable answers. An interactive terminal shows the choice with that pick as the default; noninteractive runs never prompt. Setup claims the checkout's dev session first, so a second `yarn setup` while one is running stops before changing `.env` or containers. Use `--ephemeral` for disposable PostgreSQL, Redis and Meilisearch managed by Testcontainers, `--random-ports` for a persistent isolated Compose stack on free ports, or `--infra` for Compose on configured ports. `--no-infra` and `--reuse-services` explicitly select reuse. Random and ephemeral modes update the service ports and matching connection URLs together; ephemeral mode restores the previous settings and removes its containers when the foreground session stops. Compose containers and volumes persist. Nothing installs Docker or asks for sudo.
15
18
 
16
19
  Apps created with `npx create-mercato-app` get the same check: their `yarn setup` (and `yarn infra:up` / `yarn infra:down`) runs this package's preflight from `scripts/dev-infra-preflight.mjs`, a byte-for-byte copy kept in sync by `yarn template:sync`.
17
20
 
@@ -36,9 +39,7 @@ No Node yet? The package ships pre-Node bootstraps that install a **portable, ch
36
39
 
37
40
  AI provider configuration is optional: press Enter or choose `0` at the provider prompt to continue without AI. Non-interactive setup also continues without a key. Configure a provider in `.env` later to enable AI chat.
38
41
 
39
- If setup finds ports owned by pre-existing services, it shows the container names and states and asks whether to continue using the URLs in `.env`. Accepting leaves those containers under your control and prevents the dev runtime from restarting them. Restarting or unhealthy services produce warnings; their actual connection failures still stop database setup. Declining, or running non-interactively without `--no-infra`, stops setup with `yarn om stop` guidance for the checkout that started the stack.
40
-
41
- Useful flags: `--verbose`, `--non-interactive`, `--skip-llm-prompt`, `--skip-db`, `--no-infra` (no Docker calls at all, also passed on to `yarn dev`), `--rebuild`, `--clean`, `--profile <name>`, `-- <args for yarn dev>`.
42
+ Useful flags: `--verbose`, `--reuse-services`, `--ephemeral` (foreground only), `--random-ports`, `--infra`, `--non-interactive`, `--skip-llm-prompt`, `--skip-db`, `--no-infra` (no Docker calls at all, also passed on to `yarn dev`), `--rebuild`, `--clean`, `--profile <name>`, `-- <args for yarn dev>`.
42
43
 
43
44
  `up --clean` forces a full re-converge: it clears the completed-step markers (install, build, migrations) and rebuilds the OpenCode service image, without touching any data — the one-time database seed stays done, and `reset` remains the destructive variant. Conversely, a plain `up` now also skips the database step entirely when the database is initialized and no `Migration*.ts` file changed since the last run (new migrations are detected by fingerprint and applied automatically).
44
45
 
@@ -52,7 +53,7 @@ Use `yarn setup --verbose` or `yarn infra:up --verbose` for live raw output. CI,
52
53
 
53
54
  ## Design rules
54
55
 
55
- - **Node stdlib only, no build step.** The CLI must run from a fresh clone before any `yarn install` — that is what makes it usable behind broken proxies.
56
+ - **Node stdlib bootstrap, no build step.** The CLI runs from a fresh clone before `yarn install`. Testcontainers is loaded lazily from the checkout only after dependencies are installed and only for an explicit ephemeral service choice.
56
57
  - **Install nothing system-level.** WSL2, Docker Desktop, and Rancher Desktop are detected and *proposed* (with exact commands and an IT handout), never installed. The starter installs only what it fully owns: portable Node (platform scripts), yarn via corepack, env files, CA bundles, repo state.
57
58
  - **Corporate TLS interception is a first-class citizen.** `up` probes real egress hosts, captures the interception CA (wire + Windows certificate store + vendor bundles like Netskope's), and provisions one PEM bundle everywhere: `NODE_EXTRA_CA_CERTS` + `--use-system-ca` for host tooling, `docker/certs/` + `docker/opencode/certs/` for image builds and container egress, a Rancher Desktop provisioning script for engine pulls. Prefer handing the starter your official bundle via `starters/company/config.mjs`.
58
59
  - **Probes use `127.0.0.1`, never `localhost`** (Windows resolves `localhost` to `::1` first).
@@ -62,10 +63,45 @@ Use `yarn setup --verbose` or `yarn infra:up --verbose` for live raw output. CI,
62
63
 
63
64
  Organizations customize behavior (mirrors, CA bundles, extra checks/steps, env defaults) via `starters/company/config.mjs` in the repo — see `starters/company/README.md`. The package stays generic; the repo carries the policy.
64
65
 
65
- ## Service connection verification
66
-
67
- Before migrations or initialization, setup checks PostgreSQL with `SELECT 1`,
68
- each configured Redis URL with authenticated `PING`, and Meilisearch through
69
- the protected indexes API using `MEILISEARCH_API_KEY`. Invalid credentials or
70
- unreachable services stop setup and name the relevant setting without printing
71
- passwords or tokens. Existing-service consent never bypasses these checks.
66
+ ## Recovering from setup failure
67
+
68
+ The starter prints the failed step and a manual path. Check the selected service
69
+ URLs in `apps/mercato/.env`, then run `yarn install`, `yarn build:packages`,
70
+ `yarn generate`, `yarn build:packages`, `yarn db:migrate`,
71
+ `yarn initialize -- --skip-if-initialized`, and `yarn dev --no-infra`.
72
+ Alternatively retry `yarn setup --ephemeral`, `yarn setup --random-ports`, or
73
+ `yarn setup --infra`. Ephemeral URLs are session-scoped; after failure or exit,
74
+ use the restored existing-service URLs or start another ephemeral setup session.
75
+
76
+ Before database setup, the starter verifies PostgreSQL with `SELECT 1`, every configured Redis consumer with an authenticated `PING`, and Meilisearch with its protected indexes API. Invalid credentials or unreachable services stop setup with the relevant configuration key and a redacted endpoint; passwords and API keys are never printed.
77
+
78
+
79
+ ## Setup security boundaries
80
+
81
+ Plain and noninteractive setup never start services on ports that already
82
+ answer and never contact a database held by another project's containers: they
83
+ reuse verified services, start Compose on free configured ports, or isolate
84
+ themselves on free random ports. Explicit flags keep their exact meaning.
85
+
86
+ Before any setup/development migration or initialization, the guard resolves the
87
+ actual PostgreSQL target (including connection-string overrides). Non-loopback
88
+ writes require an exact target acknowledgement, for example
89
+ `yarn setup --allow-remote-database=staging.example:5432/app_db`. A bare
90
+ `--allow-remote-database` prompts for that exact target only in a terminal;
91
+ unattended runs must provide it. Connection snapshots prevent a changed `.env`
92
+ from redirecting an already-authorized child command. Local reuse needs no flag.
93
+
94
+ Isolated modes generate independent random PostgreSQL, Redis and Meilisearch
95
+ credentials, never reuse configured remote credentials, and pin their images
96
+ (including the Testcontainers cleanup image) by verified multiarch digests.
97
+ Random stacks save their owned `OM_SETUP_LOCAL_*` values in ignored `.env` files
98
+ and reuse those values on later runs despite ambient remote URL overrides.
99
+ The new `mercato-local-v2-*` identity creates separate volumes from earlier
100
+ random stacks; old containers/data are retained and are not deleted or migrated.
101
+
102
+ Development Compose bindings default to `127.0.0.1`. An explicit
103
+ `INFRA_BIND_HOST` outside loopback additionally requires a Redis password and
104
+ matching Redis URLs. Random mode forces loopback regardless of that ambient
105
+ setting. Full application/container deployment Compose files retain their
106
+ existing bindings. Optional profiles not started by setup retain their existing
107
+ image policy; the setup services and OpenCode defaults are pinned.
package/bin/om-start.mjs CHANGED
@@ -42,7 +42,7 @@ async function ensureRepo(args) {
42
42
  process.exit(2)
43
43
  }
44
44
  console.log(`No checkout found — cloning open-mercato (${branch}) into ${dir} ...`)
45
- const clone = spawnSync('git', ['clone', '--branch', branch, REPO_URL, dir], { stdio: 'inherit' })
45
+ const clone = spawnSync('git', ['clone', '--filter=blob:none', '--branch', branch, REPO_URL, dir], { stdio: 'inherit' })
46
46
  if (clone.status !== 0) {
47
47
  console.error('❌ git clone failed. Behind a corporate proxy? Configure git first (ask IT for the proxy address):')
48
48
  console.error(' git config --global http.proxy http://proxy.example.com:8080')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/starter",
3
- "version": "0.10.1-develop.7994.1.c9f31972aa",
3
+ "version": "0.10.1-develop.8022.1.b6753de892",
4
4
  "description": "One-command, cross-platform bootstrap for Open Mercato dev environments: prerequisite doctor, corporate TLS trust, idempotent setup steps, and a supervised hybrid or fully containerized stack.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -0,0 +1,111 @@
1
+ import assert from 'node:assert/strict'
2
+ import fs from 'node:fs'
3
+ import os from 'node:os'
4
+ import path from 'node:path'
5
+ import { createRequire } from 'node:module'
6
+ import { PassThrough } from 'node:stream'
7
+ import test from 'node:test'
8
+ import { assertDatabaseWriteAllowed, resolveDatabaseWriteTarget, collectRemoteDatabaseFlags } from '../database-write-guard.mjs'
9
+ const pg = createRequire(import.meta.url)('pg')
10
+ const options = (url) => ({ projectDir: '/missing-fixture', env: { DATABASE_URL: url }, loadModule: () => pg })
11
+
12
+ test('local reuse remains automatic without an explicit service flag', async () => {
13
+ for (const host of ['localhost', '127.0.0.1', '127.1.2.3', '[::1]']) {
14
+ const result = await assertDatabaseWriteAllowed({ ...options(`postgres://fixture:secret@${host}:5432/app`), input: {}, output: {} })
15
+ assert.equal(result.remote, false)
16
+ }
17
+ })
18
+
19
+ test('remote writes fail closed without an exact-target acknowledgment and never reveal credentials', async () => {
20
+ const configuration = options('postgres://owner:fixture-secret@staging.example:6543/app?application_name=query-secret')
21
+ for (const argv of [[], ['--allow-remote-database'], ['--allow-remote-database=other.example:6543/app'], ['--allow-remote-database=staging.example:6543/other']]) {
22
+ await assert.rejects(assertDatabaseWriteAllowed({ ...configuration, argv, input: {}, output: {} }), error => {
23
+ assert.match(error.message, /Remote database writes are blocked for staging\.example:6543\/app/)
24
+ assert.ok(!error.message.includes('fixture-secret')); assert.ok(!error.message.includes('query-secret')); return true
25
+ })
26
+ }
27
+ const accepted = await assertDatabaseWriteAllowed({ ...configuration, argv: ['--allow-remote-database=staging.example:6543/app'], input: {}, output: {} })
28
+ assert.equal(accepted.argument, '--allow-remote-database=staging.example:6543/app')
29
+ assert.equal(accepted.connectionEnv.DATABASE_URL, configuration.env.DATABASE_URL)
30
+ })
31
+
32
+ test('acknowledgment uses real pg connection parameters including URL query overrides', async () => {
33
+ const configuration = options('postgres://fixture:secret@localhost:5432/local?host=production.example&port=6544&database=actual_db')
34
+ const target = resolveDatabaseWriteTarget(configuration)
35
+ assert.equal(target.remote, true); assert.equal(target.target, 'production.example:6544/local')
36
+ await assert.rejects(assertDatabaseWriteAllowed({ ...configuration, argv: ['--allow-remote-database=localhost:5432/local'] }), /blocked/)
37
+ const result = await assertDatabaseWriteAllowed({ ...configuration, argv: ['--allow-remote-database=production.example:6544/local'] })
38
+ const parameters = new pg.Client({ ...result.connectionEnv, connectionString: result.connectionEnv.DATABASE_URL }).connectionParameters
39
+ assert.equal(parameters.host, 'production.example'); assert.equal(parameters.port, 6544); assert.equal(parameters.database, 'local')
40
+ })
41
+
42
+ test('TTY boolean flag requires typing the exact target', async () => {
43
+ const input = new PassThrough(); input.isTTY = true
44
+ const output = new PassThrough(); output.isTTY = true
45
+ const pending = assertDatabaseWriteAllowed({ ...options('postgres://fixture:secret@staging.example/app'), argv: ['--allow-remote-database'], input, output })
46
+ setTimeout(() => input.write('staging.example:5432/app\n'), 5)
47
+ const result = await pending
48
+ assert.equal(result.target, 'staging.example:5432/app')
49
+ input.end(); output.end()
50
+ })
51
+
52
+ test('accepted target captures a connection snapshot instead of reloading edited .env before child writes', async () => {
53
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'om-write-guard-'))
54
+ try {
55
+ const file = path.join(dir, '.env'); const original = 'postgres://fixture:secret@staging.example:6543/app'
56
+ fs.writeFileSync(file, `DATABASE_URL=${original}\n`)
57
+ const result = await assertDatabaseWriteAllowed({ projectDir: dir, env: {}, loadModule: () => pg, argv: ['--allow-remote-database=staging.example:6543/app'] })
58
+ fs.writeFileSync(file, 'DATABASE_URL=postgres://fixture:secret@production.example/other\n')
59
+ const child = new pg.Client({ connectionString: result.connectionEnv.DATABASE_URL }).connectionParameters
60
+ assert.equal(child.host, 'staging.example'); assert.equal(child.database, 'app'); assert.equal(child.port, 6543)
61
+ assert.equal(result.connectionEnv.DATABASE_URL, original)
62
+ } finally { fs.rmSync(dir, { recursive: true, force: true }) }
63
+ })
64
+
65
+ test('shared guard mirrors are identical and parser retains only acknowledgment flags', () => {
66
+ const source = fs.readFileSync(new URL('../database-write-guard.mjs', import.meta.url))
67
+ for (const target of ['../../../../scripts/dev-database-write-guard.mjs', '../../../create-app/template/scripts/dev-database-write-guard.mjs']) assert.deepEqual(source, fs.readFileSync(new URL(target, import.meta.url)))
68
+ assert.deepEqual(collectRemoteDatabaseFlags(['--reuse-services', '--allow-remote-database', 'host:5432/db', '--classic']), ['--allow-remote-database', 'host:5432/db'])
69
+ })
70
+
71
+ test('the actual starter database step blocks remote mutations before running any child command', async () => {
72
+ const { databaseStep } = await import('../steps.mjs')
73
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'om-starter-write-'))
74
+ try {
75
+ fs.mkdirSync(path.join(dir, 'apps', 'mercato'), { recursive: true })
76
+ fs.writeFileSync(path.join(dir, 'apps', 'mercato', '.env'), 'DATABASE_URL=postgres://fixture:secret@staging.example/app\n')
77
+ const commands = []
78
+ const context = {
79
+ repoRoot: dir, env: {}, flags: { noInfra: true }, log() {},
80
+ assertDatabaseWriteAllowedImpl: options => assertDatabaseWriteAllowed({ ...options, loadModule: () => pg, input: {}, output: {} }),
81
+ runStreamingImpl(_command, args) { commands.push(args); return 0 },
82
+ }
83
+ await assert.rejects(databaseStep.apply(context), /Remote database writes are blocked/)
84
+ assert.deepEqual(commands, [])
85
+ } finally { fs.rmSync(dir, { recursive: true, force: true }) }
86
+ })
87
+
88
+ test('the starter passes the authorized immutable connection snapshot to migration and initialization children', async () => {
89
+ const { databaseStep } = await import('../steps.mjs')
90
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'om-starter-snapshot-'))
91
+ try {
92
+ const app = path.join(dir, 'apps', 'mercato'); fs.mkdirSync(app, { recursive: true })
93
+ const file = path.join(app, '.env'); const authorized = 'postgres://fixture:secret@staging.example:6543/app'
94
+ fs.writeFileSync(file, `DATABASE_URL=${authorized}\n`)
95
+ const commands = []
96
+ const context = {
97
+ repoRoot: dir, env: {}, flags: { noInfra: true, remoteDatabaseArgs: ['--allow-remote-database=staging.example:6543/app'] }, log() {},
98
+ dbMarker: 'init-fixture', dbMigrationsMarker: 'migrations-fixture', migrationsFingerprint: 'fixture',
99
+ assertDatabaseWriteAllowedImpl: options => assertDatabaseWriteAllowed({ ...options, loadModule: () => pg, input: {}, output: {} }),
100
+ runStreamingImpl(_command, args, options) {
101
+ commands.push({ args, databaseUrl: options.env.DATABASE_URL })
102
+ fs.writeFileSync(file, 'DATABASE_URL=postgres://fixture:secret@production.example/unacknowledged\n')
103
+ return 0
104
+ },
105
+ }
106
+ await databaseStep.apply(context)
107
+ assert.equal(commands.length, 2)
108
+ assert.ok(commands.every(item => item.databaseUrl === authorized))
109
+ assert.equal(context.remoteDatabaseArgument, '--allow-remote-database=staging.example:6543/app')
110
+ } finally { fs.rmSync(dir, { recursive: true, force: true }) }
111
+ })
@@ -7,6 +7,7 @@ import {
7
7
  parseListenerProcesses,
8
8
  requestExistingServicesConsent,
9
9
  startInfraServices,
10
+ suggestFreePorts,
10
11
  } from '../infra-preflight.mjs'
11
12
 
12
13
  const service = { service: 'postgres', port: 5432, envKey: 'POSTGRES_PORT' }
@@ -96,13 +97,33 @@ test('interactive diagnostics color service, port, variables and commands and ho
96
97
  test('consent separates warning emojis and the continuing paragraph from the answer', async () => {
97
98
  const lines = []
98
99
  assert.equal(await requestExistingServicesConsent(problem, { input: { isTTY: true }, output: { isTTY: false }, env: {}, question: async () => 'y', log: (line) => lines.push(line) }), true)
99
- assert.ok(lines.some((line) => line.startsWith(' ⚠️ mercato-postgres')))
100
+ assert.ok(lines.some((line) => line.startsWith(' ❗ mercato-postgres')))
100
101
  const continuing = lines.findIndex((line) => line.includes('Continuing with'))
101
102
  assert.equal(lines[continuing - 1], '')
102
- assert.ok(lines[continuing].startsWith(' ⚠️ '))
103
+ assert.ok(lines[continuing].startsWith(' ❗ '))
103
104
  assert.match(lines.join('\n'), /Listener PID: 1234/)
104
105
  })
105
106
 
106
107
  test('standalone preflight stays byte-identical to the shared starter implementation', () => {
107
108
  assert.deepEqual(fs.readFileSync(new URL('../infra-preflight.mjs', import.meta.url)), fs.readFileSync(new URL('../../../create-app/template/scripts/dev-infra-preflight.mjs', import.meta.url)))
108
109
  })
110
+
111
+ test('port conflicts suggest the next free port, skipping taken ones and ports suggested for another service', async () => {
112
+ const taken = new Set([5433, 6380])
113
+ const suggested = await suggestFreePorts(
114
+ [{ service: 'postgres', envKey: 'POSTGRES_PORT', port: 5432 }, { service: 'redis', envKey: 'REDIS_PORT', port: 6379 }],
115
+ { probe: async (port) => taken.has(port), reserved: [5432, 6379, 5435] },
116
+ )
117
+ assert.deepEqual(suggested.map((entry) => entry.suggestedPort), [5434, 6381])
118
+ const skipped = await suggestFreePorts([{ service: 'postgres', envKey: 'POSTGRES_PORT', port: 5432 }], { probe: async () => false, reserved: [5433] })
119
+ assert.equal(skipped[0].suggestedPort, 5434, 'a port configured for another service in the stack is never suggested')
120
+ const text = formatInfraProblem({ code: 'port-conflict', ports: suggested }, { output: { isTTY: false }, env: {} }).join('\n')
121
+ assert.match(text, /set POSTGRES_PORT=5434 in \.env/)
122
+ assert.match(text, /\(:5432 -> :5434\)/)
123
+ })
124
+
125
+ test('a known container owner is named instead of an unavailable listener PID', () => {
126
+ const text = formatInfraProblem({ code: 'port-conflict', ports: [{ ...service, containerName: 'other-checkout-postgres' }] }, { output: { isTTY: false }, env: {} }).join('\n')
127
+ assert.match(text, /Container: other-checkout-postgres/)
128
+ assert.doesNotMatch(text, /Listener PID: unavailable/)
129
+ })
@@ -152,5 +152,5 @@ test('a user can still configure a provider interactively and synchronize the ap
152
152
 
153
153
  test('optional AI skip output separates its warning with a blank line and wide-glyph spacing', async () => {
154
154
  const result = await runProvider({ step: true })
155
- assert.match(result.output, /\n[ \t]*\n[ \t]*⚠️ {2}Continuing without AI/)
155
+ assert.match(result.output, /\n[ \t]*\n[ \t]*❗ Continuing without AI/)
156
156
  })
@@ -0,0 +1,134 @@
1
+ import assert from 'node:assert/strict'
2
+ import { spawnSync } from 'node:child_process'
3
+ import fs from 'node:fs'
4
+ import path from 'node:path'
5
+ import os from 'node:os'
6
+ import { parseEnv } from 'node:util'
7
+ import { fileURLToPath } from 'node:url'
8
+ import test from 'node:test'
9
+
10
+ import { DEFAULT_OPENCODE_BASE_IMAGE } from '../constants.mjs'
11
+ import { startInfraServices, formatInfraProblem } from '../infra-preflight.mjs'
12
+
13
+ const repoRoot = fileURLToPath(new URL('../../../../', import.meta.url))
14
+ const composeFiles = ['starters/docker/compose.infra.yml', 'packages/create-app/template/docker-compose.yml']
15
+ const setupServices = ['postgres', 'redis', 'meilisearch']
16
+ const docker = spawnSync('docker', ['compose', 'version'], { encoding: 'utf8', windowsHide: true })
17
+ const noCompose = docker.error || docker.status !== 0 ? 'Docker Compose is not installed; source guards still run' : false
18
+
19
+ function serviceBlock(text, service) {
20
+ const match = text.match(new RegExp(`^ ${service}:\\n([\\s\\S]*?)(?=^ [a-z][a-z_]*:|^volumes:|^networks:|$(?![\\s\\S]))`, 'm'))
21
+ assert.ok(match, `${service} must exist`)
22
+ return match[0]
23
+ }
24
+
25
+ function resolvedConfig(file, env = {}, envFile) {
26
+ const shellEnv = { ...process.env, OPENCODE_BASE_IMAGE: '', INFRA_BIND_HOST: '', ...env }
27
+ if (envFile) delete shellEnv.REDIS_PASSWORD
28
+ const result = spawnSync('docker', ['compose', '--project-directory', repoRoot, ...(envFile ? ['--env-file', envFile] : []), '-f', path.join(repoRoot, file), 'config', '--format', 'json'], {
29
+ env: shellEnv,
30
+ encoding: 'utf8', windowsHide: true,
31
+ })
32
+ assert.equal(result.status, 0, `${file}: ${result.stderr}`)
33
+ return JSON.parse(result.stdout)
34
+ }
35
+
36
+ for (const file of composeFiles) {
37
+ test(`${file} pins setup service images and defaults host ports to loopback`, () => {
38
+ const text = fs.readFileSync(path.join(repoRoot, file), 'utf8')
39
+ for (const service of setupServices) {
40
+ const block = serviceBlock(text, service)
41
+ assert.match(block, /image: \S+@sha256:[a-f0-9]{64}\s*\n/)
42
+ assert.match(block, /ports:\n\s+- "\$\{INFRA_BIND_HOST:-127\.0\.0\.1\}:\$\{[A-Z_]+_PORT:-[0-9]+\}:[0-9]+"/)
43
+ }
44
+ assert.ok(serviceBlock(text, 'opencode').includes(DEFAULT_OPENCODE_BASE_IMAGE))
45
+ })
46
+
47
+ test(`${file} resolves PostgreSQL, Redis and Meilisearch bindings to 127.0.0.1`, { skip: noCompose }, () => {
48
+ const config = resolvedConfig(file)
49
+ for (const service of setupServices) {
50
+ assert.ok(config.services[service].ports.length > 0)
51
+ assert.ok(config.services[service].ports.every((port) => port.host_ip === '127.0.0.1'), `${service} must not publish to every interface`)
52
+ assert.match(config.services[service].image, /@sha256:[a-f0-9]{64}$/)
53
+ }
54
+ })
55
+
56
+ test(`${file} passes a literal dotenv Redis password as one argument and healthcheck env`, { skip: noCompose }, () => {
57
+ const fixture = fs.mkdtempSync(path.join(os.tmpdir(), 'om-compose-redis-'))
58
+ const password = String.raw`pa$$word "quoted" \literal;$(never-execute)`
59
+ const envFile = path.join(fixture, '.env')
60
+ const dotEnv = `REDIS_PASSWORD='${password}'\n`
61
+ fs.writeFileSync(envFile, dotEnv)
62
+ try {
63
+ assert.equal(parseEnv(dotEnv).REDIS_PASSWORD, password)
64
+ const config = resolvedConfig(file, {}, envFile)
65
+ const renderedPassword = password.replaceAll('$', () => '$$')
66
+ assert.deepEqual(config.services.redis.command, ['redis-server', '/usr/local/etc/redis/redis.conf', '--maxmemory', '512mb', '--requirepass', renderedPassword])
67
+ assert.equal(config.services.redis.environment.REDISCLI_AUTH, renderedPassword)
68
+ assert.equal(config.services.redis.command.at(-1).replaceAll('$$', '$'), password)
69
+ assert.equal(config.services.redis.environment.REDISCLI_AUTH.replaceAll('$$', '$'), password)
70
+ assert.deepEqual(config.services.redis.healthcheck.test, ['CMD', 'redis-cli', 'ping'])
71
+ } finally { fs.rmSync(fixture, { recursive: true, force: true }) }
72
+ })
73
+
74
+ test(`${file} permits explicit operator host-binding override`, { skip: noCompose }, () => {
75
+ const config = resolvedConfig(file, { INFRA_BIND_HOST: '192.0.2.10' })
76
+ for (const service of setupServices) assert.equal(config.services[service].ports[0].host_ip, '192.0.2.10')
77
+ })
78
+ }
79
+
80
+ test('OpenCode setup constants and build defaults retain the same pinned image', () => {
81
+ assert.match(DEFAULT_OPENCODE_BASE_IMAGE, /@sha256:[a-f0-9]{64}$/)
82
+ for (const file of ['docker/opencode/Dockerfile', 'packages/create-app/template/docker/opencode/Dockerfile']) {
83
+ assert.ok(fs.readFileSync(path.join(repoRoot, file), 'utf8').includes(`ARG OPENCODE_BASE_IMAGE=${DEFAULT_OPENCODE_BASE_IMAGE}\n`))
84
+ }
85
+ })
86
+
87
+
88
+ function preflightOptions(cwd, env, hooks = {}) {
89
+ return {
90
+ cwd, env,
91
+ composeArgs: (extra) => ['compose', ...extra],
92
+ services: [{ service: 'redis', envKey: 'REDIS_PORT', port: 6379 }],
93
+ detect: () => ({ ok: true }),
94
+ spawnSyncImpl: () => ({ status: 0, stdout: '' }),
95
+ portProbe: async () => false,
96
+ containerProbe: () => [],
97
+ processProbe: () => [],
98
+ log() {},
99
+ ...hooks,
100
+ }
101
+ }
102
+
103
+ test('nonlocal Redis without a password is rejected before every Docker call', async () => {
104
+ const fixture = fs.mkdtempSync(path.join(os.tmpdir(), 'om-infra-binding-'))
105
+ try {
106
+ fs.writeFileSync(path.join(fixture, '.env'), 'INFRA_BIND_HOST=0.0.0.0\nREDIS_PASSWORD=\n')
107
+ let dockerCalls = 0
108
+ const result = await startInfraServices(preflightOptions(fixture, {}, {
109
+ detect() { dockerCalls += 1; return { ok: true } },
110
+ spawnSyncImpl() { dockerCalls += 1; return { status: 0, stdout: '' } },
111
+ }))
112
+ assert.equal(result.ok, false)
113
+ assert.equal(result.problem.code, 'unsafe-binding')
114
+ assert.equal(dockerCalls, 0)
115
+ const message = formatInfraProblem(result.problem, { output: { isTTY: false }, env: {} }).join('\n')
116
+ assert.match(message, /REDIS_PASSWORD/)
117
+ assert.match(message, /INFRA_BIND_HOST=127\.0\.0\.1/)
118
+ } finally { fs.rmSync(fixture, { recursive: true, force: true }) }
119
+ })
120
+
121
+ test('shell binding and password values override dotenv while authenticated nonlocal Redis is allowed', async () => {
122
+ const fixture = fs.mkdtempSync(path.join(os.tmpdir(), 'om-infra-binding-'))
123
+ try {
124
+ fs.writeFileSync(path.join(fixture, '.env'), "INFRA_BIND_HOST=0.0.0.0\nREDIS_PASSWORD='configured password'\n")
125
+ const accepted = await startInfraServices(preflightOptions(fixture, {}))
126
+ assert.equal(accepted.ok, true)
127
+ const rejected = await startInfraServices(preflightOptions(fixture, { REDIS_PASSWORD: '' }))
128
+ assert.equal(rejected.problem.code, 'unsafe-binding')
129
+ const local = await startInfraServices(preflightOptions(fixture, { INFRA_BIND_HOST: '127.0.0.1', REDIS_PASSWORD: '' }))
130
+ assert.equal(local.ok, true)
131
+ const shellPassword = await startInfraServices(preflightOptions(fixture, { INFRA_BIND_HOST: '::', REDIS_PASSWORD: 'authenticated' }))
132
+ assert.equal(shellPassword.ok, true)
133
+ } finally { fs.rmSync(fixture, { recursive: true, force: true }) }
134
+ })