crewaid-selfhost 0.0.0-stage → 0.0.4

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
@@ -1,3 +1,20 @@
1
- # Temporary Holding Version
1
+ # crewaid-selfhost
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Install, update and look after a self-hosted [Crewaid](https://crewaid.io) server.
4
+
5
+ ```sh
6
+ npx crewaid-selfhost init # or: curl -fsSL https://downloads.crewaid.io/install.sh | sh
7
+ npx crewaid-selfhost update # move to a newer release (keeps your keys)
8
+ npx crewaid-selfhost status
9
+ npx crewaid-selfhost reset-password you@example.com
10
+ ```
11
+
12
+ `init` checks Docker, asks how the server will be reached — this computer, your
13
+ local network, or a domain with HTTPS — generates every secret, writes
14
+ `compose.yml` and `.env` to `~/crewaid` (`--dir` to change), starts the server
15
+ and tells you what to type into the **Crewaid Self-Hosted** app
16
+ ([macOS](https://downloads.crewaid.io/desktop/selfhosted/mac),
17
+ [Windows](https://downloads.crewaid.io/desktop/selfhosted/windows)).
18
+
19
+ Needs Docker Desktop (macOS, Windows) or Docker Engine with Compose v2 (Linux).
20
+ `crewaid-selfhost --help` lists every option.
@@ -0,0 +1,178 @@
1
+ # Self-hosted Crewaid (D-152, D-155): the orchestrator, its database and queue,
2
+ # the sandbox egress fence, and the sandbox image the computers run.
3
+ #
4
+ # `npx crewaid-selfhost init` writes this file and its .env; to run it by hand,
5
+ # copy .env.example to .env, fill it in, then `docker compose up -d`.
6
+ # Works on Linux (Docker Engine + Compose v2) and on Docker Desktop (Mac,
7
+ # Windows): the fence runs in the Docker daemon's own network namespace.
8
+
9
+ name: crewaid
10
+
11
+ services:
12
+ postgres:
13
+ image: postgres:16.10-alpine
14
+ restart: unless-stopped
15
+ environment:
16
+ POSTGRES_USER: crewaid
17
+ POSTGRES_DB: crewaid
18
+ POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD (hex, as it goes into a URL)}
19
+ volumes:
20
+ - postgres-data:/var/lib/postgresql/data
21
+ healthcheck:
22
+ test: ['CMD-SHELL', 'pg_isready -U crewaid -d crewaid']
23
+ interval: 5s
24
+ timeout: 5s
25
+ retries: 20
26
+
27
+ redis:
28
+ image: redis:7.4-alpine
29
+ restart: unless-stopped
30
+ # A password as well as a private network (#355): Redis holds every queue,
31
+ # so anything that reaches it can schedule work as any user. `$$` leaves
32
+ # the expansion to the container's shell, out of the command line.
33
+ environment:
34
+ REDIS_PASSWORD: ${REDIS_PASSWORD:?Set REDIS_PASSWORD (hex, as it goes into a URL)}
35
+ command: ['sh', '-c', 'exec redis-server --appendonly yes --requirepass "$$REDIS_PASSWORD"']
36
+ volumes:
37
+ - redis-data:/data
38
+ healthcheck:
39
+ test: ['CMD-SHELL', 'REDISCLI_AUTH="$$REDIS_PASSWORD" redis-cli ping | grep -q PONG']
40
+ interval: 5s
41
+ timeout: 5s
42
+ retries: 20
43
+
44
+ # The sandbox egress fence (D-155). A computer may reach the internet on 80
45
+ # and 443 and nothing else: not this machine, not the local network, not a
46
+ # cloud metadata address. It runs in the Docker daemon's network namespace —
47
+ # the Linux host, or Docker Desktop's VM — because that is where the sandbox
48
+ # bridge is. Privileged only to write the bridge-netfilter sysctls; it holds
49
+ # no Docker socket.
50
+ egress:
51
+ image: ghcr.io/natanael-exe/crewaid-egress:${CREWAID_VERSION}
52
+ restart: unless-stopped
53
+ network_mode: host
54
+ privileged: true
55
+ environment:
56
+ CREWAID_SANDBOX_BRIDGE: crewaid-sbx0
57
+ # The orchestrator's address on the sandbox network: the one thing that
58
+ # may open a connection to a computer, since nothing is published.
59
+ CREWAID_TRUSTED_SOURCE: ${CREWAID_ORCHESTRATOR_ADDRESS:-10.231.0.2}
60
+ CREWAID_EGRESS_STATE: /run/crewaid
61
+ volumes:
62
+ - egress-state:/run/crewaid
63
+ depends_on:
64
+ # Not used by the fence: depending on it makes compose create the
65
+ # sandbox network (and so its bridge) before this starts.
66
+ networks-ready:
67
+ condition: service_completed_successfully
68
+
69
+ # Exists to create the sandbox network, and to make sure the
70
+ # sandbox image is on this machine: the orchestrator starts computers from
71
+ # it but never pulls it. Runs once and exits.
72
+ networks-ready:
73
+ image: ghcr.io/natanael-exe/crewaid-sandbox:${CREWAID_VERSION}
74
+ entrypoint: ['true']
75
+ restart: 'no'
76
+ networks:
77
+ - sandboxes
78
+
79
+ orchestrator:
80
+ image: ghcr.io/natanael-exe/crewaid-orchestrator:${CREWAID_VERSION:?Set CREWAID_VERSION to a release, e.g. 0.1.0}
81
+ restart: unless-stopped
82
+ environment:
83
+ CREWAID_EDITION: selfhosted
84
+ NODE_ENV: production
85
+ PORT: '3000'
86
+ DATABASE_URL: postgresql://crewaid:${POSTGRES_PASSWORD}@postgres:5432/crewaid?schema=public
87
+ MIGRATION_DATABASE_URL: postgresql://crewaid:${POSTGRES_PASSWORD}@postgres:5432/crewaid?schema=public
88
+ REDIS_URL: redis://:${REDIS_PASSWORD}@redis:6379
89
+ BETTER_AUTH_URL: ${BETTER_AUTH_URL:?Set the address the desktop app will use, e.g. http://localhost:3000}
90
+ BETTER_AUTH_SECRET: ${BETTER_AUTH_SECRET:?Set BETTER_AUTH_SECRET}
91
+ CREWAID_CREDENTIAL_KEYRING: ${CREWAID_CREDENTIAL_KEYRING:?Set CREWAID_CREDENTIAL_KEYRING}
92
+ CREDENTIAL_KEY: ${CREDENTIAL_KEY:?Set CREDENTIAL_KEY}
93
+ ARTIFACT_DIR: /var/lib/crewaid/artifacts
94
+ SANDBOX_PROVIDER: docker
95
+ SANDBOX_IMAGE: ghcr.io/natanael-exe/crewaid-sandbox:${CREWAID_VERSION}
96
+ SANDBOX_NETWORK: crewaid-sandboxes
97
+ # Nothing is published: the orchestrator reaches a computer's screen and
98
+ # DevTools at the computer's own address on the sandbox network, which it
99
+ # joins below — the one address the fence lets in. (Docker Desktop
100
+ # cannot publish on a bridge gateway, and this needs no published port.)
101
+ SANDBOX_CONNECT: network
102
+ SANDBOX_MAX_RUNNING: ${SANDBOX_MAX_RUNNING:-2}
103
+ # Docker restarts this container on boot alongside the fence. Starting only
104
+ # once the fence's marker exists keeps a routine from waking a computer
105
+ # with no egress policy; if the fence fails, this never starts.
106
+ command:
107
+ - /bin/sh
108
+ - -ec
109
+ - |
110
+ if [ ! -e /run/crewaid/egress-ready ]; then
111
+ echo 'Waiting for the egress fence (the "egress" service) to install its policy' >&2
112
+ until [ -e /run/crewaid/egress-ready ]; do sleep 2; done
113
+ fi
114
+ exec infra/dokploy/orchestrator-entrypoint.sh
115
+ ports:
116
+ # This computer only, unless the installer chose the local network.
117
+ - ${CREWAID_BIND:-127.0.0.1}:${CREWAID_PORT:-3000}:3000
118
+ networks:
119
+ default: {}
120
+ sandboxes:
121
+ ipv4_address: ${CREWAID_ORCHESTRATOR_ADDRESS:-10.231.0.2}
122
+ volumes:
123
+ - /var/run/docker.sock:/var/run/docker.sock
124
+ - egress-state:/run/crewaid:ro
125
+ - artifacts:/var/lib/crewaid/artifacts
126
+ depends_on:
127
+ postgres:
128
+ condition: service_healthy
129
+ redis:
130
+ condition: service_healthy
131
+ networks-ready:
132
+ condition: service_completed_successfully
133
+
134
+ # HTTPS for a server reached by a domain name: `--profile https`, with
135
+ # CREWAID_DOMAIN pointing at this machine. Certificates come from Let's
136
+ # Encrypt automatically; WebSockets pass through.
137
+ caddy:
138
+ image: caddy:2.10-alpine
139
+ profiles: [https]
140
+ restart: unless-stopped
141
+ command: ['caddy', 'reverse-proxy', '--from', '${CREWAID_DOMAIN:-}', '--to', 'orchestrator:3000']
142
+ ports:
143
+ - 80:80
144
+ - 443:443
145
+ volumes:
146
+ - caddy-data:/data
147
+ depends_on:
148
+ - orchestrator
149
+
150
+ networks:
151
+ default: {}
152
+ # Computers. The fence lets a computer out only to the internet on 80/443,
153
+ # and lets only the orchestrator's address open connections into it.
154
+ # 10.x on purpose: Docker hands out 172.17–31 and 192.168 to new networks,
155
+ # so a fixed range there collides on any machine with a few compose
156
+ # projects. The installer checks this range is free and picks another if not.
157
+ sandboxes:
158
+ name: crewaid-sandboxes
159
+ driver: bridge
160
+ driver_opts:
161
+ com.docker.network.bridge.name: crewaid-sbx0
162
+ ipam:
163
+ config:
164
+ - subnet: ${CREWAID_SANDBOX_SUBNET:-10.231.0.0/24}
165
+
166
+ volumes:
167
+ postgres-data:
168
+ redis-data:
169
+ artifacts:
170
+ caddy-data:
171
+ # tmpfs: emptied when the daemon or machine restarts, so the orchestrator
172
+ # waits for the fence to install its policy again before it starts.
173
+ egress-state:
174
+ driver: local
175
+ driver_opts:
176
+ type: tmpfs
177
+ device: tmpfs
178
+ o: size=1m,mode=0755
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env node
2
+ import { main } from '../src/cli.mjs';
3
+
4
+ main(process.argv.slice(2)).then(
5
+ (code) => process.exit(code),
6
+ (error) => {
7
+ console.error(`crewaid-selfhost: ${error instanceof Error ? error.message : String(error)}`);
8
+ process.exit(1);
9
+ },
10
+ );
package/package.json CHANGED
@@ -1,6 +1,23 @@
1
1
  {
2
2
  "name": "crewaid-selfhost",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.4",
4
+ "description": "Install, update and look after a self-hosted Crewaid server (Docker).",
5
+ "type": "module",
6
+ "license": "UNLICENSED",
7
+ "homepage": "https://crewaid.io/self-host",
8
+ "bin": {
9
+ "crewaid-selfhost": "bin/crewaid-selfhost.mjs"
10
+ },
11
+ "files": [
12
+ "bin",
13
+ "src",
14
+ "assets",
15
+ "README.md"
16
+ ],
17
+ "engines": {
18
+ "node": ">=18"
19
+ },
20
+ "scripts": {
21
+ "test": "node --test \"test/*.test.mjs\""
22
+ }
23
+ }
package/src/cli.mjs ADDED
@@ -0,0 +1,411 @@
1
+ import { chmod, chown, mkdir, readFile, writeFile, access } from 'node:fs/promises';
2
+ import { homedir } from 'node:os';
3
+ import path from 'node:path';
4
+ import { createInterface } from 'node:readline/promises';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { generateSecrets } from './secrets.mjs';
7
+ import { parseEnv, renderEnv, setEnvValue } from './env.mjs';
8
+ import { lanAddress, pickSandboxSubnet, portIsFree } from './network.mjs';
9
+ import { capture, compose, dockerSubnets, existingProject, preflight } from './docker.mjs';
10
+
11
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
12
+ const DOWNLOADS = 'https://downloads.crewaid.io/desktop/selfhosted';
13
+
14
+ export async function ownVersion() {
15
+ const pkg = JSON.parse(await readFile(path.join(HERE, '..', 'package.json'), 'utf8'));
16
+ return pkg.version;
17
+ }
18
+
19
+ export async function composeTemplate() {
20
+ return readFile(path.join(HERE, '..', 'assets', 'compose.yml'), 'utf8');
21
+ }
22
+
23
+ const HELP = `crewaid-selfhost — run Crewaid on your own machine or server (Docker)
24
+
25
+ init [options] install: write compose.yml and .env, start the server
26
+ --dir <path> where to install (default ~/crewaid)
27
+ --mode <local|lan|domain>
28
+ local: this computer only (http://localhost:<port>)
29
+ lan: your local network (http://<lan-ip>:<port>, unencrypted)
30
+ domain: a domain name pointed here, HTTPS via Let's Encrypt
31
+ --domain <name> for --mode domain
32
+ --port <n> default 3000
33
+ --version <x.y.z> release to run (default: this installer's)
34
+ --yes accept the defaults instead of asking
35
+ update [--dir] [--version] move to a newer release (keeps .env)
36
+ status [--dir] what is running, and the server's health
37
+ reset-password <email> [--dir]
38
+ set a new password for an account
39
+ `;
40
+
41
+ export function parseArgs(argv) {
42
+ const options = { _: [] };
43
+ for (let i = 0; i < argv.length; i++) {
44
+ const arg = argv[i];
45
+ if (arg === '--yes' || arg === '-y') options.yes = true;
46
+ else if (arg === '--help' || arg === '-h') options.help = true;
47
+ else if (arg.startsWith('--')) {
48
+ const [key, inline] = arg.slice(2).split('=', 2);
49
+ options[key] = inline ?? argv[++i];
50
+ } else options._.push(arg);
51
+ }
52
+ return options;
53
+ }
54
+
55
+ function installDir(options) {
56
+ const raw = options.dir ?? process.env.CREWAID_DIR ?? path.join(homedir(), 'crewaid');
57
+ return path.resolve(raw.replace(/^~(?=$|\/)/, homedir()));
58
+ }
59
+
60
+ /**
61
+ * Give the files back to the person who ran install.sh. The installer's
62
+ * container runs as root, so on Linux what it writes is root's — including a
63
+ * mode-600 .env its owner could then not read. (Docker Desktop's file sharing
64
+ * hides this on macOS and Windows; the ids it is handed are the host's.)
65
+ */
66
+ async function returnOwnership(dir, files) {
67
+ const uid = Number(process.env.CREWAID_HOST_UID);
68
+ const gid = Number(process.env.CREWAID_HOST_GID);
69
+ if (process.env.CREWAID_IN_CONTAINER !== '1' || !Number.isInteger(uid) || !Number.isInteger(gid))
70
+ return;
71
+ for (const target of [dir, ...files.map((file) => path.join(dir, file))]) {
72
+ await chown(target, uid, gid).catch(() => undefined);
73
+ }
74
+ }
75
+
76
+ async function exists(file) {
77
+ try {
78
+ await access(file);
79
+ return true;
80
+ } catch {
81
+ return false;
82
+ }
83
+ }
84
+
85
+ /**
86
+ * The address the desktop app will use and how the server listens, for a mode.
87
+ * Pure, so the three shapes are tested without a terminal or Docker.
88
+ */
89
+ export function addressPlan({ mode, port, domain, lan }) {
90
+ if (mode === 'domain') {
91
+ if (!domain) throw new Error('--mode domain needs --domain <name>');
92
+ return {
93
+ BETTER_AUTH_URL: `https://${domain}`,
94
+ CREWAID_BIND: '127.0.0.1',
95
+ CREWAID_PORT: String(port),
96
+ CREWAID_DOMAIN: domain,
97
+ COMPOSE_PROFILES: 'https',
98
+ };
99
+ }
100
+ if (mode === 'lan') {
101
+ if (!lan)
102
+ throw new Error(
103
+ 'Could not find this machine’s local network address; use --mode local or --mode domain.',
104
+ );
105
+ return {
106
+ BETTER_AUTH_URL: `http://${lan}:${port}`,
107
+ CREWAID_BIND: '0.0.0.0',
108
+ CREWAID_PORT: String(port),
109
+ };
110
+ }
111
+ return {
112
+ BETTER_AUTH_URL: `http://localhost:${port}`,
113
+ CREWAID_BIND: '127.0.0.1',
114
+ CREWAID_PORT: String(port),
115
+ };
116
+ }
117
+
118
+ async function ask(rl, question, fallback) {
119
+ if (!rl) return fallback;
120
+ const answer = (await rl.question(`${question} [${fallback}] `)).trim();
121
+ return answer === '' ? fallback : answer;
122
+ }
123
+
124
+ /**
125
+ * The server's `/health`, or null. Asked over its published port — which also
126
+ * proves the port works — except when the installer itself runs in a
127
+ * container (install.sh without Node), where 127.0.0.1 is that container: then
128
+ * the orchestrator container is asked directly.
129
+ */
130
+ export async function readHealth(dir, port) {
131
+ if (process.env.CREWAID_IN_CONTAINER === '1') {
132
+ const result = capture('docker', [
133
+ 'compose',
134
+ '--project-directory',
135
+ dir,
136
+ '-f',
137
+ `${dir}/compose.yml`,
138
+ 'exec',
139
+ '-T',
140
+ 'orchestrator',
141
+ 'node',
142
+ '-e',
143
+ "fetch('http://127.0.0.1:3000/health').then(r=>r.text()).then(t=>process.stdout.write(t))",
144
+ ]);
145
+ try {
146
+ return result.ok ? JSON.parse(result.stdout) : null;
147
+ } catch {
148
+ return null;
149
+ }
150
+ }
151
+ try {
152
+ const response = await fetch(`http://127.0.0.1:${port}/health`);
153
+ return response.ok ? await response.json() : null;
154
+ } catch {
155
+ return null;
156
+ }
157
+ }
158
+
159
+ /**
160
+ * Ready means `/health` says `ok`. It answers 200 whenever the process is up —
161
+ * a database or Redis outage is reported in the body, not the status code —
162
+ * so a 200 alone would call a broken server running.
163
+ */
164
+ export function readiness(health) {
165
+ if (health === null) return { ready: false, problem: 'the server is not answering' };
166
+ if (health.status === 'ok') return { ready: true };
167
+ const down = ['db', 'redis', 'docker'].filter((part) => health[part] === false);
168
+ const names = { db: 'the database', redis: 'Redis', docker: 'Docker' };
169
+ return {
170
+ ready: false,
171
+ problem: down.length
172
+ ? `${down.map((part) => names[part]).join(' and ')} not reachable`
173
+ : `status ${health.status}`,
174
+ };
175
+ }
176
+
177
+ /** Wait until the server is ready; the last answer either way. */
178
+ async function waitForReady(dir, port, timeoutMs = 300_000) {
179
+ const deadline = Date.now() + timeoutMs;
180
+ let health = null;
181
+ while (Date.now() < deadline) {
182
+ health = await readHealth(dir, port);
183
+ if (readiness(health).ready) return health;
184
+ await new Promise((resolve) => setTimeout(resolve, 2000));
185
+ }
186
+ return health;
187
+ }
188
+
189
+ /**
190
+ * Why `init` must not run here, or null. The Compose project, its volumes and
191
+ * networks have fixed names, so a second install in another folder would take
192
+ * over the first one's containers and data with new keys.
193
+ */
194
+ export function installConflict({ dir, folders, dataVolume }) {
195
+ const elsewhere = folders.filter((folder) => path.resolve(folder) !== path.resolve(dir));
196
+ if (elsewhere.length > 0) {
197
+ return (
198
+ `A Crewaid server already runs from ${elsewhere[0]}. One machine runs one: use ` +
199
+ `\`crewaid-selfhost update --dir ${elsewhere[0]}\` to update it, or remove it there first ` +
200
+ '(`docker compose down`).'
201
+ );
202
+ }
203
+ if (folders.length === 0 && dataVolume) {
204
+ return (
205
+ 'An earlier Crewaid install left its data here (Docker volume crewaid_postgres-data), and it ' +
206
+ 'is encrypted with that install’s keys. Run `crewaid-selfhost update` in that install’s folder ' +
207
+ 'to bring it back, or delete the data for a fresh start: ' +
208
+ '`docker volume rm crewaid_postgres-data crewaid_redis-data crewaid_artifacts`.'
209
+ );
210
+ }
211
+ return null;
212
+ }
213
+
214
+ async function init(options) {
215
+ const check = preflight();
216
+ if (!check.ok) return fail(check.message);
217
+ console.log(`Docker ${check.docker}, Compose ${check.compose}.`);
218
+
219
+ const dir = installDir(options);
220
+ if (await exists(path.join(dir, '.env'))) {
221
+ return fail(
222
+ `${dir} already has a Crewaid server. Use \`crewaid-selfhost update\` to move it to a newer release.`,
223
+ );
224
+ }
225
+ const conflict = installConflict({ dir, ...existingProject() });
226
+ if (conflict !== null) return fail(conflict);
227
+
228
+ const interactive = !options.yes && process.stdin.isTTY;
229
+ const rl = interactive ? createInterface({ input: process.stdin, output: process.stdout }) : null;
230
+ try {
231
+ let mode = options.mode;
232
+ if (!mode) {
233
+ console.log('\nHow will the desktop app reach this server?');
234
+ console.log(' local this computer only');
235
+ console.log(' lan other computers on your local network (unencrypted)');
236
+ console.log(' domain the internet, through a domain name pointed here (HTTPS)');
237
+ mode = await ask(rl, 'Choose', 'local');
238
+ }
239
+ if (!['local', 'lan', 'domain'].includes(mode))
240
+ return fail(`Unknown mode "${mode}": use local, lan or domain.`);
241
+ const domain =
242
+ mode === 'domain' ? (options.domain ?? (await ask(rl, 'Domain name', ''))) : undefined;
243
+ const port = Number(options.port ?? 3000);
244
+ if (!Number.isInteger(port) || port < 1 || port > 65535)
245
+ return fail(`--port must be 1–65535, got ${options.port}`);
246
+ if (process.env.CREWAID_IN_CONTAINER !== '1' && !(await portIsFree(port))) {
247
+ return fail(`Port ${port} is already in use on this machine. Choose another with --port.`);
248
+ }
249
+ const lan = process.env.CREWAID_HOST_LAN_IP || lanAddress();
250
+ const plan = addressPlan({ mode, port, domain, lan });
251
+ const version = options.version ?? (await ownVersion());
252
+ const { subnet, orchestrator } = pickSandboxSubnet(dockerSubnets());
253
+
254
+ await mkdir(dir, { recursive: true });
255
+ await writeFile(path.join(dir, 'compose.yml'), await composeTemplate());
256
+ const envFile = path.join(dir, '.env');
257
+ await writeFile(
258
+ envFile,
259
+ renderEnv({
260
+ CREWAID_VERSION: version,
261
+ ...plan,
262
+ CREWAID_SANDBOX_SUBNET: subnet,
263
+ CREWAID_ORCHESTRATOR_ADDRESS: orchestrator,
264
+ SANDBOX_MAX_RUNNING: '2',
265
+ ...generateSecrets(),
266
+ }),
267
+ { mode: 0o600 },
268
+ );
269
+ await chmod(envFile, 0o600);
270
+ await returnOwnership(dir, ['compose.yml', '.env']);
271
+ console.log(`\nWrote ${dir}/compose.yml and .env (keep .env private: it holds every key).`);
272
+ if (mode === 'lan') {
273
+ console.log(
274
+ 'Note: on a local network the connection is not encrypted — fine on a network you trust.',
275
+ );
276
+ }
277
+ if (mode === 'domain') {
278
+ console.log(
279
+ `Point ${domain}'s DNS at this machine and open ports 80 and 443 for the certificate.`,
280
+ );
281
+ }
282
+
283
+ console.log(`\nStarting Crewaid ${version} (the first start downloads about 2 GB)…`);
284
+ const code = await compose(dir, ['up', '-d']);
285
+ if (code !== 0)
286
+ return fail(
287
+ `docker compose up failed (exit ${code}). Logs: cd ${dir} && docker compose logs`,
288
+ );
289
+ const health = await waitForReady(dir, port);
290
+ const state = readiness(health);
291
+ if (!state.ready) {
292
+ return fail(
293
+ `The server is not ready after 5 minutes: ${state.problem}. Logs: cd ${dir} && docker compose logs`,
294
+ );
295
+ }
296
+
297
+ console.log(`
298
+ Crewaid ${health.version} is running.
299
+
300
+ 1. Download Crewaid Self-Hosted:
301
+ macOS ${DOWNLOADS}/mac
302
+ Windows ${DOWNLOADS}/windows
303
+ 2. Open it and enter this address: ${plan.BETTER_AUTH_URL}
304
+ 3. Create your account — the first one is yours; anyone who can reach the
305
+ address can create their own.
306
+
307
+ Later: \`npx crewaid-selfhost update\` for new releases, \`npx crewaid-selfhost reset-password <email>\`
308
+ if someone forgets theirs. Everything lives in ${dir}.`);
309
+ return 0;
310
+ } finally {
311
+ rl?.close();
312
+ }
313
+ }
314
+
315
+ async function update(options) {
316
+ const check = preflight();
317
+ if (!check.ok) return fail(check.message);
318
+ const dir = installDir(options);
319
+ const envFile = path.join(dir, '.env');
320
+ if (!(await exists(envFile)))
321
+ return fail(`No Crewaid server in ${dir}. Install one with \`crewaid-selfhost init\`.`);
322
+ const text = await readFile(envFile, 'utf8');
323
+ const current = parseEnv(text).CREWAID_VERSION;
324
+ const version = options.version ?? (await ownVersion());
325
+ console.log(`Updating ${dir} from ${current} to ${version}.`);
326
+ // The compose file belongs to the release; .env belongs to the operator and
327
+ // only its version line changes.
328
+ await writeFile(path.join(dir, 'compose.yml'), await composeTemplate());
329
+ await writeFile(envFile, setEnvValue(text, 'CREWAID_VERSION', version), { mode: 0o600 });
330
+ await returnOwnership(dir, ['compose.yml', '.env']);
331
+ let code = await compose(dir, ['pull']);
332
+ if (code !== 0) {
333
+ return fail(
334
+ `Could not download Crewaid ${version}'s images (exit ${code}). Check the version exists ` +
335
+ '(https://github.com/natanael-exe — crewaid-orchestrator) and that this machine is online.',
336
+ );
337
+ }
338
+ code = await compose(dir, ['up', '-d']);
339
+ if (code !== 0)
340
+ return fail(`docker compose up failed (exit ${code}). Logs: cd ${dir} && docker compose logs`);
341
+ const health = await waitForReady(dir, Number(parseEnv(text).CREWAID_PORT ?? 3000));
342
+ const state = readiness(health);
343
+ if (!state.ready) {
344
+ return fail(
345
+ `Started, but not ready after 5 minutes: ${state.problem}. Logs: cd ${dir} && docker compose logs`,
346
+ );
347
+ }
348
+ console.log(`Crewaid ${health.version} is running.`);
349
+ return 0;
350
+ }
351
+
352
+ async function status(options) {
353
+ const dir = installDir(options);
354
+ const code = await compose(dir, ['ps']);
355
+ const env = (await exists(path.join(dir, '.env')))
356
+ ? parseEnv(await readFile(path.join(dir, '.env'), 'utf8'))
357
+ : {};
358
+ const health = await readHealth(dir, Number(env.CREWAID_PORT ?? 3000));
359
+ console.log(
360
+ health === null
361
+ ? '\nServer: not answering.'
362
+ : `\nServer: ${health.status}, version ${health.version}, address ${env.BETTER_AUTH_URL ?? '?'}`,
363
+ );
364
+ return code;
365
+ }
366
+
367
+ async function resetPassword(options) {
368
+ const email = options._[1];
369
+ if (!email) return fail('usage: crewaid-selfhost reset-password <email>');
370
+ return compose(installDir(options), [
371
+ 'exec',
372
+ 'orchestrator',
373
+ 'node',
374
+ 'apps/orchestrator/dist/cli/reset-password.js',
375
+ email,
376
+ ]);
377
+ }
378
+
379
+ function fail(message) {
380
+ console.error(`crewaid-selfhost: ${message}`);
381
+ return 1;
382
+ }
383
+
384
+ export async function main(argv) {
385
+ const options = parseArgs(argv);
386
+ const command = options._[0];
387
+ if (!command && 'version' in options && options.version === undefined) {
388
+ console.log(await ownVersion());
389
+ return 0;
390
+ }
391
+ if (options.help || !command) {
392
+ console.log(HELP);
393
+ return command || options.help ? 0 : 1;
394
+ }
395
+ if (command === '--version' || command === 'version') {
396
+ console.log(await ownVersion());
397
+ return 0;
398
+ }
399
+ switch (command) {
400
+ case 'init':
401
+ return init(options);
402
+ case 'update':
403
+ return update(options);
404
+ case 'status':
405
+ return status(options);
406
+ case 'reset-password':
407
+ return resetPassword(options);
408
+ default:
409
+ return fail(`unknown command "${command}"\n\n${HELP}`);
410
+ }
411
+ }
package/src/docker.mjs ADDED
@@ -0,0 +1,100 @@
1
+ import { spawn, spawnSync } from 'node:child_process';
2
+
3
+ /** Run a command and capture its output; never throws, so preflight can explain instead. */
4
+ export function capture(command, args) {
5
+ const result = spawnSync(command, args, { encoding: 'utf8' });
6
+ return {
7
+ ok: result.status === 0,
8
+ stdout: (result.stdout ?? '').trim(),
9
+ stderr: (result.stderr ?? '').trim(),
10
+ missing: result.error?.code === 'ENOENT',
11
+ };
12
+ }
13
+
14
+ /** Run a command attached to this terminal; resolves to its exit code. */
15
+ export function attached(command, args, options = {}) {
16
+ return new Promise((resolve) => {
17
+ const child = spawn(command, args, { stdio: 'inherit', ...options });
18
+ child.on('error', () => resolve(127));
19
+ child.on('exit', (code) => resolve(code ?? 1));
20
+ });
21
+ }
22
+
23
+ /**
24
+ * `docker compose`, pointed at the install directory. `--project-directory`
25
+ * makes Compose read that directory's .env itself — COMPOSE_PROFILES included,
26
+ * so `docker compose up -d` run by hand there does exactly what this does.
27
+ */
28
+ export function compose(dir, args) {
29
+ return attached('docker', [
30
+ 'compose',
31
+ '--project-directory',
32
+ dir,
33
+ '-f',
34
+ `${dir}/compose.yml`,
35
+ ...args,
36
+ ]);
37
+ }
38
+
39
+ /** What Docker and Compose report, or why there is nothing to talk to. */
40
+ export function preflight() {
41
+ const docker = capture('docker', ['version', '--format', '{{.Server.Version}}']);
42
+ if (docker.missing) {
43
+ return {
44
+ ok: false,
45
+ message:
46
+ 'Docker is not installed. Get Docker Desktop (Mac, Windows) or Docker Engine (Linux): https://docs.docker.com/get-docker/',
47
+ };
48
+ }
49
+ if (!docker.ok) {
50
+ return {
51
+ ok: false,
52
+ message: `Docker is installed but not running (or this user cannot reach it): ${docker.stderr.split('\n')[0]}`,
53
+ };
54
+ }
55
+ const composeVersion = capture('docker', ['compose', 'version', '--short']);
56
+ if (!composeVersion.ok) {
57
+ return {
58
+ ok: false,
59
+ message:
60
+ 'Docker Compose v2 is missing (`docker compose`). It ships with Docker Desktop; on Linux install the docker-compose-plugin package.',
61
+ };
62
+ }
63
+ return { ok: true, docker: docker.stdout, compose: composeVersion.stdout };
64
+ }
65
+
66
+ /**
67
+ * What Docker already holds of a `crewaid` Compose project: the folders its
68
+ * containers were started from, and whether its database volume exists. The
69
+ * project, network and volume names are fixed by compose.yml, so a second
70
+ * install would take these over rather than sit beside them.
71
+ */
72
+ export function existingProject() {
73
+ const containers = capture('docker', [
74
+ 'ps',
75
+ '-a',
76
+ '--filter',
77
+ 'label=com.docker.compose.project=crewaid',
78
+ '--format',
79
+ '{{.Label "com.docker.compose.project.working_dir"}}',
80
+ ]);
81
+ const volume = capture('docker', ['volume', 'inspect', 'crewaid_postgres-data']);
82
+ return {
83
+ folders: [...new Set(containers.stdout.split('\n').filter((line) => line !== ''))],
84
+ dataVolume: volume.ok,
85
+ };
86
+ }
87
+
88
+ /** Every subnet an existing Docker network uses, so a new one can avoid them. */
89
+ export function dockerSubnets() {
90
+ const ids = capture('docker', ['network', 'ls', '-q']);
91
+ if (!ids.ok || ids.stdout === '') return [];
92
+ const inspected = capture('docker', [
93
+ 'network',
94
+ 'inspect',
95
+ ...ids.stdout.split('\n'),
96
+ '--format',
97
+ '{{range .IPAM.Config}}{{.Subnet}} {{end}}',
98
+ ]);
99
+ return inspected.stdout.split(/\s+/).filter((cidr) => /^\d+\.\d+\.\d+\.\d+\/\d+$/.test(cidr));
100
+ }
package/src/env.mjs ADDED
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Read and write the server's .env — KEY=value lines, comments kept on update.
3
+ *
4
+ * A value is written bare when it is plain and single-quoted otherwise (the
5
+ * keyring is JSON), which Compose's .env parser reads back verbatim.
6
+ */
7
+ export function parseEnv(text) {
8
+ const values = {};
9
+ for (const line of text.split('\n')) {
10
+ const match = /^\s*([A-Z0-9_]+)=(.*)$/.exec(line);
11
+ if (!match) continue;
12
+ let value = match[2].trim();
13
+ if (/^'.*'$/.test(value) || /^".*"$/.test(value)) value = value.slice(1, -1);
14
+ values[match[1]] = value;
15
+ }
16
+ return values;
17
+ }
18
+
19
+ function quote(value) {
20
+ return /^[A-Za-z0-9_./:@+=-]*$/.test(value) ? value : `'${value.replace(/'/g, '')}'`;
21
+ }
22
+
23
+ export function renderEnv(entries) {
24
+ const lines = [
25
+ '# Written by crewaid-selfhost. Keep it private: it holds the keys to everything.',
26
+ '# `crewaid-selfhost update` changes CREWAID_VERSION and nothing else.',
27
+ ];
28
+ for (const [key, value] of Object.entries(entries)) {
29
+ if (value === undefined) continue;
30
+ lines.push(`${key}=${quote(String(value))}`);
31
+ }
32
+ return lines.join('\n') + '\n';
33
+ }
34
+
35
+ /** Change one key in an existing .env, leaving every other line as it was. */
36
+ export function setEnvValue(text, key, value) {
37
+ const line = `${key}=${quote(String(value))}`;
38
+ const pattern = new RegExp(`^\\s*${key}=.*$`, 'm');
39
+ return pattern.test(text) ? text.replace(pattern, line) : text.replace(/\n?$/, `\n${line}\n`);
40
+ }
@@ -0,0 +1,53 @@
1
+ import { networkInterfaces } from 'node:os';
2
+ import net from 'node:net';
3
+
4
+ /** This machine's first non-internal IPv4 address: what a LAN install advertises. */
5
+ export function lanAddress(interfaces = networkInterfaces()) {
6
+ for (const list of Object.values(interfaces)) {
7
+ for (const entry of list ?? []) {
8
+ if (entry.family === 'IPv4' && !entry.internal) return entry.address;
9
+ }
10
+ }
11
+ return null;
12
+ }
13
+
14
+ /** Whether a TCP port can be bound on this machine right now. */
15
+ export function portIsFree(port, host = '0.0.0.0') {
16
+ return new Promise((resolve) => {
17
+ const server = net.createServer();
18
+ server.once('error', () => resolve(false));
19
+ server.listen(port, host, () => server.close(() => resolve(true)));
20
+ });
21
+ }
22
+
23
+ function toInt(address) {
24
+ return address.split('.').reduce((acc, part) => acc * 256 + Number(part), 0);
25
+ }
26
+
27
+ function range(cidr) {
28
+ const [address, bits] = cidr.split('/');
29
+ const size = 2 ** (32 - Number(bits));
30
+ const start = Math.floor(toInt(address) / size) * size;
31
+ return [start, start + size - 1];
32
+ }
33
+
34
+ export function overlaps(a, b) {
35
+ const [a0, a1] = range(a);
36
+ const [b0, b1] = range(b);
37
+ return a0 <= b1 && b0 <= a1;
38
+ }
39
+
40
+ /**
41
+ * A /24 for the computers' network that no existing Docker network uses.
42
+ * 10.231.0.0/24 by default (outside Docker's own 172.17–31 and 192.168 pools);
43
+ * the next free 10.231.x.0/24 when a machine already has it.
44
+ */
45
+ export function pickSandboxSubnet(taken) {
46
+ for (let third = 0; third < 256; third++) {
47
+ const candidate = `10.231.${third}.0/24`;
48
+ if (!taken.some((cidr) => overlaps(candidate, cidr))) {
49
+ return { subnet: candidate, orchestrator: `10.231.${third}.2` };
50
+ }
51
+ }
52
+ throw new Error('No free 10.231.x.0/24 range for the computers’ network.');
53
+ }
@@ -0,0 +1,15 @@
1
+ import { randomBytes } from 'node:crypto';
2
+
3
+ /**
4
+ * Every secret a self-hosted server needs, in the formats the orchestrator
5
+ * reads (see infra/selfhost/.env.example). Hex where a value goes into a URL.
6
+ */
7
+ export function generateSecrets() {
8
+ return {
9
+ POSTGRES_PASSWORD: randomBytes(24).toString('hex'),
10
+ REDIS_PASSWORD: randomBytes(24).toString('hex'),
11
+ BETTER_AUTH_SECRET: randomBytes(32).toString('base64'),
12
+ CREWAID_CREDENTIAL_KEYRING: JSON.stringify({ 1: randomBytes(32).toString('hex') }),
13
+ CREDENTIAL_KEY: randomBytes(32).toString('hex'),
14
+ };
15
+ }