@open-mercato/starter 0.10.1-develop.7994.1.c9f31972aa → 0.10.1-develop.8004.1.a8a79ee43f
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 +45 -12
- package/package.json +1 -1
- package/src/__tests__/database-write-guard.test.mjs +111 -0
- package/src/__tests__/port-diagnostics.test.mjs +21 -0
- package/src/__tests__/service-compose-security.test.mjs +134 -0
- package/src/__tests__/service-modes.test.mjs +298 -0
- package/src/__tests__/service-selection.test.mjs +292 -0
- package/src/__tests__/setup-streaming.test.mjs +34 -0
- package/src/__tests__/starter.test.mjs +103 -3
- package/src/cli.mjs +114 -18
- package/src/compose.mjs +9 -3
- package/src/constants.mjs +1 -1
- package/src/database-write-guard.mjs +80 -0
- package/src/infra-preflight.mjs +112 -0
- package/src/service-modes.mjs +358 -0
- package/src/setup-session.mjs +77 -0
- package/src/steps.mjs +60 -3
package/README.md
CHANGED
|
@@ -11,7 +11,7 @@ yarn setup # same as `yarn om up`: everything from install to a run
|
|
|
11
11
|
yarn om # alias for node packages/starter/bin/om-start.mjs
|
|
12
12
|
```
|
|
13
13
|
|
|
14
|
-
`yarn setup`
|
|
14
|
+
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
15
|
|
|
16
16
|
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
17
|
|
|
@@ -36,9 +36,7 @@ No Node yet? The package ships pre-Node bootstraps that install a **portable, ch
|
|
|
36
36
|
|
|
37
37
|
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
38
|
|
|
39
|
-
|
|
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>`.
|
|
39
|
+
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
40
|
|
|
43
41
|
`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
42
|
|
|
@@ -52,7 +50,7 @@ Use `yarn setup --verbose` or `yarn infra:up --verbose` for live raw output. CI,
|
|
|
52
50
|
|
|
53
51
|
## Design rules
|
|
54
52
|
|
|
55
|
-
- **Node stdlib
|
|
53
|
+
- **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
54
|
- **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
55
|
- **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
56
|
- **Probes use `127.0.0.1`, never `localhost`** (Windows resolves `localhost` to `::1` first).
|
|
@@ -62,10 +60,45 @@ Use `yarn setup --verbose` or `yarn infra:up --verbose` for live raw output. CI,
|
|
|
62
60
|
|
|
63
61
|
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
62
|
|
|
65
|
-
##
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
63
|
+
## Recovering from setup failure
|
|
64
|
+
|
|
65
|
+
The starter prints the failed step and a manual path. Check the selected service
|
|
66
|
+
URLs in `apps/mercato/.env`, then run `yarn install`, `yarn build:packages`,
|
|
67
|
+
`yarn generate`, `yarn build:packages`, `yarn db:migrate`,
|
|
68
|
+
`yarn initialize -- --skip-if-initialized`, and `yarn dev --no-infra`.
|
|
69
|
+
Alternatively retry `yarn setup --ephemeral`, `yarn setup --random-ports`, or
|
|
70
|
+
`yarn setup --infra`. Ephemeral URLs are session-scoped; after failure or exit,
|
|
71
|
+
use the restored existing-service URLs or start another ephemeral setup session.
|
|
72
|
+
|
|
73
|
+
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.
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
## Setup security boundaries
|
|
77
|
+
|
|
78
|
+
Plain and noninteractive setup never start services on ports that already
|
|
79
|
+
answer and never contact a database held by another project's containers: they
|
|
80
|
+
reuse verified services, start Compose on free configured ports, or isolate
|
|
81
|
+
themselves on free random ports. Explicit flags keep their exact meaning.
|
|
82
|
+
|
|
83
|
+
Before any setup/development migration or initialization, the guard resolves the
|
|
84
|
+
actual PostgreSQL target (including connection-string overrides). Non-loopback
|
|
85
|
+
writes require an exact target acknowledgement, for example
|
|
86
|
+
`yarn setup --allow-remote-database=staging.example:5432/app_db`. A bare
|
|
87
|
+
`--allow-remote-database` prompts for that exact target only in a terminal;
|
|
88
|
+
unattended runs must provide it. Connection snapshots prevent a changed `.env`
|
|
89
|
+
from redirecting an already-authorized child command. Local reuse needs no flag.
|
|
90
|
+
|
|
91
|
+
Isolated modes generate independent random PostgreSQL, Redis and Meilisearch
|
|
92
|
+
credentials, never reuse configured remote credentials, and pin their images
|
|
93
|
+
(including the Testcontainers cleanup image) by verified multiarch digests.
|
|
94
|
+
Random stacks save their owned `OM_SETUP_LOCAL_*` values in ignored `.env` files
|
|
95
|
+
and reuse those values on later runs despite ambient remote URL overrides.
|
|
96
|
+
The new `mercato-local-v2-*` identity creates separate volumes from earlier
|
|
97
|
+
random stacks; old containers/data are retained and are not deleted or migrated.
|
|
98
|
+
|
|
99
|
+
Development Compose bindings default to `127.0.0.1`. An explicit
|
|
100
|
+
`INFRA_BIND_HOST` outside loopback additionally requires a Redis password and
|
|
101
|
+
matching Redis URLs. Random mode forces loopback regardless of that ambient
|
|
102
|
+
setting. Full application/container deployment Compose files retain their
|
|
103
|
+
existing bindings. Optional profiles not started by setup retain their existing
|
|
104
|
+
image policy; the setup services and OpenCode defaults are pinned.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-mercato/starter",
|
|
3
|
-
"version": "0.10.1-develop.
|
|
3
|
+
"version": "0.10.1-develop.8004.1.a8a79ee43f",
|
|
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' }
|
|
@@ -106,3 +107,23 @@ test('consent separates warning emojis and the continuing paragraph from the ans
|
|
|
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
|
+
})
|
|
@@ -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
|
+
})
|