@studiometa/trafic-agent 0.1.8 → 0.1.10

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.
@@ -1,904 +0,0 @@
1
- import { o as loadProjectList, f as getIdleProjects, n as loadProjectConfig, v as shouldNeverStop, h as getIdleTimeoutMs, k as getProjectInfo, u as setProjectStatus, y as stopProject } from "./server-CHT47EXr.js";
2
- import { existsSync, readFileSync, writeFileSync } from "node:fs";
3
- import { parse } from "smol-toml";
4
- import { execSync } from "node:child_process";
5
- const DEFAULT_CONFIG_PATHS = [
6
- "/etc/trafic/config.toml",
7
- "./config.toml",
8
- "./trafic.toml"
9
- ];
10
- const DEFAULT_CONFIG = {
11
- tld: "",
12
- port: 9876,
13
- dbPath: "/var/lib/trafic/db.sqlite",
14
- projectListPath: "/home/ddev/.ddev/project_list.yaml",
15
- projectsDir: "/home/ddev/www",
16
- idleTimeout: "30m",
17
- idleCheckInterval: "5m",
18
- auth: {
19
- defaultPolicy: "basic",
20
- allowedIps: [],
21
- tokens: [],
22
- basicAuth: [],
23
- rules: []
24
- }
25
- };
26
- function parseDuration(duration) {
27
- const regex = /(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?/;
28
- const match = duration.match(regex);
29
- if (!match) return 0;
30
- const hours = parseInt(match[1] ?? "0", 10);
31
- const minutes = parseInt(match[2] ?? "0", 10);
32
- const seconds = parseInt(match[3] ?? "0", 10);
33
- return (hours * 3600 + minutes * 60 + seconds) * 1e3;
34
- }
35
- function loadConfig(configPath) {
36
- let path = configPath;
37
- if (!path) {
38
- path = DEFAULT_CONFIG_PATHS.find((p) => existsSync(p));
39
- }
40
- if (!path || !existsSync(path)) {
41
- console.warn("No config file found, using defaults");
42
- return DEFAULT_CONFIG;
43
- }
44
- const content = readFileSync(path, "utf-8");
45
- const parsed = parse(content);
46
- const auth = mergeAuthConfig(parsed.auth);
47
- return {
48
- tld: parsed.tld ?? DEFAULT_CONFIG.tld,
49
- port: parsed.port ?? DEFAULT_CONFIG.port,
50
- dbPath: parsed.db_path ?? DEFAULT_CONFIG.dbPath,
51
- projectListPath: parsed.project_list_path ?? DEFAULT_CONFIG.projectListPath,
52
- projectsDir: parsed.projects_dir ?? DEFAULT_CONFIG.projectsDir,
53
- idleTimeout: parsed.idle_timeout ?? DEFAULT_CONFIG.idleTimeout,
54
- idleCheckInterval: parsed.idle_check_interval ?? DEFAULT_CONFIG.idleCheckInterval,
55
- auth
56
- };
57
- }
58
- function mergeAuthConfig(raw) {
59
- if (!raw) return DEFAULT_CONFIG.auth;
60
- const rules = raw.rules ?? [];
61
- return {
62
- defaultPolicy: raw.default_policy ?? DEFAULT_CONFIG.auth.defaultPolicy,
63
- allowedIps: raw.allowed_ips ?? DEFAULT_CONFIG.auth.allowedIps,
64
- tokens: raw.tokens ?? DEFAULT_CONFIG.auth.tokens,
65
- basicAuth: raw.basic_auth ?? DEFAULT_CONFIG.auth.basicAuth,
66
- rules: rules.map(
67
- (r) => ({
68
- match: r.match,
69
- policy: r.policy,
70
- tokens: r.tokens,
71
- allowedIps: r.allowed_ips
72
- })
73
- )
74
- };
75
- }
76
- function validateConfig(config) {
77
- const errors = [];
78
- if (!config.tld) {
79
- errors.push("tld is required");
80
- }
81
- if (config.port < 1 || config.port > 65535) {
82
- errors.push("port must be between 1 and 65535");
83
- }
84
- if (config.auth.defaultPolicy !== "allow" && config.auth.defaultPolicy !== "deny" && config.auth.defaultPolicy !== "basic" && config.auth.defaultPolicy !== "token") {
85
- errors.push('auth.default_policy must be "allow", "deny", "basic", or "token"');
86
- }
87
- return errors;
88
- }
89
- function stopIdleProjects(config) {
90
- const globalThresholdMs = parseDuration(config.idleTimeout);
91
- const projects = loadProjectList(config.projectListPath);
92
- const idleProjects = getIdleProjects(globalThresholdMs);
93
- for (const project of idleProjects) {
94
- const projectDir = projects.get(project.name);
95
- if (projectDir) {
96
- const projectConfig = loadProjectConfig(projectDir);
97
- if (shouldNeverStop(projectConfig)) {
98
- continue;
99
- }
100
- const projectThresholdMs = getIdleTimeoutMs(projectConfig);
101
- if (projectThresholdMs !== void 0) {
102
- const idleDuration = Date.now() - project.lastAccess;
103
- if (idleDuration < projectThresholdMs) {
104
- continue;
105
- }
106
- }
107
- }
108
- const info2 = getProjectInfo(project.name);
109
- if (info2?.status !== "running") {
110
- setProjectStatus(project.name, "stopped");
111
- continue;
112
- }
113
- console.log(`Stopping idle project: ${project.name}`);
114
- const success2 = stopProject(project.name);
115
- if (success2) {
116
- setProjectStatus(project.name, "stopped");
117
- console.log(`Stopped: ${project.name}`);
118
- } else {
119
- console.error(`Failed to stop: ${project.name}`);
120
- }
121
- }
122
- }
123
- function startIdleScheduler(config) {
124
- const intervalMs = parseDuration(config.idleCheckInterval);
125
- console.log(
126
- `Idle scheduler started: checking every ${config.idleCheckInterval}, timeout ${config.idleTimeout}`
127
- );
128
- stopIdleProjects(config);
129
- return setInterval(() => {
130
- stopIdleProjects(config);
131
- }, intervalMs);
132
- }
133
- let stepNumber = 0;
134
- let dryRun = false;
135
- function setDryRun(value) {
136
- dryRun = value;
137
- }
138
- function resetSteps() {
139
- stepNumber = 0;
140
- }
141
- function step(message) {
142
- stepNumber++;
143
- console.log(`
144
- \x1B[36m[${stepNumber}]\x1B[0m ${message}`);
145
- }
146
- function success(message) {
147
- console.log(` \x1B[32m✓\x1B[0m ${message}`);
148
- }
149
- function warn(message) {
150
- console.log(` \x1B[33m⚠\x1B[0m ${message}`);
151
- }
152
- function error(message) {
153
- console.log(` \x1B[31m✗\x1B[0m ${message}`);
154
- }
155
- function info(message) {
156
- console.log(` ${message}`);
157
- }
158
- function exec(command, options) {
159
- if (dryRun) {
160
- if (!options?.silent) {
161
- console.log(` \x1B[90m$ ${command}\x1B[0m`);
162
- }
163
- return "";
164
- }
165
- try {
166
- return execSync(command, {
167
- encoding: "utf-8",
168
- stdio: options?.silent ? "pipe" : "inherit"
169
- });
170
- } catch (err) {
171
- const e = err;
172
- throw new Error(`Command failed: ${command}
173
- ${e.stderr ?? ""}`);
174
- }
175
- }
176
- function execSilent$1(command) {
177
- if (dryRun) {
178
- return "";
179
- }
180
- try {
181
- return execSync(command, {
182
- encoding: "utf-8",
183
- stdio: "pipe"
184
- }).trim();
185
- } catch {
186
- return "";
187
- }
188
- }
189
- function commandExists(command) {
190
- try {
191
- execSync(`which ${command}`, { stdio: "pipe" });
192
- return true;
193
- } catch {
194
- return false;
195
- }
196
- }
197
- function isRoot() {
198
- return process.getuid?.() === 0;
199
- }
200
- function createDdevUser() {
201
- step("Create ddev user");
202
- const userExists = execSilent$1("id -u ddev 2>/dev/null");
203
- if (userExists) {
204
- info("User 'ddev' already exists");
205
- } else {
206
- exec("useradd -m -s /bin/bash ddev");
207
- success("Created user 'ddev'");
208
- }
209
- exec("usermod -aG docker ddev 2>/dev/null || true", { silent: true });
210
- exec("mkdir -p /home/ddev/www");
211
- exec("chown ddev:ddev /home/ddev/www");
212
- exec("chmod 750 /home/ddev/www");
213
- success("Created /home/ddev/www");
214
- exec("mkdir -p /home/ddev/.ssh");
215
- exec("chmod 700 /home/ddev/.ssh");
216
- exec("chown ddev:ddev /home/ddev/.ssh");
217
- success("User ddev configured (no sudo needed with proper DNS)");
218
- }
219
- function installDocker() {
220
- step("Install Docker");
221
- if (commandExists("docker")) {
222
- const version = exec("docker --version", { silent: true });
223
- info(`Docker already installed: ${version?.trim() ?? "unknown version"}`);
224
- return;
225
- }
226
- info("Downloading Docker install script...");
227
- exec("curl -fsSL https://get.docker.com -o /tmp/get-docker.sh");
228
- exec("sh /tmp/get-docker.sh");
229
- exec("rm /tmp/get-docker.sh");
230
- exec("systemctl enable docker");
231
- exec("systemctl start docker");
232
- success("Docker installed and started");
233
- exec("usermod -aG docker ddev");
234
- success("Added ddev user to docker group");
235
- }
236
- function configureDocker() {
237
- step("Configure Docker");
238
- const daemonConfig = {
239
- "log-driver": "json-file",
240
- "log-opts": {
241
- "max-size": "10m",
242
- "max-file": "3"
243
- },
244
- "storage-driver": "overlay2",
245
- "live-restore": true
246
- };
247
- exec("mkdir -p /etc/docker");
248
- const configPath = "/etc/docker/daemon.json";
249
- if (existsSync(configPath)) {
250
- try {
251
- const existing = JSON.parse(readFileSync(configPath, "utf-8"));
252
- const merged = { ...existing, ...daemonConfig };
253
- writeFileSync(configPath, JSON.stringify(merged, null, 2));
254
- info("Merged with existing Docker config");
255
- } catch {
256
- warn("Could not parse existing Docker config, skipping");
257
- return;
258
- }
259
- } else {
260
- writeFileSync(configPath, JSON.stringify(daemonConfig, null, 2));
261
- }
262
- exec("systemctl reload docker || systemctl restart docker");
263
- success("Docker configured with production settings");
264
- }
265
- function setupDockerPrune() {
266
- step("Setup Docker cleanup cron");
267
- const cronContent = `# Trafic: Clean up Docker resources weekly
268
- 0 3 * * 0 root docker system prune -af --volumes 2>&1 | logger -t docker-prune
269
- `;
270
- writeFileSync("/etc/cron.d/trafic-docker-prune", cronContent);
271
- exec("chmod 644 /etc/cron.d/trafic-docker-prune");
272
- success("Docker prune scheduled weekly at 3am on Sundays");
273
- }
274
- function installSystemDeps() {
275
- step("Install system dependencies");
276
- exec("apt-get update -qq", { silent: true });
277
- exec("DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get install -y jq curl rsync", { silent: true });
278
- success("System dependencies installed: jq, curl, rsync");
279
- }
280
- function installDdev() {
281
- step("Install DDEV");
282
- if (commandExists("ddev")) {
283
- const version = exec("ddev --version 2>/dev/null | head -1", { silent: true });
284
- info(`DDEV already installed: ${version?.trim() ?? "unknown version"}`);
285
- return;
286
- }
287
- info("Fetching latest DDEV version...");
288
- const latestVersion = exec(
289
- `curl -fsSL https://api.github.com/repos/ddev/ddev/releases/latest | grep '"tag_name"' | sed -E 's/.*"([^"]+)".*/\\1/'`,
290
- { silent: true }
291
- )?.trim();
292
- if (!latestVersion) {
293
- throw new Error("Could not determine latest DDEV version");
294
- }
295
- info(`Installing DDEV ${latestVersion}...`);
296
- const arch = exec("uname -m", { silent: true })?.trim() === "x86_64" ? "amd64" : "arm64";
297
- const tarball = `ddev_linux-${arch}.${latestVersion}.tar.gz`;
298
- const url = `https://github.com/ddev/ddev/releases/download/${latestVersion}/${tarball}`;
299
- exec(`curl -fsSL -o /tmp/${tarball} ${url}`);
300
- exec(`tar -xzf /tmp/${tarball} -C /tmp ddev`);
301
- exec("mv /tmp/ddev /usr/local/bin/ddev");
302
- exec("chmod +x /usr/local/bin/ddev");
303
- exec(`rm -f /tmp/${tarball}`);
304
- info("Installing mkcert...");
305
- const mkcertVersion = exec(
306
- `curl -fsSL https://api.github.com/repos/FiloSottile/mkcert/releases/latest | grep '"tag_name"' | sed -E 's/.*"([^"]+)".*/\\1/'`,
307
- { silent: true }
308
- )?.trim();
309
- if (mkcertVersion) {
310
- const mkcertBin = `mkcert-${mkcertVersion}-linux-${arch}`;
311
- exec(`curl -fsSL -o /usr/local/bin/mkcert https://github.com/FiloSottile/mkcert/releases/download/${mkcertVersion}/${mkcertBin}`);
312
- exec("chmod +x /usr/local/bin/mkcert");
313
- }
314
- success(`DDEV ${latestVersion} installed`);
315
- }
316
- function configureDdev(tld, email) {
317
- step("Configure DDEV");
318
- const ddevCmd = (cmd) => `su - ddev -c '${cmd}'`;
319
- exec(
320
- ddevCmd(
321
- `ddev config global --project-tld=${tld} --router-http-port=80 --router-https-port=443 --use-letsencrypt=${email ? "true" : "false"} ${email ? `--letsencrypt-email=${email}` : ""}`
322
- )
323
- );
324
- success(`DDEV configured with TLD: ${tld}`);
325
- info(`Ensure DNS is configured: *.${tld} → server IP`);
326
- if (email) {
327
- success(`Let's Encrypt enabled with email: ${email}`);
328
- }
329
- exec(ddevCmd("ddev config global --instrumentation-opt-in=false"));
330
- success("DDEV global settings configured");
331
- }
332
- function configureTraefik() {
333
- step("Configure Traefik for forward auth");
334
- exec("mkdir -p /home/ddev/.ddev/traefik");
335
- exec("chown -R ddev:ddev /home/ddev/.ddev");
336
- const staticConfig = `# Trafic: Forward auth middleware
337
- http:
338
- middlewares:
339
- trafic-auth:
340
- forwardAuth:
341
- address: "http://host.docker.internal:9876/__auth__"
342
- authResponseHeaders:
343
- - "X-Trafic-Project"
344
-
345
- trafic-errors:
346
- errors:
347
- status:
348
- - "502"
349
- - "503"
350
- service: trafic-service
351
- query: "/"
352
-
353
- services:
354
- trafic-service:
355
- loadBalancer:
356
- servers:
357
- - url: "http://host.docker.internal:9876"
358
- `;
359
- writeFileSync("/home/ddev/.ddev/traefik/trafic.yaml", staticConfig);
360
- exec("chown ddev:ddev /home/ddev/.ddev/traefik/trafic.yaml");
361
- const routerConfig = `# Trafic: Default router configuration
362
- # This file makes all DDEV projects use the Trafic auth middleware
363
- http:
364
- routers:
365
- trafic-catch-all:
366
- rule: "HostRegexp(\`.+\`)"
367
- priority: 1
368
- middlewares:
369
- - trafic-auth
370
- - trafic-errors
371
- service: api@internal
372
- `;
373
- writeFileSync("/home/ddev/.ddev/traefik/dynamic.yaml", routerConfig);
374
- exec("chown ddev:ddev /home/ddev/.ddev/traefik/dynamic.yaml");
375
- success("Traefik configured with Trafic middleware");
376
- }
377
- function installNode() {
378
- step("Install Node.js");
379
- if (commandExists("node")) {
380
- const version = exec("node --version", { silent: true });
381
- info(`Node.js already installed: ${version?.trim()}`);
382
- return;
383
- }
384
- exec(
385
- 'curl -fsSL https://fnm.vercel.app/install | bash -s -- --install-dir "/opt/fnm" --skip-shell'
386
- );
387
- const profileContent = `# Trafic: fnm (Node.js version manager)
388
- export FNM_DIR="/opt/fnm"
389
- export PATH="/opt/fnm:$PATH"
390
- eval "$(fnm env)"
391
- `;
392
- writeFileSync("/etc/profile.d/fnm.sh", profileContent);
393
- exec("chmod 644 /etc/profile.d/fnm.sh");
394
- exec("export FNM_DIR=/opt/fnm && /opt/fnm/fnm install 24");
395
- exec("export FNM_DIR=/opt/fnm && /opt/fnm/fnm default 24");
396
- exec(
397
- "ln -sf /opt/fnm/aliases/default/bin/node /usr/local/bin/node || true"
398
- );
399
- exec("ln -sf /opt/fnm/aliases/default/bin/npm /usr/local/bin/npm || true");
400
- exec("ln -sf /opt/fnm/aliases/default/bin/npx /usr/local/bin/npx || true");
401
- success("Node.js 24 installed via fnm");
402
- }
403
- function installAgent() {
404
- step("Install Trafic agent");
405
- exec("npm install -g @studiometa/trafic-agent");
406
- success("Trafic agent installed");
407
- }
408
- function createAgentConfig(tld, _email) {
409
- step("Create agent configuration");
410
- exec("mkdir -p /etc/trafic");
411
- exec("mkdir -p /var/lib/trafic");
412
- exec("chown ddev:ddev /var/lib/trafic");
413
- const configPath = "/etc/trafic/config.toml";
414
- if (existsSync(configPath)) {
415
- info("Configuration already exists at /etc/trafic/config.toml — skipping");
416
- info("Edit this file to configure authentication");
417
- return;
418
- }
419
- const config = `# Trafic agent configuration
420
- # Generated by trafic setup
421
-
422
- # Required: TLD for DDEV projects
423
- tld = "${tld}"
424
-
425
- # Agent HTTP server port
426
- port = 9876
427
-
428
- # Database and paths
429
- db_path = "/var/lib/trafic/db.sqlite"
430
- project_list_path = "/home/ddev/.ddev/project_list.yaml"
431
- projects_dir = "/home/ddev/www"
432
-
433
- # Scale-to-zero settings
434
- idle_timeout = "4h"
435
- idle_check_interval = "5m"
436
-
437
- # Authentication
438
- [auth]
439
- default_policy = "basic"
440
- allowed_ips = []
441
- tokens = []
442
- basic_auth = []
443
- rules = []
444
- `;
445
- writeFileSync(configPath, config);
446
- exec("chmod 640 /etc/trafic/config.toml");
447
- exec("chown root:ddev /etc/trafic/config.toml");
448
- success("Configuration created at /etc/trafic/config.toml");
449
- info("Edit this file to configure authentication");
450
- }
451
- function createSystemdService() {
452
- step("Create systemd service");
453
- const agentPath = exec("which trafic-agent", { silent: true })?.trim() || "/usr/bin/trafic-agent";
454
- const serviceContent = `[Unit]
455
- Description=Trafic Agent - DDEV preview environment manager
456
- After=network.target docker.service
457
- Requires=docker.service
458
-
459
- [Service]
460
- Type=simple
461
- User=ddev
462
- Group=ddev
463
- ExecStart=${agentPath} start --config /etc/trafic/config.toml
464
- Restart=always
465
- RestartSec=5
466
- StandardOutput=journal
467
- StandardError=journal
468
- SyslogIdentifier=trafic-agent
469
-
470
- # Environment
471
- Environment=NODE_ENV=production
472
- # Skip ddev-hostname /etc/hosts management — on a server, hostnames resolve
473
- # to the public IP (not localhost), which would trigger ddev-hostname on every
474
- # ddev start. DDEV_NONINTERACTIVE=true skips that entirely.
475
- Environment=DDEV_NONINTERACTIVE=true
476
-
477
- # Security hardening
478
- NoNewPrivileges=true
479
- ProtectSystem=strict
480
- ProtectHome=read-only
481
- ReadWritePaths=/var/lib/trafic /home/ddev/.ddev
482
- PrivateTmp=true
483
-
484
- [Install]
485
- WantedBy=multi-user.target
486
- `;
487
- writeFileSync("/etc/systemd/system/trafic-agent.service", serviceContent);
488
- exec("chmod 644 /etc/systemd/system/trafic-agent.service");
489
- exec("systemctl daemon-reload");
490
- exec("systemctl enable trafic-agent");
491
- exec("systemctl start trafic-agent");
492
- success("Trafic agent service started");
493
- info("View logs: journalctl -u trafic-agent -f");
494
- }
495
- function hardenSsh(allowedUsers = ["ddev"]) {
496
- step("Harden SSH configuration");
497
- const sshConfig = `# Trafic SSH hardening
498
- # Generated by trafic setup
499
-
500
- # Allow root login via SSH key only (no password) — required for server management
501
- PermitRootLogin prohibit-password
502
-
503
- # Disable password authentication (keys only)
504
- PasswordAuthentication no
505
- PubkeyAuthentication yes
506
-
507
- # Limit authentication attempts
508
- MaxAuthTries 3
509
-
510
- # Idle timeout (5 minutes)
511
- ClientAliveInterval 300
512
- ClientAliveCountMax 2
513
-
514
- # Allowed users (root kept for emergency access)
515
- AllowUsers root ${allowedUsers.join(" ")}
516
-
517
- # Disable X11 forwarding
518
- X11Forwarding no
519
-
520
- # Disable TCP forwarding
521
- AllowTcpForwarding no
522
-
523
- # Use strong algorithms only
524
- KexAlgorithms curve25519-sha256@libssh.org,diffie-hellman-group-exchange-sha256
525
- Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com
526
- MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com
527
- `;
528
- writeFileSync("/etc/ssh/sshd_config.d/trafic.conf", sshConfig);
529
- exec("chmod 644 /etc/ssh/sshd_config.d/trafic.conf");
530
- const testResult = exec("sshd -t 2>&1 || echo 'error'", { silent: true });
531
- if (testResult?.includes("error")) {
532
- warn("SSH config test failed, reverting...");
533
- exec("rm /etc/ssh/sshd_config.d/trafic.conf");
534
- return;
535
- }
536
- exec("systemctl reload ssh || systemctl reload sshd");
537
- success("SSH hardened: password auth disabled, root key-only login retained");
538
- info(`Allowed users: root, ${allowedUsers.join(", ")}`);
539
- }
540
- function configureFirewall() {
541
- step("Configure firewall (UFW)");
542
- if (!commandExists("ufw")) {
543
- exec("DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get install -y ufw", { silent: true });
544
- }
545
- exec("ufw --force reset", { silent: true });
546
- exec("ufw default deny incoming");
547
- exec("ufw default allow outgoing");
548
- exec("ufw allow 22/tcp comment 'SSH'");
549
- exec("ufw allow 80/tcp comment 'HTTP'");
550
- exec("ufw allow 443/tcp comment 'HTTPS'");
551
- exec("ufw --force enable");
552
- success("Firewall enabled: SSH (22), HTTP (80), HTTPS (443) allowed");
553
- }
554
- function configureUnattendedUpgrades() {
555
- step("Configure automatic security updates");
556
- exec(
557
- "DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get install -y unattended-upgrades apt-listchanges",
558
- { silent: true }
559
- );
560
- const upgradesConfig = `// Trafic: Automatic security updates
561
- Unattended-Upgrade::Allowed-Origins {
562
- "\${distro_id}:\${distro_codename}";
563
- "\${distro_id}:\${distro_codename}-security";
564
- "\${distro_id}ESMApps:\${distro_codename}-apps-security";
565
- "\${distro_id}ESM:\${distro_codename}-infra-security";
566
- };
567
-
568
- // Do not automatically reboot
569
- Unattended-Upgrade::Automatic-Reboot "false";
570
-
571
- // Remove unused dependencies
572
- Unattended-Upgrade::Remove-Unused-Dependencies "true";
573
-
574
- // Email notifications (optional)
575
- // Unattended-Upgrade::Mail "root";
576
- `;
577
- writeFileSync(
578
- "/etc/apt/apt.conf.d/50unattended-upgrades",
579
- upgradesConfig
580
- );
581
- const autoConfig = `APT::Periodic::Update-Package-Lists "1";
582
- APT::Periodic::Download-Upgradeable-Packages "1";
583
- APT::Periodic::AutocleanInterval "7";
584
- APT::Periodic::Unattended-Upgrade "1";
585
- `;
586
- writeFileSync("/etc/apt/apt.conf.d/20auto-upgrades", autoConfig);
587
- exec("systemctl enable unattended-upgrades");
588
- exec("systemctl start unattended-upgrades");
589
- success("Automatic security updates enabled");
590
- }
591
- function configureFail2ban() {
592
- step("Configure Fail2ban");
593
- if (!commandExists("fail2ban-client")) {
594
- exec("DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get install -y fail2ban", { silent: true });
595
- }
596
- const jailConfig = `# Trafic: Fail2ban configuration
597
- [DEFAULT]
598
- bantime = 3600
599
- findtime = 600
600
- maxretry = 5
601
- backend = auto
602
-
603
- [sshd]
604
- enabled = true
605
- port = ssh
606
- filter = sshd
607
- logpath = /var/log/auth.log
608
- maxretry = 3
609
- bantime = 7200
610
- `;
611
- writeFileSync("/etc/fail2ban/jail.local", jailConfig);
612
- exec("chmod 644 /etc/fail2ban/jail.local");
613
- exec("systemctl enable fail2ban");
614
- exec("systemctl restart fail2ban");
615
- success("Fail2ban enabled: SSH brute force protection active");
616
- }
617
- function configureSystemLimits() {
618
- step("Configure system limits");
619
- const limitsConfig = `# Trafic: System limits for ddev user
620
- ddev soft nofile 65536
621
- ddev hard nofile 65536
622
- ddev soft nproc 4096
623
- ddev hard nproc 4096
624
- `;
625
- writeFileSync("/etc/security/limits.d/trafic.conf", limitsConfig);
626
- exec("chmod 644 /etc/security/limits.d/trafic.conf");
627
- success("System limits configured for ddev user");
628
- }
629
- function configureFilePermissions() {
630
- step("Configure file permissions");
631
- exec("mkdir -p /etc/trafic");
632
- exec("mkdir -p /var/lib/trafic");
633
- exec("mkdir -p /var/backups/trafic");
634
- exec("chmod 755 /etc/trafic");
635
- exec("chmod 700 /var/lib/trafic");
636
- exec("chmod 700 /var/backups/trafic");
637
- exec("chown root:ddev /etc/trafic");
638
- exec("chown ddev:ddev /var/lib/trafic");
639
- exec("chown ddev:ddev /var/backups/trafic");
640
- if (existsSync("/etc/trafic/config.toml")) {
641
- exec("chmod 640 /etc/trafic/config.toml");
642
- exec("chown root:ddev /etc/trafic/config.toml");
643
- }
644
- success("File permissions configured");
645
- }
646
- function hardenServer(sshUsers = ["ddev"]) {
647
- hardenSsh(sshUsers);
648
- configureFirewall();
649
- configureUnattendedUpgrades();
650
- configureFail2ban();
651
- configureSystemLimits();
652
- configureFilePermissions();
653
- }
654
- function execSilent(command) {
655
- try {
656
- return execSync(command, { encoding: "utf-8", stdio: "pipe" }).trim();
657
- } catch {
658
- return "";
659
- }
660
- }
661
- function isServiceActive(service) {
662
- const status = execSilent(`systemctl is-active ${service}`);
663
- return status === "active";
664
- }
665
- function auditSsh() {
666
- const checks = [];
667
- const sshdConfig = existsSync("/etc/ssh/sshd_config") ? readFileSync("/etc/ssh/sshd_config", "utf-8") : "";
668
- const traficConfig = existsSync("/etc/ssh/sshd_config.d/trafic.conf") ? readFileSync("/etc/ssh/sshd_config.d/trafic.conf", "utf-8") : "";
669
- const config = sshdConfig + "\n" + traficConfig;
670
- const rootLoginDisabled = config.includes("PermitRootLogin no") || config.includes("PermitRootLogin prohibit-password");
671
- checks.push({
672
- name: "SSH root login",
673
- status: rootLoginDisabled ? "pass" : "fail",
674
- message: rootLoginDisabled ? "Root login disabled" : "Root login may be enabled",
675
- fix: "Add 'PermitRootLogin no' to /etc/ssh/sshd_config.d/trafic.conf"
676
- });
677
- const passwordAuthDisabled = config.includes("PasswordAuthentication no");
678
- checks.push({
679
- name: "SSH password auth",
680
- status: passwordAuthDisabled ? "pass" : "warn",
681
- message: passwordAuthDisabled ? "Password authentication disabled" : "Password authentication may be enabled",
682
- fix: "Add 'PasswordAuthentication no' to /etc/ssh/sshd_config.d/trafic.conf"
683
- });
684
- return checks;
685
- }
686
- function auditFirewall() {
687
- const checks = [];
688
- const ufwStatus = execSilent("ufw status");
689
- const isActive = ufwStatus.includes("Status: active");
690
- checks.push({
691
- name: "Firewall (UFW)",
692
- status: isActive ? "pass" : "fail",
693
- message: isActive ? "UFW is active" : "UFW is not active",
694
- fix: "Run: ufw enable"
695
- });
696
- if (isActive) {
697
- const allows22 = ufwStatus.includes("22/tcp");
698
- const allows80 = ufwStatus.includes("80/tcp");
699
- const allows443 = ufwStatus.includes("443/tcp");
700
- if (allows22 && allows80 && allows443) {
701
- checks.push({
702
- name: "Firewall ports",
703
- status: "pass",
704
- message: "Required ports (22, 80, 443) are open"
705
- });
706
- } else {
707
- checks.push({
708
- name: "Firewall ports",
709
- status: "warn",
710
- message: "Some required ports may be blocked",
711
- fix: "Run: ufw allow 22/tcp && ufw allow 80/tcp && ufw allow 443/tcp"
712
- });
713
- }
714
- }
715
- return checks;
716
- }
717
- function auditServices() {
718
- const checks = [];
719
- const fail2banActive = isServiceActive("fail2ban");
720
- checks.push({
721
- name: "Fail2ban",
722
- status: fail2banActive ? "pass" : "warn",
723
- message: fail2banActive ? "Fail2ban is active" : "Fail2ban is not running",
724
- fix: "Run: apt install fail2ban && systemctl enable fail2ban --now"
725
- });
726
- const unattendedActive = isServiceActive("unattended-upgrades");
727
- checks.push({
728
- name: "Automatic updates",
729
- status: unattendedActive ? "pass" : "warn",
730
- message: unattendedActive ? "Unattended upgrades enabled" : "Automatic updates not configured",
731
- fix: "Run: apt install unattended-upgrades && dpkg-reconfigure unattended-upgrades"
732
- });
733
- const agentActive = isServiceActive("trafic-agent");
734
- checks.push({
735
- name: "Trafic agent",
736
- status: agentActive ? "pass" : "fail",
737
- message: agentActive ? "Trafic agent is running" : "Trafic agent is not running",
738
- fix: "Run: systemctl start trafic-agent"
739
- });
740
- return checks;
741
- }
742
- function auditDocker() {
743
- const checks = [];
744
- const dockerActive = isServiceActive("docker");
745
- checks.push({
746
- name: "Docker",
747
- status: dockerActive ? "pass" : "fail",
748
- message: dockerActive ? "Docker is running" : "Docker is not running",
749
- fix: "Run: systemctl start docker"
750
- });
751
- const danglingImages = execSilent(
752
- "docker images -f dangling=true -q | wc -l"
753
- );
754
- const count = parseInt(danglingImages, 10) || 0;
755
- if (count > 0) {
756
- checks.push({
757
- name: "Docker cleanup",
758
- status: "warn",
759
- message: `${count} dangling Docker images`,
760
- fix: "Run: docker system prune -f"
761
- });
762
- }
763
- const diskUsage = execSilent("df -h / | awk 'NR==2{print $5}'");
764
- const usagePercent = parseInt(diskUsage, 10) || 0;
765
- checks.push({
766
- name: "Disk usage",
767
- status: usagePercent > 90 ? "fail" : usagePercent > 80 ? "warn" : "pass",
768
- message: `Disk usage: ${diskUsage}`,
769
- fix: usagePercent > 80 ? "Consider cleaning up old projects or Docker resources" : void 0
770
- });
771
- return checks;
772
- }
773
- function auditPermissions() {
774
- const checks = [];
775
- if (existsSync("/etc/trafic/config.toml")) {
776
- const stats = execSilent("stat -c '%a' /etc/trafic/config.toml");
777
- const isSecure = stats === "640" || stats === "600";
778
- checks.push({
779
- name: "Config permissions",
780
- status: isSecure ? "pass" : "warn",
781
- message: isSecure ? "Config file has secure permissions" : `Config file permissions: ${stats} (should be 640)`,
782
- fix: "Run: chmod 640 /etc/trafic/config.toml"
783
- });
784
- }
785
- if (existsSync("/home/ddev/www")) {
786
- const owner = execSilent("stat -c '%U:%G' /home/ddev/www");
787
- const isCorrect = owner === "ddev:ddev";
788
- checks.push({
789
- name: "Projects directory",
790
- status: isCorrect ? "pass" : "warn",
791
- message: isCorrect ? "Projects directory owned by ddev" : `Projects directory owner: ${owner}`,
792
- fix: "Run: chown ddev:ddev /home/ddev/www"
793
- });
794
- }
795
- return checks;
796
- }
797
- function runAudit() {
798
- return [
799
- ...auditSsh(),
800
- ...auditFirewall(),
801
- ...auditServices(),
802
- ...auditDocker(),
803
- ...auditPermissions()
804
- ];
805
- }
806
- function printAuditResults(checks) {
807
- console.log("\n\x1B[1mSecurity Audit Results\x1B[0m\n");
808
- for (const check of checks) {
809
- const icon = check.status === "pass" ? "\x1B[32m✓\x1B[0m" : check.status === "warn" ? "\x1B[33m⚠\x1B[0m" : "\x1B[31m✗\x1B[0m";
810
- console.log(`${icon} \x1B[1m${check.name}\x1B[0m: ${check.message}`);
811
- if (check.fix && check.status !== "pass") {
812
- console.log(` \x1B[90m${check.fix}\x1B[0m`);
813
- }
814
- }
815
- const passed = checks.filter((c) => c.status === "pass").length;
816
- const warnings = checks.filter((c) => c.status === "warn").length;
817
- const failed = checks.filter((c) => c.status === "fail").length;
818
- console.log(
819
- `
820
- \x1B[1mSummary:\x1B[0m ${passed} passed, ${warnings} warnings, ${failed} failed`
821
- );
822
- }
823
- async function setup(options) {
824
- resetSteps();
825
- setDryRun(options.dryRun ?? false);
826
- console.log("\n\x1B[1m🚦 Trafic Server Setup\x1B[0m\n");
827
- if (options.dryRun) {
828
- console.log("\x1B[33m⚠ Dry-run mode: no changes will be made\x1B[0m\n");
829
- }
830
- if (!isRoot() && !options.dryRun) {
831
- error("This command must be run as root");
832
- console.log(" Run: sudo trafic-agent setup ...");
833
- process.exit(1);
834
- }
835
- info(`TLD: ${options.tld}`);
836
- if (options.email) {
837
- info(`Let's Encrypt email: ${options.email}`);
838
- }
839
- if (options.noHardening) {
840
- info("Hardening: disabled");
841
- }
842
- try {
843
- installSystemDeps();
844
- createDdevUser();
845
- if (!options.noDocker) {
846
- installDocker();
847
- configureDocker();
848
- setupDockerPrune();
849
- } else {
850
- step("Install Docker");
851
- info("Skipped (--no-docker)");
852
- }
853
- if (!options.noDdev) {
854
- installDdev();
855
- configureDdev(options.tld, options.email);
856
- configureTraefik();
857
- } else {
858
- step("Install DDEV");
859
- info("Skipped (--no-ddev)");
860
- }
861
- installNode();
862
- installAgent();
863
- createAgentConfig(options.tld, options.email);
864
- createSystemdService();
865
- if (!options.noHardening) {
866
- const sshUsers = options.sshUsers ?? ["ddev"];
867
- hardenServer(sshUsers);
868
- } else {
869
- step("Server hardening");
870
- info("Skipped (--no-hardening)");
871
- }
872
- console.log("\n\x1B[32m✓ Setup complete!\x1B[0m\n");
873
- console.log("Next steps:");
874
- console.log(` 1. Edit /etc/trafic/config.toml to configure authentication`);
875
- console.log(` 2. Add SSH public keys to /home/ddev/.ssh/authorized_keys`);
876
- console.log(` 3. Deploy your first project:`);
877
- console.log(` npx @studiometa/trafic-cli deploy --host=<this-server> --name=my-app`);
878
- console.log(`
879
- Your projects will be available at https://<name>.${options.tld}`);
880
- } catch (err) {
881
- error(`Setup failed: ${err instanceof Error ? err.message : err}`);
882
- process.exit(1);
883
- }
884
- }
885
- async function audit() {
886
- const checks = runAudit();
887
- printAuditResults(checks);
888
- const failed = checks.filter((c) => c.status === "fail").length;
889
- if (failed > 0) {
890
- process.exit(1);
891
- }
892
- }
893
- export {
894
- audit as a,
895
- printAuditResults as b,
896
- startIdleScheduler as c,
897
- stopIdleProjects as d,
898
- loadConfig as l,
899
- parseDuration as p,
900
- runAudit as r,
901
- setup as s,
902
- validateConfig as v
903
- };
904
- //# sourceMappingURL=index-CqtdZoAx.js.map